@agoric/swingset-xsnap-supervisor 0.10.3-u16.0 → 0.10.3-u17.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/supervisor.bundle
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"moduleFormat":"nestedEvaluate","source":"function getExportWithNestedEvaluate(filePrefix) {\n 'use strict';\n // Serialised sources.\n if (filePrefix === undefined) {\n filePrefix = \"/bundled-source/...\";\n }\n const moduleFormat = \"nestedEvaluate\";\n const entrypoint = \"packages/swingset-xsnap-supervisor/lib/entry.js\";\n const sourceBundle = {\n \"node_modules/@endo/base64/atob.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('./decode.js');var\\n\\ndecode=require('./src/decode.js');/**\\n * @param {string} encodedData a binary string containing base64-encoded data\\n * @returns {string} an ASCII string containing decoded data from `encodedData`\\n */\\nconst atob=(encodedData)=>{\\nconst buf=decode.decodeBase64(encodedData);\\nreturn String.fromCharCode(...buf);};exports.atob=atob;\",\n \"node_modules/@endo/base64/btoa.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('./encode.js');var\\n\\nencode=require('./src/encode.js');/**\\n * @param {string} stringToEncode the binary string to encode\\n * @returns {string} an ASCII string containing the base64 representation of `stringToEncode`\\n */\\nconst btoa=(stringToEncode)=>{\\nconst bytes=stringToEncode.split('').map((char)=>{\\nconst b=char.charCodeAt(0);\\nif(b>0xff){\\nthrow Error(`btoa: character out of range: ${char}`);}\\n\\nreturn b;});\\n\\nconst buf=new Uint8Array(bytes);\\nreturn encode.encodeBase64(buf);};exports.btoa=btoa;\",\n \"node_modules/@endo/base64/decode.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var decode=require('./src/decode.js');exports.decodeBase64=decode.decodeBase64;\",\n \"node_modules/@endo/base64/encode.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var encode=require('./src/encode.js');exports.encodeBase64=encode.encodeBase64;\",\n \"node_modules/@endo/base64/index.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var encode=require('./src/encode.js');var decode=require('./src/decode.js');var btoa=require('./btoa.js');var atob=require('./atob.js');exports.encodeBase64=encode.encodeBase64;exports.decodeBase64=decode.decodeBase64;exports.btoa=btoa.btoa;exports.atob=atob.atob;\",\n \"node_modules/@endo/base64/src/common.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});/* @ts-check*/\\n\\nconst padding='=';\\n\\nconst alphabet64=\\n'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\\n\\n/**\\n * The numeric value corresponding to each letter of the alphabet.\\n * If an alphabet is named for the Greek letters alpha and beta, then clearly a\\n * monodu is named for the corresponding Greek numbers mono and duo.\\n *\\n * @type {Record<string, number>}\\n */\\nconst monodu64={};\\nfor(let i=0;i<alphabet64.length;i+=1){\\nconst c=alphabet64[i];\\nmonodu64[c]=i;}exports.alphabet64=alphabet64;exports.monodu64=monodu64;exports.padding=padding;\",\n \"node_modules/@endo/base64/src/decode.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var\\n\\n\\n\\n\\n\\ncommon=require('./common.js');/* @ts-check*/ /**\\n * Decodes a Base64 string into bytes, as specified in\\n * https://tools.ietf.org/html/rfc4648#section-4\\n *\\n * XSnap is a JavaScript engine based on Moddable/XS.\\n * The algorithm below is orders of magnitude too slow on this VM, but it\\n * arranges a native binding on the global object.\\n * We use that if it is available instead.\\n *\\n * This function is exported from this *file* for use in benchmarking,\\n * but is not part of the *module*'s public API.\\n *\\n * @param {string} string Base64-encoded string\\n * @param {string} [name] The name of the string as it will appear in error\\n * messages.\\n * @returns {Uint8Array} decoded bytes\\n */\\nconst jsDecodeBase64=(string,name='<unknown>')=>{\\nconst data=new Uint8Array(Math.ceil(string.length*4/3));\\nlet register=0;\\nlet quantum=0;\\nlet i=0;/* index in string*/\\nlet j=0;/* index in data*/\\n\\nwhile(i<string.length&&string[i]!==common.padding){\\nconst number=common.monodu64[string[i]];\\nif(number===undefined){\\nthrow Error(`Invalid base64 character ${string[i]} in string ${name}`);}\\n\\nregister=register<<6|number;\\nquantum+=6;\\nif(quantum>=8){\\nquantum-=8;\\ndata[j]=register>>>quantum;\\nj+=1;\\nregister&=(1<<quantum)-1;}\\n\\ni+=1;}\\n\\n\\nwhile(quantum>0){\\nif(i===string.length||string[i]!==common.padding){\\nthrow Error(`Missing padding at offset ${i} of string ${name}`);}\\n\\n/* We MAY reject non-zero padding bits, but choose not to.*/\\n/* https://datatracker.ietf.org/doc/html/rfc4648#section-3.5*/\\ni+=1;\\nquantum-=2;}\\n\\n\\nif(i<string.length){\\nthrow Error(\\n`Base64 string has trailing garbage ${string.substr(\\ni)\\n} in string ${name}`);}\\n\\n\\n\\nreturn data.subarray(0,j);};\\n\\n\\n/* The XS Base64.decode function is faster, but might return ArrayBuffer (not*/\\n/* Uint8Array). Adapt it to our needs.*/\\nconst adaptDecoder=\\n(nativeDecodeBase64)=>\\n(...args)=>{\\nconst decoded=nativeDecodeBase64(...args);\\nif(decoded instanceof Uint8Array){\\nreturn decoded;}\\n\\nreturn new Uint8Array(decoded);};\\n\\n\\n/** @type {typeof jsDecodeBase64} */\\nconst decodeBase64=\\nglobalThis.Base64!==undefined?\\nadaptDecoder(globalThis.Base64.decode):\\njsDecodeBase64;exports.decodeBase64=decodeBase64;exports.jsDecodeBase64=jsDecodeBase64;\",\n \"node_modules/@endo/base64/src/encode.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var\\n\\n\\n\\n\\n\\ncommon=require('./common.js');/* @ts-check*/ /**\\n * Encodes bytes into a Base64 string, as specified in\\n * https://tools.ietf.org/html/rfc4648#section-4\\n *\\n * XSnap is a JavaScript engine based on Moddable/XS.\\n * The algorithm below is orders of magnitude too slow on this VM, but it\\n * arranges a native binding on the global object.\\n * We use that if it is available instead.\\n *\\n * This function is exported from this *file* for use in benchmarking,\\n * but is not part of the *module*'s public API.\\n *\\n * @param {Uint8Array} data\\n * @returns {string} base64 encoding\\n */\\nconst jsEncodeBase64=(data)=>{\\n/* A cursory benchmark shows that string concatenation is about 25% faster*/\\n/* than building an array and joining it in v8, in 2020, for strings of about*/\\n/* 100 long.*/\\nlet string='';\\nlet register=0;\\nlet quantum=0;\\n\\nfor(let i=0;i<data.length;i+=1){\\nconst b=data[i];\\nregister=register<<8|b;\\nquantum+=8;\\nif(quantum===24){\\nstring+=\\ncommon.alphabet64[register>>>18&0x3f]+\\ncommon.alphabet64[register>>>12&0x3f]+\\ncommon.alphabet64[register>>>6&0x3f]+\\ncommon.alphabet64[register>>>0&0x3f];\\nregister=0;\\nquantum=0;}}\\n\\n\\n\\nswitch(quantum){\\ncase 0:\\nbreak;\\ncase 8:\\nstring+=\\ncommon.alphabet64[register>>>2&0x3f]+\\ncommon.alphabet64[register<<4&0x3f]+\\ncommon.padding+\\ncommon.padding;\\nbreak;\\ncase 16:\\nstring+=\\ncommon.alphabet64[register>>>10&0x3f]+\\ncommon.alphabet64[register>>>4&0x3f]+\\ncommon.alphabet64[register<<2&0x3f]+\\ncommon.padding;\\nbreak;\\ndefault:\\nthrow Error(`internal: bad quantum ${quantum}`);}\\n\\nreturn string;};\\n\\n\\n/** @type {typeof jsEncodeBase64} */\\nconst encodeBase64=\\nglobalThis.Base64!==undefined?globalThis.Base64.encode:jsEncodeBase64;exports.encodeBase64=encodeBase64;exports.jsEncodeBase64=jsEncodeBase64;\",\n \"node_modules/@endo/common/apply-labeling-error.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var noShim=require('../eventual-send/src/no-shim.js');require('../promise-kit/index.js');var throwLabeled=require('./throw-labeled.js');var\\n\\n\\n\\nisPromise=require('../promise-kit/src/is-promise.js');/**\\n * Calls `func(...args)`, but annotating any failure error with `label`.\\n *\\n * If `label` is omitted or `undefined`, then this is equivalent to\\n * `func(...args).\\n *\\n * Otherwise, if it successfully returns a non-promise, that non-promise is\\n * returned.\\n *\\n * If it throws, rethrow a similar error whose message is\\n * ```js\\n * `${label}: ${originalMessage}`\\n * ```\\n * That way, in an error happens deep within a stack of calls to\\n * `applyLabelingError`, the resulting error will show the stack of labels.\\n *\\n * If it returns a promise, then `applyLabelingError` cannot tell until that\\n * promise settles whether it represents a success or failure. So it immediately\\n * returns a new promise. If the original promise fulfills, then the\\n * fulfillment is propagated to the returned promise.\\n *\\n * If the promise rejects with an error, then the returned promise is\\n * rejected with a similar promise, prefixed with the label in that same way.\\n *\\n * @template A,R\\n * @param {(...args: A[]) => R} func\\n * @param {A[]} args\\n * @param {string|number} [label]\\n * @returns {R}\\n */\\nconst applyLabelingError=(func,args,label=undefined)=>{\\nif(label===undefined){\\nreturn func(...args);}\\n\\nlet result;\\ntry{\\nresult=func(...args);}\\ncatch(err){\\nthrowLabeled.throwLabeled(err,label);}\\n\\nif(isPromise.isPromise(result)){\\n/* Cannot be at-ts-expect-error because there is no type error locally.*/\\n/* Rather, a type error only as imported into exo.*/\\n/* @ts-ignore If result is a rejected promise, this will*/\\n/* return a promise with a different rejection reason. But this*/\\n/* confuses TypeScript because it types that case as `Promise<never>`*/\\n/* which is cool for a promise that will never fulfll.*/\\n/* But TypeScript doesn't understand that this will only happen*/\\n/* when `result` was a rejected promise. In only this case `R`*/\\n/* should already allow `Promise<never>` as a subtype.*/\\nreturn noShim.E.when(result,undefined,(reason)=>throwLabeled.throwLabeled(reason,label));}else\\n{\\nreturn result;}};\\n\\n\\nharden(applyLabelingError);exports.applyLabelingError=applyLabelingError;\",\n \"node_modules/@endo/common/from-unique-entries.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var index=require('../errors/index.js');\\n\\nconst{fromEntries}=Object;\\nconst{ownKeys}=Reflect;\\n\\n/**\\n * Throws if multiple entries use the same property name. Otherwise acts\\n * like `Object.fromEntries` but hardens the result.\\n * Use it to protect from property names computed from user-provided data.\\n *\\n * @template K,V\\n * @param {Iterable<[K,V]>} allEntries\\n * @returns {{[k: K]: V}}\\n */\\nconst fromUniqueEntries=(allEntries)=>{\\nconst entriesArray=[...allEntries];\\nconst result=harden(fromEntries(entriesArray));\\nif(ownKeys(result).length===entriesArray.length){\\nreturn result;}\\n\\nconst names=new Set();\\nfor(const[name,_]of entriesArray){\\nif(names.has(name)){\\nindex.throwRedacted`collision on property name ${index.quote(name)}: ${entriesArray}`;}\\n\\nnames.add(name);}\\n\\nthrow index.throwRedacted`internal: failed to create object from unique entries`;};\\n\\nharden(fromUniqueEntries);exports.fromUniqueEntries=fromUniqueEntries;\",\n \"node_modules/@endo/common/ident-checker.js\": \"'use strict';\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nObject.defineProperty(exports,'__esModule',{value:true});/* TODO Complete migration of Checker type from @endo/pass-style to @endo/common*/ /* by having @endo/pass-style, and everyone else who needs it, import it from*/ /* `@endo/common/ident-checker.js`.*/ /**\\n * @callback Checker\\n * Internal to a useful pattern for writing checking logic\\n * (a \\\"checkFoo\\\" function) that can be used to implement a predicate\\n * (an \\\"isFoo\\\" function) or a validator (an \\\"assertFoo\\\" function).\\n *\\n * * A predicate ideally only returns `true` or `false` and rarely throws.\\n * * A validator throws an informative diagnostic when the predicate\\n * would have returned `false`, and simply returns `undefined` normally\\n * when the predicate would have returned `true`.\\n * * The internal checking function that they share is parameterized by a\\n * `Checker` that determines how to proceed with a failure condition.\\n * Predicates pass in an identity function as checker. Validators\\n * pass in `assertChecker` which is a trivial wrapper around `assert`.\\n *\\n * See the various uses for good examples.\\n * @param {boolean} cond\\n * @param {IMPORT('ses').Details} [details]\\n * @returns {boolean}\\n */ /**\\n * In the `assertFoo`/`isFoo`/`checkFoo` pattern, `checkFoo` has a `check`\\n * parameter of type `Checker`. `assertFoo` calls `checkFoo` passes\\n * `assertChecker` as the `check` argument. `isFoo` passes `identChecker`\\n * as the `check` argument. `identChecker` acts precisely like an\\n * identity function, but is typed as a `Checker` to indicate its\\n * intended use.\\n *\\n * @type {Checker}\\n */const identChecker=(cond,_details)=>cond;harden(identChecker);exports.identChecker=identChecker;\",\n \"node_modules/@endo/common/list-difference.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});/**\\n * Return a list of all the elements present in the `leftList` and not\\n * in the `rightList`. Return in the order of their appearance in `leftList`.\\n * Uses the comparison built into `Set` membership (SameValueZero)\\n * which is like JavaScript's `===` except that it judges any `NaN` to\\n * be the same as any `NaN` and it judges `0` to be the same a `-0`.\\n *\\n * This is often used on lists of names that should match, in order to generate\\n * useful diagnostics about the unmatched names.\\n *\\n * @template {any} V\\n * @param {V[]} leftList\\n * @param {V[]} rightList\\n */\\nconst listDifference=(leftList,rightList)=>{\\nconst rightSet=new Set(rightList);\\nreturn leftList.filter((element)=>!rightSet.has(element));};\\n\\nharden(listDifference);exports.listDifference=listDifference;\",\n \"node_modules/@endo/common/make-array-iterator.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var\\n\\nmakeIterator=require('./make-iterator.js');/**\\n * A `harden`ing analog of Array.prototype[Symbol.iterator].\\n *\\n * @template [T=unknown]\\n * @param {Array<T>} arr\\n * @returns {IterableIterator<T>}\\n */\\nconst makeArrayIterator=(arr)=>{\\nconst{length}=arr;\\nlet i=0;\\nreturn makeIterator.makeIterator(()=>{\\n/** @type {T} */\\nlet value;\\nif(i<length){\\nvalue=arr[i];\\ni+=1;\\nreturn harden({done:false,value});}\\n\\n/* @ts-expect-error The terminal value doesn't matter*/\\nreturn harden({done:true,value});});};\\n\\n\\nharden(makeArrayIterator);exports.makeArrayIterator=makeArrayIterator;\",\n \"node_modules/@endo/common/make-iterator.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});/**\\n * Makes a one-shot iterable iterator from a provided `next` function.\\n *\\n * @template [T=unknown]\\n * @param {() => IteratorResult<T>} next\\n * @returns {IterableIterator<T>}\\n */\\nconst makeIterator=(next)=>{\\nconst iter=harden({\\n[Symbol.iterator]:()=>iter,\\nnext});\\n\\nreturn iter;};\\n\\nharden(makeIterator);exports.makeIterator=makeIterator;\",\n \"node_modules/@endo/common/object-map.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});const{entries,fromEntries}=Object;\\n\\n/**\\n * By analogy with how `Array.prototype.map` will map the elements of\\n * an array to transformed elements of an array of the same shape,\\n * `objectMap` will do likewise for the string-named own enumerable\\n * properties of an object.\\n *\\n * Typical usage applies `objectMap` to a CopyRecord, i.e.,\\n * an object for which `passStyleOf(original) === 'copyRecord'`. For these,\\n * none of the following edge cases arise. The result will be a CopyRecord\\n * with exactly the same property names, whose values are the mapped form of\\n * the original's values.\\n *\\n * When the original is not a CopyRecord, some edge cases to be aware of\\n * * No matter how mutable the original object, the returned object is\\n * hardened.\\n * * Only the string-named enumerable own properties of the original\\n * are mapped. All other properties are ignored.\\n * * If any of the original properties were accessors, `Object.entries`\\n * will cause its `getter` to be called and will use the resulting\\n * value.\\n * * No matter whether the original property was an accessor, writable,\\n * or configurable, all the properties of the returned object will be\\n * non-writable, non-configurable, data properties.\\n * * No matter what the original object may have inherited from, and\\n * no matter whether it was a special kind of object such as an array,\\n * the returned object will always be a plain object inheriting directly\\n * from `Object.prototype` and whose state is only these new mapped\\n * own properties.\\n *\\n * With these differences, even if the original object was not a CopyRecord,\\n * if all the mapped values are Passable, then the returned object will be\\n * a CopyRecord.\\n *\\n * @template {Record<string, any>} O\\n * @template R map result\\n * @param {O} original\\n * @param {(value: O[keyof O], key: keyof O) => R} mapFn\\n * @returns {Record<keyof O, R>}\\n */\\nconst objectMap=(original,mapFn)=>{\\nconst ents=entries(original);\\nconst mapEnts=ents.map(\\n([k,v])=>/** @type {[keyof O, R]} */[k,mapFn(v,k)]);\\n\\nreturn(/** @type {Record<keyof O, R>} */harden(fromEntries(mapEnts)));};\\n\\nharden(objectMap);exports.objectMap=objectMap;\",\n \"node_modules/@endo/common/throw-labeled.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var\\n\\nindex=require('../errors/index.js');/**\\n * Given an error `innerErr` and a `label`, throws a similar\\n * error whose message string is `${label}: ${innerErr.message}`.\\n * See `applyLabelingError` for the motivating use.\\n *\\n * @param {Error} innerErr\\n * @param {string|number} label\\n * @param {IMPORT('ses').GenericErrorConstructor} [errConstructor]\\n * @param {IMPORT('ses').AssertMakeErrorOptions} [options]\\n * @returns {never}\\n */\\nconst throwLabeled=(\\ninnerErr,\\nlabel,\\nerrConstructor=undefined,\\noptions=undefined)=>\\n{\\nif(typeof label==='number'){\\nlabel=`[${label}]`;}\\n\\nconst outerErr=index.makeError(\\n`${label}: ${innerErr.message}`,\\nerrConstructor,\\noptions);\\n\\nindex.note(outerErr,index.redacted`Caused by ${innerErr}`);\\nthrow outerErr;};\\n\\nharden(throwLabeled);exports.throwLabeled=throwLabeled;\",\n \"node_modules/@endo/compartment-mapper/import-archive.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var importArchive=require('./src/import-archive.js');exports.importArchive=importArchive.importArchive;exports.loadArchive=importArchive.loadArchive;exports.parseArchive=importArchive.parseArchive;\",\n \"node_modules/@endo/compartment-mapper/src/compartment-map.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var\\n\\n\\n\\n\\n\\n\\n\\npolicyFormat=require('./policy-format.js');/* @ts-check*/ /* TODO convert to the new `||` assert style.*/ /* Deferred because this file pervasively uses simple template strings rather than*/ /* template strings tagged with `assert.details` (aka `X`), and uses*/ /* this definition of `q` rather than `assert.quote`*/\\nconst q=JSON.stringify;\\n\\nconst moduleLanguages=[\\n'cjs',\\n'mjs',\\n'json',\\n'text',\\n'bytes',\\n'pre-mjs-json',\\n'pre-cjs-json'];\\n\\n\\n/** @type {(a: string, b: string) => number} */\\n/* eslint-disable-next-line no-nested-ternary*/\\nconst stringCompare=(a,b)=>a===b?0:a<b?-1:1;\\n\\n/**\\n * @param {number} length\\n * @param {string} term\\n */\\nconst cumulativeLength=(length,term)=>{\\nreturn length+term.length;};\\n\\n\\n/**\\n * @param {Array<string> | undefined} a\\n * @param {Array<string> | undefined} b\\n */\\nconst pathCompare=(a,b)=>{\\n/* Undefined is not preferred*/\\nif(a===undefined&&b===undefined){\\nreturn 0;}\\n\\nif(a===undefined){\\nreturn 1;}\\n\\nif(b===undefined){\\nreturn-1;}\\n\\n/* Prefer the shortest dependency path.*/\\nif(a.length!==b.length){\\nreturn a.length-b.length;}\\n\\n/* Otherwise, favor the shortest cumulative length.*/\\nconst aSum=a.reduce(cumulativeLength,0);\\nconst bSum=b.reduce(cumulativeLength,0);\\nif(aSum!==bSum){\\nreturn aSum-bSum;}\\n\\n/* Otherwise, compare terms lexically.*/\\nassert(a.length===b.length);/* Reminder*/\\n/* This loop guarantees that if any pair of terms is different, including the*/\\n/* case where one is a prefix of the other, we will return a non-zero value.*/\\nfor(let i=0;i<a.length;i+=1){\\nconst comparison=stringCompare(a[i],b[i]);\\nif(comparison!==0){\\nreturn comparison;}}\\n\\n\\n/* If all pairs of terms are the same respective lengths, we are guaranteed*/\\n/* that they are exactly the same or one of them is lexically distinct and would*/\\n/* have already been caught.*/\\nreturn 0;};\\n\\n\\n/**\\n * @template T\\n * @param {Iterable<T>} iterable\\n */\\nfunction*enumerate(iterable){\\nlet index=0;\\nfor(const value of iterable){\\nyield[index,value];\\nindex+=1;}}\\n\\n\\n\\n/**\\n * @param {Record<string, unknown>} object\\n * @param {string} message\\n */\\nconst assertEmptyObject=(object,message)=>{\\nassert(Object.keys(object).length===0,message);};\\n\\n\\n/**\\n * @param {unknown} tags\\n * @param {string} url\\n */\\nconst assertTags=(tags,url)=>{\\nif(tags===undefined)return;\\nassert(\\nArray.isArray(tags),\\n`tags must be an array, got ${tags} in ${q(url)}`);\\n\\nfor(const[index,value]of enumerate(tags)){\\nassert.typeof(\\nvalue,\\n'string',\\n`tags[${index}] must be a string, got ${value} in ${q(url)}`);}};\\n\\n\\n\\n\\n/**\\n * @param {Record<string, unknown>} allegedModule\\n * @param {string} path\\n * @param {string} url\\n */\\nconst assertCompartmentModule=(allegedModule,path,url)=>{\\nconst{compartment,module,...extra}=allegedModule;\\nassertEmptyObject(\\nextra,\\n`${path} must not have extra properties, got ${q({\\nextra,\\ncompartment})\\n} in ${q(url)}`);\\n\\nassert.typeof(\\ncompartment,\\n'string',\\n`${path}.compartment must be a string, got ${q(compartment)} in ${q(url)}`);\\n\\nassert.typeof(\\nmodule,\\n'string',\\n`${path}.module must be a string, got ${q(module)} in ${q(url)}`);};\\n\\n\\n\\n/**\\n * @param {Record<string, unknown>} allegedModule\\n * @param {string} path\\n * @param {string} url\\n */\\nconst assertFileModule=(allegedModule,path,url)=>{\\nconst{location,parser,sha512,...extra}=allegedModule;\\nassertEmptyObject(\\nextra,\\n`${path} must not have extra properties, got ${q(\\nObject.keys(extra))\\n} in ${q(url)}`);\\n\\nassert.typeof(\\nlocation,\\n'string',\\n`${path}.location must be a string, got ${q(location)} in ${q(url)}`);\\n\\nassert.typeof(\\nparser,\\n'string',\\n`${path}.parser must be a string, got ${q(parser)} in ${q(url)}`);\\n\\nassert(\\nmoduleLanguages.includes(parser),\\n`${path}.parser must be one of ${q(moduleLanguages)}, got ${parser} in ${q(\\nurl)\\n}`);\\n\\n\\nif(sha512!==undefined){\\nassert.typeof(\\nsha512,\\n'string',\\n`${path}.sha512 must be a string, got ${q(sha512)} in ${q(url)}`);}};\\n\\n\\n\\n\\n/**\\n * @param {Record<string, unknown>} allegedModule\\n * @param {string} path\\n * @param {string} url\\n */\\nconst assertExitModule=(allegedModule,path,url)=>{\\nconst{exit,...extra}=allegedModule;\\nassertEmptyObject(\\nextra,\\n`${path} must not have extra properties, got ${q(\\nObject.keys(extra))\\n} in ${q(url)}`);\\n\\nassert.typeof(\\nexit,\\n'string',\\n`${path}.exit must be a string, got ${q(exit)} in ${q(url)}`);};\\n\\n\\n\\n/**\\n * @param {unknown} allegedModule\\n * @param {string} path\\n * @param {string} url\\n */\\nconst assertModule=(allegedModule,path,url)=>{\\nconst moduleDescriptor=Object(allegedModule);\\nassert(\\nallegedModule===moduleDescriptor&&!Array.isArray(moduleDescriptor),\\n`${path} must be an object, got ${allegedModule} in ${q(url)}`);\\n\\n\\nconst{compartment,module,location,parser,exit,deferredError}=\\nmoduleDescriptor;\\nif(compartment!==undefined||module!==undefined){\\nassertCompartmentModule(moduleDescriptor,path,url);}else\\nif(location!==undefined||parser!==undefined){\\nassertFileModule(moduleDescriptor,path,url);}else\\nif(exit!==undefined){\\nassertExitModule(moduleDescriptor,path,url);}else\\nif(deferredError!==undefined){\\nassert.typeof(\\ndeferredError,\\n'string',\\n`${path}.deferredError must be a string contaiing an error message`);}else\\n\\n{\\nassert.fail(\\n`${path} is not a valid module descriptor, got ${q(allegedModule)} in ${q(\\nurl)\\n}`);}};\\n\\n\\n\\n\\n/**\\n * @param {unknown} allegedModules\\n * @param {string} path\\n * @param {string} url\\n */\\nconst assertModules=(allegedModules,path,url)=>{\\nconst modules=Object(allegedModules);\\nassert(\\nallegedModules===modules||!Array.isArray(modules),\\n`modules must be an object, got ${q(allegedModules)} in ${q(url)}`);\\n\\nfor(const[key,value]of Object.entries(modules)){\\nassertModule(value,`${path}.modules[${q(key)}]`,url);}};\\n\\n\\n\\n/**\\n * @param {unknown} allegedParsers\\n * @param {string} path\\n * @param {string} url\\n */\\nconst assertParsers=(allegedParsers,path,url)=>{\\nif(allegedParsers===undefined){\\nreturn;}\\n\\nconst parsers=Object(allegedParsers);\\nassert(\\nallegedParsers===parsers&&!Array.isArray(parsers),\\n`${path}.parsers must be an object, got ${allegedParsers} in ${q(url)}`);\\n\\n\\nfor(const[key,value]of Object.entries(parsers)){\\nassert.typeof(\\nkey,\\n'string',\\n`all keys of ${path}.parsers must be strings, got ${key} in ${q(url)}`);\\n\\nassert.typeof(\\nvalue,\\n'string',\\n`${path}.parsers[${q(key)}] must be a string, got ${value} in ${q(url)}`);\\n\\nassert(\\nmoduleLanguages.includes(value),\\n`${path}.parsers[${q(key)}] must be one of ${q(\\nmoduleLanguages)\\n}, got ${value} in ${q(url)}`);}};\\n\\n\\n\\n\\n/**\\n * @param {unknown} allegedScope\\n * @param {string} path\\n * @param {string} url\\n */\\nconst assertScope=(allegedScope,path,url)=>{\\nconst scope=Object(allegedScope);\\nassert(\\nallegedScope===scope&&!Array.isArray(scope),\\n`${path} must be an object, got ${allegedScope} in ${q(url)}`);\\n\\n\\nconst{compartment,...extra}=scope;\\nassertEmptyObject(\\nextra,\\n`${path} must not have extra properties, got ${q(\\nObject.keys(extra))\\n} in ${q(url)}`);\\n\\n\\nassert.typeof(\\ncompartment,\\n'string',\\n`${path}.compartment must be a string, got ${q(compartment)} in ${q(url)}`);};\\n\\n\\n\\n/**\\n * @param {unknown} allegedScopes\\n * @param {string} path\\n * @param {string} url\\n */\\nconst assertScopes=(allegedScopes,path,url)=>{\\nif(allegedScopes===undefined){\\nreturn;}\\n\\nconst scopes=Object(allegedScopes);\\nassert(\\nallegedScopes===scopes&&!Array.isArray(scopes),\\n`${path}.scopes must be an object, got ${q(allegedScopes)} in ${q(url)}`);\\n\\n\\nfor(const[key,value]of Object.entries(scopes)){\\nassert.typeof(\\nkey,\\n'string',\\n`all keys of ${path}.scopes must be strings, got ${key} in ${q(url)}`);\\n\\nassertScope(value,`${path}.scopes[${q(key)}]`,url);}};\\n\\n\\n\\n/**\\n * @param {unknown} allegedTypes\\n * @param {string} path\\n * @param {string} url\\n */\\nconst assertTypes=(allegedTypes,path,url)=>{\\nif(allegedTypes===undefined){\\nreturn;}\\n\\nconst types=Object(allegedTypes);\\nassert(\\nallegedTypes===types&&!Array.isArray(types),\\n`${path}.types must be an object, got ${allegedTypes} in ${q(url)}`);\\n\\n\\nfor(const[key,value]of Object.entries(types)){\\nassert.typeof(\\nkey,\\n'string',\\n`all keys of ${path}.types must be strings, got ${key} in ${q(url)}`);\\n\\nassert.typeof(\\nvalue,\\n'string',\\n`${path}.types[${q(key)}] must be a string, got ${value} in ${q(url)}`);\\n\\nassert(\\nmoduleLanguages.includes(value),\\n`${path}.types[${q(key)}] must be one of ${q(\\nmoduleLanguages)\\n}, got ${value} in ${q(url)}`);}};\\n\\n\\n\\n\\n/**\\n * @param {unknown} allegedPolicy\\n * @param {string} path\\n * @param {string} [url]\\n */\\n\\nconst assertPolicy=(\\nallegedPolicy,\\npath,\\nurl='<unknown-compartment-map.json>')=>\\n{\\npolicyFormat.assertPackagePolicy(allegedPolicy,`${path}.policy`,url);};\\n\\n\\n/**\\n * @param {unknown} allegedCompartment\\n * @param {string} path\\n * @param {string} url\\n */\\nconst assertCompartment=(allegedCompartment,path,url)=>{\\nconst compartment=Object(allegedCompartment);\\nassert(\\nallegedCompartment===compartment&&!Array.isArray(compartment),\\n`${path} must be an object, got ${allegedCompartment} in ${q(url)}`);\\n\\n\\nconst{\\nlocation,\\nname,\\nlabel,\\nparsers,\\ntypes,\\nscopes,\\nmodules,\\npolicy,\\n...extra}=\\ncompartment;\\n\\nassertEmptyObject(\\nextra,\\n`${path} must not have extra properties, got ${q(\\nObject.keys(extra))\\n} in ${q(url)}`);\\n\\n\\nassert.typeof(\\nlocation,\\n'string',\\n`${path}.location in ${q(url)} must be string, got ${q(location)}`);\\n\\nassert.typeof(\\nname,\\n'string',\\n`${path}.name in ${q(url)} must be string, got ${q(name)}`);\\n\\nassert.typeof(\\nlabel,\\n'string',\\n`${path}.label in ${q(url)} must be string, got ${q(label)}`);\\n\\n\\nassertModules(modules,path,url);\\nassertParsers(parsers,path,url);\\nassertScopes(scopes,path,url);\\nassertTypes(types,path,url);\\nassertPolicy(policy,path,url);};\\n\\n\\n/**\\n * @param {unknown} allegedCompartments\\n * @param {string} url\\n */\\nconst assertCompartments=(allegedCompartments,url)=>{\\nconst compartments=Object(allegedCompartments);\\nassert(\\nallegedCompartments===compartments||!Array.isArray(compartments),\\n`compartments must be an object, got ${q(allegedCompartments)} in ${q(\\nurl)\\n}`);\\n\\nfor(const[key,value]of Object.entries(compartments)){\\nassertCompartment(value,`compartments[${q(key)}]`,url);}};\\n\\n\\n\\n/**\\n * @param {unknown} allegedEntry\\n * @param {string} url\\n */\\nconst assertEntry=(allegedEntry,url)=>{\\nconst entry=Object(allegedEntry);\\nassert(\\nallegedEntry===entry&&!Array.isArray(entry),\\n`\\\"entry\\\" must be an object in compartment map, got ${allegedEntry} in ${q(\\nurl)\\n}`);\\n\\nconst{compartment,module,...extra}=entry;\\nassertEmptyObject(\\nextra,\\n`\\\"entry\\\" must not have extra properties in compartment map, got ${q(\\nObject.keys(extra))\\n} in ${q(url)}`);\\n\\nassert.typeof(\\ncompartment,\\n'string',\\n`entry.compartment must be a string in compartment map, got ${compartment} in ${q(\\nurl)\\n}`);\\n\\nassert.typeof(\\nmodule,\\n'string',\\n`entry.module must be a string in compartment map, got ${module} in ${q(\\nurl)\\n}`);};\\n\\n\\n\\n/**\\n * @param {unknown} allegedCompartmentMap\\n * @param {string} [url]\\n * @returns {asserts compartmentMap is IMPORT('./types.js').CompartmentMapDescriptor}\\n */\\n\\nconst assertCompartmentMap=(\\nallegedCompartmentMap,\\nurl='<unknown-compartment-map.json>')=>\\n{\\nconst compartmentMap=Object(allegedCompartmentMap);\\nassert(\\nallegedCompartmentMap===compartmentMap&&!Array.isArray(compartmentMap),\\n`Compartment map must be an object, got ${allegedCompartmentMap} in ${q(\\nurl)\\n}`);\\n\\nconst{tags,entry,compartments,...extra}=Object(compartmentMap);\\nassertEmptyObject(\\nextra,\\n`Compartment map must not have extra properties, got ${q(\\nObject.keys(extra))\\n} in ${q(url)}`);\\n\\nassertTags(tags,url);\\nassertEntry(entry,url);\\nassertCompartments(compartments,url);};exports.assertCompartmentMap=assertCompartmentMap;exports.pathCompare=pathCompare;exports.stringCompare=stringCompare;\",\n \"node_modules/@endo/compartment-mapper/src/extension.js\": \"'use strict';\\n\\nObject.defineProperty(exports,'__esModule',{value:true});/* @ts-check*/ /**\\n * `parseExtension` returns the file extension for the given URL, or an empty\\n * string if the path has no extension.\\n * Exported for tests.\\n *\\n * @param {string} location\\n * @returns {string}\\n */\\nconst parseExtension=(location)=>{\\nconst lastSlash=location.lastIndexOf('/');\\nif(lastSlash<0){\\nreturn'';}\\n\\nconst base=location.slice(lastSlash+1);\\nconst lastDot=base.lastIndexOf('.');\\nif(lastDot<0){\\nreturn'';}\\n\\nreturn base.slice(lastDot+1);};exports.parseExtension=parseExtension;\",\n \"node_modules/@endo/compartment-mapper/src/import-archive.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../zip/index.js');var link=require('./link.js');var parsePreCjs=require('./parse-pre-cjs.js');var parseJson=require('./parse-json.js');var parseText=require('./parse-text.js');var parseBytes=require('./parse-bytes.js');var parsePreMjs=require('./parse-pre-mjs.js');var json=require('./json.js');var powers=require('./powers.js');var nodeModuleSpecifier=require('./node-module-specifier.js');var compartmentMap=require('./compartment-map.js');var importHook=require('./import-hook.js');var policy=require('./policy.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nreader=require('../../zip/src/reader.js');/* @ts-check*/ /** @import {StaticModuleType} from 'ses' */ /** @import {Application, CompartmentDescriptor, ComputeSourceLocationHook, ComputeSourceMapLocationHook, ExecuteFn, ExecuteOptions, ExitModuleImportHook, HashFn, ImportHookMaker, LoadArchiveOptions, ParserImplementation, ReadPowers} from './types.js' */\\n\\nconst DefaultCompartment=Compartment;\\n\\nconst{Fail,quote:q}=assert;\\n\\nconst textDecoder=new TextDecoder();\\n\\nconst{freeze}=Object;\\n\\n/** @type {Record<string, ParserImplementation>} */\\nconst parserForLanguage={\\n'pre-cjs-json':parsePreCjs[\\\"default\\\"],\\n'pre-mjs-json':parsePreMjs[\\\"default\\\"],\\njson:parseJson[\\\"default\\\"],\\ntext:parseText[\\\"default\\\"],\\nbytes:parseBytes[\\\"default\\\"]};\\n\\n\\n/**\\n * @param {string} errorMessage - error to throw on execute\\n * @returns {StaticModuleType}\\n */\\nconst postponeErrorToExecute=(errorMessage)=>{\\n/* Return a place-holder that'd throw an error if executed*/\\n/* This allows cjs parser to more eagerly find calls to require*/\\n/* - if parser identified a require call that's a local function, execute will never be called*/\\n/* - if actual required module is missing, the error will happen anyway - at execution time*/\\n\\nconst record=freeze({\\nimports:[],\\nexports:[],\\nexecute:()=>{\\nthrow Error(errorMessage);}});\\n\\n\\n\\nreturn record;};\\n\\n\\n/**\\n * @param {(path: string) => Uint8Array} get\\n * @param {Record<string, CompartmentDescriptor>} compartments\\n * @param {string} archiveLocation\\n * @param {HashFn} [computeSha512]\\n * @param {ComputeSourceLocationHook} [computeSourceLocation]\\n * @param {ExitModuleImportHook} [exitModuleImportHook]\\n * @param {ComputeSourceMapLocationHook} [computeSourceMapLocation]\\n * @returns {ImportHookMaker}\\n */\\nconst makeArchiveImportHookMaker=(\\nget,\\ncompartments,\\narchiveLocation,\\ncomputeSha512=undefined,\\ncomputeSourceLocation=undefined,\\nexitModuleImportHook=undefined,\\ncomputeSourceMapLocation=undefined)=>\\n{\\n/* per-assembly:*/\\n/** @type {ImportHookMaker} */\\nconst makeImportHook=({\\npackageLocation,\\npackageName,\\nattenuators\\n/* note `compartments` are not passed to makeImportHook because*/\\n/* the reference was passed to makeArchiveImportHookMaker.*/})=>\\n{\\n/* per-compartment:*/\\nconst compartmentDescriptor=compartments[packageLocation];\\nconst{modules}=compartmentDescriptor;\\n/** @type {IMPORT('ses').ImportHook} */\\nconst importHook=async(moduleSpecifier)=>{\\n/* per-module:*/\\nconst module=modules[moduleSpecifier];\\nif(module===undefined){\\nif(exitModuleImportHook){\\n/* At this point in archive importing, if a module is not found and*/\\n/* exitModuleImportHook exists, the only possibility is that the*/\\n/* module is a \\\"builtin\\\" module and the policy needs to be enforced.*/\\npolicy.enforceModulePolicy(moduleSpecifier,compartmentDescriptor,{\\nexit:true,\\nerrorHint:`Blocked in loading. ${q(\\nmoduleSpecifier)\\n} was not in the archive and an attempt was made to load it as a builtin`});\\n\\nconst record=await exitModuleImportHook(moduleSpecifier);\\nif(record){\\n/* note it's not being marked as exit in sources*/\\n/* it could get marked and the second pass, when the archive is being executed, would have the data*/\\n/* to enforce which exits can be dynamically imported*/\\nreturn{\\nrecord:await policy.attenuateModuleHook(\\nmoduleSpecifier,\\nrecord,\\ncompartmentDescriptor.policy,\\nattenuators),\\n\\nspecifier:moduleSpecifier};}else\\n\\n{\\n/* if exitModuleImportHook is allowed, the mechanism to defer*/\\n/* errors in archive creation is never used. We don't want to*/\\n/* throw until the module execution is attempted. This is because*/\\n/* the cjs parser eagerly looks for require calls, and if it finds*/\\n/* one, it will try to import the module even if the require is*/\\n/* never reached.*/\\nreturn postponeErrorToExecute(\\n`Cannot find external module ${q(moduleSpecifier)} in package ${q(\\npackageLocation)\\n} in archive ${q(archiveLocation)}`);}}\\n\\n\\n\\nthrow Error(\\n`Cannot find module ${q(moduleSpecifier)} in package ${q(\\npackageLocation)\\n} in archive ${q(archiveLocation)}`);}\\n\\n\\nif(module.deferredError!==undefined){\\nreturn postponeErrorToExecute(module.deferredError);}\\n\\nif(module.parser===undefined){\\nthrow Error(\\n`Cannot parse module ${q(moduleSpecifier)} in package ${q(\\npackageLocation)\\n} in archive ${q(archiveLocation)}`);}\\n\\n\\nif(parserForLanguage[module.parser]===undefined){\\nthrow Error(\\n`Cannot parse ${q(module.parser)} module ${q(\\nmoduleSpecifier)\\n} in package ${q(packageLocation)} in archive ${q(archiveLocation)}`);}\\n\\n\\nconst{parse}=parserForLanguage[module.parser];\\nconst moduleLocation=`${packageLocation}/${module.location}`;\\nconst moduleBytes=get(moduleLocation);\\n\\nif(computeSha512!==undefined&&module.sha512!==undefined){\\nconst sha512=computeSha512(moduleBytes);\\nif(sha512!==module.sha512){\\nthrow Error(\\n`Module ${q(module.location)} of package ${q(\\npackageLocation)\\n} in archive ${q(\\narchiveLocation)\\n} failed a SHA-512 integrity check`);}}\\n\\n\\n\\n\\nlet sourceLocation=`file:///${moduleLocation}`;\\nif(packageName!==undefined){\\nconst base=packageName.split('/').slice(-1).join('/');\\nsourceLocation=`.../${nodeModuleSpecifier.join(base,moduleSpecifier)}`;}\\n\\nif(computeSourceLocation!==undefined){\\nsourceLocation=\\ncomputeSourceLocation(packageLocation,moduleSpecifier)||\\nsourceLocation;}\\n\\n\\nlet sourceMapUrl;\\nif(\\ncomputeSourceMapLocation!==undefined&&\\nmodule.sha512!==undefined)\\n{\\nsourceMapUrl=computeSourceMapLocation({\\ncompartment:packageLocation,\\nmodule:moduleSpecifier,\\nlocation:sourceLocation,\\nsha512:module.sha512});}\\n\\n\\n\\n/* eslint-disable-next-line no-await-in-loop*/\\nconst{record}=await parse(\\nmoduleBytes,\\nmoduleSpecifier,\\nsourceLocation,\\npackageLocation,\\n{\\nsourceMapUrl});\\n\\n\\nreturn{record,specifier:moduleSpecifier};};\\n\\nreturn importHook;};\\n\\nreturn makeImportHook;};\\n\\n\\n/**\\n * Creates a fake module namespace object that passes a brand check.\\n *\\n * @param {typeof Compartment} Compartment\\n * @returns {IMPORT('ses').ModuleExportsNamespace}\\n */\\nconst makeFauxModuleExportsNamespace=(Compartment)=>{\\nconst compartment=new Compartment(\\n{},\\n{},\\n{\\nresolveHook(){\\nreturn'.';},\\n\\nasync importHook(){\\nreturn{\\nimports:[],\\nexecute(){},\\nexports:[]};}});\\n\\n\\n\\n\\nreturn compartment.module('.');};\\n\\n\\n/* Have to give it a name to capture the external meaning of Compartment*/\\n/* Otherwise @param {typeof Compartment} takes the Compartment to mean*/\\n/* the const variable defined within the function.*/\\n/** @typedef {typeof Compartment} CompartmentConstructor */\\n\\n/**\\n * @param {Uint8Array} archiveBytes\\n * @param {string} [archiveLocation]\\n * @param {object} [options]\\n * @param {string} [options.expectedSha512]\\n * @param {HashFn} [options.computeSha512]\\n * @param {Record<string, unknown>} [options.modules]\\n * @param {ExitModuleImportHook} [options.importHook]\\n * @param {CompartmentConstructor} [options.Compartment]\\n * @param {ComputeSourceLocationHook} [options.computeSourceLocation]\\n * @param {ComputeSourceMapLocationHook} [options.computeSourceMapLocation]\\n * @returns {Promise<Application>}\\n */\\nconst parseArchive=async(\\narchiveBytes,\\narchiveLocation='<unknown>',\\noptions={})=>\\n{\\nconst{\\ncomputeSha512=undefined,\\nexpectedSha512=undefined,\\ncomputeSourceLocation=undefined,\\ncomputeSourceMapLocation=undefined,\\nCompartment=DefaultCompartment,\\nmodules=undefined,\\nimportHook:exitModuleImportHook=undefined}=\\noptions;\\n\\nconst compartmentExitModuleImportHook=importHook.exitModuleImportHookMaker({\\nmodules,\\nexitModuleImportHook});\\n\\n\\nconst archive=new reader.ZipReader(archiveBytes,{name:archiveLocation});\\n\\n/* Track all modules that get loaded, all files that are used.*/\\nconst unseen=new Set(archive.files.keys());\\nunseen.size>=2||\\nFail`Archive failed sanity check: should contain at least a compartment map file and one module file in ${q(\\narchiveLocation)\\n}`;\\n\\n/**\\n * @param {string} path\\n */\\nconst get=(path)=>{\\nunseen.delete(path);\\nreturn archive.read(path);};\\n\\n\\nconst compartmentMapBytes=get('compartment-map.json');\\n\\nlet sha512;\\nif(computeSha512!==undefined){\\nsha512=computeSha512(compartmentMapBytes);}\\n\\nif(expectedSha512!==undefined){\\nif(sha512===undefined){\\nthrow Error(\\n`Cannot verify expectedSha512 without also providing computeSha512, for archive ${archiveLocation}`);}\\n\\n\\nif(sha512!==expectedSha512){\\nthrow Error(\\n`Archive compartment map failed a SHA-512 integrity check, expected ${expectedSha512}, got ${sha512}, for archive ${archiveLocation}`);}}\\n\\n\\n\\nconst compartmentMapText=textDecoder.decode(compartmentMapBytes);\\nconst compartmentMap$1=json.parseLocatedJson(\\ncompartmentMapText,\\n'compartment-map.json');\\n\\ncompartmentMap.assertCompartmentMap(compartmentMap$1,archiveLocation);\\n\\nconst{\\ncompartments,\\nentry:{module:moduleSpecifier}}=\\ncompartmentMap$1;\\n\\n/* Archive integrity checks: ensure every module is pre-loaded so its hash*/\\n/* gets checked, and ensure that every file in the archive is used, and*/\\n/* therefore checked.*/\\nif(computeSha512!==undefined){\\nconst makeImportHook=makeArchiveImportHookMaker(\\nget,\\ncompartments,\\narchiveLocation,\\ncomputeSha512,\\ncomputeSourceLocation,\\ncompartmentExitModuleImportHook,\\ncomputeSourceMapLocation);\\n\\n/* A weakness of the current Compartment design is that the `modules` map*/\\n/* must be given a module namespace object that passes a brand check.*/\\n/* We don't have module instances for the preload phase, so we supply fake*/\\n/* namespaces.*/\\nconst{compartment,pendingJobsPromise}=link.link(compartmentMap$1,{\\nmakeImportHook,\\nparserForLanguage,\\nmodules:Object.fromEntries(\\nObject.keys(modules||{}).map((specifier)=>{\\nreturn[specifier,makeFauxModuleExportsNamespace(Compartment)];})),\\n\\n\\nCompartment});\\n\\n\\nawait pendingJobsPromise;\\n\\nawait compartment.load(moduleSpecifier);\\nunseen.size===0||\\nFail`Archive contains extraneous files: ${q([...unseen])} in ${q(\\narchiveLocation)\\n}`;}\\n\\n\\n/** @type {ExecuteFn} */\\nconst execute=async(options)=>{\\nconst{\\nglobals,\\nmodules,\\ntransforms,\\n__shimTransforms__,\\nCompartment,\\nimportHook:exitModuleImportHook}=\\noptions||{};\\n\\nconst compartmentExitModuleImportHook=importHook.exitModuleImportHookMaker({\\nmodules,\\nexitModuleImportHook});\\n\\nconst makeImportHook=makeArchiveImportHookMaker(\\nget,\\ncompartments,\\narchiveLocation,\\ncomputeSha512,\\ncomputeSourceLocation,\\ncompartmentExitModuleImportHook,\\ncomputeSourceMapLocation);\\n\\nconst{compartment,pendingJobsPromise}=link.link(compartmentMap$1,{\\nmakeImportHook,\\nparserForLanguage,\\nglobals,\\nmodules,\\ntransforms,\\n__shimTransforms__,\\nCompartment});\\n\\n\\nawait pendingJobsPromise;\\n\\n/* eslint-disable-next-line dot-notation*/\\nreturn compartment['import'](moduleSpecifier);};\\n\\n\\nreturn{import:execute,sha512};};\\n\\n\\n/**\\n * @param {IMPORT('@endo/zip').ReadFn | ReadPowers} readPowers\\n * @param {string} archiveLocation\\n * @param {LoadArchiveOptions} [options]\\n * @returns {Promise<Application>}\\n */\\nconst loadArchive=async(\\nreadPowers,\\narchiveLocation,\\noptions={})=>\\n{\\nconst{read,computeSha512}=powers.unpackReadPowers(readPowers);\\nconst{\\nexpectedSha512,\\ncomputeSourceLocation,\\nmodules,\\ncomputeSourceMapLocation}=\\noptions;\\nconst archiveBytes=await read(archiveLocation);\\nreturn parseArchive(archiveBytes,archiveLocation,{\\ncomputeSha512,\\nexpectedSha512,\\ncomputeSourceLocation,\\nmodules,\\ncomputeSourceMapLocation});};\\n\\n\\n\\n/**\\n * @param {IMPORT('@endo/zip').ReadFn | ReadPowers} readPowers\\n * @param {string} archiveLocation\\n * @param {ExecuteOptions & LoadArchiveOptions} options\\n * @returns {Promise<object>}\\n */\\nconst importArchive=async(readPowers,archiveLocation,options)=>{\\nconst archive=await loadArchive(readPowers,archiveLocation,options);\\nreturn archive.import(options);};exports.importArchive=importArchive;exports.loadArchive=loadArchive;exports.parseArchive=parseArchive;\",\n \"node_modules/@endo/compartment-mapper/src/import-hook.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var policy=require('./policy.js');var nodeModuleSpecifier=require('./node-module-specifier.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\npowers=require('./powers.js');/* @ts-check*/ /* q, as in quote, for quoting strings in error messages.*/\\nconst q=JSON.stringify;\\n\\nconst{apply}=Reflect;\\n\\n/**\\n * TypeScript cannot be relied upon to deal with the nuances of Readonly, so we\\n * borrow the pass-through type definition of harden here.\\n *\\n * @type {IMPORT('ses').Harden}\\n */\\nconst freeze=Object.freeze;\\n\\nconst{hasOwnProperty}=Object.prototype;\\n/**\\n * @param {Record<string, any>} haystack\\n * @param {string} needle\\n */\\nconst has=(haystack,needle)=>apply(hasOwnProperty,haystack,[needle]);\\n\\n/**\\n * @param {string} rel - a relative URL\\n * @param {string} abs - a fully qualified URL\\n * @returns {string}\\n */\\nconst resolveLocation=(rel,abs)=>new URL(rel,abs).toString();\\n\\n/* this is annoying*/\\nfunction getImportsFromRecord(record){\\nreturn(has(record,'record')?record.record.imports:record.imports)||[];}\\n\\n\\n/* Node.js default resolution allows for an incomplement specifier that does not include a suffix.*/\\n/* https://nodejs.org/api/modules.html#all-together*/\\nconst nodejsConventionSearchSuffixes=[\\n/* LOAD_AS_FILE(X)*/\\n'.js',\\n'.json',\\n'.node',\\n/* LOAD_INDEX(X)*/\\n'/index.js',\\n'/index.json',\\n'/index.node'];\\n\\n\\n/**\\n * @param {object} params\\n * @param {Record<string, any>=} params.modules\\n * @param {ExitModuleImportHook=} params.exitModuleImportHook\\n * @returns {ExitModuleImportHook|undefined}\\n */\\nconst exitModuleImportHookMaker=({\\nmodules=undefined,\\nexitModuleImportHook=undefined})=>\\n{\\nif(!modules&&!exitModuleImportHook){\\nreturn undefined;}\\n\\nreturn async(specifier)=>{\\nif(modules&&has(modules,specifier)){\\nconst ns=modules[specifier];\\nreturn Object.freeze({\\nimports:[],\\nexports:ns?Object.keys(ns):[],\\nexecute:(moduleExports)=>{\\nmoduleExports.default=ns;\\nObject.assign(moduleExports,ns);}});}\\n\\n\\n\\nif(exitModuleImportHook){\\nreturn exitModuleImportHook(specifier);}\\n\\nreturn undefined;};};\\n\\n\\n\\n/**\\n * @param {ReadFn|ReadPowers} readPowers\\n * @param {string} baseLocation\\n * @param {object} options\\n * @param {Sources} [options.sources]\\n * @param {Record<string, CompartmentDescriptor>} [options.compartmentDescriptors]\\n * @param {boolean} [options.archiveOnly]\\n * @param {HashFn} [options.computeSha512]\\n * @param {Array<string>} [options.searchSuffixes] - Suffixes to search if the\\n * unmodified specifier is not found.\\n * Pass [] to emulate Node.js’s strict behavior.\\n * The default handles Node.js’s CommonJS behavior.\\n * Unlike Node.js, the Compartment Mapper lifts CommonJS up, more like a\\n * bundler, and does not attempt to vary the behavior of resolution depending\\n * on the language of the importing module.\\n * @param {string} options.entryCompartmentName\\n * @param {string} options.entryModuleSpecifier\\n * @param {ExitModuleImportHook} [options.exitModuleImportHook]\\n * @param {IMPORT('./types.js').SourceMapHook} [options.sourceMapHook]\\n * @returns {ImportHookMaker}\\n */\\nconst makeImportHookMaker=(\\nreadPowers,\\nbaseLocation,\\n{\\nsources=Object.create(null),\\ncompartmentDescriptors=Object.create(null),\\narchiveOnly=false,\\ncomputeSha512=undefined,\\nsearchSuffixes=nodejsConventionSearchSuffixes,\\nsourceMapHook=undefined,\\nentryCompartmentName,\\nentryModuleSpecifier,\\nexitModuleImportHook=undefined})=>\\n\\n{\\n/* Set of specifiers for modules (scoped to compartment) whose parser is not*/\\n/* using heuristics to determine imports.*/\\n/** @type {Map<string, Set<string>>} compartment name ->* module specifier */\\nconst strictlyRequired=new Map([\\n[entryCompartmentName,new Set([entryModuleSpecifier])]]);\\n\\n\\n/**\\n * @param {string} compartmentName\\n */\\nconst strictlyRequiredForCompartment=(compartmentName)=>{\\nlet compartmentStrictlyRequired=strictlyRequired.get(compartmentName);\\nif(compartmentStrictlyRequired!==undefined){\\nreturn compartmentStrictlyRequired;}\\n\\ncompartmentStrictlyRequired=new Set();\\nstrictlyRequired.set(compartmentName,compartmentStrictlyRequired);\\nreturn compartmentStrictlyRequired;};\\n\\n\\n/* per-compartment:*/\\n/** @type {ImportHookMaker} */\\nconst makeImportHook=({\\npackageLocation,\\npackageName:_packageName,\\nattenuators,\\nparse,\\nshouldDeferError,\\ncompartments})=>\\n{\\n/* per-compartment:*/\\npackageLocation=resolveLocation(packageLocation,baseLocation);\\nconst packageSources=sources[packageLocation]||Object.create(null);\\nsources[packageLocation]=packageSources;\\nconst compartmentDescriptor=compartmentDescriptors[packageLocation]||{};\\nconst{modules:moduleDescriptors=Object.create(null)}=\\ncompartmentDescriptor;\\ncompartmentDescriptor.modules=moduleDescriptors;\\n\\n/**\\n * @param {string} specifier\\n * @param {Error} error - error to throw on execute\\n * @returns {StaticModuleType}\\n */\\nconst deferError=(specifier,error)=>{\\n/* strictlyRequired is populated with imports declared by modules whose parser is not using heuristics to figure*/\\n/* out imports. We're guaranteed they're reachable. If the same module is imported and required, it will not*/\\n/* defer, because importing from esm makes it strictly required.*/\\n/* Note that ultimately a situation may arise, with exit modules, where the module never reaches importHook but*/\\n/* its imports do. In that case the notion of strictly required is no longer boolean, it's true,false,noidea.*/\\nif(strictlyRequiredForCompartment(packageLocation).has(specifier)){\\nthrow error;}\\n\\n/* Return a place-holder that'd throw an error if executed*/\\n/* This allows cjs parser to more eagerly find calls to require*/\\n/* - if parser identified a require call that's a local function, execute will never be called*/\\n/* - if actual required module is missing, the error will happen anyway - at execution time*/\\nconst record=freeze({\\nimports:[],\\nexports:[],\\nexecute:()=>{\\nthrow error;}});\\n\\n\\npackageSources[specifier]={\\ndeferredError:error.message};\\n\\n\\nreturn record;};\\n\\n\\n/** @type {ImportHook} */\\nconst importHook=async(moduleSpecifier)=>{\\ncompartmentDescriptor.retained=true;\\n\\n/* per-module:*/\\n\\n/* In Node.js, an absolute specifier always indicates a built-in or*/\\n/* third-party dependency.*/\\n/* The `moduleMapHook` captures all third-party dependencies, unless*/\\n/* we allow importing any exit.*/\\nif(moduleSpecifier!=='.'&&!moduleSpecifier.startsWith('./')){\\nif(exitModuleImportHook){\\nconst record=await exitModuleImportHook(moduleSpecifier);\\nif(record){\\n/* It'd be nice to check the policy before importing it, but we can only throw a policy error if the*/\\n/* hook returns something. Otherwise, we need to fall back to the 'cannot find' error below.*/\\npolicy.enforceModulePolicy(moduleSpecifier,compartmentDescriptor,{\\nexit:true,\\nerrorHint:`Blocked in loading. ${q(\\nmoduleSpecifier)\\n} was not in the compartment map and an attempt was made to load it as a builtin`});\\n\\nif(archiveOnly){\\n/* Return a place-holder.*/\\n/* Archived compartments are not executed.*/\\nreturn freeze({imports:[],exports:[],execute(){}});}\\n\\n/* note it's not being marked as exit in sources*/\\n/* it could get marked and the second pass, when the archive is being executed, would have the data*/\\n/* to enforce which exits can be dynamically imported*/\\nconst attenuatedRecord=await policy.attenuateModuleHook(\\nmoduleSpecifier,\\nrecord,\\ncompartmentDescriptor.policy,\\nattenuators);\\n\\nreturn attenuatedRecord;}}\\n\\n\\nreturn deferError(\\nmoduleSpecifier,\\nError(\\n`Cannot find external module ${q(\\nmoduleSpecifier)\\n} in package ${packageLocation}`));}\\n\\n\\n\\n\\n/* Collate candidate locations for the moduleSpecifier,*/\\n/* to support Node.js conventions and similar.*/\\nconst candidates=[moduleSpecifier];\\nfor(const candidateSuffix of searchSuffixes){\\ncandidates.push(`${moduleSpecifier}${candidateSuffix}`);}\\n\\n\\nconst{maybeRead}=powers.unpackReadPowers(readPowers);\\n\\nfor(const candidateSpecifier of candidates){\\nconst candidateModuleDescriptor=moduleDescriptors[candidateSpecifier];\\nif(candidateModuleDescriptor!==undefined){\\nconst{compartment:candidateCompartmentName=packageLocation}=\\ncandidateModuleDescriptor;\\nconst candidateCompartment=compartments[candidateCompartmentName];\\nif(candidateCompartment===undefined){\\nthrow Error(\\n`compartment missing for candidate ${candidateSpecifier} in ${candidateCompartmentName}`);}\\n\\n\\n/* modify compartmentMap to include this redirect*/\\nconst candidateCompartmentDescriptor=\\ncompartmentDescriptors[candidateCompartmentName];\\nif(candidateCompartmentDescriptor===undefined){\\nthrow Error(\\n`compartmentDescriptor missing for candidate ${candidateSpecifier} in ${candidateCompartmentName}`);}\\n\\n\\ncandidateCompartmentDescriptor.modules[moduleSpecifier]=\\ncandidateModuleDescriptor;\\n/* return a redirect*/\\n/** @type {RedirectStaticModuleInterface} */\\nconst record={\\nspecifier:candidateSpecifier,\\ncompartment:candidateCompartment};\\n\\nreturn record;}\\n\\n\\n/* Using a specifier as a location.*/\\n/* This is not always valid.*/\\n/* But, for Node.js, when the specifier is relative and not a directory*/\\n/* name, they are usable as URL's.*/\\nconst moduleLocation=resolveLocation(\\ncandidateSpecifier,\\npackageLocation);\\n\\n/* eslint-disable-next-line no-await-in-loop*/\\nconst moduleBytes=await maybeRead(moduleLocation);\\nif(moduleBytes!==undefined){\\n/** @type {string | undefined} */\\nlet sourceMap;\\n/* eslint-disable-next-line no-await-in-loop*/\\nconst envelope=await parse(\\nmoduleBytes,\\ncandidateSpecifier,\\nmoduleLocation,\\npackageLocation,\\n{\\nreadPowers,\\nsourceMapHook:\\nsourceMapHook&&(\\n(nextSourceMapObject)=>{\\nsourceMap=JSON.stringify(nextSourceMapObject);})});\\n\\n\\n\\nconst{\\nparser,\\nbytes:transformedBytes,\\nrecord:concreteRecord}=\\nenvelope;\\n\\n/* Facilitate a redirect if the returned record has a different*/\\n/* module specifier than the requested one.*/\\nif(candidateSpecifier!==moduleSpecifier){\\nmoduleDescriptors[moduleSpecifier]={\\nmodule:candidateSpecifier,\\ncompartment:packageLocation};}\\n\\n\\n/** @type {StaticModuleType} */\\nconst record={\\nrecord:concreteRecord,\\nspecifier:candidateSpecifier,\\nimportMeta:{url:moduleLocation}};\\n\\n\\nlet sha512;\\nif(computeSha512!==undefined){\\nsha512=computeSha512(transformedBytes);\\n\\nif(sourceMapHook!==undefined&&sourceMap!==undefined){\\nsourceMapHook(sourceMap,{\\ncompartment:packageLocation,\\nmodule:candidateSpecifier,\\nlocation:moduleLocation,\\nsha512});}}\\n\\n\\n\\n\\nconst packageRelativeLocation=moduleLocation.slice(\\npackageLocation.length);\\n\\npackageSources[candidateSpecifier]={\\nlocation:packageRelativeLocation,\\nsourceLocation:moduleLocation,\\nparser,\\nbytes:transformedBytes,\\nrecord:concreteRecord,\\nsha512};\\n\\nif(!shouldDeferError(parser)){\\nfor(const importSpecifier of getImportsFromRecord(record)){\\nstrictlyRequiredForCompartment(packageLocation).add(\\nnodeModuleSpecifier.resolve(importSpecifier,moduleSpecifier));}}\\n\\n\\n\\n\\nreturn record;}}\\n\\n\\n\\nreturn deferError(\\nmoduleSpecifier,\\n/* TODO offer breadcrumbs in the error message, or how to construct breadcrumbs with another tool.*/\\nError(\\n`Cannot find file for internal module ${q(\\nmoduleSpecifier)\\n} (with candidates ${candidates.\\nmap((x)=>q(x)).\\njoin(', ')}) in package ${packageLocation}`));};\\n\\n\\n\\nreturn importHook;};\\n\\nreturn makeImportHook;};exports.exitModuleImportHookMaker=exitModuleImportHookMaker;exports.makeImportHookMaker=makeImportHookMaker;\",\n \"node_modules/@endo/compartment-mapper/src/json.js\": \"'use strict';\\n\\nObject.defineProperty(exports,'__esModule',{value:true});/* @ts-check*/ /**\\n * Parses JSON and, if necessary, throws exceptions that include the location\\n * of the offending file.\\n *\\n * @param {string} source\\n * @param {string} location\\n */\\nconst parseLocatedJson=(source,location)=>{\\ntry{\\nreturn JSON.parse(source);}\\ncatch(error){\\nif(error instanceof SyntaxError){\\nthrow SyntaxError(`Cannot parse JSON from ${location}, ${error}`);}\\n\\nthrow error;}};exports.parseLocatedJson=parseLocatedJson;\",\n \"node_modules/@endo/compartment-mapper/src/link.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var nodeModuleSpecifier=require('./node-module-specifier.js');var extension=require('./extension.js');var policy=require('./policy.js');/* @ts-check*/\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nconst{entries,fromEntries}=Object;\\nconst{hasOwnProperty}=Object.prototype;\\nconst{apply}=Reflect;\\nconst{allSettled}=Promise;\\n\\n/**\\n * @template T\\n * @type {(iterable: Iterable<ERef<T>>) => Promise<Array<PromiseSettledResult<T>>>}\\n */\\nconst promiseAllSettled=allSettled.bind(Promise);\\n\\nconst defaultCompartment=Compartment;\\n\\n/* q, as in quote, for strings in error messages.*/\\nconst q=JSON.stringify;\\n\\n/**\\n * @param {Record<string, unknown>} object\\n * @param {string} key\\n * @returns {boolean}\\n */\\nconst has=(object,key)=>apply(hasOwnProperty,object,[key]);\\n\\n/**\\n * Decide if extension is clearly indicating a parser/language for a file\\n *\\n * @param {string} extension\\n * @returns {boolean}\\n */\\nconst extensionImpliesLanguage=(extension)=>extension!=='js';\\n\\n/**\\n * `makeExtensionParser` produces a `parser` that parses the content of a\\n * module according to the corresponding module language, given the extension\\n * of the module specifier and the configuration of the containing compartment.\\n * We do not yet support import assertions and we do not have a mechanism\\n * for validating the MIME type of the module content against the\\n * language implied by the extension or file name.\\n *\\n * @param {Record<string, string>} languageForExtension - maps a file extension\\n * to the corresponding language.\\n * @param {Record<string, string>} languageForModuleSpecifier - In a rare case,\\n * the type of a module is implied by package.json and should not be inferred\\n * from its extension.\\n * @param {Record<string, ParserImplementation>} parserForLanguage\\n * @param {ModuleTransforms} moduleTransforms\\n * @returns {ParseFn}\\n */\\nconst makeExtensionParser=(\\nlanguageForExtension,\\nlanguageForModuleSpecifier,\\nparserForLanguage,\\nmoduleTransforms)=>\\n{\\nreturn async(bytes,specifier,location,packageLocation,options)=>{\\nlet language;\\nconst extension$1=extension.parseExtension(location);\\n\\nif(\\n!extensionImpliesLanguage(extension$1)&&\\nhas(languageForModuleSpecifier,specifier))\\n{\\nlanguage=languageForModuleSpecifier[specifier];}else\\n{\\nlanguage=languageForExtension[extension$1]||extension$1;}\\n\\n\\nlet sourceMap;\\n\\nif(has(moduleTransforms,language)){\\ntry{\\n({\\nbytes,\\nparser:language,\\nsourceMap}=\\nawait moduleTransforms[language](\\nbytes,\\nspecifier,\\nlocation,\\npackageLocation,\\n{\\n/* At time of writing, sourceMap is always undefined, but keeping*/\\n/* it here is more resilient if the surrounding if block becomes a*/\\n/* loop for multi-step transforms.*/\\nsourceMap}));}\\n\\n\\ncatch(err){\\nthrow Error(\\n`Error transforming ${q(language)} source in ${q(location)}: ${\\nerr.message\\n}`,\\n{cause:err});}}\\n\\n\\n\\n\\nif(!has(parserForLanguage,language)){\\nthrow Error(\\n`Cannot parse module ${specifier} at ${location}, no parser configured for the language ${language}`);}\\n\\n\\nconst{parse}=parserForLanguage[language];\\nreturn parse(bytes,specifier,location,packageLocation,{\\nsourceMap,\\n...options});};};\\n\\n\\n\\n\\n/**\\n * @param {Record<string, Language>} languageForExtension\\n * @param {Record<string, string>} languageForModuleSpecifier - In a rare case, the type of a module\\n * is implied by package.json and should not be inferred from its extension.\\n * @param {Record<string, ParserImplementation>} parserForLanguage\\n * @param {ModuleTransforms} moduleTransforms\\n * @returns {ParseFn}\\n */\\nconst mapParsers=(\\nlanguageForExtension,\\nlanguageForModuleSpecifier,\\nparserForLanguage,\\nmoduleTransforms={})=>\\n{\\nconst languageForExtensionEntries=[];\\nconst problems=[];\\nfor(const[extension,language]of entries(languageForExtension)){\\nif(has(parserForLanguage,language)){\\nlanguageForExtensionEntries.push([extension,language]);}else\\n{\\nproblems.push(`${q(language)} for extension ${q(extension)}`);}}\\n\\n\\nif(problems.length>0){\\nthrow Error(`No parser available for language: ${problems.join(', ')}`);}\\n\\nreturn makeExtensionParser(\\nfromEntries(languageForExtensionEntries),\\nlanguageForModuleSpecifier,\\nparserForLanguage,\\nmoduleTransforms);};\\n\\n\\n\\n/**\\n * For a full, absolute module specifier like \\\"dependency\\\",\\n * produce the module specifier in the dependency, like \\\".\\\".\\n * For a deeper path like \\\"@org/dep/aux\\\" and a prefix like \\\"@org/dep\\\", produce\\n * \\\"./aux\\\".\\n *\\n * @param {string} moduleSpecifier\\n * @param {string} prefix\\n * @returns {string=}\\n */\\nconst trimModuleSpecifierPrefix=(moduleSpecifier,prefix)=>{\\nif(moduleSpecifier===prefix){\\nreturn'.';}\\n\\nif(moduleSpecifier.startsWith(`${prefix}/`)){\\nreturn`./${moduleSpecifier.slice(prefix.length+1)}`;}\\n\\nreturn undefined;};\\n\\n\\n/**\\n * `makeModuleMapHook` generates a `moduleMapHook` for the `Compartment`\\n * constructor, suitable for Node.js style packages where any module in the\\n * package might be imported.\\n * Since searching for all of these modules up front is either needlessly\\n * costly (on a file system) or impossible (from a web service), we\\n * let the import graph guide our search.\\n * Any module specifier with an absolute prefix should be captured by\\n * the `moduleMap` or `moduleMapHook`.\\n *\\n * @param {CompartmentDescriptor} compartmentDescriptor\\n * @param {Record<string, Compartment>} compartments\\n * @param {string} compartmentName\\n * @param {Record<string, ModuleDescriptor>} moduleDescriptors\\n * @param {Record<string, ModuleDescriptor>} scopeDescriptors\\n * @returns {ModuleMapHook | undefined}\\n */\\nconst makeModuleMapHook=(\\ncompartmentDescriptor,\\ncompartments,\\ncompartmentName,\\nmoduleDescriptors,\\nscopeDescriptors)=>\\n{\\n/**\\n * @param {string} moduleSpecifier\\n * @returns {string | object | undefined}\\n */\\nconst moduleMapHook=(moduleSpecifier)=>{\\ncompartmentDescriptor.retained=true;\\n\\nconst moduleDescriptor=moduleDescriptors[moduleSpecifier];\\nif(moduleDescriptor!==undefined){\\n/* \\\"foreignCompartmentName\\\" refers to the compartment which*/\\n/* may differ from the current compartment*/\\nconst{\\ncompartment:foreignCompartmentName=compartmentName,\\nmodule:foreignModuleSpecifier,\\nexit}=\\nmoduleDescriptor;\\nif(exit!==undefined){\\nreturn undefined;/* fall through to import hook*/}\\n\\nif(foreignModuleSpecifier!==undefined){\\n/* archive goes through foreignModuleSpecifier for local modules too*/\\nif(!moduleSpecifier.startsWith('./')){\\n/* This code path seems to only be reached on subsequent imports of the same specifier in the same compartment.*/\\n/* The check should be redundant and is only left here out of abundance of caution.*/\\npolicy.enforceModulePolicy(moduleSpecifier,compartmentDescriptor,{\\nexit:false,\\nerrorHint:\\n'This check should not be reachable. If you see this error, please file an issue.'});}\\n\\n\\n\\nconst foreignCompartment=compartments[foreignCompartmentName];\\nif(foreignCompartment===undefined){\\nthrow Error(\\n`Cannot import from missing compartment ${q(\\nforeignCompartmentName)\\n}}`);}\\n\\n\\nreturn foreignCompartment.module(foreignModuleSpecifier);}}\\n\\n\\n\\n/* Search for a scope that shares a prefix with the requested module*/\\n/* specifier.*/\\n/* This might be better with a trie, but only a benchmark on real-world*/\\n/* data would tell us whether the additional complexity would translate to*/\\n/* better performance, so this is left readable and presumed slow for now.*/\\nfor(const[scopePrefix,scopeDescriptor]of entries(scopeDescriptors)){\\nconst foreignModuleSpecifier=trimModuleSpecifierPrefix(\\nmoduleSpecifier,\\nscopePrefix);\\n\\n\\nif(foreignModuleSpecifier!==undefined){\\nconst{compartment:foreignCompartmentName}=scopeDescriptor;\\nif(foreignCompartmentName===undefined){\\nthrow Error(\\n`Cannot import from scope ${scopePrefix} due to missing \\\"compartment\\\" property`);}\\n\\n\\nconst foreignCompartment=compartments[foreignCompartmentName];\\nif(foreignCompartment===undefined){\\nthrow Error(\\n`Cannot import from missing compartment ${q(\\nforeignCompartmentName)\\n}`);}\\n\\n\\n\\npolicy.enforceModulePolicy(scopePrefix,compartmentDescriptor,{\\nexit:false,\\nerrorHint:`Blocked in linking. ${q(\\nmoduleSpecifier)\\n} is part of the compartment map and resolves to ${q(\\nforeignCompartmentName)\\n}.`});\\n\\n/* The following line is weird.*/\\n/* Information is flowing backward.*/\\n/* This moduleMapHook writes back to the `modules` descriptor, from the*/\\n/* original compartment map.*/\\n/* So the compartment map that was used to create the compartment*/\\n/* assembly, can then be captured in an archive, obviating the need for*/\\n/* a moduleMapHook when we assemble compartments from the resulting*/\\n/* archive.*/\\nmoduleDescriptors[moduleSpecifier]={\\ncompartment:foreignCompartmentName,\\nmodule:foreignModuleSpecifier};\\n\\nreturn foreignCompartment.module(foreignModuleSpecifier);}}\\n\\n\\n\\n/* No entry in the module map.*/\\n/* Compartments will fall through to their `importHook`.*/\\nreturn undefined;};\\n\\n\\nreturn moduleMapHook;};\\n\\n\\n/**\\n * Assemble a DAG of compartments as declared in a compartment map starting at\\n * the named compartment and building all compartments that it depends upon,\\n * recursively threading the modules exported by one compartment into the\\n * compartment that imports them.\\n * Returns the root of the compartment DAG.\\n * Does not load or execute any modules.\\n * Uses makeImportHook with the given \\\"location\\\" string of each compartment in\\n * the DAG.\\n * Passes the given globals and external modules into the root compartment\\n * only.\\n *\\n * @param {CompartmentMapDescriptor} compartmentMap\\n * @param {LinkOptions} options\\n */\\nconst link=(\\n{entry,compartments:compartmentDescriptors},\\n{\\nresolve=nodeModuleSpecifier.resolve,\\nmakeImportHook,\\nparserForLanguage,\\nglobals={},\\ntransforms=[],\\nmoduleTransforms={},\\n__shimTransforms__=[],\\narchiveOnly=false,\\nCompartment=defaultCompartment})=>\\n\\n{\\nconst{compartment:entryCompartmentName}=entry;\\n\\n/** @type {Record<string, Compartment>} */\\nconst compartments=Object.create(null);\\n\\n/**\\n * @param {string} attenuatorSpecifier\\n */\\nconst attenuators=policy.makeDeferredAttenuatorsProvider(\\ncompartments,\\ncompartmentDescriptors);\\n\\n\\nconst pendingJobs=[];\\n\\nfor(const[compartmentName,compartmentDescriptor]of entries(\\ncompartmentDescriptors))\\n{\\nconst{\\nlocation,\\nname,\\nmodules=Object.create(null),\\nparsers:languageForExtension=Object.create(null),\\ntypes:languageForModuleSpecifier=Object.create(null),\\nscopes=Object.create(null)}=\\ncompartmentDescriptor;\\n\\n/* Capture the default.*/\\n/* The `moduleMapHook` writes back to the compartment map.*/\\ncompartmentDescriptor.modules=modules;\\n\\nconst parse=mapParsers(\\nlanguageForExtension,\\nlanguageForModuleSpecifier,\\nparserForLanguage,\\nmoduleTransforms);\\n\\n/** @type {ShouldDeferError} */\\nconst shouldDeferError=(language)=>{\\nif(language&&has(parserForLanguage,language)){\\nreturn parserForLanguage[language].heuristicImports;}else\\n{\\n/* If language is undefined or there's no parser, the error we could consider deferring is surely related to*/\\n/* that. Nothing to throw here.*/\\nreturn false;}};\\n\\n\\n\\n/* If we ever need an alternate resolution algorithm, it should be*/\\n/* indicated in the compartment descriptor and a behavior selected here.*/\\nconst resolveHook=resolve;\\nconst importHook=makeImportHook({\\npackageLocation:location,\\npackageName:name,\\nattenuators,\\nparse,\\nshouldDeferError,\\ncompartments});\\n\\nconst moduleMapHook=makeModuleMapHook(\\ncompartmentDescriptor,\\ncompartments,\\ncompartmentName,\\nmodules,\\nscopes);\\n\\n\\nconst compartment=new Compartment(Object.create(null),undefined,{\\nresolveHook,\\nimportHook,\\nmoduleMapHook,\\ntransforms,\\n__shimTransforms__,\\nname:location});\\n\\n\\nif(!archiveOnly){\\npolicy.attenuateGlobals(\\ncompartment.globalThis,\\nglobals,\\ncompartmentDescriptor.policy,\\nattenuators,\\npendingJobs,\\ncompartmentDescriptor.name);}\\n\\n\\n\\ncompartments[compartmentName]=compartment;}\\n\\n\\nconst compartment=compartments[entryCompartmentName];\\nif(compartment===undefined){\\nthrow Error(\\n`Cannot assemble compartment graph because the root compartment named ${q(\\nentryCompartmentName)\\n} is missing from the compartment map`);}\\n\\n\\nconst attenuatorsCompartment=compartments[policy.ATTENUATORS_COMPARTMENT];\\n\\nreturn{\\ncompartment,\\ncompartments,\\nattenuatorsCompartment,\\npendingJobsPromise:promiseAllSettled(pendingJobs).then(\\n/** @param {PromiseSettledResult<unknown>[]} results */(results)=>{\\nconst errors=results.\\nfilter((result)=>result.status==='rejected').\\nmap(\\n/** @param {PromiseRejectedResult} result */(result)=>\\nresult.reason);\\n\\nif(errors.length>0){\\nthrow Error(\\n`Globals attenuation errors: ${errors.\\nmap((error)=>error.message).\\njoin(', ')}`);}})};};\\n\\n\\n\\n\\n\\n\\n\\n/**\\n * @param {CompartmentMapDescriptor} compartmentMap\\n * @param {LinkOptions} options\\n */\\nconst assemble=(compartmentMap,options)=>\\nlink(compartmentMap,options).compartment;exports.assemble=assemble;exports.link=link;exports.mapParsers=mapParsers;\",\n \"node_modules/@endo/compartment-mapper/src/node-module-specifier.js\": \"'use strict';\\n\\nObject.defineProperty(exports,'__esModule',{value:true});/* @ts-check*/ /* q, as in quote, for error messages.*/\\nconst q=JSON.stringify;\\n\\n/**\\n * Advances a partial module specifier solution by following the path\\n * components in the given problem.\\n * The problem may not produce a path that escapes the solution, that is, the\\n * problem may not traverse up from an empty solution.\\n * `Solve` returns false if the problem attempts to escape.\\n * Advanding a partial solution is the core of `resolve`, `join`, and\\n * `relativize`, which have different invariants.\\n *\\n * @param {Array<string>} solution - fully resolved path components, including\\n * any from a prior path resolution initially.\\n * @param {Array<string>} problem - partially resolved path components, that\\n * is, including '.' and '..' components.\\n * @returns {boolean} whether the solver terminated early because of a\\n * nonsensical attempt to traverse above the root directory.\\n */\\nconst solve=(solution,problem)=>{\\nfor(const part of problem){\\nif(part==='.'||part===''){\\n/* no-op*/}else\\nif(part==='..'){\\nif(solution.length===0){\\nreturn false;}\\n\\nsolution.pop();}else\\n{\\nsolution.push(part);}}\\n\\n\\nreturn true;};\\n\\n\\n/**\\n * `Resolve` computes the full module specifier for a given imported module specifier\\n * relative to the referrer module specifier.\\n * In Node.js compartments, the referrer must be an internal module specifier\\n * in the context of a compartment, and all internal module specifiers begin\\n * with a \\\".\\\" path component.\\n * The referent may be either internal or external.\\n * In Node.js, fully resolved paths are valid module specifiers, but these\\n * paths that begin with / are disallowed as they could be used to defeat\\n * compartment containment.\\n *\\n * @param {string} spec - a path to resolve.\\n * @param {string} referrer - the fully resolved path of referrer module.\\n * @returns {string} the fully resolved path.\\n */\\nconst resolve=(spec,referrer)=>{\\nspec=String(spec||'');\\nreferrer=String(referrer||'');\\n\\nif(spec.startsWith('/')){\\nthrow Error(`Module specifier ${q(spec)} must not begin with \\\"/\\\"`);}\\n\\nif(!referrer.startsWith('./')){\\nthrow Error(`Module referrer ${q(referrer)} must begin with \\\"./\\\"`);}\\n\\n\\nconst specParts=spec.split('/');\\nconst solution=[];\\nconst problem=[];\\nif(specParts[0]==='.'||specParts[0]==='..'){\\nconst referrerParts=referrer.split('/');\\nproblem.push(...referrerParts);\\nproblem.pop();\\nsolution.push('.');}\\n\\nproblem.push(...specParts);\\n\\nif(!solve(solution,problem)){\\nthrow Error(\\n`Module specifier ${q(spec)} via referrer ${q(\\nreferrer)\\n} must not traverse behind an empty path`);}\\n\\n\\n\\nreturn solution.join('/');};\\n\\n\\n/**\\n * To construct a module map from a node_modules package, inter-package linkage\\n * requires connecting a full base module specifier like \\\"dependency-package\\\"\\n * to the other package's full internal module specifier like \\\".\\\" or\\n * \\\"./utility\\\", to form a local full module specifier like \\\"dependency-package\\\"\\n * or \\\"dependency-package/utility\\\".\\n * This type of join may assert that the base is absolute and the referrent is\\n * relative.\\n *\\n * @param {string} base - the fully resolved path of a module.\\n * @param {string} spec - the partially resolved path of another module.\\n * @returns {string} the fully resolved path of the specified module.\\n */\\nconst join=(base,spec)=>{\\nspec=String(spec||'');\\nbase=String(base||'');\\n\\nconst specParts=spec.split('/');\\nconst baseParts=base.split('/');\\n\\nif(specParts.length>1&&specParts[0]===''){\\nthrow Error(`Module specifier ${q(spec)} must not start with \\\"/\\\"`);}\\n\\nif(baseParts[0]==='.'||baseParts[0]==='..'){\\nthrow Error(`External module specifier ${q(base)} must be absolute`);}\\n\\nif(specParts[0]!=='.'){\\nthrow Error(`Internal module specifier ${q(spec)} must be relative`);}\\n\\n\\nconst solution=[];\\nif(!solve(solution,specParts)){\\nthrow Error(\\n`Module specifier ${q(spec)} via base ${q(\\nbase)\\n} must not refer to a module outside of the base`);}\\n\\n\\n\\nreturn[base,...solution].join('/');};\\n\\n\\n/**\\n * Relativize turns absolute identifiers into relative identifiers.\\n * In package.json, internal module identifiers can be either relative or\\n * absolute, but compartments backed by node_modules always use relative module\\n * specifiers for internal linkage.\\n *\\n * @param {string} spec - a module specifier that of a local module, that might\\n * be erroneously framed without an initial '.' path component.\\n * @returns {string} the idempotent module specifier, ensured to begin with\\n * '.'.\\n */\\nconst relativize=(spec)=>{\\nspec=String(spec||'');\\n\\nconst solution=[];\\nif(!solve(solution,spec.split('/'))){\\nthrow Error(\\n`Module specifier ${q(spec)} must not traverse behind an empty path`);}\\n\\n\\n\\nreturn['.',...solution].join('/');};exports.join=join;exports.relativize=relativize;exports.resolve=resolve;\",\n \"node_modules/@endo/compartment-mapper/src/parse-bytes.js\": \"'use strict';\\n\\nObject.defineProperty(exports,'__esModule',{value:true});/* @ts-check*/ /**\\n * TypeScript cannot be relied upon to deal with the nuances of Readonly, so we\\n * borrow the pass-through type definition of harden here.\\n *\\n * @type {IMPORT('ses').Harden}\\n */\\nconst freeze=Object.freeze;\\n\\n/** @type {IMPORT('./types.js').ParseFn} */\\nconst parseBytes=async(\\nbytes,\\n_specifier,\\n_location,\\n_packageLocation)=>\\n{\\n/* Snapshot ArrayBuffer*/\\nconst buffer=new ArrayBuffer(bytes.length);\\nconst bytesView=new Uint8Array(buffer);\\nbytesView.set(bytes);\\n\\n/** @type {Array<string>} */\\nconst imports=freeze([]);\\n\\n/**\\n * @param {object} exports\\n */\\nconst execute=(exports)=>{\\nexports.default=buffer;};\\n\\n\\nreturn{\\nparser:'bytes',\\nbytes,\\nrecord:freeze({\\nimports,\\nexports:freeze(['default']),\\nexecute:freeze(execute)})};};\\n\\n\\n\\n\\n/** @type {IMPORT('./types.js').ParserImplementation} */\\nvar parserBytes={\\nparse:parseBytes,\\nheuristicImports:false};exports[\\\"default\\\"]=parserBytes;exports.parseBytes=parseBytes;\",\n \"node_modules/@endo/compartment-mapper/src/parse-cjs-shared-export-wrapper.js\": \"'use strict';\\n\\n\\nObject.defineProperty(exports,'__esModule',{value:true});/* @ts-check*/ /** @import {ReadFn} from './types.js' */ /** @import {ReadPowers} from './types.js' */\\n\\nconst{apply}=Reflect;\\nconst{freeze,keys,create,hasOwnProperty,defineProperty}=Object;\\n\\n/**\\n * @param {object} object\\n * @param {string} key\\n * @returns {boolean}\\n */\\nconst has=(object,key)=>apply(hasOwnProperty,object,[key]);\\n\\nconst noTrailingSlash=(path)=>{\\nconst l=path.length-1;\\nreturn path[l]==='\\\\\\\\'||path[l]==='/'?path.slice(0,-1):path;};\\n\\n\\n/**\\n * Generates values for __filename and __dirname from location\\n *\\n * @param {ReadPowers | ReadFn | undefined} readPowers\\n * @param {string} location\\n * @returns {{\\n * filename:string|null,\\n * dirname: string|null\\n * }}\\n */\\nconst getModulePaths=(readPowers,location)=>{\\nif(\\nreadPowers&&\\ntypeof readPowers!=='function'&&\\nreadPowers.fileURLToPath)\\n{\\nlet filename=location;\\nlet dirname;\\ntry{\\ndirname=new URL('./',filename).href;}\\ncatch(_){\\nreturn{\\nfilename:null,\\ndirname:null};}\\n\\n\\n\\nfilename=readPowers.fileURLToPath(filename).toString();\\ndirname=noTrailingSlash(readPowers.fileURLToPath(dirname).toString());\\n\\nreturn{\\nfilename,\\ndirname};}else\\n\\n{\\nreturn{\\nfilename:null,\\ndirname:null};}};\\n\\n\\n\\n\\n/**\\n * ModuleEnvironmentRecord wrapper\\n * Creates shared export processing primitives to be used both Location and Archive usecases of cjs\\n *\\n * @param {object} in\\n * @param {object} in.moduleEnvironmentRecord\\n * @param {Compartment} in.compartment\\n * @param {Record<string, string>} in.resolvedImports\\n * @param {string} in.location\\n * @param {ReadFn | ReadPowers | undefined} in.readPowers\\n * @returns {{\\n * module: { exports: any },\\n * moduleExports: any,\\n * afterExecute: Function,\\n * require: Function,\\n * }}\\n */\\nconst wrap=({\\nmoduleEnvironmentRecord,\\ncompartment,\\nresolvedImports,\\nlocation,\\nreadPowers})=>\\n{\\n/* This initial default value makes things like exports.hasOwnProperty() work in cjs.*/\\nmoduleEnvironmentRecord.default=create(\\ncompartment.globalThis.Object.prototype);\\n\\n\\n/* Set all exported properties on the defult and call namedExportProp to add them on the namespace for import *.*/\\n/* Root namespace is only accessible for imports. Requiring from cjs gets the default field of the namespace.*/\\nconst promoteToNamedExport=(prop,value)=>{\\n/* __esModule needs to be present for typescript-compiled modules to work, can't be skipped*/\\nif(prop!=='default'){\\nmoduleEnvironmentRecord[prop]=value;}};\\n\\n\\n\\nconst originalExports=new Proxy(moduleEnvironmentRecord.default,{\\nset(_target,prop,value){\\npromoteToNamedExport(prop,value);\\nmoduleEnvironmentRecord.default[prop]=value;\\nreturn true;},\\n\\ndefineProperty(target,prop,descriptor){\\nif(has(descriptor,'value')){\\n/* This will result in non-enumerable properties being enumerable for named import purposes. We could check*/\\n/* enumerable here, but I don't see possible benefits of such restriction.*/\\npromoteToNamedExport(prop,descriptor.value);}\\n\\n/* All the defineProperty trickery with getters used for lazy initialization will work. The trap is here only to*/\\n/* elevate the values with namedExportProp whenever possible. Replacing getters with wrapped ones to facilitate*/\\n/* propagating the lazy value to the namespace is not possible because defining a property with modified*/\\n/* descriptor.get in the trap will cause an error.*/\\n/* Object.defineProperty is used instead of Reflect.defineProperty for better error messages.*/\\ndefineProperty(target,prop,descriptor);\\nreturn true;}});\\n\\n\\n\\nlet finalExports=originalExports;\\n\\nconst module=freeze({\\nget exports(){\\nreturn finalExports;},\\n\\nset exports(value){\\nfinalExports=value;}});\\n\\n\\n\\nconst require=(/** @type {string} */importSpecifier)=>{\\nif(!has(resolvedImports,importSpecifier)){\\nthrow new Error(\\n`Cannot find module \\\"${importSpecifier}\\\" in \\\"${location}\\\"`);}\\n\\n\\nconst namespace=compartment.importNow(resolvedImports[importSpecifier]);\\n/* If you read this file carefully, you'll see it's not possible for a cjs module to not have the default anymore.*/\\n/* It's currently possible to require modules that were not created by this file though.*/\\nif(has(namespace,'default')){\\nreturn namespace.default;}else\\n{\\nreturn namespace;}};\\n\\n\\nif(typeof readPowers==='object'&&readPowers.requireResolve){\\nconst{requireResolve}=readPowers;\\nrequire.resolve=freeze((specifier,options)=>\\nrequireResolve(location,specifier,options));}else\\n\\n{\\nrequire.resolve=freeze((specifier)=>{\\nconst error=Error(\\n`Cannot find module '${specifier}'\\\\nAdd requireResolve to Endo Compartment Mapper readPowers.`);\\n\\ndefineProperty(error,'code',{value:'MODULE_NOT_FOUND'});\\nthrow error;});}\\n\\n\\n\\nfreeze(require);\\n\\nconst afterExecute=()=>{\\nconst exportsHaveBeenOverwritten=finalExports!==originalExports;\\n/* Promotes keys from redefined module.export to top level namespace for import **/\\n/* Note: We could do it less consistently but closer to how node does it if we iterated over exports detected by*/\\n/* the lexer.*/\\nif(exportsHaveBeenOverwritten){\\nmoduleEnvironmentRecord.default=finalExports;\\nfor(const prop of keys(moduleEnvironmentRecord.default||{})){\\nif(prop!=='default')\\nmoduleEnvironmentRecord[prop]=moduleEnvironmentRecord.default[prop];}}};\\n\\n\\n\\n\\nreturn{\\nmodule,\\nmoduleExports:originalExports,\\nafterExecute,\\nrequire};};exports.getModulePaths=getModulePaths;exports.wrap=wrap;\",\n \"node_modules/@endo/compartment-mapper/src/parse-json.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var\\n\\n\\n\\njson=require('./json.js');/* @ts-check*/ /**\\n * TypeScript cannot be relied upon to deal with the nuances of Readonly, so we\\n * borrow the pass-through type definition of harden here.\\n *\\n * @type {IMPORT('ses').Harden}\\n */\\nconst freeze=Object.freeze;\\n\\nconst textDecoder=new TextDecoder();\\n\\n/** @type {IMPORT('./types.js').ParseFn} */\\nconst parseJson=async(\\nbytes,\\n_specifier,\\nlocation,\\n_packageLocation)=>\\n{\\nconst source=textDecoder.decode(bytes);\\nconst imports=freeze([]);\\n\\n/**\\n * @param {object} exports\\n */\\nconst execute=(exports)=>{\\nexports.default=json.parseLocatedJson(source,location);};\\n\\nreturn{\\nparser:'json',\\nbytes,\\nrecord:freeze({\\nimports,\\nexports:freeze(['default']),\\nexecute:freeze(execute)})};};\\n\\n\\n\\n\\n/** @type {IMPORT('./types.js').ParserImplementation} */\\nvar parserJson={\\nparse:parseJson,\\nheuristicImports:false};exports[\\\"default\\\"]=parserJson;exports.parseJson=parseJson;\",\n \"node_modules/@endo/compartment-mapper/src/parse-pre-cjs.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var json=require('./json.js');var parseCjsSharedExportWrapper=require('./parse-cjs-shared-export-wrapper.js');/* @ts-check*/\\n\\n\\n\\n\\nconst textDecoder=new TextDecoder();\\n\\n/** @type {IMPORT('./types.js').ParseFn} */\\nconst parsePreCjs=async(\\nbytes,\\n_specifier,\\nlocation,\\n_packageLocation,\\n{readPowers}={})=>\\n{\\nconst text=textDecoder.decode(bytes);\\nconst{source,imports,exports,reexports}=json.parseLocatedJson(\\ntext,\\nlocation);\\n\\n\\nconst{filename,dirname}=await parseCjsSharedExportWrapper.getModulePaths(readPowers,location);\\n\\n/**\\n * @param {object} moduleEnvironmentRecord\\n * @param {Compartment} compartment\\n * @param {Record<string, string>} resolvedImports\\n */\\nconst execute=(moduleEnvironmentRecord,compartment,resolvedImports)=>{\\nconst functor=compartment.evaluate(source);\\n\\nconst{require,moduleExports,module,afterExecute}=parseCjsSharedExportWrapper.wrap({\\nmoduleEnvironmentRecord,\\ncompartment,\\nresolvedImports,\\nlocation,\\nreadPowers});\\n\\n\\nfunctor(require,moduleExports,module,filename,dirname);\\n\\nafterExecute();};\\n\\n\\nreturn{\\nparser:'pre-cjs-json',\\nbytes,\\nrecord:{\\nimports,\\nreexports,\\nexports,\\nexecute}};};\\n\\n\\n\\n\\n/** @type {IMPORT('./types.js').ParserImplementation} */\\nvar parserPreCjs={\\nparse:parsePreCjs,\\nheuristicImports:true};exports[\\\"default\\\"]=parserPreCjs;exports.parsePreCjs=parsePreCjs;\",\n \"node_modules/@endo/compartment-mapper/src/parse-pre-mjs.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var json=require('./json.js');/* @ts-check*/\\n\\n\\n\\nconst textDecoder=new TextDecoder();\\n\\n/** @type {IMPORT('./types.js').ParseFn} */\\nconst parsePreMjs=async(\\nbytes,\\n_specifier,\\nlocation,\\n_packageLocation,\\n{sourceMapUrl}={})=>\\n{\\nconst text=textDecoder.decode(bytes);\\nconst record=json.parseLocatedJson(text,location);\\nif(sourceMapUrl){\\n/* eslint-disable-next-line no-underscore-dangle*/\\nrecord.__syncModuleProgram__+=`//# sourceMappingURL=${sourceMapUrl}\\\\n`;}else\\n{\\n/* eslint-disable-next-line no-underscore-dangle*/\\nrecord.__syncModuleProgram__+=`//# sourceURL=${location}\\\\n`;}\\n\\nreturn{\\nparser:'pre-mjs-json',\\nbytes,\\nrecord};};\\n\\n\\n\\n/** @type {IMPORT('./types.js').ParserImplementation} */\\nvar parserPreMjs={\\nparse:parsePreMjs,\\nheuristicImports:false};exports[\\\"default\\\"]=parserPreMjs;exports.parsePreMjs=parsePreMjs;\",\n \"node_modules/@endo/compartment-mapper/src/parse-text.js\": \"'use strict';\\n\\nObject.defineProperty(exports,'__esModule',{value:true});/* @ts-check*/ /**\\n * TypeScript cannot be relied upon to deal with the nuances of Readonly, so we\\n * borrow the pass-through type definition of harden here.\\n *\\n * @type {IMPORT('ses').Harden}\\n */\\nconst freeze=Object.freeze;\\n\\nconst textDecoder=new TextDecoder();\\n\\n/** @type {IMPORT('./types.js').ParseFn} */\\nconst parseText=async(\\nbytes,\\n_specifier,\\n_location,\\n_packageLocation)=>\\n{\\nconst text=textDecoder.decode(bytes);\\n\\n/** @type {Array<string>} */\\nconst imports=freeze([]);\\n\\n/**\\n * @param {object} exports\\n */\\nconst execute=(exports)=>{\\nexports.default=text;};\\n\\n\\nreturn{\\nparser:'text',\\nbytes,\\nrecord:freeze({\\nimports,\\nexports:freeze(['default']),\\nexecute:freeze(execute)})};};\\n\\n\\n\\n\\n/** @type {IMPORT('./types.js').ParserImplementation} */\\nvar parserText={\\nparse:parseText,\\nheuristicImports:false};exports[\\\"default\\\"]=parserText;exports.parseText=parseText;\",\n \"node_modules/@endo/compartment-mapper/src/policy-format.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});/* @ts-check*/\\n\\nconst{entries,keys}=Object;\\nconst{isArray}=Array;\\nconst q=JSON.stringify;\\n\\nconst ATTENUATOR_KEY='attenuate';\\nconst ATTENUATOR_PARAMS_KEY='params';\\nconst WILDCARD_POLICY_VALUE='any';\\nconst POLICY_FIELDS_LOOKUP=/** @type {const} */[\\n'builtins',\\n'globals',\\n'packages'];\\n\\n\\n/**\\n *\\n * @param {IMPORT('./types.js').PackagePolicy} packagePolicy\\n * @param {'builtins'|'globals'|'packages'} field\\n * @param {string} itemName\\n * @returns {boolean | IMPORT('./types.js').AttenuationDefinition}\\n */\\nconst policyLookupHelper=(packagePolicy,field,itemName)=>{\\nif(!POLICY_FIELDS_LOOKUP.includes(field)){\\nthrow Error(`Invalid field ${q(field)}`);}\\n\\nif(\\ntypeof packagePolicy!=='object'||\\npackagePolicy===null||\\n!packagePolicy[field])\\n{\\nreturn false;}\\n\\n\\nif(packagePolicy[field]===WILDCARD_POLICY_VALUE){\\nreturn true;}\\n\\n\\nconst value=/** @type {IMPORT('./types.js').AttenuationDefinition} */\\npackagePolicy[field];\\n\\nif(itemName in value){\\nreturn value[itemName];}\\n\\nreturn false;};\\n\\n\\n/**\\n * Type guard; checks if the policy value is set to the wildcard value to allow everything\\n *\\n * @param {unknown} policyValue\\n * @returns {policyValue is IMPORT('./types.js').WildcardPolicy}\\n */\\nconst isAllowingEverything=(policyValue)=>\\npolicyValue===WILDCARD_POLICY_VALUE;\\n\\n/**\\n * Type guard for `AttenuationDefinition`\\n * @param {unknown} allegedDefinition\\n * @returns {allegedDefinition is IMPORT('./types.js').AttenuationDefinition}\\n */\\nconst isAttenuationDefinition=(allegedDefinition)=>{\\nreturn Boolean(\\nallegedDefinition&&\\ntypeof allegedDefinition==='object'&&\\ntypeof allegedDefinition[ATTENUATOR_KEY]==='string'||/* object with attenuator name*/\\nisArray(allegedDefinition)/* params for default attenuator*/);};\\n\\n\\n\\n/**\\n *\\n * @param {IMPORT('./types.js').AttenuationDefinition} attenuationDefinition\\n * @returns {IMPORT('./types.js').UnifiedAttenuationDefinition}\\n */\\nconst getAttenuatorFromDefinition=(attenuationDefinition)=>{\\nif(!isAttenuationDefinition(attenuationDefinition)){\\nthrow Error(\\n`Invalid attenuation ${q(\\nattenuationDefinition)\\n}, must be an array of params for default attenuator or an object with an attenuator key`);}\\n\\n\\nif(isArray(attenuationDefinition)){\\nreturn{\\ndisplayName:'<default attenuator>',\\nspecifier:null,\\nparams:attenuationDefinition};}else\\n\\n{\\nreturn{\\ndisplayName:attenuationDefinition[ATTENUATOR_KEY],\\nspecifier:attenuationDefinition[ATTENUATOR_KEY],\\nparams:attenuationDefinition[ATTENUATOR_PARAMS_KEY]};}};\\n\\n\\n\\n\\n/* TODO: should be a type guard*/\\nconst isRecordOf=(item,predicate)=>{\\nif(typeof item!=='object'||item===null||isArray(item)){\\nreturn false;}\\n\\nreturn entries(item).every(([key,value])=>predicate(value,key));};\\n\\n\\n/**\\n * Type guard for `boolean`\\n * @param {unknown} item\\n * @returns {item is boolean}\\n */\\nconst isBoolean=(item)=>typeof item==='boolean';\\n\\n/* TODO: should be a type guard*/\\nconst predicateOr=\\n(...predicates)=>\\n(item)=>\\npredicates.some((p)=>p(item));\\n\\n/**\\n * @param {unknown} item\\n * @returns {item is IMPORT('./types.js').PolicyItem}\\n */\\nconst isPolicyItem=(item)=>\\nitem===undefined||\\nitem===WILDCARD_POLICY_VALUE||\\nisRecordOf(item,isBoolean);\\n\\n/**\\n * This asserts (i.e., throws) that `allegedPackagePolicy` is a valid `PackagePolicy`.\\n *\\n * Mild-mannered during the day, but fights crime at night as a type guard.\\n *\\n * @param {unknown} allegedPackagePolicy - Alleged `PackagePolicy` to test\\n * @param {string} path - Path in the `Policy` object; used for error messages only\\n * @param {string} [url] - URL of the policy file; used for error messages only\\n * @returns {asserts allegedPackagePolicy is IMPORT('./types.js').PackagePolicy|undefined}\\n */\\nconst assertPackagePolicy=(allegedPackagePolicy,path,url)=>{\\nif(allegedPackagePolicy===undefined){\\nreturn;}\\n\\nconst inUrl=url?` in ${q(url)}`:'';\\n\\nconst packagePolicy=Object(allegedPackagePolicy);\\nassert(\\nallegedPackagePolicy===packagePolicy&&!isArray(allegedPackagePolicy),\\n`${path} must be an object, got ${q(allegedPackagePolicy)}${inUrl}`);\\n\\nconst{\\npackages,\\nbuiltins,\\nglobals,\\nnoGlobalFreeze,\\ndefaultAttenuator:_ignore,/* a carve out for the default attenuator in compartment map*/\\n...extra}=\\npackagePolicy;\\n\\nassert(\\nkeys(extra).length===0,\\n`${path} must not have extra properties, got ${q(keys(extra))}${inUrl}`);\\n\\n\\nassert(\\nnoGlobalFreeze===undefined||typeof noGlobalFreeze==='boolean',\\n`${path}.noGlobalFreeze must be a boolean, got ${q({\\nnoGlobalFreeze})\\n}${inUrl}`);\\n\\n\\nisPolicyItem(packages)||\\nassert.fail(\\n`${path}.packages must be a record of booleans, got ${q({\\npackages})\\n}${inUrl}`);\\n\\n\\nisPolicyItem(globals)||\\nisAttenuationDefinition(globals)||\\nassert.fail(\\n`${path}.globals must be a record of booleans or a single attenuation, got ${q(\\n{\\nglobals})\\n\\n}${inUrl}`);\\n\\n\\nisPolicyItem(builtins)||\\nisRecordOf(builtins,predicateOr(isBoolean,isAttenuationDefinition))||\\nassert.fail(\\n`${path}.builtins must be a record of booleans or attenuations, got ${q({\\nbuiltins})\\n}${inUrl}`);};\\n\\n\\n\\n/**\\n * This asserts (i.e., throws) that `allegedPolicy` is a valid `Policy`\\n *\\n * It also moonlights as a type guard.\\n *\\n * @param {unknown} allegedPolicy - Alleged `Policy` to test\\n * @returns {asserts allegedPolicy is IMPORT('./types.js').Policy|undefined}\\n */\\nconst assertPolicy=(allegedPolicy)=>{\\nif(allegedPolicy===undefined){\\nreturn;}\\n\\nconst policy=Object(allegedPolicy);\\nassert(\\nallegedPolicy===policy&&!Array.isArray(policy),\\n`policy must be an object, got ${allegedPolicy}`);\\n\\n\\nconst{resources,entry,defaultAttenuator,...extra}=policy;\\nassert(\\nkeys(extra).length===0,\\n`policy must not have extra properties, got ${q(keys(extra))}`);\\n\\n\\nassert(\\ntypeof resources==='object'&&resources!==null&&!isArray(resources),\\n`policy.resources must be an object, got ${q(resources)}`);\\n\\nassert(\\n!defaultAttenuator||typeof defaultAttenuator==='string',\\n`policy.defaultAttenuator must be a string, got ${q(defaultAttenuator)}`);\\n\\n\\nassertPackagePolicy(entry,`policy.entry`);\\n\\nfor(const[key,value]of entries(resources)){\\nassertPackagePolicy(value,`policy.resources[\\\"${key}\\\"]`);}};exports.assertPackagePolicy=assertPackagePolicy;exports.assertPolicy=assertPolicy;exports.getAttenuatorFromDefinition=getAttenuatorFromDefinition;exports.isAllowingEverything=isAllowingEverything;exports.isAttenuationDefinition=isAttenuationDefinition;exports.policyLookupHelper=policyLookupHelper;\",\n \"node_modules/@endo/compartment-mapper/src/policy.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var policyFormat=require('./policy-format.js');/* @ts-check*/\\n\\n\\n\\n\\n\\n\\n\\n\\nconst{create,entries,values,assign,keys,freeze}=Object;\\nconst q=JSON.stringify;\\n\\n/**\\n * Const string to identify the internal attenuators compartment\\n */\\nconst ATTENUATORS_COMPARTMENT='<ATTENUATORS>';\\n\\n/**\\n * Copies properties (optionally limited to a specific list) from one object to another.\\n *\\n * @param {object} from\\n * @param {object} to\\n * @param {Array<string | symbol>} [list]\\n * @returns {object}\\n */\\nconst selectiveCopy=(from,to,list)=>{\\nif(!list){\\nlist=keys(from);}\\n\\nfor(let index=0;index<list.length;index+=1){\\nconst key=list[index];\\n/* If an endowment is missing, global value is undefined.*/\\n/* This is an expected behavior if globals are used for platform feature detection*/\\nto[key]=from[key];}\\n\\nreturn to;};\\n\\n\\n/**\\n * Parses an attenuation definition for attenuator names\\n *\\n * Note: this function is recursive\\n * @param {string[]} attenuators - List of attenuator names; may be mutated\\n * @param {IMPORT('./types.js').AttenuationDefinition|IMPORT('./types.js').Policy} policyFragment\\n */\\nconst collectAttenuators=(attenuators,policyFragment)=>{\\nif('attenuate'in policyFragment){\\nattenuators.push(policyFragment.attenuate);}\\n\\nfor(const value of values(policyFragment)){\\nif(typeof value==='object'&&value!==null){\\ncollectAttenuators(attenuators,value);}}};\\n\\n\\n\\n\\nconst attenuatorsCache=new WeakMap();\\n\\n/**\\n * Goes through policy and lists all attenuator specifiers used.\\n * Memoization keyed on policy object reference\\n *\\n * @param {IMPORT('./types.js').Policy} [policy]\\n * @returns {Array<string>} attenuators\\n */\\nconst detectAttenuators=(policy)=>{\\nif(!policy){\\nreturn[];}\\n\\nif(!attenuatorsCache.has(policy)){\\nconst attenuators=[];\\nif(policy.defaultAttenuator){\\nattenuators.push(policy.defaultAttenuator);}\\n\\ncollectAttenuators(attenuators,policy);\\nattenuatorsCache.set(policy,attenuators);}\\n\\nreturn attenuatorsCache.get(policy);};\\n\\n\\n/**\\n * Generates a string identifying a package for policy lookup purposes.\\n *\\n * @param {IMPORT('./types.js').PackageNamingKit} namingKit\\n * @returns {string}\\n */\\nconst generateCanonicalName=({isEntry=false,name,path})=>{\\nif(isEntry){\\nthrow Error('Entry module cannot be identified with a canonicalName');}\\n\\nif(name===ATTENUATORS_COMPARTMENT){\\nreturn ATTENUATORS_COMPARTMENT;}\\n\\nreturn path.join('>');};\\n\\n\\n/**\\n * Verifies if a module identified by `namingKit` can be a dependency of a package per `packagePolicy`.\\n * `packagePolicy` is required, when policy is not set, skipping needs to be handled by the caller.\\n *\\n * @param {IMPORT('./types.js').PackageNamingKit} namingKit\\n * @param {IMPORT('./types.js').PackagePolicy} packagePolicy\\n * @returns {boolean}\\n */\\nconst dependencyAllowedByPolicy=(namingKit,packagePolicy)=>{\\nif(namingKit.isEntry){\\n/* dependency on entry compartment should never be allowed*/\\nreturn false;}\\n\\nconst canonicalName=generateCanonicalName(namingKit);\\nreturn!!policyFormat.policyLookupHelper(packagePolicy,'packages',canonicalName);};\\n\\n\\n/**\\n * Returns the policy applicable to the canonicalName of the package\\n *\\n * @overload\\n * @param {IMPORT('./types.js').PackageNamingKit} namingKit - a key in the policy resources spec is derived from these\\n * @param {IMPORT('./types.js').Policy} policy - user supplied policy\\n * @returns {IMPORT('./types.js').PackagePolicy} packagePolicy if policy was specified\\n */\\n\\n/**\\n * Returns `undefined`\\n *\\n * @overload\\n * @param {IMPORT('./types.js').PackageNamingKit} namingKit - a key in the policy resources spec is derived from these\\n * @param {IMPORT('./types.js').Policy} [policy] - user supplied policy\\n * @returns {IMPORT('./types.js').PackagePolicy|undefined} packagePolicy if policy was specified\\n */\\n\\n/**\\n * Returns the policy applicable to the canonicalName of the package\\n *\\n * @param {IMPORT('./types.js').PackageNamingKit} namingKit - a key in the policy resources spec is derived from these\\n * @param {IMPORT('./types.js').Policy} [policy] - user supplied policy\\n */\\nconst getPolicyForPackage=(namingKit,policy)=>{\\nif(!policy){\\nreturn undefined;}\\n\\nif(namingKit.isEntry){\\nreturn policy.entry;}\\n\\nconst canonicalName=generateCanonicalName(namingKit);\\nif(canonicalName===ATTENUATORS_COMPARTMENT){\\nreturn{\\ndefaultAttenuator:policy.defaultAttenuator,\\npackages:'any'};}\\n\\n\\nif(policy.resources&&policy.resources[canonicalName]!==undefined){\\nreturn policy.resources[canonicalName];}else\\n{\\n/* Allow skipping policy entries for packages with no powers.*/\\nreturn create(null);}};\\n\\n\\n\\n/**\\n * Get list of globals from package policy\\n * @param {IMPORT('./types.js').PackagePolicy} [packagePolicy]\\n * @returns {Array<string>}\\n */\\nconst getGlobalsList=(packagePolicy)=>{\\nif(!packagePolicy||!packagePolicy.globals){\\nreturn[];}\\n\\nreturn entries(packagePolicy.globals).\\nfilter(([_key,value])=>value).\\nmap(([key,_vvalue])=>key);};\\n\\n\\nconst GLOBAL_ATTENUATOR='attenuateGlobals';\\nconst MODULE_ATTENUATOR='attenuateModule';\\n\\n/**\\n * Imports attenuator per its definition and provider\\n * @param {IMPORT('./types.js').AttenuationDefinition} attenuationDefinition\\n * @param {IMPORT('./types.js').DeferredAttenuatorsProvider} attenuatorsProvider\\n * @param {string} attenuatorExportName\\n * @returns {Promise<Function>}\\n */\\nconst importAttenuatorForDefinition=async(\\nattenuationDefinition,\\nattenuatorsProvider,\\nattenuatorExportName)=>\\n{\\nif(!attenuatorsProvider){\\nthrow Error(`attenuatorsProvider is required to import attenuators`);}\\n\\nconst{specifier,params,displayName}=policyFormat.getAttenuatorFromDefinition(\\nattenuationDefinition);\\n\\nconst attenuator=await attenuatorsProvider.import(specifier);\\nif(!attenuator[attenuatorExportName]){\\nthrow Error(\\n`Attenuator ${q(displayName)} does not export ${q(attenuatorExportName)}`);}\\n\\n\\n/* TODO: uncurry bind for security?*/\\nconst attenuate=attenuator[attenuatorExportName].bind(attenuator,params);\\nreturn attenuate;};\\n\\n\\n/**\\n * Makes an async provider for attenuators\\n * @param {Record<string, Compartment>} compartments\\n * @param {Record<string, IMPORT('./types.js').CompartmentDescriptor>} compartmentDescriptors\\n * @returns {IMPORT('./types.js').DeferredAttenuatorsProvider}\\n */\\nconst makeDeferredAttenuatorsProvider=(\\ncompartments,\\ncompartmentDescriptors)=>\\n{\\nlet importAttenuator;\\nlet defaultAttenuator;\\n/* Attenuators compartment is not created when there's no policy.*/\\n/* Errors should be thrown when the provider is used.*/\\nif(!compartmentDescriptors[ATTENUATORS_COMPARTMENT]){\\nimportAttenuator=async()=>{\\nthrow Error(`No attenuators specified in policy`);};}else\\n\\n{\\ndefaultAttenuator=\\ncompartmentDescriptors[ATTENUATORS_COMPARTMENT].policy.defaultAttenuator;\\n\\n/* At the time of this function being called, attenuators compartment won't*/\\n/* exist yet, we need to defer looking them up in the compartment to the*/\\n/* time of the import function being called.*/\\n/**\\n *\\n * @param {string} attenuatorSpecifier\\n * @returns {Promise<IMPORT('./types.js').Attenuator>}\\n */\\nimportAttenuator=async(attenuatorSpecifier)=>{\\nif(!attenuatorSpecifier){\\nif(!defaultAttenuator){\\nthrow Error(`No default attenuator specified in policy`);}\\n\\nattenuatorSpecifier=defaultAttenuator;}\\n\\nconst{namespace}=\\nawait compartments[ATTENUATORS_COMPARTMENT].import(attenuatorSpecifier);\\nreturn namespace;};}\\n\\n\\n\\nreturn{\\nimport:importAttenuator};};\\n\\n\\n\\n/**\\n * Attenuates the `globalThis` object\\n *\\n * @param {object} options\\n * @param {IMPORT('./types.js').DeferredAttenuatorsProvider} options.attenuators\\n * @param {IMPORT('./types.js').AttenuationDefinition} options.attenuationDefinition\\n * @param {object} options.globalThis\\n * @param {object} options.globals\\n */\\nasync function attenuateGlobalThis({\\nattenuators,\\nattenuationDefinition,\\nglobalThis,\\nglobals})\\n{\\nconst attenuate=await importAttenuatorForDefinition(\\nattenuationDefinition,\\nattenuators,\\nGLOBAL_ATTENUATOR);\\n\\n\\n/* attenuate can either define properties on globalThis on its own,*/\\n/* or return an object with properties to transfer onto globalThis.*/\\n/* The latter is consistent with how module attenuators work so that*/\\n/* one attenuator implementation can be used for both if use of*/\\n/* defineProperty is not needed for attenuating globals.*/\\n\\n/* Globals attenuator could be made async by adding a single `await`*/\\n/* here, but module attenuation must be synchronous, so we make it*/\\n/* synchronous too for consistency.*/\\n\\n/* For async attenuators see PR https://github.com/endojs/endo/pull/1535*/\\n\\nconst result=/* await */attenuate(globals,globalThis);\\nif(typeof result==='object'&&result!==null){\\nassign(globalThis,result);}}\\n\\n\\n\\n/**\\n * Filters available globals and returns a copy according to the policy\\n *\\n * @param {object} globalThis\\n * @param {object} globals\\n * @param {IMPORT('./types.js').PackagePolicy} packagePolicy\\n * @param {IMPORT('./types.js').DeferredAttenuatorsProvider} attenuators\\n * @param {Array<Promise>} pendingJobs\\n * @param {string} name\\n * @returns {void}\\n */\\nconst attenuateGlobals=(\\nglobalThis,\\nglobals,\\npackagePolicy,\\nattenuators,\\npendingJobs,\\nname='<unknown>')=>\\n{\\nlet freezeGlobalThisUnlessOptedOut=()=>{\\nfreeze(globalThis);};\\n\\nif(packagePolicy&&packagePolicy.noGlobalFreeze){\\nfreezeGlobalThisUnlessOptedOut=()=>{};}\\n\\nif(!packagePolicy||policyFormat.isAllowingEverything(packagePolicy.globals)){\\nselectiveCopy(globals,globalThis);\\nfreezeGlobalThisUnlessOptedOut();\\nreturn;}\\n\\nif(policyFormat.isAttenuationDefinition(packagePolicy.globals)){\\nconst attenuationDefinition=packagePolicy.globals;\\nconst{displayName}=policyFormat.getAttenuatorFromDefinition(attenuationDefinition);\\nconst attenuationPromise=Promise.resolve()/* delay to next tick while linking is synchronously finalized*/.\\nthen(()=>\\nattenuateGlobalThis({\\nattenuators,\\nattenuationDefinition,\\nglobalThis,\\nglobals})).\\n\\n\\nthen(freezeGlobalThisUnlessOptedOut,(error)=>{\\nfreezeGlobalThisUnlessOptedOut();\\nthrow Error(\\n`Error while attenuating globals for ${q(name)} with ${q(\\ndisplayName)\\n}: ${q(error.message)}`/* TODO: consider an option to expose stacktrace for ease of debugging*/);});\\n\\n\\npendingJobs.push(attenuationPromise);\\n\\nreturn;}\\n\\nconst list=getGlobalsList(packagePolicy);\\nselectiveCopy(globals,globalThis,list);\\nfreezeGlobalThisUnlessOptedOut();};\\n\\n\\n/**\\n * @param {string} [errorHint]\\n * @returns {string}\\n */\\nconst diagnoseModulePolicy=(errorHint)=>{\\nif(!errorHint){\\nreturn'';}\\n\\nreturn` (info: ${errorHint})`;};\\n\\n\\n/**\\n * Options for {@link enforceModulePolicy}\\n * @typedef EnforceModulePolicyOptions\\n * @property {boolean} [exit] - Whether it is an exit module\\n * @property {string} [errorHint] - Error hint message\\n */\\n\\n/**\\n * Throws if importing of the specifier is not allowed by the policy\\n *\\n * @param {string} specifier\\n * @param {IMPORT('./types.js').CompartmentDescriptor} compartmentDescriptor\\n * @param {EnforceModulePolicyOptions} [options]\\n */\\nconst enforceModulePolicy=(\\nspecifier,\\ncompartmentDescriptor,\\n{exit,errorHint}={})=>\\n{\\nconst{policy,modules,label}=compartmentDescriptor;\\nif(!policy){\\nreturn;}\\n\\n\\nif(!exit){\\nif(!modules[specifier]){\\nthrow Error(\\n`Importing ${q(specifier)} in ${q(\\nlabel)\\n} was not allowed by packages policy ${q(\\npolicy.packages)\\n}${diagnoseModulePolicy(errorHint)}`);}\\n\\n\\nreturn;}\\n\\n\\nif(!policyFormat.policyLookupHelper(policy,'builtins',specifier)){\\nthrow Error(\\n`Importing ${q(specifier)} was not allowed by policy builtins:${q(\\npolicy.builtins)\\n}${diagnoseModulePolicy(errorHint)}`);}};\\n\\n\\n\\n\\n/**\\n * Attenuates a module\\n * @param {object} options\\n * @param {IMPORT('./types.js').DeferredAttenuatorsProvider} options.attenuators\\n * @param {IMPORT('./types.js').AttenuationDefinition} options.attenuationDefinition\\n * @param {IMPORT('ses').ThirdPartyStaticModuleInterface} options.originalModuleRecord\\n * @returns {Promise<IMPORT('ses').ThirdPartyStaticModuleInterface>}\\n */\\nasync function attenuateModule({\\nattenuators,\\nattenuationDefinition,\\noriginalModuleRecord})\\n{\\nconst attenuate=await importAttenuatorForDefinition(\\nattenuationDefinition,\\nattenuators,\\nMODULE_ATTENUATOR);\\n\\n\\n/* An async attenuator maker could be introduced here to return a synchronous attenuator.*/\\n/* For async attenuators see PR https://github.com/endojs/endo/pull/1535*/\\n\\nreturn freeze({\\nimports:originalModuleRecord.imports,\\n/* It seems ok to declare the exports but then let the attenuator trim the values.*/\\n/* Seems ok for attenuation to leave them undefined - accessing them is malicious behavior.*/\\nexports:originalModuleRecord.exports,\\nexecute:(moduleExports,compartment,resolvedImports)=>{\\nconst ns={};\\noriginalModuleRecord.execute(ns,compartment,resolvedImports);\\nconst attenuated=attenuate(ns);\\nmoduleExports.default=attenuated;\\nassign(moduleExports,attenuated);}});}\\n\\n\\n\\n\\n/**\\n * Throws if importing of the specifier is not allowed by the policy\\n *\\n * @param {string} specifier - exit module name\\n * @param {IMPORT('ses').ThirdPartyStaticModuleInterface} originalModuleRecord - reference to the exit module\\n * @param {IMPORT('./types.js').PackagePolicy} policy - local compartment policy\\n * @param {IMPORT('./types.js').DeferredAttenuatorsProvider} attenuators - a key-value where attenuations can be found\\n * @returns {Promise<IMPORT('ses').ThirdPartyStaticModuleInterface>} - the attenuated module\\n */\\nconst attenuateModuleHook=async(\\nspecifier,\\noriginalModuleRecord,\\npolicy,\\nattenuators)=>\\n{\\nconst policyValue=policyFormat.policyLookupHelper(policy,'builtins',specifier);\\nif(!policy||policyValue===true){\\nreturn originalModuleRecord;}\\n\\n\\nif(!policyValue){\\nthrow Error(\\n`Attenuation failed '${specifier}' was not in policy builtins:${q(\\npolicy.builtins)\\n}`);}\\n\\n\\nreturn attenuateModule({\\nattenuators,\\nattenuationDefinition:policyValue,\\noriginalModuleRecord});};exports.ATTENUATORS_COMPARTMENT=ATTENUATORS_COMPARTMENT;exports.attenuateGlobals=attenuateGlobals;exports.attenuateModuleHook=attenuateModuleHook;exports.dependencyAllowedByPolicy=dependencyAllowedByPolicy;exports.detectAttenuators=detectAttenuators;exports.enforceModulePolicy=enforceModulePolicy;exports.getPolicyForPackage=getPolicyForPackage;exports.makeDeferredAttenuatorsProvider=makeDeferredAttenuatorsProvider;\",\n \"node_modules/@endo/compartment-mapper/src/powers.js\": \"'use strict';\\n\\nObject.defineProperty(exports,'__esModule',{value:true});/* @ts-check*/ /** @type {IMPORT('./types.js').CanonicalFn} */\\nconst canonicalShim=async(path)=>path;\\n\\n/**\\n * @param {IMPORT('./types.js').ReadFn | IMPORT('./types.js').ReadPowers | IMPORT('./types.js').MaybeReadPowers} powers\\n * @returns {IMPORT('./types.js').MaybeReadPowers}\\n */\\nconst unpackReadPowers=(powers)=>{\\n/** @type {IMPORT('./types.js').ReadFn | undefined} */\\nlet read;\\n/** @type {IMPORT('./types.js').MaybeReadFn | undefined} */\\nlet maybeRead;\\n/** @type {IMPORT('./types.js').CanonicalFn | undefined} */\\nlet canonical;\\n\\nif(typeof powers==='function'){\\nread=powers;}else\\n{\\n({read,maybeRead,canonical}=powers);}\\n\\n\\nif(canonical===undefined){\\ncanonical=canonicalShim;}\\n\\n\\nif(maybeRead===undefined){\\n/** @param {string} path */\\nmaybeRead=(path)=>\\n/** @type {IMPORT('./types.js').ReadFn} */read(path).catch(\\n(_error)=>undefined);}\\n\\n\\n\\nreturn{\\n...powers,\\nread,\\nmaybeRead,\\ncanonical};};exports.unpackReadPowers=unpackReadPowers;\",\n \"node_modules/@endo/env-options/index.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var envOptions=require('./src/env-options.js');exports.environmentOptionsListHas=envOptions.environmentOptionsListHas;exports.getEnvironmentOption=envOptions.getEnvironmentOption;exports.getEnvironmentOptionsList=envOptions.getEnvironmentOptionsList;exports.makeEnvironmentCaptor=envOptions.makeEnvironmentCaptor;\",\n \"node_modules/@endo/env-options/src/env-options.js\": \"'use strict';\\n\\n\\n\\n\\n\\n\\n\\nObject.defineProperty(exports,'__esModule',{value:true});/* global globalThis */ /* @ts-check*/ /* `@endo/env-options` needs to be imported quite early, and so should*/ /* avoid importing from ses or anything that depends on ses.*/ /* /////////////////////////////////////////////////////////////////////////////*/ /* Prelude of cheap good - enough imitations of things we'd use or*/ /* do differently if we could depend on ses*/\\n\\nconst{freeze}=Object;\\nconst{apply}=Reflect;\\n\\n/* Should be equivalent to the one in ses' commons.js even though it*/\\n/* uses the other technique.*/\\nconst uncurryThis=\\n(fn)=>\\n(receiver,...args)=>\\napply(fn,receiver,args);\\nconst arrayPush=uncurryThis(Array.prototype.push);\\nconst arrayIncludes=uncurryThis(Array.prototype.includes);\\nconst stringSplit=uncurryThis(String.prototype.split);\\n\\nconst q=JSON.stringify;\\n\\nconst Fail=(literals,...args)=>{\\nlet msg=literals[0];\\nfor(let i=0;i<args.length;i+=1){\\nmsg=`${msg}${args[i]}${literals[i+1]}`;}\\n\\nthrow Error(msg);};\\n\\n\\n/* end prelude*/\\n/* /////////////////////////////////////////////////////////////////////////////*/\\n\\n/**\\n * `makeEnvironmentCaptor` provides a mechanism for getting environment\\n * variables, if they are needed, and a way to catalog the names of all\\n * the environment variables that were captured.\\n *\\n * @param {object} aGlobal\\n * @param {boolean} [dropNames] Defaults to false. If true, don't track\\n * names used.\\n */\\nconst makeEnvironmentCaptor=(aGlobal,dropNames=false)=>{\\nconst capturedEnvironmentOptionNames=[];\\n\\n/**\\n * Gets an environment option by name and returns the option value or the\\n * given default.\\n *\\n * @param {string} optionName\\n * @param {string} defaultSetting\\n * @param {string[]} [optOtherValues]\\n * If provided, the option value must be included or match `defaultSetting`.\\n * @returns {string}\\n */\\nconst getEnvironmentOption=(\\noptionName,\\ndefaultSetting,\\noptOtherValues=undefined)=>\\n{\\ntypeof optionName==='string'||\\nFail`Environment option name ${q(optionName)} must be a string.`;\\ntypeof defaultSetting==='string'||\\nFail`Environment option default setting ${q(\\ndefaultSetting)\\n} must be a string.`;\\n\\n/** @type {string} */\\nlet setting=defaultSetting;\\nconst globalProcess=aGlobal.process||undefined;\\nconst globalEnv=\\ntypeof globalProcess==='object'&&globalProcess.env||undefined;\\nif(typeof globalEnv==='object'){\\nif(optionName in globalEnv){\\nif(!dropNames){\\narrayPush(capturedEnvironmentOptionNames,optionName);}\\n\\nconst optionValue=globalEnv[optionName];\\n/* eslint-disable-next-line @endo/no-polymorphic-call*/\\ntypeof optionValue==='string'||\\nFail`Environment option named ${q(\\noptionName)\\n}, if present, must have a corresponding string value, got ${q(\\noptionValue)\\n}`;\\nsetting=optionValue;}}\\n\\n\\noptOtherValues===undefined||\\nsetting===defaultSetting||\\narrayIncludes(optOtherValues,setting)||\\nFail`Unrecognized ${q(optionName)} value ${q(\\nsetting)\\n}. Expected one of ${q([defaultSetting,...optOtherValues])}`;\\nreturn setting;};\\n\\nfreeze(getEnvironmentOption);\\n\\n/**\\n * @param {string} optionName\\n * @returns {string[]}\\n */\\nconst getEnvironmentOptionsList=(optionName)=>{\\nconst option=getEnvironmentOption(optionName,'');\\nreturn freeze(option===''?[]:stringSplit(option,','));};\\n\\nfreeze(getEnvironmentOptionsList);\\n\\nconst environmentOptionsListHas=(optionName,element)=>\\narrayIncludes(getEnvironmentOptionsList(optionName),element);\\n\\nconst getCapturedEnvironmentOptionNames=()=>{\\nreturn freeze([...capturedEnvironmentOptionNames]);};\\n\\nfreeze(getCapturedEnvironmentOptionNames);\\n\\nreturn freeze({\\ngetEnvironmentOption,\\ngetEnvironmentOptionsList,\\nenvironmentOptionsListHas,\\ngetCapturedEnvironmentOptionNames});};\\n\\n\\nfreeze(makeEnvironmentCaptor);\\n\\n/**\\n * For the simple case, where the global in question is `globalThis` and no\\n * reporting of option names is desired.\\n */\\nconst{\\ngetEnvironmentOption,\\ngetEnvironmentOptionsList,\\nenvironmentOptionsListHas}=\\nmakeEnvironmentCaptor(globalThis,true);exports.environmentOptionsListHas=environmentOptionsListHas;exports.getEnvironmentOption=getEnvironmentOption;exports.getEnvironmentOptionsList=getEnvironmentOptionsList;exports.makeEnvironmentCaptor=makeEnvironmentCaptor;\",\n \"node_modules/@endo/errors/index.js\": \"'use strict';\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nObject.defineProperty(exports,'__esModule',{value:true});/* global globalThis */ /*/ <reference types=\\\"ses\\\"/>*/ /* This module assumes the existence of a non-standard `assert` host object.*/ /* SES version 0.11.0 introduces this global object and entangles it*/ /* with the `console` host object in scope when it initializes,*/ /* allowing errors, particularly assertion errors, to hide their \\\"details\\\"*/ /* from callers that might catch those errors, then reveal them to the*/ /* underlying console.*/ /* To the extent that this `console` is considered a resource,*/ /* this module must be considered a resource module.*/ /* The assertions re-exported here are defined in*/ /* https://github.com/endojs/endo/blob/HEAD/packages/ses/src/error/assert.js*/\\n\\nconst globalAssert=globalThis.assert;\\n\\nif(globalAssert===undefined){\\nthrow Error(\\n`Cannot initialize @endo/errors, missing globalThis.assert, import 'ses' before '@endo/errors'`);}\\n\\n\\n\\nconst missing=/** @type {const} */[\\n'typeof',\\n'error',\\n'fail',\\n'equal',\\n'string',\\n'note',\\n'details',\\n'Fail',\\n'quote',\\n/* As of 2024-02, the Agoric chain's bootstrap vat runs with a version of SES that*/\\n/* predates addition of the 'bare' method, so we must tolerate its absence and fall*/\\n/* back to quote behavior in that environment (see below).*/\\n/* 'bare',*/\\n'makeAssert'].\\nfilter((name)=>globalAssert[name]===undefined);\\nif(missing.length>0){\\nthrow Error(\\n`Cannot initialize @endo/errors, missing globalThis.assert methods ${missing.join(\\n', ')\\n}`);}\\n\\n\\n\\n/* The global assert mixed assertions and utility functions.*/\\n/* This module splits them apart*/\\n/* and also updates the names of the utility functions.*/\\nconst{\\nbare,\\ndetails:redacted,\\nerror:makeError,\\nFail:throwRedacted,\\nmakeAssert:_omittedMakeAssert,\\nnote,\\nquote,\\n...assertions}=\\nglobalAssert;\\n/** @type {IMPORT(\\\"ses\\\").AssertionFunctions } */\\n/* @ts-expect-error missing properties assigned next*/\\nconst assert=(value,optDetails,errContructor,options)=>\\nglobalAssert(value,optDetails,errContructor,options);\\nObject.assign(assert,assertions);\\n\\n/* As of 2024-02, the Agoric chain's bootstrap vat runs with a version of SES*/\\n/* that predates the addition of the 'bare' method, so we must fall back to*/\\n/* quote behavior for that environment.*/\\nconst bareOrQuote=bare||quote;exports.Fail=throwRedacted;exports.X=redacted;exports.annotateError=note;exports.assert=assert;exports.b=bareOrQuote;exports.bare=bareOrQuote;exports.makeError=makeError;exports.note=note;exports.q=quote;exports.quote=quote;exports.redacted=redacted;exports.throwRedacted=throwRedacted;\",\n \"node_modules/@endo/eventual-send/src/E.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var trackTurns=require('./track-turns.js');var messageBreakpoints=require('./message-breakpoints.js');\\n\\n\\nconst{details:X,quote:q,Fail}=assert;\\nconst{assign,create}=Object;\\n\\nconst onSend=messageBreakpoints.makeMessageBreakpointTester('ENDO_SEND_BREAKPOINTS');\\n\\n/** @type {ProxyHandler<any>} */\\nconst baseFreezableProxyHandler={\\nset(_target,_prop,_value){\\nreturn false;},\\n\\nisExtensible(_target){\\nreturn false;},\\n\\nsetPrototypeOf(_target,_value){\\nreturn false;},\\n\\ndeleteProperty(_target,_prop){\\nreturn false;}};\\n\\n\\n\\n/* E Proxy handlers pretend that any property exists on the target and returns*/\\n/* a function for their value. While this function is \\\"bound\\\" by context, it is*/\\n/* meant to be called as a method. For that reason, the returned function*/\\n/* includes a check that the `this` argument corresponds to the initial*/\\n/* receiver when the function was retrieved.*/\\n/* E Proxy handlers also forward direct calls to the target in case the remote*/\\n/* is a function instead of an object. No such receiver checks are necessary in*/\\n/* that case.*/\\n\\n/**\\n * A Proxy handler for E(x).\\n *\\n * @param {any} recipient Any value passed to E(x)\\n * @param {IMPORT('./types').HandledPromiseConstructor} HandledPromise\\n * @returns {ProxyHandler} the Proxy handler\\n */\\nconst makeEProxyHandler=(recipient,HandledPromise)=>\\nharden({\\n...baseFreezableProxyHandler,\\nget:(_target,propertyKey,receiver)=>{\\nreturn harden(\\n{\\n/* This function purposely checks the `this` value (see above)*/\\n/* In order to be `this` sensitive it is defined using concise method*/\\n/* syntax rather than as an arrow function. To ensure the function*/\\n/* is not constructable, it also avoids the `function` syntax.*/\\n[propertyKey](...args){\\nif(this!==receiver){\\n/* Reject the async function call*/\\nreturn HandledPromise.reject(\\nassert.error(\\nX`Unexpected receiver for \\\"${q(propertyKey)}\\\" method of E(${q(\\nrecipient)\\n})`));}\\n\\n\\n\\n\\nif(onSend&&onSend.shouldBreakpoint(recipient,propertyKey)){\\n/* eslint-disable-next-line no-debugger*/\\ndebugger;/* LOOK UP THE STACK*/\\n/* Stopped at a breakpoint on eventual-send of a method-call*/\\n/* message,*/\\n/* so that you can walk back on the stack to see how we came to*/\\n/* make this eventual-send*/}\\n\\nreturn HandledPromise.applyMethod(recipient,propertyKey,args);}\\n\\n/* @ts-expect-error https://github.com/microsoft/TypeScript/issues/50319*/}[\\npropertyKey]);},\\n\\n\\napply:(_target,_thisArg,argArray=[])=>{\\nif(onSend&&onSend.shouldBreakpoint(recipient,undefined)){\\n/* eslint-disable-next-line no-debugger*/\\ndebugger;/* LOOK UP THE STACK*/\\n/* Stopped at a breakpoint on eventual-send of a function-call message,*/\\n/* so that you can walk back on the stack to see how we came to*/\\n/* make this eventual-send*/}\\n\\nreturn HandledPromise.applyFunction(recipient,argArray);},\\n\\nhas:(_target,_p)=>{\\n/* We just pretend everything exists.*/\\nreturn true;}});\\n\\n\\n\\n/**\\n * A Proxy handler for E.sendOnly(x)\\n * It is a variant on the E(x) Proxy handler.\\n *\\n * @param {any} recipient Any value passed to E.sendOnly(x)\\n * @param {IMPORT('./types').HandledPromiseConstructor} HandledPromise\\n * @returns {ProxyHandler} the Proxy handler\\n */\\nconst makeESendOnlyProxyHandler=(recipient,HandledPromise)=>\\nharden({\\n...baseFreezableProxyHandler,\\nget:(_target,propertyKey,receiver)=>{\\nreturn harden(\\n{\\n/* This function purposely checks the `this` value (see above)*/\\n/* In order to be `this` sensitive it is defined using concise method*/\\n/* syntax rather than as an arrow function. To ensure the function*/\\n/* is not constructable, it also avoids the `function` syntax.*/\\n[propertyKey](...args){\\n/* Throw since the function returns nothing*/\\nthis===receiver||\\nFail`Unexpected receiver for \\\"${q(\\npropertyKey)\\n}\\\" method of E.sendOnly(${q(recipient)})`;\\nif(onSend&&onSend.shouldBreakpoint(recipient,propertyKey)){\\n/* eslint-disable-next-line no-debugger*/\\ndebugger;/* LOOK UP THE STACK*/\\n/* Stopped at a breakpoint on eventual-send of a method-call*/\\n/* message,*/\\n/* so that you can walk back on the stack to see how we came to*/\\n/* make this eventual-send*/}\\n\\nHandledPromise.applyMethodSendOnly(recipient,propertyKey,args);\\nreturn undefined;}\\n\\n/* @ts-expect-error https://github.com/microsoft/TypeScript/issues/50319*/}[\\npropertyKey]);},\\n\\n\\napply:(_target,_thisArg,argsArray=[])=>{\\nif(onSend&&onSend.shouldBreakpoint(recipient,undefined)){\\n/* eslint-disable-next-line no-debugger*/\\ndebugger;/* LOOK UP THE STACK*/\\n/* Stopped at a breakpoint on eventual-send of a function-call message,*/\\n/* so that you can walk back on the stack to see how we came to*/\\n/* make this eventual-send*/}\\n\\nHandledPromise.applyFunctionSendOnly(recipient,argsArray);\\nreturn undefined;},\\n\\nhas:(_target,_p)=>{\\n/* We just pretend that everything exists.*/\\nreturn true;}});\\n\\n\\n\\n/**\\n * A Proxy handler for E.get(x)\\n * It is a variant on the E(x) Proxy handler.\\n *\\n * @param {any} x Any value passed to E.get(x)\\n * @param {IMPORT('./types').HandledPromiseConstructor} HandledPromise\\n * @returns {ProxyHandler} the Proxy handler\\n */\\nconst makeEGetProxyHandler=(x,HandledPromise)=>\\nharden({\\n...baseFreezableProxyHandler,\\nhas:(_target,_prop)=>true,\\nget:(_target,prop)=>HandledPromise.get(x,prop)});\\n\\n\\n/**\\n * @param {IMPORT('./types').HandledPromiseConstructor} HandledPromise\\n */\\nconst makeE=(HandledPromise)=>{\\nreturn harden(\\nassign(\\n/**\\n * E(x) returns a proxy on which you can call arbitrary methods. Each of these\\n * method calls returns a promise. The method will be invoked on whatever\\n * 'x' designates (or resolves to) in a future turn, not this one.\\n *\\n * @template T\\n * @param {T} x target for method/function call\\n * @returns {ECallableOrMethods<RemoteFunctions<T>>} method/function call proxy\\n */\\n(x)=>harden(new Proxy(()=>{},makeEProxyHandler(x,HandledPromise))),\\n{\\n/**\\n * E.get(x) returns a proxy on which you can get arbitrary properties.\\n * Each of these properties returns a promise for the property. The promise\\n * value will be the property fetched from whatever 'x' designates (or\\n * resolves to) in a future turn, not this one.\\n *\\n * @template T\\n * @param {T} x target for property get\\n * @returns {EGetters<LocalRecord<T>>} property get proxy\\n * @readonly\\n */\\nget:(x)=>\\nharden(\\nnew Proxy(create(null),makeEGetProxyHandler(x,HandledPromise))),\\n\\n\\n/**\\n * E.resolve(x) converts x to a handled promise. It is\\n * shorthand for HandledPromise.resolve(x)\\n *\\n * @template T\\n * @param {T} x value to convert to a handled promise\\n * @returns {Promise<Awaited<T>>} handled promise for x\\n * @readonly\\n */\\nresolve:HandledPromise.resolve,\\n\\n/**\\n * E.sendOnly returns a proxy similar to E, but for which the results\\n * are ignored (undefined is returned).\\n *\\n * @template T\\n * @param {T} x target for method/function call\\n * @returns {ESendOnlyCallableOrMethods<RemoteFunctions<T>>} method/function call proxy\\n * @readonly\\n */\\nsendOnly:(x)=>\\nharden(\\nnew Proxy(()=>{},makeESendOnlyProxyHandler(x,HandledPromise))),\\n\\n\\n/**\\n * E.when(x, res, rej) is equivalent to\\n * HandledPromise.resolve(x).then(res, rej)\\n *\\n * @template T\\n * @template [U = T]\\n * @param {T|PromiseLike<T>} x value to convert to a handled promise\\n * @param {(value: T) => ERef<U>} [onfulfilled]\\n * @param {(reason: any) => ERef<U>} [onrejected]\\n * @returns {Promise<U>}\\n * @readonly\\n */\\nwhen:(x,onfulfilled,onrejected)=>\\nHandledPromise.resolve(x).then(\\n...trackTurns.trackTurns([onfulfilled,onrejected]))}));};\\n\\n\\n\\n\\n\\n\\n\\n\\n/** @typedef {ReturnType<makeE>} EProxy */\\n\\n/**\\n * Creates a type that accepts both near and marshalled references that were\\n * returned from `Remotable` or `Far`, and also promises for such references.\\n *\\n * @template Primary The type of the primary reference.\\n * @template [Local=DataOnly<Primary>] The local properties of the object.\\n * @typedef {ERef<Local & IMPORT('./types').RemotableBrand<Local, Primary>>} FarRef\\n */\\n\\n/**\\n * `DataOnly<T>` means to return a record type `T2` consisting only of\\n * properties that are *not* functions.\\n *\\n * @template T The type to be filtered.\\n * @typedef {Omit<T, FilteredKeys<T, IMPORT('./types').Callable>>} DataOnly\\n */\\n\\n/**\\n * @see {@link https://github.com/microsoft/TypeScript/issues/31394}\\n * @template T\\n * @typedef {PromiseLike<T> | T} ERef\\n */\\n\\n/**\\n * @template {IMPORT('./types').Callable} T\\n * @typedef {(\\n * ReturnType<T> extends PromiseLike<infer U> // if function returns a promise\\n * ? T // return the function\\n * : (...args: Parameters<T>) => Promise<Awaited<ReturnType<T>>> // make it return a promise\\n * )} ECallable\\n */\\n\\n/**\\n * @template T\\n * @typedef {{\\n * readonly [P in keyof T]: T[P] extends IMPORT('./types').Callable\\n * ? ECallable<T[P]>\\n * : never;\\n * }} EMethods\\n */\\n\\n/**\\n * @template T\\n * @typedef {{\\n * readonly [P in keyof T]: T[P] extends PromiseLike<infer U>\\n * ? T[P]\\n * : Promise<Awaited<T[P]>>;\\n * }} EGetters\\n */\\n\\n/**\\n * @template {IMPORT('./types').Callable} T\\n * @typedef {(...args: Parameters<T>) => Promise<void>} ESendOnlyCallable\\n */\\n\\n/**\\n * @template T\\n * @typedef {{\\n * readonly [P in keyof T]: T[P] extends IMPORT('./types').Callable\\n * ? ESendOnlyCallable<T[P]>\\n * : never;\\n * }} ESendOnlyMethods\\n */\\n\\n/**\\n * @template T\\n * @typedef {(\\n * T extends IMPORT('./types').Callable\\n * ? ESendOnlyCallable<T> & ESendOnlyMethods<Required<T>>\\n * : ESendOnlyMethods<Required<T>>\\n * )} ESendOnlyCallableOrMethods\\n */\\n\\n/**\\n * @template T\\n * @typedef {(\\n * T extends IMPORT('./types').Callable\\n * ? ECallable<T> & EMethods<Required<T>>\\n * : EMethods<Required<T>>\\n * )} ECallableOrMethods\\n */\\n\\n/**\\n * Return a union of property names/symbols/numbers P for which the record element T[P]'s type extends U.\\n *\\n * Given const x = { a: 123, b: 'hello', c: 42, 49: () => {}, 53: 67 },\\n *\\n * FilteredKeys<typeof x, number> is the type 'a' | 'c' | 53.\\n * FilteredKeys<typeof x, string> is the type 'b'.\\n * FilteredKeys<typeof x, 42 | 67> is the type 'c' | 53.\\n * FilteredKeys<typeof x, boolean> is the type never.\\n *\\n * @template T\\n * @template U\\n * @typedef {{ [P in keyof T]: T[P] extends U ? P : never; }[keyof T]} FilteredKeys\\n */\\n\\n/**\\n * `PickCallable<T>` means to return a single root callable or a record type\\n * consisting only of properties that are functions.\\n *\\n * @template T\\n * @typedef {(\\n * T extends IMPORT('./types').Callable\\n * ? (...args: Parameters<T>) => ReturnType<T> // a root callable, no methods\\n * : Pick<T, FilteredKeys<T, IMPORT('./types').Callable>> // any callable methods\\n * )} PickCallable\\n */\\n\\n/**\\n * `RemoteFunctions<T>` means to return the functions and properties that are remotely callable.\\n *\\n * @template T\\n * @typedef {(\\n * T extends IMPORT('./types').RemotableBrand<infer L, infer R> // if a given T is some remote interface R\\n * ? PickCallable<R> // then return the callable properties of R\\n * : Awaited<T> extends IMPORT('./types').RemotableBrand<infer L, infer R> // otherwise, if the final resolution of T is some remote interface R\\n * ? PickCallable<R> // then return the callable properties of R\\n * : T extends PromiseLike<infer U> // otherwise, if T is a promise\\n * ? Awaited<T> // then return resolved value T\\n * : T // otherwise, return T\\n * )} RemoteFunctions\\n */\\n\\n/**\\n * @template T\\n * @typedef {(\\n * T extends IMPORT('./types').RemotableBrand<infer L, infer R>\\n * ? L\\n * : Awaited<T> extends IMPORT('./types').RemotableBrand<infer L, infer R>\\n * ? L\\n * : T extends PromiseLike<infer U>\\n * ? Awaited<T>\\n * : T\\n * )} LocalRecord\\n */\\n\\n/**\\n * @template [R = unknown]\\n * @typedef {{\\n * promise: Promise<R>;\\n * settler: IMPORT('./types').Settler<R>;\\n * }} EPromiseKit\\n */\\n\\n/**\\n * Type for an object that must only be invoked with E. It supports a given\\n * interface but declares all the functions as asyncable.\\n *\\n * @template T\\n * @typedef {(\\n * T extends IMPORT('./types').Callable\\n * ? (...args: Parameters<T>) => ERef<Awaited<EOnly<ReturnType<T>>>>\\n * : T extends Record<PropertyKey, IMPORT('./types').Callable>\\n * ? {\\n * [K in keyof T]: T[K] extends IMPORT('./types').Callable\\n * ? (...args: Parameters<T[K]>) => ERef<Awaited<EOnly<ReturnType<T[K]>>>>\\n * : T[K];\\n * }\\n * : T\\n * )} EOnly\\n */exports[\\\"default\\\"]=makeE;\",\n \"node_modules/@endo/eventual-send/src/exports.js\": \"'use strict';/* Just a dummy to use exports.d.ts and satisfy runtime imports.*/\",\n \"node_modules/@endo/eventual-send/src/local.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var messageBreakpoints=require('./message-breakpoints.js');\\n\\nconst{details:X,quote:q,Fail}=assert;\\n\\nconst{getOwnPropertyDescriptors,getPrototypeOf,freeze}=Object;\\nconst{apply,ownKeys}=Reflect;\\n\\nconst ntypeof=(specimen)=>specimen===null?'null':typeof specimen;\\n\\nconst onDelivery=messageBreakpoints.makeMessageBreakpointTester('ENDO_DELIVERY_BREAKPOINTS');\\n\\n/**\\n * TODO Consolidate with `isObject` that's currently in `@endo/marshal`\\n *\\n * @param {any} val\\n * @returns {boolean}\\n */\\nconst isObject=(val)=>Object(val)===val;\\n\\n/**\\n * Prioritize symbols as earlier than strings.\\n *\\n * @param {string|symbol} a\\n * @param {string|symbol} b\\n * @returns {-1 | 0 | 1}\\n */\\nconst compareStringified=(a,b)=>{\\nif(typeof a===typeof b){\\nconst left=String(a);\\nconst right=String(b);\\n/* eslint-disable-next-line no-nested-ternary*/\\nreturn left<right?-1:left>right?1:0;}\\n\\nif(typeof a==='symbol'){\\nassert(typeof b==='string');\\nreturn-1;}\\n\\nassert(typeof a==='string');\\nassert(typeof b==='symbol');\\nreturn 1;};\\n\\n\\n/**\\n * @param {any} val\\n * @returns {(string|symbol)[]}\\n */\\nconst getMethodNames=(val)=>{\\nlet layer=val;\\nconst names=new Set();/* Set to deduplicate*/\\nwhile(layer!==null&&layer!==Object.prototype){\\n/* be tolerant of non-objects*/\\nconst descs=getOwnPropertyDescriptors(layer);\\nfor(const name of ownKeys(descs)){\\n/* In case a method is overridden by a non-method,*/\\n/* test `val[name]` rather than `layer[name]`*/\\nif(typeof val[name]==='function'){\\nnames.add(name);}}\\n\\n\\nif(!isObject(val)){\\nbreak;}\\n\\nlayer=getPrototypeOf(layer);}\\n\\nreturn harden([...names].sort(compareStringified));};\\n\\n/* The top level of the eventual send modules can be evaluated before*/\\n/* ses creates `harden`, and so cannot rely on `harden` at top level.*/\\nfreeze(getMethodNames);\\n\\nconst localApplyFunction=(recipient,args)=>{\\ntypeof recipient==='function'||\\nassert.fail(\\nX`Cannot invoke target as a function; typeof target is ${q(\\nntypeof(recipient))\\n}`,\\nTypeError);\\n\\nif(onDelivery&&onDelivery.shouldBreakpoint(recipient,undefined)){\\n/* eslint-disable-next-line no-debugger*/\\ndebugger;/* STEP INTO APPLY*/\\n/* Stopped at a breakpoint on this delivery of an eventual function call*/\\n/* so that you can step *into* the following `apply` in order to see the*/\\n/* function call as it happens. Or step *over* to see what happens*/\\n/* after the function call returns.*/}\\n\\nconst result=apply(recipient,undefined,args);\\nreturn result;};\\n\\n\\nconst localApplyMethod=(recipient,methodName,args)=>{\\nif(methodName===undefined||methodName===null){\\n/* Base case; bottom out to apply functions.*/\\nreturn localApplyFunction(recipient,args);}\\n\\nif(recipient===undefined||recipient===null){\\nassert.fail(\\nX`Cannot deliver ${q(methodName)} to target; typeof target is ${q(\\nntypeof(recipient))\\n}`,\\nTypeError);}\\n\\n\\nconst fn=recipient[methodName];\\nif(fn===undefined){\\nassert.fail(\\nX`target has no method ${q(methodName)}, has ${q(\\ngetMethodNames(recipient))\\n}`,\\nTypeError);}\\n\\n\\nconst ftype=ntypeof(fn);\\ntypeof fn==='function'||\\nFail`invoked method ${q(methodName)} is not a function; it is a ${q(\\nftype)\\n}`;\\nif(onDelivery&&onDelivery.shouldBreakpoint(recipient,methodName)){\\n/* eslint-disable-next-line no-debugger*/\\ndebugger;/* STEP INTO APPLY*/\\n/* Stopped at a breakpoint on this delivery of an eventual method call*/\\n/* so that you can step *into* the following `apply` in order to see the*/\\n/* method call as it happens. Or step *over* to see what happens*/\\n/* after the method call returns.*/}\\n\\nconst result=apply(fn,recipient,args);\\nreturn result;};\\n\\n\\nconst localGet=(t,key)=>t[key];exports.getMethodNames=getMethodNames;exports.localApplyFunction=localApplyFunction;exports.localApplyMethod=localApplyMethod;exports.localGet=localGet;\",\n \"node_modules/@endo/eventual-send/src/message-breakpoints.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../env-options/index.js');var envOptions=require('../../env-options/src/env-options.js');\\n\\nconst{quote:q,Fail}=assert;\\n\\nconst{hasOwn,freeze,entries}=Object;\\n\\n/**\\n * @typedef {string | '*'} MatchStringTag\\n * A star `'*'` matches any recipient. Otherwise, the string is\\n * matched against the value of a recipient's `@@toStringTag`\\n * after stripping out any leading `'Alleged: '` or `'DebugName: '`\\n * prefix. For objects defined with `Far` this is the first argument,\\n * known as the `farName`. For exos, this is the tag.\\n */\\n/**\\n * @typedef {string | '*'} MatchMethodName\\n * A star `'*'` matches any method name. Otherwise, the string is\\n * matched against the method name. Currently, this is only an exact match.\\n * However, beware that we may introduce a string syntax for\\n * symbol method names.\\n */\\n/**\\n * @typedef {number | '*'} MatchCountdown\\n * A star `'*'` will always breakpoint. Otherwise, the string\\n * must be a non-negative integer. Once that is zero, always breakpoint.\\n * Otherwise decrement by one each time it matches until it reaches zero.\\n * In other words, the countdown represents the number of\\n * breakpoint occurrences to skip before actually breakpointing.\\n */\\n\\n/**\\n * This is the external JSON representation, in which\\n * - the outer property name is the class-like tag or '*',\\n * - the inner property name is the method name or '*',\\n * - the value is a non-negative integer countdown or '*'.\\n *\\n * @typedef {Record<MatchStringTag, Record<MatchMethodName, MatchCountdown>>} MessageBreakpoints\\n */\\n\\n/**\\n * This is the internal JSON representation, in which\\n * - the outer property name is the method name or '*',\\n * - the inner property name is the class-like tag or '*',\\n * - the value is a non-negative integer countdown or '*'.\\n *\\n * @typedef {Record<MatchMethodName, Record<MatchStringTag, MatchCountdown>>} BreakpointTable\\n */\\n\\n/**\\n * @typedef {object} MessageBreakpointTester\\n * @property {() => MessageBreakpoints} getBreakpoints\\n * @property {(newBreakpoints?: MessageBreakpoints) => void} setBreakpoints\\n * @property {(\\n * recipient: object,\\n * methodName: string | symbol | undefined\\n * ) => boolean} shouldBreakpoint\\n */\\n\\n/**\\n * @param {any} val\\n * @returns {val is Record<string, any>}\\n */\\nconst isJSONRecord=(val)=>\\ntypeof val==='object'&&val!==null&&!Array.isArray(val);\\n\\n/**\\n * Return `tag` after stripping off any `'Alleged: '` or `'DebugName: '`\\n * prefix if present.\\n * ```js\\n * simplifyTag('Alleged: moola issuer') === 'moola issuer'\\n * ```\\n * If there are multiple such prefixes, only the outer one is removed.\\n *\\n * @param {string} tag\\n * @returns {string}\\n */\\nconst simplifyTag=(tag)=>{\\nfor(const prefix of['Alleged: ','DebugName: ']){\\nif(tag.startsWith(prefix)){\\nreturn tag.slice(prefix.length);}}\\n\\n\\nreturn tag;};\\n\\n\\n/**\\n * @param {string} optionName\\n * @returns {MessageBreakpointTester | undefined}\\n */\\nconst makeMessageBreakpointTester=(optionName)=>{\\nlet breakpoints=JSON.parse(envOptions.getEnvironmentOption(optionName,'null'));\\n\\nif(breakpoints===null){\\nreturn undefined;}\\n\\n\\n/** @type {BreakpointTable} */\\nlet breakpointsTable;\\n\\nconst getBreakpoints=()=>breakpoints;\\nfreeze(getBreakpoints);\\n\\nconst setBreakpoints=(newBreakpoints=breakpoints)=>{\\nisJSONRecord(newBreakpoints)||\\nFail`Expected ${q(optionName)} option to be a JSON breakpoints record`;\\n\\n/** @type {BreakpointTable} */\\n/* @ts-expect-error confused by __proto__*/\\nconst newBreakpointsTable={__proto__:null};\\n\\nfor(const[tag,methodBPs]of entries(newBreakpoints)){\\ntag===simplifyTag(tag)||\\nFail`Just use simple tag ${q(simplifyTag(tag))} rather than ${q(tag)}`;\\nisJSONRecord(methodBPs)||\\nFail`Expected ${q(optionName)} option's ${q(\\ntag)\\n} to be a JSON methods breakpoints record`;\\nfor(const[methodName,count]of entries(methodBPs)){\\ncount==='*'||\\ntypeof count==='number'&&\\nNumber.isSafeInteger(count)&&\\ncount>=0||\\nFail`Expected ${q(optionName)} option's ${q(tag)}.${q(\\nmethodName)\\n} to be \\\"*\\\" or a non-negative integer`;\\n\\nconst classBPs=hasOwn(newBreakpointsTable,methodName)?\\nnewBreakpointsTable[methodName]:\\nnewBreakpointsTable[methodName]={\\n/* @ts-expect-error confused by __proto__*/\\n__proto__:null};\\n\\nclassBPs[tag]=count;}}\\n\\n\\nbreakpoints=newBreakpoints;\\nbreakpointsTable=newBreakpointsTable;};\\n\\nfreeze(setBreakpoints);\\n\\nconst shouldBreakpoint=(recipient,methodName)=>{\\nif(methodName===undefined||methodName===null){\\n/* TODO enable function breakpointing*/\\nreturn false;}\\n\\nconst classBPs=breakpointsTable[methodName]||breakpointsTable['*'];\\nif(classBPs===undefined){\\nreturn false;}\\n\\nlet tag=simplifyTag(recipient[Symbol.toStringTag]);\\nlet count=classBPs[tag];\\nif(count===undefined){\\ntag='*';\\ncount=classBPs[tag];\\nif(count===undefined){\\nreturn false;}}\\n\\n\\nif(count==='*'){\\nreturn true;}\\n\\nif(count===0){\\nreturn true;}\\n\\nassert(typeof count==='number'&&count>=1);\\nclassBPs[tag]=count-1;\\nreturn false;};\\n\\nfreeze(shouldBreakpoint);\\n\\nconst breakpointTester=freeze({\\ngetBreakpoints,\\nsetBreakpoints,\\nshouldBreakpoint});\\n\\nbreakpointTester.setBreakpoints();\\nreturn breakpointTester;};\\n\\nfreeze(makeMessageBreakpointTester);exports.makeMessageBreakpointTester=makeMessageBreakpointTester;\",\n \"node_modules/@endo/eventual-send/src/no-shim.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var E$1=require('./E.js');require('./exports.js');\\n\\nconst hp=HandledPromise;\\nconst E=E$1[\\\"default\\\"](hp);exports.E=E;exports.HandledPromise=hp;\",\n \"node_modules/@endo/eventual-send/src/track-turns.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../env-options/index.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nenvOptions=require('../../env-options/src/env-options.js');/* global globalThis */ /* NOTE: We can't import these because they're not in scope before lockdown.*/ /* import { assert, details as X, Fail } from '@agoric/assert';*/ /* WARNING: Global Mutable State!*/ /* This state is communicated to `assert` that makes it available to the*/ /* causal console, which affects the console log output. Normally we*/ /* regard the ability to see console log output as a meta-level privilege*/ /* analogous to the ability to debug. Aside from that, this module should*/ /* not have any observably mutable state.*/\\n\\nlet hiddenPriorError;\\nlet hiddenCurrentTurn=0;\\nlet hiddenCurrentEvent=0;\\n\\n/* Turn on if you seem to be losing error logging at the top of the event loop*/\\nconst VERBOSE=envOptions.environmentOptionsListHas('DEBUG','track-turns');\\n\\n/* Track-turns is disabled by default and can be enabled by an environment*/\\n/* option.*/\\nconst ENABLED=\\nenvOptions.getEnvironmentOption('TRACK_TURNS','disabled',['enabled'])==='enabled';\\n\\n/* We hoist the following functions out of trackTurns() to discourage the*/\\n/* closures from holding onto 'args' or 'func' longer than necessary,*/\\n/* which we've seen cause HandledPromise arguments to be retained for*/\\n/* a surprisingly long time.*/\\n\\nconst addRejectionNote=(detailsNote)=>(reason)=>{\\nif(reason instanceof Error){\\nassert.note(reason,detailsNote);}\\n\\nif(VERBOSE){\\nconsole.log('REJECTED at top of event loop',reason);}};\\n\\n\\n\\nconst wrapFunction=\\n(func,sendingError,X)=>\\n(...args)=>{\\nhiddenPriorError=sendingError;\\nhiddenCurrentTurn+=1;\\nhiddenCurrentEvent=0;\\ntry{\\nlet result;\\ntry{\\nresult=func(...args);}\\ncatch(err){\\nif(err instanceof Error){\\nassert.note(\\nerr,\\nX`Thrown from: ${hiddenPriorError}:${hiddenCurrentTurn}.${hiddenCurrentEvent}`);}\\n\\n\\nif(VERBOSE){\\nconsole.log('THROWN to top of event loop',err);}\\n\\nthrow err;}\\n\\n/* Must capture this now, not when the catch triggers.*/\\nconst detailsNote=X`Rejection from: ${hiddenPriorError}:${hiddenCurrentTurn}.${hiddenCurrentEvent}`;\\nPromise.resolve(result).catch(addRejectionNote(detailsNote));\\nreturn result;}finally\\n{\\nhiddenPriorError=undefined;}};\\n\\n\\n\\n/**\\n * Given a list of `TurnStarterFn`s, returns a list of `TurnStarterFn`s whose\\n * `this`-free call behaviors are not observably different to those that\\n * cannot see console output. The only purpose is to cause additional\\n * information to appear on the console.\\n *\\n * The call to `trackTurns` is itself a sending event, that occurs in some call\\n * stack in some turn number at some event number within that turn. Each call\\n * to any of the returned `TurnStartFn`s is a receiving event that begins a new\\n * turn. This sending event caused each of those receiving events.\\n *\\n * @template {TurnStarterFn[]} T\\n * @param {T} funcs\\n * @returns {T}\\n */\\nconst trackTurns=(funcs)=>{\\nif(!ENABLED||typeof globalThis==='undefined'||!globalThis.assert){\\nreturn funcs;}\\n\\nconst{details:X}=assert;\\n\\nhiddenCurrentEvent+=1;\\nconst sendingError=Error(\\n`Event: ${hiddenCurrentTurn}.${hiddenCurrentEvent}`);\\n\\nif(hiddenPriorError!==undefined){\\nassert.note(sendingError,X`Caused by: ${hiddenPriorError}`);}\\n\\n\\nreturn(/** @type {T} */\\nfuncs.map((func)=>func&&wrapFunction(func,sendingError,X)));};\\n\\n\\n\\n/**\\n * An optional function that is not this-sensitive, expected to be called at\\n * bottom of stack to start a new turn.\\n *\\n * @typedef {((...args: any[]) => any) | undefined} TurnStarterFn\\n */exports.trackTurns=trackTurns;\",\n \"node_modules/@endo/eventual-send/utils.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var local=require('./src/local.js');var messageBreakpoints=require('./src/message-breakpoints.js');exports.getMethodNames=local.getMethodNames;exports.makeMessageBreakpointTester=messageBreakpoints.makeMessageBreakpointTester;\",\n \"node_modules/@endo/exo/index.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var exoMakers=require('./src/exo-makers.js');require('./src/types.js');var getInterface=require('./src/get-interface.js');exports.defineExoClass=exoMakers.defineExoClass;exports.defineExoClassKit=exoMakers.defineExoClassKit;exports.initEmpty=exoMakers.initEmpty;exports.makeExo=exoMakers.makeExo;exports.GET_INTERFACE_GUARD=getInterface.GET_INTERFACE_GUARD;\",\n \"node_modules/@endo/exo/src/exo-makers.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var objectMap=require('../../common/object-map.js');require('../../env-options/index.js');var index=require('../../errors/index.js');var exoTools=require('./exo-tools.js');var\\n\\n\\n\\n\\n\\n\\nenvOptions=require('../../env-options/src/env-options.js');/*/ <reference types=\\\"ses\\\"/>*/ /**\\n * @import {Amplify, ExoClassKitMethods, ExoClassMethods, FarClassOptions, Guarded, GuardedKit, ExoClassInterfaceGuardKit, IsInstance, KitContext, ExoClassInterfaceGuard, Methods, FacetName} from './types.js';\\n */\\n\\nconst{create,seal,freeze,defineProperty,values}=Object;\\n\\n/* Turn on to give each exo instance its own toStringTag value.*/\\nconst LABEL_INSTANCES=envOptions.environmentOptionsListHas('DEBUG','label-instances');\\n\\n/**\\n * @template {{}} T\\n * @param {T} proto\\n * @param {number} instanceCount\\n * @returns {T}\\n */\\nconst makeSelf=(proto,instanceCount)=>{\\nconst self=create(proto);\\nif(LABEL_INSTANCES){\\ndefineProperty(self,Symbol.toStringTag,{\\nvalue:`${proto[Symbol.toStringTag]}#${instanceCount}`,\\nwritable:false,\\nenumerable:false,\\nconfigurable:false});}\\n\\n\\nreturn harden(self);};\\n\\n\\nconst emptyRecord=harden({});\\n\\n/**\\n * When calling `defineDurableKind` and\\n * its siblings, used as the `init` function argument to indicate that the\\n * state record of the (virtual/durable) instances of the kind/exoClass\\n * should be empty, and that the returned maker function should have zero\\n * parameters.\\n *\\n * @returns {{}}\\n */\\nconst initEmpty=()=>emptyRecord;\\n\\n/**\\n * @template {(...args: any[]) => any} I init function\\n * @template {Methods} M methods\\n * @param {string} tag\\n * @param {ExoClassInterfaceGuard<M> | undefined} interfaceGuard\\n * @param {I} init\\n * @param {ExoClassMethods<M, I>} methods\\n * @param {FarClassOptions<IMPORT('./types.js').ClassContext<ReturnType<I>, M>>} [options]\\n * @returns {(...args: Parameters<I>) => Guarded<M>}\\n */\\nconst defineExoClass=(\\ntag,\\ninterfaceGuard,\\ninit,\\nmethods,\\noptions={})=>\\n{\\nharden(methods);\\nconst{\\nfinish=undefined,\\nreceiveAmplifier=undefined,\\nreceiveInstanceTester=undefined}=\\noptions;\\nreceiveAmplifier===undefined||\\nindex.throwRedacted`Only facets of an exo class kit can be amplified ${index.quote(tag)}`;\\n\\n/** @type {WeakMap<M, IMPORT('./types.js').ClassContext<ReturnType<I>, M>>} */\\nconst contextMap=new WeakMap();\\nconst proto=exoTools.defendPrototype(\\ntag,\\n(self)=>/** @type {any} */contextMap.get(self),\\nmethods,\\ntrue,\\ninterfaceGuard);\\n\\nlet instanceCount=0;\\n/**\\n * @param {Parameters<I>} args\\n */\\nconst makeInstance=(...args)=>{\\n/* Be careful not to freeze the state record*/\\nconst state=seal(init(...args));\\ninstanceCount+=1;\\nconst self=makeSelf(proto,instanceCount);\\n\\n/* Be careful not to freeze the state record*/\\n/** @type {IMPORT('./types.js').ClassContext<ReturnType<I>,M>} */\\nconst context=freeze({state,self});\\ncontextMap.set(self,context);\\nif(finish){\\nfinish(context);}\\n\\nreturn self;};\\n\\n\\nif(receiveInstanceTester){\\n/** @type {IsInstance} */\\nconst isInstance=(exo,facetName=undefined)=>{\\nfacetName===undefined||\\nindex.throwRedacted`facetName can only be used with an exo class kit: ${index.quote(\\ntag)\\n} has no facet ${index.quote(facetName)}`;\\nreturn contextMap.has(exo);};\\n\\nharden(isInstance);\\nreceiveInstanceTester(isInstance);}\\n\\n\\nreturn harden(makeInstance);};\\n\\nharden(defineExoClass);\\n\\n/**\\n * @template {(...args: any[]) => any} I init function\\n * @template {Record<FacetName, Methods>} F facet methods\\n * @param {string} tag\\n * @param {ExoClassInterfaceGuardKit<F> | undefined } interfaceGuardKit\\n * @param {I} init\\n * @param {ExoClassKitMethods<F, I>} methodsKit\\n * @param {FarClassOptions<\\n * KitContext<ReturnType<I>, GuardedKit<F>>,\\n * GuardedKit<F>\\n * >} [options]\\n * @returns {(...args: Parameters<I>) => GuardedKit<F>}\\n */\\nconst defineExoClassKit=(\\ntag,\\ninterfaceGuardKit,\\ninit,\\nmethodsKit,\\noptions={})=>\\n{\\nharden(methodsKit);\\nconst{\\nfinish=undefined,\\nreceiveAmplifier=undefined,\\nreceiveInstanceTester=undefined}=\\noptions;\\nconst contextMapKit=objectMap.objectMap(methodsKit,()=>new WeakMap());\\nconst getContextKit=objectMap.objectMap(\\ncontextMapKit,\\n(contextMap)=>(facet)=>contextMap.get(facet));\\n\\nconst prototypeKit=exoTools.defendPrototypeKit(\\ntag,\\ngetContextKit,\\nmethodsKit,\\ntrue,\\ninterfaceGuardKit);\\n\\nlet instanceCount=0;\\n/**\\n * @param {Parameters<I>} args\\n */\\nconst makeInstanceKit=(...args)=>{\\n/* Be careful not to freeze the state record*/\\nconst state=seal(init(...args));\\n/* Don't freeze context until we add facets*/\\n/** @type {{ state: ReturnType<I>, facets: any }} */\\nconst context={state,facets:null};\\ninstanceCount+=1;\\nconst facets=objectMap.objectMap(prototypeKit,(proto,facetName)=>{\\nconst self=makeSelf(proto,instanceCount);\\ncontextMapKit[facetName].set(self,context);\\nreturn self;});\\n\\ncontext.facets=facets;\\n/* Be careful not to freeze the state record*/\\nfreeze(context);\\nif(finish){\\nfinish(context);}\\n\\nreturn(/** @type {GuardedKit<F>} */context.facets);};\\n\\n\\nif(receiveAmplifier){\\n/** @type {Amplify} */\\nconst amplify=(exoFacet)=>{\\nfor(const contextMap of values(contextMapKit)){\\nif(contextMap.has(exoFacet)){\\nconst{facets}=contextMap.get(exoFacet);\\nreturn facets;}}\\n\\n\\nthrow index.throwRedacted`Must be a facet of ${index.quote(tag)}: ${exoFacet}`;};\\n\\nharden(amplify);\\nreceiveAmplifier(amplify);}\\n\\n\\nif(receiveInstanceTester){\\n/** @type {IsInstance} */\\nconst isInstance=(exoFacet,facetName=undefined)=>{\\nif(facetName===undefined){\\nreturn values(contextMapKit).some((contextMap)=>\\ncontextMap.has(exoFacet));}\\n\\n\\nassert.typeof(facetName,'string');\\nconst contextMap=contextMapKit[facetName];\\ncontextMap!==undefined||\\nindex.throwRedacted`exo class kit ${index.quote(tag)} has no facet named ${index.quote(facetName)}`;\\nreturn contextMap.has(exoFacet);};\\n\\nharden(isInstance);\\nreceiveInstanceTester(isInstance);}\\n\\n\\nreturn harden(makeInstanceKit);};\\n\\nharden(defineExoClassKit);\\n\\n/**\\n * @template {Methods} T\\n * @param {string} tag\\n * @param {IMPORT('@endo/patterns').InterfaceGuard<{\\n * [M in keyof T]: IMPORT('@endo/patterns').MethodGuard\\n * }> | undefined} interfaceGuard CAVEAT: static typing does not yet support `callWhen` transformation\\n * @param {T} methods\\n * @param {FarClassOptions<IMPORT('./types.js').ClassContext<{},T>>} [options]\\n * @returns {Guarded<T>}\\n */\\nconst makeExo=(tag,interfaceGuard,methods,options=undefined)=>{\\nconst makeInstance=defineExoClass(\\ntag,\\ninterfaceGuard,\\ninitEmpty,\\nmethods,\\noptions);\\n\\nreturn makeInstance();};\\n\\nharden(makeExo);exports.defineExoClass=defineExoClass;exports.defineExoClassKit=defineExoClassKit;exports.initEmpty=initEmpty;exports.makeExo=makeExo;\",\n \"node_modules/@endo/exo/src/exo-tools.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../eventual-send/utils.js');require('../../pass-style/index.js');require('../../far/src/index.js');require('../../patterns/index.js');var listDifference=require('../../common/list-difference.js');var objectMap=require('../../common/object-map.js');var index=require('../../errors/index.js');var getInterface=require('./get-interface.js');var patternMatchers=require('../../patterns/src/patterns/patternMatchers.js');var passStyleOf=require('../../pass-style/src/passStyleOf.js');var getGuardPayloads=require('../../patterns/src/patterns/getGuardPayloads.js');var noShim=require('../../eventual-send/src/no-shim.js');var local=require('../../eventual-send/src/local.js');var checkKey=require('../../patterns/src/keys/checkKey.js');var passStyleHelpers=require('../../pass-style/src/passStyle-helpers.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nmakeFar=require('../../pass-style/src/make-far.js');/**\\n * @import {InterfaceGuard, Method, MethodGuard, MethodGuardPayload} from '@endo/patterns'\\n * @import {ClassContext, ContextProvider, FacetName, KitContext, KitContextProvider, MatchConfig, Methods} from './types.js'\\n */\\n\\nconst{apply,ownKeys}=Reflect;\\nconst{defineProperties,fromEntries}=Object;\\n\\n/**\\n * A method guard, for inclusion in an interface guard, that does not\\n * enforce any constraints of incoming arguments or return results.\\n */\\nconst RawMethodGuard=patternMatchers.M.call().rest(patternMatchers.M.raw()).returns(patternMatchers.M.raw());\\n\\nconst REDACTED_RAW_ARG='<redacted raw arg>';\\n\\n/**\\n * A method guard, for inclusion in an interface guard, that enforces only that\\n * all arguments are passable and that the result is passable. (In far classes,\\n * \\\"any\\\" means any *passable*.) This is the least possible non-raw\\n * enforcement for a method guard, and is implied by all other\\n * non-raw method guards.\\n */\\nconst PassableMethodGuard=patternMatchers.M.call().rest(patternMatchers.M.any()).returns(patternMatchers.M.any());\\n\\n/**\\n * @param {IMPORT('@endo/pass-style').Passable[]} syncArgs\\n * @param {MatchConfig} matchConfig\\n * @param {string} [label]\\n * @returns {IMPORT('@endo/pass-style').Passable[]} Returns the args that should be passed to the raw method.\\n */\\nconst defendSyncArgs=(syncArgs,matchConfig,label=undefined)=>{\\nconst{\\ndeclaredLen,\\nhasRestArgGuard,\\nrestArgGuardIsRaw,\\nparamsPattern,\\nredactedIndices}=\\nmatchConfig;\\n\\n/* Use syncArgs if possible, but copy it when necessary to implement*/\\n/* redactions.*/\\nlet matchableArgs=syncArgs;\\nif(restArgGuardIsRaw&&syncArgs.length>declaredLen){\\nconst restLen=syncArgs.length-declaredLen;\\nconst redactedRest=Array(restLen).fill(REDACTED_RAW_ARG);\\nmatchableArgs=[...syncArgs.slice(0,declaredLen),...redactedRest];}else\\nif(\\nredactedIndices.length>0&&\\nredactedIndices[0]<syncArgs.length)\\n{\\n/* Copy the arguments array, avoiding hardening the redacted ones (which are*/\\n/* trivially matched using REDACTED_RAW_ARG as a sentinel value).*/\\nmatchableArgs=[...syncArgs];}\\n\\n\\nfor(const i of redactedIndices){\\nif(i>=matchableArgs.length){\\nbreak;}\\n\\nmatchableArgs[i]=REDACTED_RAW_ARG;}\\n\\n\\npatternMatchers.mustMatch(harden(matchableArgs),paramsPattern,label);\\n\\nif(hasRestArgGuard){\\nreturn syncArgs;}\\n\\nsyncArgs.length<=declaredLen||\\nindex.throwRedacted`${index.quote(label)} accepts at most ${index.quote(declaredLen)} arguments, not ${index.quote(\\nsyncArgs.length)\\n}: ${syncArgs}`;\\nreturn syncArgs;};\\n\\n\\n/**\\n * Convert a method guard to a match config for more efficient per-call\\n * execution. This is a one-time conversion, so it's OK to be slow.\\n *\\n * Most of the work is done to detect `M.raw()` so that we build a match pattern\\n * and metadata instead of doing this in the hot path.\\n * @param {MethodGuardPayload} methodGuardPayload\\n * @returns {MatchConfig}\\n */\\nconst buildMatchConfig=(methodGuardPayload)=>{\\nconst{\\nargGuards,\\noptionalArgGuards=[],\\nrestArgGuard}=\\nmethodGuardPayload;\\n\\nconst matchableArgGuards=[...argGuards,...optionalArgGuards];\\n\\nconst redactedIndices=[];\\nfor(let i=0;i<matchableArgGuards.length;i+=1){\\nif(patternMatchers.isRawGuard(matchableArgGuards[i])){\\nmatchableArgGuards[i]=REDACTED_RAW_ARG;\\nredactedIndices.push(i);}}\\n\\n\\n\\n/* Pass through raw rest arguments without matching.*/\\nlet matchableRestArgGuard=restArgGuard;\\nif(patternMatchers.isRawGuard(matchableRestArgGuard)){\\nmatchableRestArgGuard=patternMatchers.M.arrayOf(REDACTED_RAW_ARG);}\\n\\nconst matchableMethodGuardPayload=harden({\\n...methodGuardPayload,\\nargGuards:matchableArgGuards.slice(0,argGuards.length),\\noptionalArgGuards:matchableArgGuards.slice(argGuards.length),\\nrestArgGuard:matchableRestArgGuard});\\n\\n\\nconst paramsPattern=patternMatchers.M.splitArray(\\nmatchableMethodGuardPayload.argGuards,\\nmatchableMethodGuardPayload.optionalArgGuards,\\nmatchableMethodGuardPayload.restArgGuard);\\n\\n\\nreturn harden({\\ndeclaredLen:matchableArgGuards.length,\\nhasRestArgGuard:restArgGuard!==undefined,\\nrestArgGuardIsRaw:restArgGuard!==matchableRestArgGuard,\\nparamsPattern,\\nredactedIndices,\\nmatchableMethodGuardPayload});};\\n\\n\\n\\n/**\\n * @param {(representative: any) => ClassContext | KitContext} getContext\\n * @param {CallableFunction} behaviorMethod\\n * @param {MethodGuardPayload} methodGuardPayload\\n * @param {string} label\\n * @returns {Method}\\n */\\nconst defendSyncMethod=(\\ngetContext,\\nbehaviorMethod,\\nmethodGuardPayload,\\nlabel)=>\\n{\\nconst{returnGuard}=methodGuardPayload;\\nconst isRawReturn=patternMatchers.isRawGuard(returnGuard);\\nconst matchConfig=buildMatchConfig(methodGuardPayload);\\nconst{syncMethod}={\\n/* Note purposeful use of `this` and concise method syntax*/\\nsyncMethod(...syncArgs){\\ntry{\\nconst context=getContext(this);\\n/* Only harden args and return value if not dealing with a raw value guard.*/\\nconst realArgs=defendSyncArgs(syncArgs,matchConfig,label);\\nconst result=apply(behaviorMethod,context,realArgs);\\nif(!isRawReturn){\\npatternMatchers.mustMatch(harden(result),returnGuard,`${label}: result`);}\\n\\nreturn result;}\\ncatch(thrownThing){\\nthrow passStyleOf.toThrowable(thrownThing);}}};\\n\\n\\n\\nreturn syncMethod;};\\n\\n\\n/**\\n * @param {MethodGuardPayload} methodGuardPayload\\n */\\nconst desync=(methodGuardPayload)=>{\\nconst{\\nargGuards,\\noptionalArgGuards=[],\\nrestArgGuard}=\\nmethodGuardPayload;\\n!patternMatchers.isAwaitArgGuard(restArgGuard)||\\nindex.throwRedacted`Rest args may not be awaited: ${restArgGuard}`;\\nconst rawArgGuards=[...argGuards,...optionalArgGuards];\\n\\nconst awaitIndexes=[];\\nfor(let i=0;i<rawArgGuards.length;i+=1){\\nconst argGuard=rawArgGuards[i];\\nif(patternMatchers.isAwaitArgGuard(argGuard)){\\nrawArgGuards[i]=getGuardPayloads.getAwaitArgGuardPayload(argGuard).argGuard;\\nawaitIndexes.push(i);}}\\n\\n\\nreturn{\\nawaitIndexes,\\nrawMethodGuardPayload:{\\n...methodGuardPayload,\\nargGuards:rawArgGuards.slice(0,argGuards.length),\\noptionalArgGuards:rawArgGuards.slice(argGuards.length)}};};\\n\\n\\n\\n\\n/**\\n * @param {(representative: any) => ClassContext | KitContext} getContext\\n * @param {CallableFunction} behaviorMethod\\n * @param {MethodGuardPayload} methodGuardPayload\\n * @param {string} label\\n */\\nconst defendAsyncMethod=(\\ngetContext,\\nbehaviorMethod,\\nmethodGuardPayload,\\nlabel)=>\\n{\\nconst{returnGuard}=methodGuardPayload;\\nconst isRawReturn=patternMatchers.isRawGuard(returnGuard);\\n\\nconst{awaitIndexes,rawMethodGuardPayload}=desync(methodGuardPayload);\\nconst matchConfig=buildMatchConfig(rawMethodGuardPayload);\\n\\nconst{asyncMethod}={\\n/* Note purposeful use of `this` and concise method syntax*/\\nasyncMethod(...args){\\nconst awaitList=[];\\nfor(const i of awaitIndexes){\\nif(i>=args.length){\\nbreak;}\\n\\nawaitList.push(args[i]);}\\n\\nconst p=Promise.all(awaitList);\\nconst syncArgs=[...args];\\nconst resultP=noShim.E.when(\\np,\\n/** @param {any[]} awaitedArgs */(awaitedArgs)=>{\\nfor(let j=0;j<awaitedArgs.length;j+=1){\\nsyncArgs[awaitIndexes[j]]=awaitedArgs[j];}\\n\\n/* Get the context after all waiting in case we ever do revocation*/\\n/* by removing the context entry. Avoid TOCTTOU!*/\\nconst context=getContext(this);\\nconst realArgs=defendSyncArgs(syncArgs,matchConfig,label);\\nreturn apply(behaviorMethod,context,realArgs);});\\n\\n\\nreturn noShim.E.when(resultP,(fulfillment)=>{\\nif(!isRawReturn){\\npatternMatchers.mustMatch(harden(fulfillment),returnGuard,`${label}: result`);}\\n\\nreturn fulfillment;}).\\ncatch((reason)=>\\n/* Done is a chained `.catch` rather than an onRejected clause of the*/\\n/* `E.when` above in case the `mustMatch` throws.*/\\nPromise.reject(passStyleOf.toThrowable(reason)));}};\\n\\n\\n\\nreturn asyncMethod;};\\n\\n\\n/**\\n *\\n * @param {(representative: any) => ClassContext | KitContext} getContext\\n * @param {CallableFunction} behaviorMethod\\n * @param {MethodGuard} methodGuard\\n * @param {string} label\\n */\\nconst defendMethod=(getContext,behaviorMethod,methodGuard,label)=>{\\nconst methodGuardPayload=getGuardPayloads.getMethodGuardPayload(methodGuard);\\nconst{callKind}=methodGuardPayload;\\nif(callKind==='sync'){\\nreturn defendSyncMethod(\\ngetContext,\\nbehaviorMethod,\\nmethodGuardPayload,\\nlabel);}else\\n\\n{\\nassert(callKind==='async');\\nreturn defendAsyncMethod(\\ngetContext,\\nbehaviorMethod,\\nmethodGuardPayload,\\nlabel);}};\\n\\n\\n\\n\\n/**\\n * @param {string} methodTag\\n * @param {ContextProvider} contextProvider\\n * @param {CallableFunction} behaviorMethod\\n * @param {MethodGuard} methodGuard\\n */\\nconst bindMethod=(\\nmethodTag,\\ncontextProvider,\\nbehaviorMethod,\\nmethodGuard)=>\\n{\\nassert.typeof(behaviorMethod,'function');\\n\\n/**\\n * @param {any} representative\\n * @returns {ClassContext | KitContext}\\n */\\nconst getContext=(representative)=>{\\nrepresentative||\\n/* separate line to ease breakpointing*/\\nindex.throwRedacted`Method ${methodTag} called without 'this' object`;\\nconst context=contextProvider(representative);\\nif(context===undefined){\\nthrow index.throwRedacted`${index.quote(\\nmethodTag)\\n} may only be applied to a valid instance: ${representative}`;}\\n\\nreturn context;};\\n\\n\\nconst method=defendMethod(\\ngetContext,\\nbehaviorMethod,\\nmethodGuard,\\nmethodTag);\\n\\n\\ndefineProperties(method,{\\nname:{value:methodTag},\\nlength:{value:behaviorMethod.length}});\\n\\nreturn method;};\\n\\n\\n/**\\n * @template {Record<PropertyKey, CallableFunction>} T\\n * @param {string} tag\\n * @param {ContextProvider} contextProvider\\n * @param {T} behaviorMethods\\n * @param {boolean} [thisfulMethods]\\n * @param {InterfaceGuard<{ [M in keyof T]: MethodGuard }>} [interfaceGuard]\\n */\\nconst defendPrototype=(\\ntag,\\ncontextProvider,\\nbehaviorMethods,\\nthisfulMethods=false,\\ninterfaceGuard=undefined)=>\\n{\\nconst prototype={};\\nconst methodNames=local.getMethodNames(behaviorMethods).filter(\\n/* By ignoring any method that seems to be a constructor, we can use a*/\\n/* class.prototype as a behaviorMethods.*/\\n(key)=>{\\nif(key!=='constructor'){\\nreturn true;}\\n\\nconst constructor=behaviorMethods.constructor;\\nreturn!(\\nconstructor.prototype&&\\nconstructor.prototype.constructor===constructor);});\\n\\n\\n\\n/** @type {Record<PropertyKey, MethodGuard> | undefined} */\\nlet methodGuards;\\n/** @type {IMPORT('@endo/patterns').DefaultGuardType} */\\nlet defaultGuards;\\nif(interfaceGuard){\\nconst{\\ninterfaceName,\\nmethodGuards:mg,\\nsymbolMethodGuards,\\nsloppy,\\ndefaultGuards:dg=sloppy?'passable':defaultGuards}=\\ngetGuardPayloads.getInterfaceGuardPayload(interfaceGuard);\\nmethodGuards=harden({\\n...mg,\\n...(symbolMethodGuards&&\\nfromEntries(checkKey.getCopyMapEntries(symbolMethodGuards)))});\\n\\ndefaultGuards=dg;\\n{\\nconst methodGuardNames=ownKeys(methodGuards);\\nconst unimplemented=listDifference.listDifference(methodGuardNames,methodNames);\\nunimplemented.length===0||\\nindex.throwRedacted`methods ${index.quote(unimplemented)} not implemented by ${index.quote(tag)}`;\\nif(defaultGuards===undefined){\\nconst unguarded=listDifference.listDifference(methodNames,methodGuardNames);\\nunguarded.length===0||\\nindex.throwRedacted`methods ${index.quote(unguarded)} not guarded by ${index.quote(interfaceName)}`;}}}\\n\\n\\n\\n\\nfor(const prop of methodNames){\\nconst originalMethod=behaviorMethods[prop];\\nconst{shiftedMethod}={\\nshiftedMethod(...args){\\nreturn originalMethod(this,...args);}};\\n\\n\\nconst behaviorMethod=thisfulMethods?originalMethod:shiftedMethod;\\n/* TODO some tool does not yet understand the `?.[` syntax*/\\n/* See https://github.com/endojs/endo/pull/2247#discussion_r1583724424*/\\nlet methodGuard=methodGuards&&methodGuards[prop];\\nif(!methodGuard){\\nswitch(defaultGuards){\\ncase undefined:{\\nif(thisfulMethods){\\nmethodGuard=PassableMethodGuard;}else\\n{\\nmethodGuard=RawMethodGuard;}\\n\\nbreak;}\\n\\ncase'passable':{\\nmethodGuard=PassableMethodGuard;\\nbreak;}\\n\\ncase'raw':{\\nmethodGuard=RawMethodGuard;\\nbreak;}\\n\\ndefault:{\\nthrow index.throwRedacted`Unrecognized defaultGuards ${index.quote(defaultGuards)}`;}}}\\n\\n\\n\\nprototype[prop]=bindMethod(\\n`In ${index.quote(prop)} method of (${tag})`,\\ncontextProvider,\\nbehaviorMethod,\\nmethodGuard);}\\n\\n\\n\\nif(!passStyleHelpers.hasOwnPropertyOf(prototype,getInterface.GET_INTERFACE_GUARD)){\\nconst getInterfaceGuardMethod={\\n[getInterface.GET_INTERFACE_GUARD](){\\n/* Note: May be `undefined`*/\\nreturn interfaceGuard;}}[\\n\\ngetInterface.GET_INTERFACE_GUARD];\\nprototype[getInterface.GET_INTERFACE_GUARD]=bindMethod(\\n`In ${index.quote(getInterface.GET_INTERFACE_GUARD)} method of (${tag})`,\\ncontextProvider,\\ngetInterfaceGuardMethod,\\nPassableMethodGuard);}\\n\\n\\n\\nreturn makeFar.Far(\\ntag,\\n/** @type {T & IMPORT('./get-interface.js').GetInterfaceGuard<T>} */\\nprototype);};\\n\\n\\n\\nharden(defendPrototype);\\n\\n/**\\n * @template {Record<FacetName, Methods>} F\\n * @param {string} tag\\n * @param {{ [K in keyof F]: KitContextProvider }} contextProviderKit\\n * @param {F} behaviorMethodsKit\\n * @param {boolean} [thisfulMethods]\\n * @param {{ [K in keyof F]: InterfaceGuard<Record<keyof F[K], MethodGuard>> }} [interfaceGuardKit]\\n */\\nconst defendPrototypeKit=(\\ntag,\\ncontextProviderKit,\\nbehaviorMethodsKit,\\nthisfulMethods=false,\\ninterfaceGuardKit=undefined)=>\\n{\\nconst facetNames=ownKeys(behaviorMethodsKit).sort();\\nfacetNames.length>1||index.throwRedacted`A multi-facet object must have multiple facets`;\\nif(interfaceGuardKit){\\nconst interfaceNames=ownKeys(interfaceGuardKit);\\nconst extraInterfaceNames=listDifference.listDifference(facetNames,interfaceNames);\\nextraInterfaceNames.length===0||\\nindex.throwRedacted`Interfaces ${index.quote(extraInterfaceNames)} not implemented by ${index.quote(tag)}`;\\nconst extraFacetNames=listDifference.listDifference(interfaceNames,facetNames);\\nextraFacetNames.length===0||\\nindex.throwRedacted`Facets ${index.quote(extraFacetNames)} of ${index.quote(tag)} not guarded by interfaces`;}\\n\\nconst contextMapNames=ownKeys(contextProviderKit);\\nconst extraContextNames=listDifference.listDifference(facetNames,contextMapNames);\\nextraContextNames.length===0||\\nindex.throwRedacted`Contexts ${index.quote(extraContextNames)} not implemented by ${index.quote(tag)}`;\\nconst extraFacetNames=listDifference.listDifference(contextMapNames,facetNames);\\nextraFacetNames.length===0||\\nindex.throwRedacted`Facets ${index.quote(extraFacetNames)} of ${index.quote(tag)} missing contexts`;\\nconst protoKit=objectMap.objectMap(behaviorMethodsKit,(behaviorMethods,facetName)=>\\ndefendPrototype(\\n`${tag} ${String(facetName)}`,\\ncontextProviderKit[facetName],\\nbehaviorMethods,\\nthisfulMethods,\\ninterfaceGuardKit&&interfaceGuardKit[facetName]));\\n\\n\\nreturn protoKit;};exports.defendPrototype=defendPrototype;exports.defendPrototypeKit=defendPrototypeKit;\",\n \"node_modules/@endo/exo/src/get-interface.js\": \"'use strict';\\n\\nObject.defineProperty(exports,'__esModule',{value:true});/* @ts-check*/ /**\\n * The name of the automatically added default meta-method for\\n * obtaining an exo's interface, if it has one.\\n *\\n * Intended to be similar to `GET_METHOD_NAMES` from `@endo/pass-style`.\\n *\\n * TODO Name to be bikeshed. Perhaps even whether it is a\\n * string or symbol to be bikeshed. See\\n * https://github.com/endojs/endo/pull/1809#discussion_r1388052454\\n *\\n * TODO Beware that an exo's interface can change across an upgrade,\\n * so remotes that cache it can become stale.\\n */\\nconst GET_INTERFACE_GUARD='__getInterfaceGuard__';\\n\\n/**\\n * @template {Record<PropertyKey, CallableFunction>} M\\n * @typedef {{\\n * [GET_INTERFACE_GUARD]?: () =>\\n * IMPORT('@endo/patterns').InterfaceGuard<{\\n * [K in keyof M]: IMPORT('@endo/patterns').MethodGuard\\n * }> | undefined\\n * }} GetInterfaceGuard\\n */exports.GET_INTERFACE_GUARD=GET_INTERFACE_GUARD;\",\n \"node_modules/@endo/exo/src/types.js\": \"'use strict';/** @file Empty twin for .d.ts */\",\n \"node_modules/@endo/exo/tools.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var exoTools=require('./src/exo-tools.js');exports.defendPrototype=exoTools.defendPrototype;exports.defendPrototypeKit=exoTools.defendPrototypeKit;\",\n \"node_modules/@endo/far/src/index.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var noShim=require('../../eventual-send/src/no-shim.js');\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nrequire('../../pass-style/index.js');/* TODO re-export from eventual-send, may require .d.ts*/ /**\\n * @template Primary\\n * @template [Local=IMPORT('@endo/eventual-send').DataOnly<Primary>]\\n * @typedef {IMPORT('@endo/eventual-send').FarRef<Primary, Local>} FarRef\\n * Declare an object that is potentially a far reference of type Primary whose\\n * auxilliary data has type Local. This should be used only for consumers of\\n * Far objects in arguments and declarations; the only creators of Far objects\\n * are distributed object creator components like the `Far` or `Remotable`\\n * functions.\\n */ /**\\n * @template T\\n * @typedef {IMPORT('@endo/eventual-send').ERef<T>} ERef\\n * Declare that `T` may or may not be a Promise. This should be used only for\\n * consumers of arguments and declarations; return values should specifically be\\n * `Promise<T>` or `T` itself.\\n */ /**\\n * @template T\\n * @typedef {IMPORT('@endo/eventual-send').EOnly<T>} EOnly\\n * Declare a near object that must only be invoked with E, even locally. It\\n * supports the `T` interface but additionally permits `T`'s methods to return\\n * `PromiseLike`s even if `T` declares them as only synchronous.\\n */exports.E=noShim.E;\",\n \"node_modules/@endo/import-bundle/src/compartment-wrapper.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});function wrapInescapableCompartment(\\nOldCompartment,\\ninescapableTransforms,\\ninescapableGlobalProperties)\\n{\\n/* This is the new Compartment constructor. We name it `Compartment` so*/\\n/* that it's .name property is correct, but we hold it in 'NewCompartment'*/\\n/* so that lint doesn't think we're shadowing the original.*/\\nconst NewCompartment=function Compartment(\\nendowments,\\nmodules,\\noldOptions={})\\n{\\nconst{transforms:oldTransforms=[],...otherOptions}=oldOptions;\\nconst newTransforms=[...oldTransforms,...inescapableTransforms];\\nconst newOptions={\\n...otherOptions,\\ntransforms:newTransforms};\\n\\n\\n/* The real Compartment is defined as a class, so 'new Compartment()'*/\\n/* works but not 'Compartment()'. We can behave the same way. It would be*/\\n/* nice to delegate the 'throw' to the original constructor by knowing*/\\n/* calling it the wrong way, but I don't know how to do that.*/\\nif(new.target===undefined){\\n/* `newCompartment` was called as a function*/\\nthrow Error('Compartment must be called as a constructor');}\\n\\n\\n/* It, or a subclass, was called as a constructor*/\\n\\nconst c=Reflect.construct(\\nOldCompartment,\\n[endowments,modules,newOptions],\\nnew.target);\\n\\n/* The confinement applies to all compartments too. This relies upon the*/\\n/* child's normal Compartment behaving the same way as the parent's,*/\\n/* which will cease to be the case soon (their module tables are*/\\n/* different). TODO: update this when that happens, we need something*/\\n/* like c.globalThis.Compartment = wrap(c.globalThis.Compartment), but*/\\n/* there are details to work out.*/\\nc.globalThis.Compartment=NewCompartment;\\n\\nfor(const prop of Object.keys(inescapableGlobalProperties)){\\nObject.defineProperty(c.globalThis,prop,{\\nvalue:inescapableGlobalProperties[prop],\\nwritable:true,\\nenumerable:false,\\nconfigurable:true});}\\n\\n\\n\\nreturn c;};\\n\\n\\n/* ensure `(c isinstance Compartment)` remains true*/\\nNewCompartment.prototype=OldCompartment.prototype;\\n\\n/* SECURITY NOTE: if this were used outside of SES, this might leave*/\\n/* c.prototype.constructor pointing at the original (untamed) Compartment,*/\\n/* which would allow a breach. Kris says this will be hard to fix until he*/\\n/* rewrites the compartment shim, possibly as a plain function instead of a*/\\n/* class. Under SES, OldCompartment.prototype.constructor is tamed*/\\n\\nreturn NewCompartment;}\\n\\n\\n/* swingset would do this to each dynamic vat*/\\n/* c.globalThis.Compartment = wrapCompartment(c.globalThis.Compartment, ..);*/exports.wrapInescapableCompartment=wrapInescapableCompartment;\",\n \"node_modules/@endo/import-bundle/src/index.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../compartment-mapper/import-archive.js');require('../../base64/index.js');var index=require('../../errors/index.js');var compartmentWrapper=require('./compartment-wrapper.js');var decode=require('../../base64/src/decode.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nimportArchive=require('../../compartment-mapper/src/import-archive.js');/* XXX Omit from typecheck for TypeScript packages depending upon*/ /* importBundle takes the output of bundle-source, and returns a namespace*/ /* object (with .default, and maybe other properties for named exports)*/\\n\\nasync function importBundle(bundle,options={},powers={}){\\nconst{\\nbundleUrl=undefined,\\nfilePrefix,\\nendowments:optEndowments={},\\n/* transforms are indeed __shimTransforms__, intended to apply to both*/\\n/* evaluated programs and modules shimmed to programs.*/\\ntransforms=[],\\ninescapableTransforms=[],\\ninescapableGlobalProperties={},\\nexpectedSha512=undefined}=\\noptions;\\nconst{\\ncomputeSha512=undefined,\\ncomputeSourceLocation=undefined,\\ncomputeSourceMapLocation=undefined}=\\npowers;\\nconst endowments={\\nTextEncoder,\\nTextDecoder,\\nURL:globalThis.URL,/* Absent only in XSnap*/\\nBase64:globalThis.Base64,/* Present only in XSnap*/\\natob:globalThis.atob,\\nbtoa:globalThis.btoa,\\n...optEndowments};\\n\\n\\nlet CompartmentToUse=Compartment;\\nif(\\ninescapableTransforms.length||\\nObject.keys(inescapableGlobalProperties).length)\\n{\\n/* @ts-expect-error TS2322 no match for the signature*/\\nCompartmentToUse=compartmentWrapper.wrapInescapableCompartment(\\nCompartment,\\ninescapableTransforms,\\ninescapableGlobalProperties);}\\n\\n\\n\\nconst{moduleFormat}=bundle;\\nif(moduleFormat==='endoZipBase64'){\\nconst{endoZipBase64}=bundle;\\nconst bytes=decode.decodeBase64(endoZipBase64);\\nconst archive=await importArchive.parseArchive(bytes,bundleUrl,{\\ncomputeSha512,\\nexpectedSha512,\\ncomputeSourceLocation,\\ncomputeSourceMapLocation});\\n\\n/* Call import by property to bypass SES censoring for dynamic import.*/\\n/* eslint-disable-next-line dot-notation*/\\nconst{namespace}=await archive['import']({\\nglobals:endowments,\\n__shimTransforms__:transforms,\\n/* @ts-expect-error TS2740 missing properties from type*/\\nCompartment:CompartmentToUse});\\n\\n/* namespace.default has the default export*/\\nreturn namespace;}\\n\\n\\nlet c;\\nconst{source,sourceMap}=bundle;\\nif(moduleFormat==='getExport'){\\n/* The 'getExport' format is a string which defines a wrapper function*/\\n/* named `getExport()`. This function provides a `module` to the*/\\n/* linearized source file, executes that source, then returns*/\\n/* `module.exports`. To get the function object out of a program-mode*/\\n/* evaluation, we must wrap the function definition in parentheses*/\\n/* (making it an expression). We also want to append the `sourceMap`*/\\n/* comment so `evaluate` can attach useful debug information. Finally, to*/\\n/* extract the namespace object, we need to invoke this function.*/}else\\nif(moduleFormat==='nestedEvaluate'){\\n/* The 'nestedEvaluate' format is similar, except the wrapper function*/\\n/* (now named `getExportWithNestedEvaluate`) wraps more than a single*/\\n/* linearized string. Each source module is processed (converting*/\\n/* `import` into `require`) and added to a table named `sourceBundle`.*/\\n/* Each module will be evaluated separately (so they can get distinct*/\\n/* sourceMap strings), using a mandatory endowment named*/\\n/* `nestedEvaluate`. The wrapper function should be called with*/\\n/* `filePrefix`, which will be used as the sourceMap for the top-level*/\\n/* module. The sourceMap name for other modules will be derived from*/\\n/* `filePrefix` and the relative import path of each module.*/\\nendowments.nestedEvaluate=(src)=>c.evaluate(src);}else\\n{\\nindex.throwRedacted`unrecognized moduleFormat '${moduleFormat}'`;}\\n\\n\\nc=new CompartmentToUse(endowments,{},{transforms});\\nharden(c.globalThis);\\nconst actualSource=`(${source})\\\\n${sourceMap||''}`;\\nconst namespace=c.evaluate(actualSource)(filePrefix);\\n/* namespace.default has the default export*/\\nreturn namespace;}\\n\\n\\n/* importBundle(bundle, { metering: { getMeter, meteringOptions } });\\nimportBundle(bundle, { transforms: [ meterTransform ], lexicals: { getMeter } });\\nimportBundle(bundle, { mandatoryTransforms: [ meterTransform ], mandatoryLexicals: { getMeter } });\\n // then importBundle builds the Compartment wrapper\\n XS:\\n xs.setMeter();\\nxs.callWithMeter(meter, ns.dispatch);\\nxs.callWithKeeper(keeper, ns.dispatch); // keeper.getMeter() -> meter, then ns.dispatch()\\n// keeper.startCrank(metadata.tshirtsize)\\n// // keeper sets meter to some fixed value\\n// initialMeter = keeper.getMeter()\\n// ns.dispatch() // drains initialMeter\\n// maybe: keeper.endCrank() ???\\n */exports.importBundle=importBundle;\",\n \"node_modules/@endo/marshal/index.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var deeplyFulfilled=require('./src/deeplyFulfilled.js');var encodeToCapData=require('./src/encodeToCapData.js');var marshal=require('./src/marshal.js');var marshalStringify=require('./src/marshal-stringify.js');var marshalJustin=require('./src/marshal-justin.js');var encodePassable=require('./src/encodePassable.js');var rankOrder=require('./src/rankOrder.js');require('./src/types.js');require('../pass-style/index.js');exports.deeplyFulfilled=deeplyFulfilled.deeplyFulfilled;exports.QCLASS=encodeToCapData.QCLASS;exports.makeMarshal=marshal.makeMarshal;exports.parse=marshalStringify.parse;exports.stringify=marshalStringify.stringify;exports.decodeToJustin=marshalJustin.decodeToJustin;exports.isEncodedRemotable=encodePassable.isEncodedRemotable;exports.makeDecodePassable=encodePassable.makeDecodePassable;exports.makeEncodePassable=encodePassable.makeEncodePassable;exports.makePassableKit=encodePassable.makePassableKit;exports.recordNames=encodePassable.recordNames;exports.recordValues=encodePassable.recordValues;exports.zeroPad=encodePassable.zeroPad;exports.assertRankSorted=rankOrder.assertRankSorted;exports.compareAntiRank=rankOrder.compareAntiRank;exports.compareRank=rankOrder.compareRank;exports.getPassStyleCover=rankOrder.getPassStyleCover;exports.intersectRankCovers=rankOrder.intersectRankCovers;exports.isRankSorted=rankOrder.isRankSorted;exports.makeFullOrderComparatorKit=rankOrder.makeFullOrderComparatorKit;exports.sortByRank=rankOrder.sortByRank;exports.trivialComparator=rankOrder.trivialComparator;exports.unionRankCovers=rankOrder.unionRankCovers;\",\n \"node_modules/@endo/marshal/src/deeplyFulfilled.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var noShim=require('../../eventual-send/src/no-shim.js');require('../../promise-kit/index.js');require('../../pass-style/index.js');var index=require('../../errors/index.js');var passStyleHelpers=require('../../pass-style/src/passStyle-helpers.js');var isPromise=require('../../promise-kit/src/is-promise.js');var passStyleOf=require('../../pass-style/src/passStyleOf.js');var makeTagged=require('../../pass-style/src/makeTagged.js');/*/ <reference types=\\\"ses\\\"/>*/\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nconst{ownKeys}=Reflect;\\nconst{fromEntries}=Object;\\n\\n/* TODO return a type contingent on the parameter as deeplyFullfilledObject from agoric-sdk does*/\\n/**\\n * Given a Passable `val` whose pass-by-copy structure may contain leaf\\n * promises, return a promise for a replacement Passable,\\n * where that replacement is *deeply fulfilled*, i.e., its\\n * pass-by-copy structure does not contain any promises.\\n *\\n * This is a deep form of `Promise.all` specialized for Passables. For each\\n * encountered promise, replace it with the deeply fulfilled form of\\n * its fulfillment.\\n * If any of the promises reject, then the promise for the replacement\\n * rejects. If any of the promises never settle, then the promise for\\n * the replacement never settles.\\n *\\n * If the replacement would not be Passable, i.e., if `val` is not\\n * Passable, or if any of the transitive promises fulfill to something\\n * that is not Passable, then the returned promise rejects.\\n *\\n * If `val` or its parts are non-key Passables only *because* they contains\\n * promises, the deeply fulfilled forms of val or its parts may be keys. This\\n * is for the higher \\\"store\\\" level of abstraction to determine, because it\\n * defines the \\\"key\\\" notion in question.\\n *\\n * // TODO: That higher level is in the process of being migrated from\\n * // `@agoric/store` to `@endo/patterns`. Once that is far enough along,\\n * // revise the above comment to match.\\n * // See https://github.com/endojs/endo/pull/1451\\n *\\n * @param {any} val\\n * @returns {Promise<Passable>}\\n */\\nconst deeplyFulfilled=async(val)=>{\\nif(!passStyleHelpers.isObject(val)){\\nreturn val;}\\n\\nif(isPromise.isPromise(val)){\\nreturn noShim.E.when(val,(nonp)=>deeplyFulfilled(nonp));}\\n\\nconst passStyle=passStyleOf.passStyleOf(val);\\nswitch(passStyle){\\ncase'copyRecord':{\\nconst names=ownKeys(val);\\nconst valPs=names.map((name)=>deeplyFulfilled(val[name]));\\nreturn noShim.E.when(Promise.all(valPs),(vals)=>\\nharden(fromEntries(vals.map((c,i)=>[names[i],c]))));}\\n\\n\\ncase'copyArray':{\\nconst valPs=val.map((p)=>deeplyFulfilled(p));\\nreturn noShim.E.when(Promise.all(valPs),(vals)=>harden(vals));}\\n\\ncase'tagged':{\\nconst tag=passStyleHelpers.getTag(val);\\nreturn noShim.E.when(deeplyFulfilled(val.payload),(payload)=>\\nmakeTagged.makeTagged(tag,payload));}\\n\\n\\ncase'remotable':{\\nreturn val;}\\n\\ncase'error':{\\nreturn val;}\\n\\ncase'promise':{\\nreturn noShim.E.when(val,(nonp)=>deeplyFulfilled(nonp));}\\n\\ndefault:{\\nthrow assert.fail(index.redacted`Unexpected passStyle ${index.quote(passStyle)}`,TypeError);}}};\\n\\n\\n\\nharden(deeplyFulfilled);exports.deeplyFulfilled=deeplyFulfilled;\",\n \"node_modules/@endo/marshal/src/encodePassable.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../pass-style/index.js');var index=require('../../errors/index.js');var passStyleOf=require('../../pass-style/src/passStyleOf.js');var typeGuards=require('../../pass-style/src/typeGuards.js');var passStyleHelpers=require('../../pass-style/src/passStyle-helpers.js');var makeTagged=require('../../pass-style/src/makeTagged.js');var error=require('../../pass-style/src/error.js');var symbol=require('../../pass-style/src/symbol.js');/* eslint-disable no-bitwise */\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nconst{isArray}=Array;\\nconst{fromEntries,is}=Object;\\nconst{ownKeys}=Reflect;\\n\\n/* eslint-disable-next-line no-control-regex*/\\nconst rC0=/[\\\\x00-\\\\x1F]/;\\n\\n/**\\n * Return the suffix of a string starting at a particular index.\\n * This both expresses intent and potentially avoids slow `substring` in XS.\\n * https://github.com/endojs/endo/issues/1984\\n *\\n * @param {string} str\\n * @param {number} index\\n * @returns {string}\\n */\\nconst getSuffix=(str,index)=>index===0?str:str.substring(index);\\n\\n/**\\n * Assuming that `record` is a CopyRecord, we have only\\n * string-named own properties. `recordNames` returns those name *reverse*\\n * sorted, because that's how records are compared, encoded, and sorted.\\n *\\n * @template {Passable} T\\n * @param {CopyRecord<T>} record\\n * @returns {string[]}\\n */\\nconst recordNames=(record)=>\\n/* https://github.com/endojs/endo/pull/1260#discussion_r1003657244*/\\n/* compares two ways of reverse sorting, and shows that `.sort().reverse()`*/\\n/* is currently faster on Moddable XS, while the other way,*/\\n/* `.sort(reverseComparator)`, is faster on v8. We currently care more about*/\\n/* XS performance, so we reverse sort using `.sort().reverse()`.*/\\nharden(/** @type {string[]} */ownKeys(record).sort().reverse());\\nharden(recordNames);\\n\\n/**\\n * Assuming that `record` is a CopyRecord and `names` is `recordNames(record)`,\\n * return the corresponding array of property values.\\n *\\n * @template {Passable} T\\n * @param {CopyRecord<T>} record\\n * @param {string[]} names\\n * @returns {T[]}\\n */\\nconst recordValues=(record,names)=>\\nharden(names.map((name)=>record[name]));\\nharden(recordValues);\\n\\nconst zeroes=Array(16).\\nfill(undefined).\\nmap((_,i)=>'0'.repeat(i));\\n\\n/**\\n * @param {unknown} n\\n * @param {number} size\\n * @returns {string}\\n */\\nconst zeroPad=(n,size)=>{\\nconst nStr=`${n}`;\\nconst fillLen=size-nStr.length;\\nif(fillLen===0)return nStr;\\nassert(fillLen>0&&fillLen<zeroes.length);\\nreturn`${zeroes[fillLen]}${nStr}`;};\\n\\nharden(zeroPad);\\n\\n/* This is the JavaScript analog to a C union: a way to map between a float as a*/\\n/* number and the bits that represent the float as a buffer full of bytes. Note*/\\n/* that the mutation of static state here makes this invalid Jessie code, but*/\\n/* doing it this way saves the nugatory and gratuitous allocations that would*/\\n/* happen every time you do a conversion -- and in practical terms it's safe*/\\n/* because we put the value in one side and then immediately take it out the*/\\n/* other; there is no actual state retained in the classic sense and thus no*/\\n/* re-entrancy issue.*/\\nconst asNumber=new Float64Array(1);\\nconst asBits=new BigUint64Array(asNumber.buffer);\\n\\n/* JavaScript numbers are encoded by outputting the base-16*/\\n/* representation of the binary value of the underlying IEEE floating point*/\\n/* representation. For negative values, all bits of this representation are*/\\n/* complemented prior to the base-16 conversion, while for positive values, the*/\\n/* sign bit is complemented. This ensures both that negative values sort before*/\\n/* positive values and that negative values sort according to their negative*/\\n/* magnitude rather than their positive magnitude. This results in an ASCII*/\\n/* encoding whose lexicographic sort order is the same as the numeric sort order*/\\n/* of the corresponding numbers.*/\\n\\n/* TODO Choose the same canonical NaN encoding that cosmWasm and ewasm chose.*/\\nconst CanonicalNaNBits='fff8000000000000';\\n\\n/**\\n * @param {number} n\\n * @returns {string}\\n */\\nconst encodeBinary64=(n)=>{\\n/* Normalize -0 to 0 and NaN to a canonical encoding*/\\nif(is(n,-0)){\\nn=0;}else\\nif(is(n,NaN)){\\nreturn`f${CanonicalNaNBits}`;}\\n\\nasNumber[0]=n;\\nlet bits=asBits[0];\\nif(n<0){\\nbits^=0xffffffffffffffffn;}else\\n{\\nbits^=0x8000000000000000n;}\\n\\nreturn`f${zeroPad(bits.toString(16),16)}`;};\\n\\n\\n/**\\n * @param {string} encoded\\n * @param {number} [skip]\\n * @returns {number}\\n */\\nconst decodeBinary64=(encoded,skip=0)=>{\\nencoded.charAt(skip)==='f'||index.throwRedacted`Encoded number expected: ${encoded}`;\\nlet bits=BigInt(`0x${getSuffix(encoded,skip+1)}`);\\nif(encoded.charAt(skip+1)<'8'){\\nbits^=0xffffffffffffffffn;}else\\n{\\nbits^=0x8000000000000000n;}\\n\\nasBits[0]=bits;\\nconst result=asNumber[0];\\n!is(result,-0)||\\nindex.throwRedacted`Unexpected negative zero: ${getSuffix(encoded,skip)}`;\\nreturn result;};\\n\\n\\n/**\\n * Encode a JavaScript bigint using a variant of Elias delta coding, with an\\n * initial component for the length of the digit count as a unary string, a\\n * second component for the decimal digit count, and a third component for the\\n * decimal digits preceded by a gratuitous separating colon.\\n * To ensure that the lexicographic sort order of encoded values matches the\\n * numeric sort order of the corresponding numbers, the characters of the unary\\n * prefix are different for negative values (type \\\"n\\\" followed by any number of\\n * \\\"#\\\"s [which sort before decimal digits]) vs. positive and zero values (type\\n * \\\"p\\\" followed by any number of \\\"~\\\"s [which sort after decimal digits]) and\\n * each decimal digit of the encoding for a negative value is replaced with its\\n * ten's complement (so that negative values of the same scale sort by\\n * *descending* absolute value).\\n *\\n * @param {bigint} n\\n * @returns {string}\\n */\\nconst encodeBigInt=(n)=>{\\nconst abs=n<0n?-n:n;\\nconst nDigits=abs.toString().length;\\nconst lDigits=nDigits.toString().length;\\nif(n<0n){\\nreturn`n${\\n/* A \\\"#\\\" for each digit beyond the first*/\\n/* in the decimal *count* of decimal digits.*/\\n'#'.repeat(lDigits-1)\\n}${\\n/* The ten's complement of the count of digits.*/\\n(10**lDigits-nDigits).toString().padStart(lDigits,'0')\\n}:${\\n/* The ten's complement of the digits.*/\\n(10n**BigInt(nDigits)+n).toString().padStart(nDigits,'0')\\n}`;}else\\n{\\nreturn`p${\\n/* A \\\"~\\\" for each digit beyond the first*/\\n/* in the decimal *count* of decimal digits.*/\\n'~'.repeat(lDigits-1)\\n}${\\n/* The count of digits.*/\\nnDigits\\n}:${\\n/* The digits.*/\\nn\\n}`;}};\\n\\n\\n\\nconst rBigIntPayload=/([0-9]+)(:([0-9]+$|)|)/s;\\n\\n/**\\n * @param {string} encoded\\n * @returns {bigint}\\n */\\nconst decodeBigInt=(encoded)=>{\\nconst typePrefix=encoded.charAt(0);/* faster than encoded[0]*/\\ntypePrefix==='p'||\\ntypePrefix==='n'||\\nindex.throwRedacted`Encoded bigint expected: ${encoded}`;\\n\\nconst{\\nindex:lDigits,\\n1:snDigits,\\n2:tail,\\n3:digits}=\\nencoded.match(rBigIntPayload)||index.throwRedacted`Digit count expected: ${encoded}`;\\n\\nsnDigits.length===lDigits||\\nindex.throwRedacted`Unary-prefixed decimal digit count expected: ${encoded}`;\\nlet nDigits=parseInt(snDigits,10);\\nif(typePrefix==='n'){\\n/* TODO Assert to reject forbidden encodings*/\\n/* like \\\"n0:\\\" and \\\"n00:…\\\" and \\\"n91:…\\\" through \\\"n99:…\\\"?*/\\nnDigits=10**/** @type {number} */lDigits-nDigits;}\\n\\n\\ntail.charAt(0)===':'||index.throwRedacted`Separator expected: ${encoded}`;\\ndigits.length===nDigits||\\nindex.throwRedacted`Fixed-length digit sequence expected: ${encoded}`;\\nlet n=BigInt(digits);\\nif(typePrefix==='n'){\\n/* TODO Assert to reject forbidden encodings*/\\n/* like \\\"n9:0\\\" and \\\"n8:00\\\" and \\\"n8:91\\\" through \\\"n8:99\\\"?*/\\nn=-(10n**BigInt(nDigits)-n);}\\n\\n\\nreturn n;};\\n\\n\\n/**\\n * A sparse array for which every present index maps a code point in the ASCII\\n * range to a corresponding escape sequence.\\n *\\n * Escapes all characters from U+0000 NULL to U+001F INFORMATION SEPARATOR ONE\\n * like `!<character offset by 0x21>` to avoid JSON.stringify expansion as\\n * `\\\\uHHHH`, and specially escapes U+0020 SPACE (the array element terminator)\\n * as `!_` and U+0021 EXCLAMATION MARK (the escape prefix) as `!|` (both chosen\\n * for visual approximation).\\n * Relative lexicographic ordering is preserved by this mapping of any character\\n * at or before `!` in the contiguous range [0x00..0x21] to a respective\\n * character in [0x21..0x40, 0x5F, 0x7C] preceded by `!` (which is itself in the\\n * replaced range).\\n * Similarly, escapes `^` as `_@` and `_` as `__` because `^` indicates the\\n * start of an encoded array.\\n *\\n * @type {Array<string>}\\n */\\nconst stringEscapes=Array(0x22).\\nfill(undefined).\\nmap((_,cp)=>{\\nswitch(String.fromCharCode(cp)){\\ncase' ':\\nreturn'!_';\\ncase'!':\\nreturn'!|';\\ndefault:\\nreturn`!${String.fromCharCode(cp+0x21)}`;}});\\n\\n\\nstringEscapes['^'.charCodeAt(0)]='_@';\\nstringEscapes['_'.charCodeAt(0)]='__';\\n\\n/**\\n * Encodes a string with escape sequences for use in the \\\"compactOrdered\\\" format.\\n *\\n * @type {(str: string) => string}\\n */\\nconst encodeCompactStringSuffix=(str)=>\\nstr.replace(/[\\\\0-!^_]/g,(ch)=>stringEscapes[ch.charCodeAt(0)]);\\n\\n/**\\n * Decodes a string from the \\\"compactOrdered\\\" format.\\n *\\n * @type {(encoded: string) => string}\\n */\\nconst decodeCompactStringSuffix=(encoded)=>{\\nreturn encoded.replace(/([\\\\0-!_])(.|\\\\n)?/g,(esc,prefix,suffix)=>{\\nswitch(esc){\\ncase'!_':\\nreturn' ';\\ncase'!|':\\nreturn'!';\\ncase'_@':\\nreturn'^';\\ncase'__':\\nreturn'_';\\ndefault:{\\nconst ch=/** @type {string} */suffix;\\n/* The range of valid `!`-escape suffixes is [(0x00+0x21)..(0x1F+0x21)], i.e.*/\\n/* [0x21..0x40] (U+0021 EXCLAMATION MARK to U+0040 COMMERCIAL AT).*/\\nprefix==='!'&&suffix!==undefined&&ch>='!'&&ch<='@'||\\nindex.throwRedacted`invalid string escape: ${index.quote(esc)}`;\\nreturn String.fromCharCode(ch.charCodeAt(0)-0x21);}}});};\\n\\n\\n\\n\\n\\n/**\\n * Trivially identity-encodes a string for use in the \\\"legacyOrdered\\\" format.\\n *\\n * @type {(str: string) => string}\\n */\\nconst encodeLegacyStringSuffix=(str)=>str;\\n\\n/**\\n * Trivially identity-decodes a string from the \\\"legacyOrdered\\\" format.\\n *\\n * @type {(encoded: string) => string}\\n */\\nconst decodeLegacyStringSuffix=(encoded)=>encoded;\\n\\n/**\\n * Encodes an array into a sequence of encoded elements for use in the \\\"compactOrdered\\\"\\n * format, each terminated by a space (which is part of the escaped range in\\n * \\\"compactOrdered\\\" encoded strings).\\n *\\n * @param {Passable[]} array\\n * @param {(p: Passable) => string} encodePassable\\n * @returns {string}\\n */\\nconst encodeCompactArray=(array,encodePassable)=>{\\nconst chars=['^'];\\nfor(const element of array){\\nconst enc=encodePassable(element);\\nchars.push(enc,' ');}\\n\\nreturn chars.join('');};\\n\\n\\n/**\\n * @param {string} encoded\\n * @param {(encoded: string) => Passable} decodePassable\\n * @param {number} [skip]\\n * @returns {Array}\\n */\\nconst decodeCompactArray=(encoded,decodePassable,skip=0)=>{\\nconst elements=[];\\nlet depth=0;\\n/* Scan encoded rather than its tail to avoid slow `substring` in XS.*/\\n/* https://github.com/endojs/endo/issues/1984*/\\nlet nextIndex=skip+1;\\nlet currentElementStart=skip+1;\\nfor(const{0:ch,index:i}of encoded.matchAll(/[\\\\^ ]/g)){\\nconst index$1=/** @type {number} */i;\\nif(index$1<=skip){\\nif(index$1===skip){\\nch==='^'||index.throwRedacted`Encoded array expected: ${getSuffix(encoded,skip)}`;}}else\\n\\nif(ch==='^'){\\n/* This is the start of a nested array.*/\\n/* TODO: Since the syntax of nested arrays must be validated as part of*/\\n/* decoding the outer one, consider decoding them here into a shared cache*/\\n/* rather than discarding information about their contents until the later*/\\n/* decodePassable.*/\\ndepth+=1;}else\\n{\\n/* This is a terminated element.*/\\nif(index$1===nextIndex){\\n/* A terminator after `[` or an another terminator indicates that an array is done.*/\\ndepth-=1;\\ndepth>=0||\\n/* prettier-ignore*/\\nindex.throwRedacted`unexpected array element terminator: ${encoded.slice(skip,index$1+2)}`;}\\n\\nif(depth===0){\\n/* We have a complete element of the topmost array.*/\\nelements.push(\\ndecodePassable(encoded.slice(currentElementStart,index$1)));\\n\\ncurrentElementStart=index$1+1;}}\\n\\n\\n/* Advance the index.*/\\nnextIndex=index$1+1;}\\n\\ndepth===0||index.throwRedacted`unterminated array: ${getSuffix(encoded,skip)}`;\\nnextIndex===encoded.length||\\nindex.throwRedacted`unterminated array element: ${getSuffix(\\nencoded,\\ncurrentElementStart)\\n}`;\\nreturn harden(elements);};\\n\\n\\n/**\\n * Performs the original array encoding, which escapes all encoded array\\n * elements rather than just strings (`\\\\u0000` as the element terminator and\\n * `\\\\u0001` as the escape prefix for `\\\\u0000` or `\\\\u0001`).\\n * This necessitated an undesirable amount of iteration and expansion; see\\n * https://github.com/endojs/endo/pull/1260#discussion_r960369826\\n *\\n * @param {Passable[]} array\\n * @param {(p: Passable) => string} encodePassable\\n * @returns {string}\\n */\\nconst encodeLegacyArray=(array,encodePassable)=>{\\nconst chars=['['];\\nfor(const element of array){\\nconst enc=encodePassable(element);\\nfor(const c of enc){\\nif(c==='\\\\u0000'||c==='\\\\u0001'){\\nchars.push('\\\\u0001');}\\n\\nchars.push(c);}\\n\\nchars.push('\\\\u0000');}\\n\\nreturn chars.join('');};\\n\\n\\n/**\\n * @param {string} encoded\\n * @param {(encoded: string) => Passable} decodePassable\\n * @param {number} [skip]\\n * @returns {Array}\\n */\\nconst decodeLegacyArray=(encoded,decodePassable,skip=0)=>{\\nconst elements=[];\\nconst elemChars=[];\\n/* Use a string iterator to avoid slow indexed access in XS.*/\\n/* https://github.com/endojs/endo/issues/1984*/\\nlet stillToSkip=skip+1;\\nlet inEscape=false;\\nfor(const c of encoded){\\nif(stillToSkip>0){\\nstillToSkip-=1;\\nif(stillToSkip===0){\\nc==='['||index.throwRedacted`Encoded array expected: ${getSuffix(encoded,skip)}`;}}else\\n\\nif(inEscape){\\nc==='\\\\u0000'||\\nc==='\\\\u0001'||\\nindex.throwRedacted`Unexpected character after u0001 escape: ${c}`;\\nelemChars.push(c);}else\\nif(c==='\\\\u0000'){\\nconst encodedElement=elemChars.join('');\\nelemChars.length=0;\\nconst element=decodePassable(encodedElement);\\nelements.push(element);}else\\nif(c==='\\\\u0001'){\\ninEscape=true;\\n/* eslint-disable-next-line no-continue*/\\ncontinue;}else\\n{\\nelemChars.push(c);}\\n\\ninEscape=false;}\\n\\n!inEscape||index.throwRedacted`unexpected end of encoding ${getSuffix(encoded,skip)}`;\\nelemChars.length===0||\\nindex.throwRedacted`encoding terminated early: ${getSuffix(encoded,skip)}`;\\nreturn harden(elements);};\\n\\n\\nconst encodeRecord=(record,encodeArray,encodePassable)=>{\\nconst names=recordNames(record);\\nconst values=recordValues(record,names);\\nreturn`(${encodeArray(harden([names,values]),encodePassable)}`;};\\n\\n\\nconst decodeRecord=(encoded,decodeArray,decodePassable,skip=0)=>{\\nassert(encoded.charAt(skip)==='(');\\n/* Skip the \\\"(\\\" inside `decodeArray` to avoid slow `substring` in XS.*/\\n/* https://github.com/endojs/endo/issues/1984*/\\nconst unzippedEntries=decodeArray(encoded,decodePassable,skip+1);\\nunzippedEntries.length===2||\\nindex.throwRedacted`expected keys,values pair: ${getSuffix(encoded,skip)}`;\\nconst[keys,vals]=unzippedEntries;\\n\\npassStyleOf.passStyleOf(keys)==='copyArray'&&\\npassStyleOf.passStyleOf(vals)==='copyArray'&&\\nkeys.length===vals.length&&\\nkeys.every((key)=>typeof key==='string')||\\nindex.throwRedacted`not a valid record encoding: ${getSuffix(encoded,skip)}`;\\nconst mapEntries=keys.map((key,i)=>[key,vals[i]]);\\nconst record=harden(fromEntries(mapEntries));\\ntypeGuards.assertRecord(record,'decoded record');\\nreturn record;};\\n\\n\\nconst encodeTagged=(tagged,encodeArray,encodePassable)=>\\n`:${encodeArray(harden([passStyleHelpers.getTag(tagged),tagged.payload]),encodePassable)}`;\\n\\nconst decodeTagged=(encoded,decodeArray,decodePassable,skip=0)=>{\\nassert(encoded.charAt(skip)===':');\\n/* Skip the \\\":\\\" inside `decodeArray` to avoid slow `substring` in XS.*/\\n/* https://github.com/endojs/endo/issues/1984*/\\nconst taggedPayload=decodeArray(encoded,decodePassable,skip+1);\\ntaggedPayload.length===2||\\nindex.throwRedacted`expected tag,payload pair: ${getSuffix(encoded,skip)}`;\\nconst[tag,payload]=taggedPayload;\\npassStyleOf.passStyleOf(tag)==='string'||\\nindex.throwRedacted`not a valid tagged encoding: ${getSuffix(encoded,skip)}`;\\nreturn makeTagged.makeTagged(tag,payload);};\\n\\n\\nconst makeEncodeRemotable=(unsafeEncodeRemotable,verifyEncoding)=>{\\nconst encodeRemotable=(r,innerEncode)=>{\\nconst encoding=unsafeEncodeRemotable(r,innerEncode);\\ntypeof encoding==='string'&&encoding.charAt(0)==='r'||\\nindex.throwRedacted`Remotable encoding must start with \\\"r\\\": ${encoding}`;\\nverifyEncoding(encoding,'Remotable');\\nreturn encoding;};\\n\\nreturn encodeRemotable;};\\n\\n\\nconst makeEncodePromise=(unsafeEncodePromise,verifyEncoding)=>{\\nconst encodePromise=(p,innerEncode)=>{\\nconst encoding=unsafeEncodePromise(p,innerEncode);\\ntypeof encoding==='string'&&encoding.charAt(0)==='?'||\\nindex.throwRedacted`Promise encoding must start with \\\"?\\\": ${encoding}`;\\nverifyEncoding(encoding,'Promise');\\nreturn encoding;};\\n\\nreturn encodePromise;};\\n\\n\\nconst makeEncodeError=(unsafeEncodeError,verifyEncoding)=>{\\nconst encodeError=(err,innerEncode)=>{\\nconst encoding=unsafeEncodeError(err,innerEncode);\\ntypeof encoding==='string'&&encoding.charAt(0)==='!'||\\nindex.throwRedacted`Error encoding must start with \\\"!\\\": ${encoding}`;\\nverifyEncoding(encoding,'Error');\\nreturn encoding;};\\n\\nreturn encodeError;};\\n\\n\\n/**\\n * @typedef {object} EncodeOptions\\n * @property {(\\n * remotable: Remotable,\\n * encodeRecur: (p: Passable) => string,\\n * ) => string} [encodeRemotable]\\n * @property {(\\n * promise: Promise,\\n * encodeRecur: (p: Passable) => string,\\n * ) => string} [encodePromise]\\n * @property {(\\n * error: Error,\\n * encodeRecur: (p: Passable) => string,\\n * ) => string} [encodeError]\\n * @property {'legacyOrdered' | 'compactOrdered'} [format]\\n */\\n\\n/**\\n * @param {(str: string) => string} encodeStringSuffix\\n * @param {(arr: unknown[], encodeRecur: (p: Passable) => string) => string} encodeArray\\n * @param {Required<EncodeOptions> & {verifyEncoding?: (encoded: string, label: string) => void}} options\\n * @returns {(p: Passable) => string}\\n */\\nconst makeInnerEncode=(encodeStringSuffix,encodeArray,options)=>{\\nconst{\\nencodeRemotable:unsafeEncodeRemotable,\\nencodePromise:unsafeEncodePromise,\\nencodeError:unsafeEncodeError,\\nverifyEncoding=()=>{}}=\\noptions;\\nconst encodeRemotable=makeEncodeRemotable(\\nunsafeEncodeRemotable,\\nverifyEncoding);\\n\\nconst encodePromise=makeEncodePromise(unsafeEncodePromise,verifyEncoding);\\nconst encodeError=makeEncodeError(unsafeEncodeError,verifyEncoding);\\n\\nconst innerEncode=(passable)=>{\\nif(error.isErrorLike(passable)){\\n/* We pull out this special case to accommodate errors that are not*/\\n/* valid Passables. For example, because they're not frozen.*/\\n/* The special case can only ever apply at the root, and therefore*/\\n/* outside the recursion, since an error could only be deeper in*/\\n/* a passable structure if it were passable.*/\\n/**/\\n/* We pull out this special case because, for these errors, we're much*/\\n/* more interested in reporting whatever diagnostic information they*/\\n/* carry than we are about reporting problems encountered in reporting*/\\n/* this information.*/\\nreturn encodeError(passable,innerEncode);}\\n\\nconst passStyle=passStyleOf.passStyleOf(passable);\\nswitch(passStyle){\\ncase'null':{\\nreturn'v';}\\n\\ncase'undefined':{\\nreturn'z';}\\n\\ncase'number':{\\nreturn encodeBinary64(passable);}\\n\\ncase'string':{\\nreturn`s${encodeStringSuffix(passable)}`;}\\n\\ncase'boolean':{\\nreturn`b${passable}`;}\\n\\ncase'bigint':{\\nreturn encodeBigInt(passable);}\\n\\ncase'remotable':{\\nreturn encodeRemotable(passable,innerEncode);}\\n\\ncase'error':{\\nreturn encodeError(passable,innerEncode);}\\n\\ncase'promise':{\\nreturn encodePromise(passable,innerEncode);}\\n\\ncase'symbol':{\\n/* Strings and symbols share encoding logic.*/\\nconst name=symbol.nameForPassableSymbol(passable);\\nassert.typeof(name,'string');\\nreturn`y${encodeStringSuffix(name)}`;}\\n\\ncase'copyArray':{\\nreturn encodeArray(passable,innerEncode);}\\n\\ncase'copyRecord':{\\nreturn encodeRecord(passable,encodeArray,innerEncode);}\\n\\ncase'tagged':{\\nreturn encodeTagged(passable,encodeArray,innerEncode);}\\n\\ndefault:{\\nthrow index.throwRedacted`a ${index.quote(passStyle)} cannot be used as a collection passable`;}}};\\n\\n\\n\\nreturn innerEncode;};\\n\\n\\n/**\\n * @typedef {object} DecodeOptions\\n * @property {(\\n * encodedRemotable: string,\\n * decodeRecur: (e: string) => Passable\\n * ) => Remotable} [decodeRemotable]\\n * @property {(\\n * encodedPromise: string,\\n * decodeRecur: (e: string) => Passable\\n * ) => Promise} [decodePromise]\\n * @property {(\\n * encodedError: string,\\n * decodeRecur: (e: string) => Passable\\n * ) => Error} [decodeError]\\n */\\n\\nconst liberalDecoders=/** @type {Required<DecodeOptions>} */\\n/** @type {unknown} */{\\ndecodeRemotable:(_encoding,_innerDecode)=>undefined,\\ndecodePromise:(_encoding,_innerDecode)=>undefined,\\ndecodeError:(_encoding,_innerDecode)=>undefined};\\n\\n\\n\\n/**\\n * @param {(encoded: string) => string} decodeStringSuffix\\n * @param {(encoded: string, decodeRecur: (e: string) => Passable, skip?: number) => unknown[]} decodeArray\\n * @param {Required<DecodeOptions>} options\\n * @returns {(encoded: string, skip?: number) => Passable}\\n */\\nconst makeInnerDecode=(decodeStringSuffix,decodeArray,options)=>{\\nconst{decodeRemotable,decodePromise,decodeError}=options;\\nconst innerDecode=(encoded,skip=0)=>{\\nswitch(encoded.charAt(skip)){\\ncase'v':{\\nreturn null;}\\n\\ncase'z':{\\nreturn undefined;}\\n\\ncase'f':{\\nreturn decodeBinary64(encoded,skip);}\\n\\ncase's':{\\nreturn decodeStringSuffix(getSuffix(encoded,skip+1));}\\n\\ncase'b':{\\nconst substring=getSuffix(encoded,skip+1);\\nif(substring==='true'){\\nreturn true;}else\\nif(substring==='false'){\\nreturn false;}\\n\\nthrow index.throwRedacted`expected encoded boolean to be \\\"btrue\\\" or \\\"bfalse\\\": ${substring}`;}\\n\\ncase'n':\\ncase'p':{\\nreturn decodeBigInt(getSuffix(encoded,skip));}\\n\\ncase'r':{\\nreturn decodeRemotable(getSuffix(encoded,skip),innerDecode);}\\n\\ncase'?':{\\nreturn decodePromise(getSuffix(encoded,skip),innerDecode);}\\n\\ncase'!':{\\nreturn decodeError(getSuffix(encoded,skip),innerDecode);}\\n\\ncase'y':{\\n/* Strings and symbols share decoding logic.*/\\nconst name=decodeStringSuffix(getSuffix(encoded,skip+1));\\nreturn symbol.passableSymbolForName(name);}\\n\\ncase'[':\\ncase'^':{\\nreturn decodeArray(encoded,innerDecode,skip);}\\n\\ncase'(':{\\nreturn decodeRecord(encoded,decodeArray,innerDecode,skip);}\\n\\ncase':':{\\nreturn decodeTagged(encoded,decodeArray,innerDecode,skip);}\\n\\ndefault:{\\nthrow index.throwRedacted`invalid database key: ${getSuffix(encoded,skip)}`;}}};\\n\\n\\n\\n/* @ts-expect-error Type 'unknown' is not assignable to type 'Passable<PassableCap, Error>'.*/\\nreturn innerDecode;};\\n\\n\\n/**\\n * @typedef {object} PassableKit\\n * @property {ReturnType<makeInnerEncode>} encodePassable\\n * @property {ReturnType<makeInnerDecode>} decodePassable\\n */\\n\\n/**\\n * @param {EncodeOptions & DecodeOptions} [options]\\n * @returns {PassableKit}\\n */\\nconst makePassableKit=(options={})=>{\\nconst{\\nencodeRemotable=(r,_)=>index.throwRedacted`remotable unexpected: ${r}`,\\nencodePromise=(p,_)=>index.throwRedacted`promise unexpected: ${p}`,\\nencodeError=(err,_)=>index.throwRedacted`error unexpected: ${err}`,\\nformat='legacyOrdered',\\n\\ndecodeRemotable=(encoding,_)=>index.throwRedacted`remotable unexpected: ${encoding}`,\\ndecodePromise=(encoding,_)=>index.throwRedacted`promise unexpected: ${encoding}`,\\ndecodeError=(encoding,_)=>index.throwRedacted`error unexpected: ${encoding}`}=\\noptions;\\n\\n/** @type {PassableKit['encodePassable']} */\\nlet encodePassable;\\nconst encodeOptions={encodeRemotable,encodePromise,encodeError,format};\\nif(format==='compactOrdered'){\\nconst liberalDecode=makeInnerDecode(\\ndecodeCompactStringSuffix,\\ndecodeCompactArray,\\nliberalDecoders);\\n\\n/**\\n * @param {string} encoding\\n * @param {string} label\\n * @returns {void}\\n */\\nconst verifyEncoding=(encoding,label)=>{\\n!encoding.match(rC0)||\\nindex.throwRedacted`${index.bare(\\nlabel)\\n} encoding must not contain a C0 control character: ${encoding}`;\\nconst decoded=decodeCompactArray(`^v ${encoding} v `,liberalDecode);\\nisArray(decoded)&&\\ndecoded.length===3&&\\ndecoded[0]===null&&\\ndecoded[2]===null||\\nindex.throwRedacted`${index.bare(label)} encoding must be embeddable: ${encoding}`;};\\n\\nconst encodeCompact=makeInnerEncode(\\nencodeCompactStringSuffix,\\nencodeCompactArray,\\n{...encodeOptions,verifyEncoding});\\n\\nencodePassable=(passable)=>`~${encodeCompact(passable)}`;}else\\nif(format==='legacyOrdered'){\\nencodePassable=makeInnerEncode(\\nencodeLegacyStringSuffix,\\nencodeLegacyArray,\\nencodeOptions);}else\\n\\n{\\nthrow index.throwRedacted`Unrecognized format: ${index.quote(format)}`;}\\n\\n\\nconst decodeOptions={decodeRemotable,decodePromise,decodeError};\\nconst decodeCompact=makeInnerDecode(\\ndecodeCompactStringSuffix,\\ndecodeCompactArray,\\ndecodeOptions);\\n\\nconst decodeLegacy=makeInnerDecode(\\ndecodeLegacyStringSuffix,\\ndecodeLegacyArray,\\ndecodeOptions);\\n\\nconst decodePassable=(encoded)=>{\\n/* A leading \\\"~\\\" indicates the v2 encoding (with escaping in strings rather than arrays).*/\\n/* Skip it inside `decodeCompact` to avoid slow `substring` in XS.*/\\n/* https://github.com/endojs/endo/issues/1984*/\\nif(encoded.charAt(0)==='~'){\\nreturn decodeCompact(encoded,1);}\\n\\nreturn decodeLegacy(encoded);};\\n\\n\\nreturn harden({encodePassable,decodePassable});};\\n\\nharden(makePassableKit);\\n\\n/**\\n * @param {EncodeOptions} [encodeOptions]\\n * @returns {PassableKit['encodePassable']}\\n */\\nconst makeEncodePassable=(encodeOptions)=>{\\nconst{encodePassable}=makePassableKit(encodeOptions);\\nreturn encodePassable;};\\n\\nharden(makeEncodePassable);\\n\\n/**\\n * @param {DecodeOptions} [decodeOptions]\\n * @returns {PassableKit['decodePassable']}\\n */\\nconst makeDecodePassable=(decodeOptions)=>{\\nconst{decodePassable}=makePassableKit(decodeOptions);\\nreturn decodePassable;};\\n\\nharden(makeDecodePassable);\\n\\nconst isEncodedRemotable=(encoded)=>encoded.charAt(0)==='r';\\nharden(isEncodedRemotable);\\n\\n/* /////////////////////////////////////////////////////////////////////////////*/\\n\\n/**\\n * @type {Record<PassStyle, string>}\\n * The single prefix characters to be used for each PassStyle category.\\n * `bigint` is a two-character string because each of those characters\\n * individually is a valid bigint prefix (`n` for \\\"negative\\\" and `p` for\\n * \\\"positive\\\"), and copyArray is a two-character string because one encoding\\n * prefixes arrays with `[` while the other uses `^` (which is prohibited from\\n * appearing in an encoded string).\\n * The ordering of these prefixes is the same as the rankOrdering of their\\n * respective PassStyles, and rankOrder.js imports the table for this purpose.\\n *\\n * In addition, `|` is the remotable->ordinal mapping prefix:\\n * This is not used in covers but it is\\n * reserved from the same set of strings. Note that the prefix is > any\\n * prefix used by any cover so that ordinal mapping keys are always outside\\n * the range of valid collection entry keys.\\n */\\nconst passStylePrefixes={\\nerror:'!',\\ncopyRecord:'(',\\ntagged:':',\\npromise:'?',\\ncopyArray:'[^',\\nboolean:'b',\\nnumber:'f',\\nbigint:'np',\\nremotable:'r',\\nstring:'s',\\nnull:'v',\\nsymbol:'y',\\nundefined:'z'};\\n\\nObject.setPrototypeOf(passStylePrefixes,null);\\nharden(passStylePrefixes);exports.isEncodedRemotable=isEncodedRemotable;exports.makeDecodePassable=makeDecodePassable;exports.makeEncodePassable=makeEncodePassable;exports.makePassableKit=makePassableKit;exports.passStylePrefixes=passStylePrefixes;exports.recordNames=recordNames;exports.recordValues=recordValues;exports.zeroPad=zeroPad;\",\n \"node_modules/@endo/marshal/src/encodeToCapData.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../pass-style/index.js');var index=require('../../errors/index.js');var passStyleHelpers=require('../../pass-style/src/passStyle-helpers.js');var passStyleOf=require('../../pass-style/src/passStyleOf.js');var symbol=require('../../pass-style/src/symbol.js');var error=require('../../pass-style/src/error.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nmakeTagged=require('../../pass-style/src/makeTagged.js');/*/ <reference types=\\\"ses\\\"/>*/ /** @import {Passable, RemotableObject} from '@endo/pass-style' */ /** @import {Encoding, EncodingUnion} from './types.js' */\\n\\nconst{ownKeys}=Reflect;\\nconst{isArray}=Array;\\nconst{\\ngetOwnPropertyDescriptors,\\ndefineProperties,\\nis,\\nentries,\\nfromEntries,\\nfreeze}=\\nObject;\\n\\n/**\\n * Special property name that indicates an encoding that needs special\\n * decoding.\\n */\\nconst QCLASS='@qclass';\\n\\n\\n/**\\n * @param {Encoding} encoded\\n * @returns {encoded is EncodingUnion}\\n */\\nconst hasQClass=(encoded)=>passStyleHelpers.hasOwnPropertyOf(encoded,QCLASS);\\n\\n/**\\n * @param {Encoding} encoded\\n * @param {string} qclass\\n * @returns {boolean}\\n */\\nconst qclassMatches=(encoded,qclass)=>\\npassStyleHelpers.isObject(encoded)&&\\n!isArray(encoded)&&\\nhasQClass(encoded)&&\\nencoded[QCLASS]===qclass;\\n\\n/**\\n * @typedef {object} EncodeToCapDataOptions\\n * @property {(\\n * remotable: RemotableObject,\\n * encodeRecur: (p: Passable) => Encoding\\n * ) => Encoding} [encodeRemotableToCapData]\\n * @property {(\\n * promise: Promise,\\n * encodeRecur: (p: Passable) => Encoding\\n * ) => Encoding} [encodePromiseToCapData]\\n * @property {(\\n * error: Error,\\n * encodeRecur: (p: Passable) => Encoding\\n * ) => Encoding} [encodeErrorToCapData]\\n */\\n\\nconst dontEncodeRemotableToCapData=(rem)=>index.throwRedacted`remotable unexpected: ${rem}`;\\n\\nconst dontEncodePromiseToCapData=(prom)=>index.throwRedacted`promise unexpected: ${prom}`;\\n\\nconst dontEncodeErrorToCapData=(err)=>index.throwRedacted`error object unexpected: ${err}`;\\n\\n/**\\n * @param {EncodeToCapDataOptions} [encodeOptions]\\n * @returns {(passable: Passable) => Encoding}\\n */\\nconst makeEncodeToCapData=(encodeOptions={})=>{\\nconst{\\nencodeRemotableToCapData=dontEncodeRemotableToCapData,\\nencodePromiseToCapData=dontEncodePromiseToCapData,\\nencodeErrorToCapData=dontEncodeErrorToCapData}=\\nencodeOptions;\\n\\n/**\\n * Must encode `val` into plain JSON data *canonically*, such that\\n * `JSON.stringify(encode(v1)) === JSON.stringify(encode(v1))`. For most\\n * encodings, the order of properties of each node of the output\\n * structure is determined by the algorithm below without special\\n * arrangement, usually by being expressed directly as an object literal.\\n * The exception is copyRecords, whose natural enumeration order\\n * can differ between copyRecords that our distributed object semantics\\n * considers to be equivalent.\\n * Since, for each copyRecord, we only accept string property names,\\n * not symbols, we can canonically sort the names first.\\n * JSON.stringify will then visit these in that sorted order.\\n *\\n * Encoding with a canonical-JSON encoder would also solve this canonicalness\\n * problem in a more modular and encapsulated manner. Note that the\\n * actual order produced here, though it agrees with canonical-JSON on\\n * copyRecord property ordering, differs from canonical-JSON as a whole\\n * in that the other record properties are visited in the order in which\\n * they are literally written below. TODO perhaps we should indeed switch\\n * to a canonical JSON encoder, and not delicately depend on the order\\n * in which these object literals are written.\\n *\\n * Readers must not care about this order anyway. We impose this requirement\\n * mainly to reduce non-determinism exposed outside a vat.\\n *\\n * @param {any} passable\\n * @returns {Encoding} except that `encodeToCapData` does not generally\\n * `harden` this result before returning. Rather, `encodeToCapData` is not\\n * directly exposed.\\n * What's exposed instead is a wrapper that freezes the output before\\n * returning. If this turns out to impede static analysis for `harden` safety,\\n * we can always put the (now redundant) hardens back in. They don't hurt.\\n */\\nconst encodeToCapDataRecur=(passable)=>{\\n/* First we handle all primitives. Some can be represented directly as*/\\n/* JSON, and some must be encoded as [QCLASS] composites.*/\\nconst passStyle=passStyleOf.passStyleOf(passable);\\nswitch(passStyle){\\ncase'null':\\ncase'boolean':\\ncase'string':{\\n/* pass through to JSON*/\\nreturn passable;}\\n\\ncase'undefined':{\\nreturn{[QCLASS]:'undefined'};}\\n\\ncase'number':{\\n/* Special-case numbers with no digit-based representation.*/\\nif(Number.isNaN(passable)){\\nreturn{[QCLASS]:'NaN'};}else\\nif(passable===Infinity){\\nreturn{[QCLASS]:'Infinity'};}else\\nif(passable===-Infinity){\\nreturn{[QCLASS]:'-Infinity'};}\\n\\n/* Pass through everything else, replacing -0 with 0.*/\\nreturn is(passable,-0)?0:passable;}\\n\\ncase'bigint':{\\nreturn{\\n[QCLASS]:'bigint',\\ndigits:String(passable)};}\\n\\n\\ncase'symbol':{\\nsymbol.assertPassableSymbol(passable);\\nconst name=/** @type {string} */symbol.nameForPassableSymbol(passable);\\nreturn{\\n[QCLASS]:'symbol',\\nname};}\\n\\n\\ncase'copyRecord':{\\nif(passStyleHelpers.hasOwnPropertyOf(passable,QCLASS)){\\n/* Hilbert hotel*/\\nconst{[QCLASS]:qclassValue,...rest}=passable;\\n/** @type {Encoding} */\\nconst result={\\n[QCLASS]:'hilbert',\\noriginal:encodeToCapDataRecur(qclassValue)};\\n\\nif(ownKeys(rest).length>=1){\\n/* We harden the entire capData encoding before we return it.*/\\n/* `encodeToCapData` requires that its input be Passable, and*/\\n/* therefore hardened.*/\\n/* The `freeze` here is needed anyway, because the `rest` is*/\\n/* freshly constructed by the `...` above, and we're using it*/\\n/* as imput in another call to `encodeToCapData`.*/\\nresult.rest=encodeToCapDataRecur(freeze(rest));}\\n\\nreturn result;}\\n\\n/* Currently copyRecord allows only string keys so this will*/\\n/* work. If we allow sortable symbol keys, this will need to*/\\n/* become more interesting.*/\\nconst names=ownKeys(passable).sort();\\nreturn fromEntries(\\nnames.map((name)=>[name,encodeToCapDataRecur(passable[name])]));}\\n\\n\\ncase'copyArray':{\\nreturn passable.map(encodeToCapDataRecur);}\\n\\ncase'tagged':{\\nreturn{\\n[QCLASS]:'tagged',\\ntag:passStyleHelpers.getTag(passable),\\npayload:encodeToCapDataRecur(passable.payload)};}\\n\\n\\ncase'remotable':{\\nconst encoded=encodeRemotableToCapData(\\npassable,\\nencodeToCapDataRecur);\\n\\nif(qclassMatches(encoded,'slot')){\\nreturn encoded;}\\n\\n/* `throw` is noop since `Fail` throws. But linter confused*/\\nthrow index.throwRedacted`internal: Remotable encoding must be an object with ${index.quote(\\nQCLASS)\\n} ${index.quote('slot')}: ${encoded}`;}\\n\\ncase'promise':{\\nconst encoded=encodePromiseToCapData(passable,encodeToCapDataRecur);\\nif(qclassMatches(encoded,'slot')){\\nreturn encoded;}\\n\\nthrow index.throwRedacted`internal: Promise encoding must be an object with ${index.quote(\\nQCLASS,\\n'slot')\\n}: ${encoded}`;}\\n\\ncase'error':{\\nconst encoded=encodeErrorToCapData(passable,encodeToCapDataRecur);\\nif(qclassMatches(encoded,'error')){\\nreturn encoded;}\\n\\nthrow index.throwRedacted`internal: Error encoding must be an object with ${index.quote(\\nQCLASS,\\n'error')\\n}: ${encoded}`;}\\n\\ndefault:{\\nthrow assert.fail(\\nindex.redacted`internal: Unrecognized passStyle ${index.quote(passStyle)}`,\\nTypeError);}}};\\n\\n\\n\\n\\nconst encodeToCapData=(passable)=>{\\nif(error.isErrorLike(passable)){\\n/* We pull out this special case to accommodate errors that are not*/\\n/* valid Passables. For example, because they're not frozen.*/\\n/* The special case can only ever apply at the root, and therefore*/\\n/* outside the recursion, since an error could only be deeper in*/\\n/* a passable structure if it were passable.*/\\n/**/\\n/* We pull out this special case because, for these errors, we're much*/\\n/* more interested in reporting whatever diagnostic information they*/\\n/* carry than we are about reporting problems encountered in reporting*/\\n/* this information.*/\\nreturn harden(encodeErrorToCapData(passable,encodeToCapDataRecur));}\\n\\nreturn harden(encodeToCapDataRecur(passable));};\\n\\nreturn harden(encodeToCapData);};\\n\\nharden(makeEncodeToCapData);\\n\\n/**\\n * @typedef {object} DecodeOptions\\n * @property {(\\n * encodedRemotable: Encoding,\\n * decodeRecur: (e: Encoding) => Passable\\n * ) => (Promise|RemotableObject)} [decodeRemotableFromCapData]\\n * @property {(\\n * encodedPromise: Encoding,\\n * decodeRecur: (e: Encoding) => Passable\\n * ) => (Promise|RemotableObject)} [decodePromiseFromCapData]\\n * @property {(\\n * encodedError: Encoding,\\n * decodeRecur: (e: Encoding) => Passable\\n * ) => Error} [decodeErrorFromCapData]\\n */\\n\\nconst dontDecodeRemotableOrPromiseFromCapData=(slotEncoding)=>\\nindex.throwRedacted`remotable or promise unexpected: ${slotEncoding}`;\\nconst dontDecodeErrorFromCapData=(errorEncoding)=>\\nindex.throwRedacted`error unexpected: ${errorEncoding}`;\\n\\n/**\\n * The current encoding does not give the decoder enough into to distinguish\\n * whether a slot represents a promise or a remotable. As an implementation\\n * restriction until this is fixed, if either is provided, both must be\\n * provided and they must be the same.\\n *\\n * This seems like the best starting point to incrementally evolve to an\\n * API where these can reliably differ.\\n * See https://github.com/Agoric/agoric-sdk/issues/4334\\n *\\n * @param {DecodeOptions} [decodeOptions]\\n * @returns {(encoded: Encoding) => Passable}\\n */\\nconst makeDecodeFromCapData=(decodeOptions={})=>{\\nconst{\\ndecodeRemotableFromCapData=dontDecodeRemotableOrPromiseFromCapData,\\ndecodePromiseFromCapData=dontDecodeRemotableOrPromiseFromCapData,\\ndecodeErrorFromCapData=dontDecodeErrorFromCapData}=\\ndecodeOptions;\\n\\ndecodeRemotableFromCapData===decodePromiseFromCapData||\\nindex.throwRedacted`An implementation restriction for now: If either decodeRemotableFromCapData or decodePromiseFromCapData is provided, both must be provided and they must be the same: ${index.quote(\\ndecodeRemotableFromCapData)\\n} vs ${index.quote(decodePromiseFromCapData)}`;\\n\\n/**\\n * `decodeFromCapData` may rely on `jsonEncoded` being the result of a\\n * plain call to JSON.parse. However, it *cannot* rely on `jsonEncoded`\\n * having been produced by JSON.stringify on the output of `encodeToCapData`\\n * above, i.e., `decodeFromCapData` cannot rely on `jsonEncoded` being a\\n * valid marshalled representation. Rather, `decodeFromCapData` must\\n * validate that.\\n *\\n * @param {Encoding} jsonEncoded must be hardened\\n */\\nconst decodeFromCapData=(jsonEncoded)=>{\\nif(!passStyleHelpers.isObject(jsonEncoded)){\\n/* primitives pass through*/\\nreturn jsonEncoded;}\\n\\nif(isArray(jsonEncoded)){\\nreturn jsonEncoded.map((encodedVal)=>decodeFromCapData(encodedVal));}else\\nif(hasQClass(jsonEncoded)){\\nconst qclass=jsonEncoded[QCLASS];\\ntypeof qclass==='string'||\\nindex.throwRedacted`invalid ${index.quote(QCLASS)} typeof ${index.quote(typeof qclass)}`;\\nswitch(qclass){\\n/* Encoding of primitives not handled by JSON*/\\ncase'undefined':{\\nreturn undefined;}\\n\\ncase'NaN':{\\nreturn NaN;}\\n\\ncase'Infinity':{\\nreturn Infinity;}\\n\\ncase'-Infinity':{\\nreturn-Infinity;}\\n\\ncase'bigint':{\\nconst{digits}=jsonEncoded;\\ntypeof digits==='string'||\\nindex.throwRedacted`invalid digits typeof ${index.quote(typeof digits)}`;\\nreturn BigInt(digits);}\\n\\ncase'@@asyncIterator':{\\n/* Deprecated qclass. TODO make conditional*/\\n/* on environment variable. Eventually remove, but after confident*/\\n/* that there are no more supported senders.*/\\n/**/\\nreturn Symbol.asyncIterator;}\\n\\ncase'symbol':{\\nconst{name}=jsonEncoded;\\nreturn symbol.passableSymbolForName(name);}\\n\\ncase'tagged':{\\nconst{tag,payload}=jsonEncoded;\\nreturn makeTagged.makeTagged(tag,decodeFromCapData(payload));}\\n\\ncase'slot':{\\n/* See note above about how the current encoding cannot reliably*/\\n/* distinguish which we should call, so in the non-default case*/\\n/* both must be the same and it doesn't matter which we call.*/\\nconst decoded=decodeRemotableFromCapData(\\njsonEncoded,\\ndecodeFromCapData);\\n\\n/* BEWARE: capdata does not check that `decoded` is*/\\n/* a promise or a remotable, since that would break some*/\\n/* capdata clients. We are deprecating capdata, and these clients*/\\n/* will need to update before switching to smallcaps.*/\\nreturn decoded;}\\n\\ncase'error':{\\nconst decoded=decodeErrorFromCapData(\\njsonEncoded,\\ndecodeFromCapData);\\n\\nif(passStyleOf.passStyleOf(decoded)==='error'){\\nreturn decoded;}\\n\\nthrow index.throwRedacted`internal: decodeErrorFromCapData option must return an error: ${decoded}`;}\\n\\ncase'hilbert':{\\nconst{original,rest}=jsonEncoded;\\npassStyleHelpers.hasOwnPropertyOf(jsonEncoded,'original')||\\nindex.throwRedacted`Invalid Hilbert Hotel encoding ${jsonEncoded}`;\\n/* Don't harden since we're not done mutating it*/\\nconst result={[QCLASS]:decodeFromCapData(original)};\\nif(passStyleHelpers.hasOwnPropertyOf(jsonEncoded,'rest')){\\nconst isNonEmptyObject=\\ntypeof rest==='object'&&\\nrest!==null&&\\nownKeys(rest).length>=1;\\nif(!isNonEmptyObject){\\nthrow index.throwRedacted`Rest encoding must be a non-empty object: ${rest}`;}\\n\\nconst restObj=decodeFromCapData(rest);\\n/* TODO really should assert that `passStyleOf(rest)` is*/\\n/* `'copyRecord'` but we'd have to harden it and it is too*/\\n/* early to do that.*/\\n!passStyleHelpers.hasOwnPropertyOf(restObj,QCLASS)||\\nindex.throwRedacted`Rest must not contain its own definition of ${index.quote(QCLASS)}`;\\ndefineProperties(result,getOwnPropertyDescriptors(restObj));}\\n\\nreturn result;}\\n\\n/* @ts-expect-error This is the error case we're testing for*/\\ncase'ibid':{\\nthrow index.throwRedacted`The capData protocol no longer supports ${index.quote(QCLASS)} ${index.quote(\\nqclass)\\n}`;}\\n\\ndefault:{\\nthrow assert.fail(\\nindex.redacted`unrecognized ${index.quote(QCLASS)} ${index.quote(qclass)}`,\\nTypeError);}}}else\\n\\n\\n\\n{\\nassert(typeof jsonEncoded==='object'&&jsonEncoded!==null);\\nconst decodeEntry=([name,encodedVal])=>{\\ntypeof name==='string'||\\nindex.throwRedacted`Property ${index.quote(name)} of ${jsonEncoded} must be a string`;\\nreturn[name,decodeFromCapData(encodedVal)];};\\n\\nconst decodedEntries=entries(jsonEncoded).map(decodeEntry);\\nreturn fromEntries(decodedEntries);}};\\n\\n\\nreturn harden(decodeFromCapData);};exports.QCLASS=QCLASS;exports.makeDecodeFromCapData=makeDecodeFromCapData;exports.makeEncodeToCapData=makeEncodeToCapData;\",\n \"node_modules/@endo/marshal/src/encodeToSmallcaps.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../pass-style/index.js');var index=require('../../errors/index.js');var passStyleHelpers=require('../../pass-style/src/passStyle-helpers.js');var passStyleOf=require('../../pass-style/src/passStyleOf.js');var symbol=require('../../pass-style/src/symbol.js');var error=require('../../pass-style/src/error.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nmakeTagged=require('../../pass-style/src/makeTagged.js');/* @ts-check*/ /** @import {Passable, Remotable} from '@endo/pass-style' */ /* FIXME define actual types*/ /** @typedef {any} SmallcapsEncoding */ /** @typedef {any} SmallcapsEncodingUnion */\\n\\nconst{ownKeys}=Reflect;\\nconst{isArray}=Array;\\nconst{is,entries,fromEntries}=Object;\\n\\nconst BANG='!'.charCodeAt(0);\\nconst DASH='-'.charCodeAt(0);\\n\\n/**\\n * An `encodeToSmallcaps` function takes a passable and returns a\\n * JSON-representable object (i.e., round-tripping it through\\n * `JSON.stringify` and `JSON.parse` with no replacers or revivers\\n * returns an equivalent structure except for object identity).\\n * We call this representation a Smallcaps Encoding.\\n *\\n * A `decodeFromSmallcaps` function takes as argument what it\\n * *assumes* is the result of a plain `JSON.parse` with no resolver. It then\\n * must validate that it is a valid Smallcaps Encoding, and if it is,\\n * return a corresponding passable.\\n *\\n * Smallcaps considers the characters between `!` (ascii code 33, BANG)\\n * and `-` (ascii code 45, DASH) to be special prefixes allowing\\n * representation of JSON-incompatible data using strings.\\n * These characters, in order, are `!\\\"#$%&'()*+,-`\\n * Of these, smallcaps currently uses the following:\\n *\\n * * `!` - escaped string\\n * * `+` - non-negative bigint\\n * * `-` - negative bigint\\n * * `#` - manifest constant\\n * * `%` - symbol\\n * * `$` - remotable\\n * * `&` - promise\\n *\\n * All other special characters (`\\\"'()*,`) are reserved for future use.\\n *\\n * The manifest constants that smallcaps currently uses for values:\\n * * `#undefined`\\n * * `#NaN`\\n * * `#Infinity`\\n * * `#-Infinity`\\n *\\n * and for property names analogous to capdata @qclass:\\n * * `#tag`\\n * * `#error`\\n *\\n * All other encoded strings beginning with `#` are reserved for\\n * future use.\\n *\\n * @param {string} encodedStr\\n * @returns {boolean}\\n */\\nconst startsSpecial=(encodedStr)=>{\\nif(encodedStr===''){\\nreturn false;}\\n\\n/* charCodeAt(0) and number compare is a bit faster.*/\\nconst code=encodedStr.charCodeAt(0);\\n/* eslint-disable-next-line yoda*/\\nreturn BANG<=code&&code<=DASH;};\\n\\n\\n/**\\n * @typedef {object} EncodeToSmallcapsOptions\\n * @property {(\\n * remotable: Remotable,\\n * encodeRecur: (p: Passable) => SmallcapsEncoding\\n * ) => SmallcapsEncoding} [encodeRemotableToSmallcaps]\\n * @property {(\\n * promise: Promise,\\n * encodeRecur: (p: Passable) => SmallcapsEncoding\\n * ) => SmallcapsEncoding} [encodePromiseToSmallcaps]\\n * @property {(\\n * error: Error,\\n * encodeRecur: (p: Passable) => SmallcapsEncoding\\n * ) => SmallcapsEncoding} [encodeErrorToSmallcaps]\\n */\\n\\nconst dontEncodeRemotableToSmallcaps=(rem)=>\\nindex.throwRedacted`remotable unexpected: ${rem}`;\\n\\nconst dontEncodePromiseToSmallcaps=(prom)=>index.throwRedacted`promise unexpected: ${prom}`;\\n\\nconst dontEncodeErrorToSmallcaps=(err)=>\\nindex.throwRedacted`error object unexpected: ${index.quote(err)}`;\\n\\n/**\\n * @param {EncodeToSmallcapsOptions} [encodeOptions]\\n * encodeOptions is actually optional, but not marked as such to work around\\n * https://github.com/microsoft/TypeScript/issues/50286\\n *\\n * @returns {(passable: Passable) => SmallcapsEncoding}\\n */\\nconst makeEncodeToSmallcaps=(encodeOptions={})=>{\\nconst{\\nencodeRemotableToSmallcaps=dontEncodeRemotableToSmallcaps,\\nencodePromiseToSmallcaps=dontEncodePromiseToSmallcaps,\\nencodeErrorToSmallcaps=dontEncodeErrorToSmallcaps}=\\nencodeOptions;\\n\\nconst assertEncodedError=(encoding)=>{\\ntypeof encoding==='object'&&passStyleHelpers.hasOwnPropertyOf(encoding,'#error')||\\nindex.throwRedacted`internal: Error encoding must have \\\"#error\\\" property: ${index.quote(\\nencoding)\\n}`;\\n/* Assert that the #error property decodes to a string.*/\\nconst message=encoding['#error'];\\ntypeof message==='string'&&(\\n!startsSpecial(message)||message.charAt(0)==='!')||\\nindex.throwRedacted`internal: Error encoding must have string message: ${index.quote(message)}`;};\\n\\n\\n/**\\n * Must encode `val` into plain JSON data *canonically*, such that\\n * `JSON.stringify(encode(v1)) === JSON.stringify(encode(v1))`. For most\\n * encodings, the order of properties of each node of the output\\n * structure is determined by the algorithm below without special\\n * arrangement, usually by being expressed directly as an object literal.\\n * The exception is copyRecords, whose natural enumeration order\\n * can differ between copyRecords that our distributed object semantics\\n * considers to be equivalent.\\n * Since, for each copyRecord, we only accept string property names,\\n * not symbols, we can canonically sort the names first.\\n * JSON.stringify will then visit these in that sorted order.\\n *\\n * Encoding with a canonical-JSON encoder would also solve this canonicalness\\n * problem in a more modular and encapsulated manner. Note that the\\n * actual order produced here, though it agrees with canonical-JSON on\\n * copyRecord property ordering, differs from canonical-JSON as a whole\\n * in that the other record properties are visited in the order in which\\n * they are literally written below. TODO perhaps we should indeed switch\\n * to a canonical JSON encoder, and not delicately depend on the order\\n * in which these object literals are written.\\n *\\n * Readers must not care about this order anyway. We impose this requirement\\n * mainly to reduce non-determinism exposed outside a vat.\\n *\\n * @param {any} passable\\n * @returns {SmallcapsEncoding} except that `encodeToSmallcaps` does not generally\\n * `harden` this result before returning. Rather, `encodeToSmallcaps` is not\\n * directly exposed.\\n * What's exposed instead is a wrapper that freezes the output before\\n * returning. If this turns out to impede static analysis for `harden` safety,\\n * we can always put the (now redundant) hardens back in. They don't hurt.\\n */\\nconst encodeToSmallcapsRecur=(passable)=>{\\n/* First we handle all primitives. Some can be represented directly as*/\\n/* JSON, and some must be encoded into smallcaps strings.*/\\nconst passStyle=passStyleOf.passStyleOf(passable);\\nswitch(passStyle){\\ncase'null':\\ncase'boolean':{\\n/* pass through to JSON*/\\nreturn passable;}\\n\\ncase'string':{\\nif(startsSpecial(passable)){\\n/* Strings that start with a special char are quoted with `!`.*/\\n/* Since `!` is itself a special character, this trivially does*/\\n/* the Hilbert hotel. Also, since the special characters are*/\\n/* a continuous subrange of ascii, this quoting is sort-order*/\\n/* preserving.*/\\nreturn`!${passable}`;}\\n\\n/* All other strings pass through to JSON*/\\nreturn passable;}\\n\\ncase'undefined':{\\nreturn'#undefined';}\\n\\ncase'number':{\\n/* Special-case numbers with no digit-based representation.*/\\nif(Number.isNaN(passable)){\\nreturn'#NaN';}else\\nif(passable===Infinity){\\nreturn'#Infinity';}else\\nif(passable===-Infinity){\\nreturn'#-Infinity';}\\n\\n/* Pass through everything else, replacing -0 with 0.*/\\nreturn is(passable,-0)?0:passable;}\\n\\ncase'bigint':{\\nconst str=String(passable);\\nreturn(/** @type {bigint} */passable<0n?str:`+${str}`);}\\n\\ncase'symbol':{\\nsymbol.assertPassableSymbol(passable);\\nconst name=/** @type {string} */symbol.nameForPassableSymbol(passable);\\nreturn`%${name}`;}\\n\\ncase'copyRecord':{\\n/* Currently copyRecord allows only string keys so this will*/\\n/* work. If we allow sortable symbol keys, this will need to*/\\n/* become more interesting.*/\\nconst names=ownKeys(passable).sort();\\nreturn fromEntries(\\nnames.map((name)=>[\\nencodeToSmallcapsRecur(name),\\nencodeToSmallcapsRecur(passable[name])]));}\\n\\n\\n\\ncase'copyArray':{\\nreturn passable.map(encodeToSmallcapsRecur);}\\n\\ncase'tagged':{\\nreturn{\\n'#tag':encodeToSmallcapsRecur(passStyleHelpers.getTag(passable)),\\npayload:encodeToSmallcapsRecur(passable.payload)};}\\n\\n\\ncase'remotable':{\\nconst result=encodeRemotableToSmallcaps(\\npassable,\\nencodeToSmallcapsRecur);\\n\\nif(typeof result==='string'&&result.charAt(0)==='$'){\\nreturn result;}\\n\\n/* `throw` is noop since `Fail` throws. But linter confused*/\\nthrow index.throwRedacted`internal: Remotable encoding must start with \\\"$\\\": ${result}`;}\\n\\ncase'promise':{\\nconst result=encodePromiseToSmallcaps(\\npassable,\\nencodeToSmallcapsRecur);\\n\\nif(typeof result==='string'&&result.charAt(0)==='&'){\\nreturn result;}\\n\\nthrow index.throwRedacted`internal: Promise encoding must start with \\\"&\\\": ${result}`;}\\n\\ncase'error':{\\nconst result=encodeErrorToSmallcaps(passable,encodeToSmallcapsRecur);\\nassertEncodedError(result);\\nreturn result;}\\n\\ndefault:{\\nthrow assert.fail(\\nindex.redacted`internal: Unrecognized passStyle ${index.quote(passStyle)}`,\\nTypeError);}}};\\n\\n\\n\\n\\nconst encodeToSmallcaps=(passable)=>{\\nif(error.isErrorLike(passable)){\\n/* We pull out this special case to accommodate errors that are not*/\\n/* valid Passables. For example, because they're not frozen.*/\\n/* The special case can only ever apply at the root, and therefore*/\\n/* outside the recursion, since an error could only be deeper in*/\\n/* a passable structure if it were passable.*/\\n/**/\\n/* We pull out this special case because, for these errors, we're much*/\\n/* more interested in reporting whatever diagnostic information they*/\\n/* carry than we are about reporting problems encountered in reporting*/\\n/* this information.*/\\nconst result=harden(\\nencodeErrorToSmallcaps(passable,encodeToSmallcapsRecur));\\n\\nassertEncodedError(result);\\nreturn result;}\\n\\nreturn harden(encodeToSmallcapsRecur(passable));};\\n\\nreturn harden(encodeToSmallcaps);};\\n\\nharden(makeEncodeToSmallcaps);\\n\\n/**\\n * @typedef {object} DecodeFromSmallcapsOptions\\n * @property {(\\n * encodedRemotable: SmallcapsEncoding,\\n * decodeRecur: (e :SmallcapsEncoding) => Passable\\n * ) => Remotable} [decodeRemotableFromSmallcaps]\\n * @property {(\\n * encodedPromise: SmallcapsEncoding,\\n * decodeRecur: (e :SmallcapsEncoding) => Passable\\n * ) => Promise} [decodePromiseFromSmallcaps]\\n * @property {(\\n * encodedError: SmallcapsEncoding,\\n * decodeRecur: (e :SmallcapsEncoding) => Passable\\n * ) => Error} [decodeErrorFromSmallcaps]\\n */\\n\\nconst dontDecodeRemotableFromSmallcaps=(encoding)=>\\nindex.throwRedacted`remotable unexpected: ${encoding}`;\\nconst dontDecodePromiseFromSmallcaps=(encoding)=>\\nindex.throwRedacted`promise unexpected: ${encoding}`;\\nconst dontDecodeErrorFromSmallcaps=(encoding)=>\\nindex.throwRedacted`error unexpected: ${index.quote(encoding)}`;\\n\\n/**\\n * @param {DecodeFromSmallcapsOptions} [decodeOptions]\\n * @returns {(encoded: SmallcapsEncoding) => Passable}\\n */\\nconst makeDecodeFromSmallcaps=(decodeOptions={})=>{\\nconst{\\ndecodeRemotableFromSmallcaps=dontDecodeRemotableFromSmallcaps,\\ndecodePromiseFromSmallcaps=dontDecodePromiseFromSmallcaps,\\ndecodeErrorFromSmallcaps=dontDecodeErrorFromSmallcaps}=\\ndecodeOptions;\\n\\n/**\\n * `decodeFromSmallcaps` may rely on `encoding` being the result of a\\n * plain call to JSON.parse. However, it *cannot* rely on `encoding`\\n * having been produced by JSON.stringify on the output of `encodeToSmallcaps`\\n * above, i.e., `decodeFromSmallcaps` cannot rely on `encoding` being a\\n * valid marshalled representation. Rather, `decodeFromSmallcaps` must\\n * validate that.\\n *\\n * @param {SmallcapsEncoding} encoding must be hardened\\n */\\nconst decodeFromSmallcaps=(encoding)=>{\\nswitch(typeof encoding){\\ncase'boolean':\\ncase'number':{\\nreturn encoding;}\\n\\ncase'string':{\\nif(!startsSpecial(encoding)){\\nreturn encoding;}\\n\\nconst c=encoding.charAt(0);\\nswitch(c){\\ncase'!':{\\n/* un-hilbert-ify the string*/\\nreturn encoding.slice(1);}\\n\\ncase'%':{\\nreturn symbol.passableSymbolForName(encoding.slice(1));}\\n\\ncase'#':{\\nswitch(encoding){\\ncase'#undefined':{\\nreturn undefined;}\\n\\ncase'#NaN':{\\nreturn NaN;}\\n\\ncase'#Infinity':{\\nreturn Infinity;}\\n\\ncase'#-Infinity':{\\nreturn-Infinity;}\\n\\ndefault:{\\nthrow assert.fail(\\nindex.redacted`unknown constant \\\"${index.quote(encoding)}\\\"`,\\nTypeError);}}}\\n\\n\\n\\n\\ncase'+':\\ncase'-':{\\nreturn BigInt(encoding);}\\n\\ncase'$':{\\nconst result=decodeRemotableFromSmallcaps(\\nencoding,\\ndecodeFromSmallcaps);\\n\\n/* @ts-ignore XXX SmallCapsEncoding*/\\nif(passStyleOf.passStyleOf(result)!=='remotable'){\\nindex.throwRedacted`internal: decodeRemotableFromSmallcaps option must return a remotable: ${result}`;}\\n\\nreturn result;}\\n\\ncase'&':{\\nconst result=decodePromiseFromSmallcaps(\\nencoding,\\ndecodeFromSmallcaps);\\n\\nif(passStyleOf.passStyleOf(result)!=='promise'){\\nindex.throwRedacted`internal: decodePromiseFromSmallcaps option must return a promise: ${result}`;}\\n\\nreturn result;}\\n\\ndefault:{\\nthrow index.throwRedacted`Special char ${index.quote(\\nc)\\n} reserved for future use: ${encoding}`;}}}\\n\\n\\n\\ncase'object':{\\nif(encoding===null){\\nreturn encoding;}\\n\\n\\nif(isArray(encoding)){\\nreturn encoding.map((val)=>decodeFromSmallcaps(val));}\\n\\n\\nif(passStyleHelpers.hasOwnPropertyOf(encoding,'#tag')){\\nconst{'#tag':tag,payload,...rest}=encoding;\\ntypeof tag==='string'||\\nindex.throwRedacted`Value of \\\"#tag\\\", the tag, must be a string: ${encoding}`;\\nownKeys(rest).length===0||\\nindex.throwRedacted`#tag record unexpected properties: ${index.quote(ownKeys(rest))}`;\\nreturn makeTagged.makeTagged(\\ndecodeFromSmallcaps(tag),\\ndecodeFromSmallcaps(payload));}\\n\\n\\n\\nif(passStyleHelpers.hasOwnPropertyOf(encoding,'#error')){\\nconst result=decodeErrorFromSmallcaps(\\nencoding,\\ndecodeFromSmallcaps);\\n\\npassStyleOf.passStyleOf(result)==='error'||\\nindex.throwRedacted`internal: decodeErrorFromSmallcaps option must return an error: ${result}`;\\nreturn result;}\\n\\n\\nconst decodeEntry=([encodedName,encodedVal])=>{\\ntypeof encodedName==='string'||\\nindex.throwRedacted`Property name ${index.quote(\\nencodedName)\\n} of ${encoding} must be a string`;\\nencodedName.charAt(0)!=='#'||\\nindex.throwRedacted`Unrecognized record type ${index.quote(encodedName)}: ${encoding}`;\\nconst name=decodeFromSmallcaps(encodedName);\\ntypeof name==='string'||\\nindex.throwRedacted`Decoded property name ${name} from ${encoding} must be a string`;\\nreturn[name,decodeFromSmallcaps(encodedVal)];};\\n\\nconst decodedEntries=entries(encoding).map(decodeEntry);\\nreturn fromEntries(decodedEntries);}\\n\\ndefault:{\\nthrow assert.fail(\\nindex.redacted`internal: unrecognized JSON typeof ${index.quote(\\ntypeof encoding)\\n}: ${encoding}`,\\nTypeError);}}};\\n\\n\\n\\n\\nreturn harden(decodeFromSmallcaps);};exports.makeDecodeFromSmallcaps=makeDecodeFromSmallcaps;exports.makeEncodeToSmallcaps=makeEncodeToSmallcaps;\",\n \"node_modules/@endo/marshal/src/marshal-justin.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var index$1=require('../../nat/src/index.js');require('../../pass-style/index.js');var index=require('../../errors/index.js');var encodeToCapData=require('./encodeToCapData.js');var passStyleHelpers=require('../../pass-style/src/passStyle-helpers.js');var error=require('../../pass-style/src/error.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nsymbol=require('../../pass-style/src/symbol.js');/*/ <reference types=\\\"ses\\\"/>*/ /** @import {Encoding} from './types.js' */\\n\\nconst{ownKeys}=Reflect;\\nconst{isArray}=Array;\\nconst{stringify:quote}=JSON;\\n\\n/**\\n * @typedef {object} Indenter\\n * @property {(openBracket: string) => number} open\\n * @property {() => number} line\\n * @property {(token: string) => number} next\\n * @property {(closeBracket: string) => number} close\\n * @property {() => string} done\\n */\\n\\n/**\\n * Generous whitespace for readability\\n *\\n * @returns {Indenter}\\n */\\nconst makeYesIndenter=()=>{\\nconst strings=[];\\nlet level=0;\\nlet needSpace=false;\\nconst line=()=>{\\nneedSpace=false;\\nreturn strings.push('\\\\n',' '.repeat(level));};\\n\\nreturn harden({\\nopen:(openBracket)=>{\\nlevel+=1;\\nif(needSpace){\\nstrings.push(' ');}\\n\\nneedSpace=false;\\nreturn strings.push(openBracket);},\\n\\nline,\\nnext:(token)=>{\\nif(needSpace&&token!==','){\\nstrings.push(' ');}\\n\\nneedSpace=true;\\nreturn strings.push(token);},\\n\\nclose:(closeBracket)=>{\\nassert(level>=1);\\nlevel-=1;\\nline();\\nreturn strings.push(closeBracket);},\\n\\ndone:()=>{\\nassert.equal(level,0);\\nreturn strings.join('');}});};\\n\\n\\n\\n\\n/**\\n * If the last character of one token together with the first character\\n * of the next token matches this pattern, then the two tokens must be\\n * separated by whitespace to preserve their meaning. Otherwise the\\n * whitespace in unnecessary.\\n *\\n * The `<!` and `->` cases prevent the accidental formation of an\\n * html-like comment. I don't think the double angle brackets are actually\\n * needed but I haven't thought about it enough to remove them.\\n */\\nconst badPairPattern=/^(?:\\\\w\\\\w|<<|>>|\\\\+\\\\+|--|<!|->)$/;\\n\\n/**\\n * Minimum whitespace needed to preseve meaning.\\n *\\n * @returns {Indenter}\\n */\\nconst makeNoIndenter=()=>{\\n/** @type {string[]} */\\nconst strings=[];\\nreturn harden({\\nopen:(openBracket)=>strings.push(openBracket),\\nline:()=>strings.length,\\nnext:(token)=>{\\nif(strings.length>=1){\\nconst last=strings[strings.length-1];\\n/* eslint-disable-next-line @endo/restrict-comparison-operands -- error*/\\nif(last.length>=1&&token.length>=1){\\nconst pair=`${last[last.length-1]}${token[0]}`;\\nif(badPairPattern.test(pair)){\\nstrings.push(' ');}}}\\n\\n\\n\\nreturn strings.push(token);},\\n\\nclose:(closeBracket)=>{\\nif(strings.length>=1&&strings[strings.length-1]===','){\\nstrings.pop();}\\n\\nreturn strings.push(closeBracket);},\\n\\ndone:()=>strings.join('')});};\\n\\n\\n\\nconst identPattern=/^[a-zA-Z]\\\\w*$/;\\nharden(identPattern);\\nconst AtAtPrefixPattern=/^@@(.*)$/;\\nharden(AtAtPrefixPattern);\\n\\n/**\\n * @param {Encoding} encoding\\n * @param {boolean=} shouldIndent\\n * @param {any[]} [slots]\\n * @returns {string}\\n */\\nconst decodeToJustin=(encoding,shouldIndent=false,slots=[])=>{\\n/**\\n * The first pass does some input validation.\\n * Its control flow should mirror `recur` as closely as possible\\n * and the two should be maintained together. They must visit everything\\n * in the same order.\\n *\\n * TODO now that ibids are gone, we should fold this back together into\\n * one validating pass.\\n *\\n * @param {Encoding} rawTree\\n * @returns {void}\\n */\\nconst prepare=(rawTree)=>{\\nif(!passStyleHelpers.isObject(rawTree)){\\nreturn;}\\n\\n/* Assertions of the above to narrow the type.*/\\nassert.typeof(rawTree,'object');\\nassert(rawTree!==null);\\nif(encodeToCapData.QCLASS in rawTree){\\nconst qclass=rawTree[encodeToCapData.QCLASS];\\ntypeof qclass==='string'||\\nindex.throwRedacted`invalid qclass typeof ${index.quote(typeof qclass)}`;\\nassert(!isArray(rawTree));\\nswitch(rawTree['@qclass']){\\ncase'undefined':\\ncase'NaN':\\ncase'Infinity':\\ncase'-Infinity':{\\nreturn;}\\n\\ncase'bigint':{\\nconst{digits}=rawTree;\\ntypeof digits==='string'||\\nindex.throwRedacted`invalid digits typeof ${index.quote(typeof digits)}`;\\nreturn;}\\n\\ncase'@@asyncIterator':{\\nreturn;}\\n\\ncase'symbol':{\\nconst{name}=rawTree;\\nassert.typeof(name,'string');\\nconst sym=symbol.passableSymbolForName(name);\\nassert.typeof(sym,'symbol');\\nreturn;}\\n\\ncase'tagged':{\\nconst{tag,payload}=rawTree;\\nassert.typeof(tag,'string');\\nprepare(payload);\\nreturn;}\\n\\ncase'slot':{\\nconst{index,iface}=rawTree;\\nassert.typeof(index,'number');\\nindex$1.Nat(index);\\nif(iface!==undefined){\\nassert.typeof(iface,'string');}\\n\\nreturn;}\\n\\ncase'hilbert':{\\nconst{original,rest}=rawTree;\\n'original'in rawTree||\\nindex.throwRedacted`Invalid Hilbert Hotel encoding ${rawTree}`;\\nprepare(original);\\nif('rest'in rawTree){\\nif(typeof rest!=='object'){\\nthrow index.throwRedacted`Rest ${rest} encoding must be an object`;}\\n\\nif(rest===null){\\nthrow index.throwRedacted`Rest ${rest} encoding must not be null`;}\\n\\nif(isArray(rest)){\\nthrow index.throwRedacted`Rest ${rest} encoding must not be an array`;}\\n\\nif(encodeToCapData.QCLASS in rest){\\nthrow index.throwRedacted`Rest encoding ${rest} must not contain ${index.quote(encodeToCapData.QCLASS)}`;}\\n\\nconst names=ownKeys(rest);\\nfor(const name of names){\\ntypeof name==='string'||\\nindex.throwRedacted`Property name ${name} of ${rawTree} must be a string`;\\nprepare(rest[name]);}}\\n\\n\\nreturn;}\\n\\ncase'error':{\\nconst{name,message}=rawTree;\\nif(typeof name!=='string'){\\nthrow index.throwRedacted`invalid error name typeof ${index.quote(typeof name)}`;}\\n\\nerror.getErrorConstructor(name)!==undefined||\\nindex.throwRedacted`Must be the name of an Error constructor ${name}`;\\ntypeof message==='string'||\\nindex.throwRedacted`invalid error message typeof ${index.quote(typeof message)}`;\\nreturn;}\\n\\n\\ndefault:{\\nassert.fail(index.redacted`unrecognized ${index.quote(encodeToCapData.QCLASS)} ${index.quote(qclass)}`,TypeError);}}}else\\n\\n\\nif(isArray(rawTree)){\\nconst{length}=rawTree;\\nfor(let i=0;i<length;i+=1){\\nprepare(rawTree[i]);}}else\\n\\n{\\nconst names=ownKeys(rawTree);\\nfor(const name of names){\\nif(typeof name!=='string'){\\nthrow index.throwRedacted`Property name ${name} of ${rawTree} must be a string`;}\\n\\nprepare(rawTree[name]);}}};\\n\\n\\n\\n\\nconst makeIndenter=shouldIndent?makeYesIndenter:makeNoIndenter;\\nlet out=makeIndenter();\\n\\n/**\\n * This is the second pass recursion after the first pass `prepare`.\\n * The first pass did some input validation so\\n * here we can safely assume everything those things are validated.\\n *\\n * @param {Encoding} rawTree\\n * @returns {number}\\n */\\nconst decode=(rawTree)=>{\\n/* eslint-disable-next-line no-use-before-define*/\\nreturn recur(rawTree);};\\n\\n\\nconst decodeProperty=(name,value)=>{\\nout.line();\\nif(name==='__proto__'){\\n/* JavaScript interprets `{__proto__: x, ...}`*/\\n/* as making an object inheriting from `x`, whereas*/\\n/* in JSON it is simply a property name. Preserve the*/\\n/* JSON meaning.*/\\nout.next(`[\\\"__proto__\\\"]:`);}else\\nif(identPattern.test(name)){\\nout.next(`${name}:`);}else\\n{\\nout.next(`${quote(name)}:`);}\\n\\ndecode(value);\\nout.next(',');};\\n\\n\\n/**\\n * Modeled after `fullRevive` in marshal.js\\n *\\n * @param {Encoding} rawTree\\n * @returns {number}\\n */\\nconst recur=(rawTree)=>{\\nif(!passStyleHelpers.isObject(rawTree)){\\n/* primitives get quoted*/\\nreturn out.next(quote(rawTree));}\\n\\n/* Assertions of the above to narrow the type.*/\\nassert.typeof(rawTree,'object');\\nassert(rawTree!==null);\\nif(encodeToCapData.QCLASS in rawTree){\\nconst qclass=rawTree[encodeToCapData.QCLASS];\\nassert.typeof(qclass,'string');\\nassert(!isArray(rawTree));\\n/* Switching on `encoded[QCLASS]` (or anything less direct, like*/\\n/* `qclass`) does not discriminate rawTree in typescript@4.2.3 and*/\\n/* earlier.*/\\nswitch(rawTree['@qclass']){\\n/* Encoding of primitives not handled by JSON*/\\ncase'undefined':\\ncase'NaN':\\ncase'Infinity':\\ncase'-Infinity':{\\n/* Their qclass is their expression source.*/\\nreturn out.next(qclass);}\\n\\ncase'bigint':{\\nconst{digits}=rawTree;\\nassert.typeof(digits,'string');\\nreturn out.next(`${BigInt(digits)}n`);}\\n\\ncase'@@asyncIterator':{\\n/* TODO deprecated. Eventually remove.*/\\nreturn out.next('Symbol.asyncIterator');}\\n\\ncase'symbol':{\\nconst{name}=rawTree;\\nassert.typeof(name,'string');\\nconst sym=symbol.passableSymbolForName(name);\\nassert.typeof(sym,'symbol');\\nconst registeredName=Symbol.keyFor(sym);\\nif(registeredName===undefined){\\nconst match=AtAtPrefixPattern.exec(name);\\nassert(match!==null);\\nconst suffix=match[1];\\nassert(Symbol[suffix]===sym);\\nassert(identPattern.test(suffix));\\nreturn out.next(`Symbol.${suffix}`);}\\n\\nreturn out.next(`Symbol.for(${quote(registeredName)})`);}\\n\\ncase'tagged':{\\nconst{tag,payload}=rawTree;\\nout.next(`makeTagged(${quote(tag)},`);\\ndecode(payload);\\nreturn out.next(')');}\\n\\n\\ncase'slot':{\\nlet{iface}=rawTree;\\nconst index=Number(index$1.Nat(rawTree.index));\\nconst nestedRender=(arg)=>{\\nconst oldOut=out;\\ntry{\\nout=makeNoIndenter();\\ndecode(arg);\\nreturn out.done();}finally\\n{\\nout=oldOut;}};\\n\\n\\nif(index<slots.length){\\nconst slot=nestedRender(slots[index]);\\nif(iface===undefined){\\nreturn out.next(`slotToVal(${slot})`);}\\n\\niface=nestedRender(iface);\\nreturn out.next(`slotToVal(${slot},${iface})`);}else\\nif(iface===undefined){\\nreturn out.next(`slot(${index})`);}\\n\\niface=nestedRender(iface);\\nreturn out.next(`slot(${index},${iface})`);}\\n\\n\\ncase'hilbert':{\\nconst{original,rest}=rawTree;\\nout.open('{');\\ndecodeProperty(encodeToCapData.QCLASS,original);\\nif('rest'in rawTree){\\nassert.typeof(rest,'object');\\nassert(rest!==null);\\nconst names=ownKeys(rest);\\nfor(const name of names){\\nif(typeof name!=='string'){\\nthrow index.throwRedacted`Property name ${index.quote(\\nname)\\n} of ${rest} must be a string`;}\\n\\ndecodeProperty(name,rest[name]);}}\\n\\n\\nreturn out.close('}');}\\n\\n\\ncase'error':{\\nconst{\\nname,\\nmessage,\\ncause=undefined,\\nerrors=undefined}=\\nrawTree;\\ncause===undefined||\\nindex.throwRedacted`error cause not yet implemented in marshal-justin`;\\nname!==`AggregateError`||\\nindex.throwRedacted`AggregateError not yet implemented in marshal-justin`;\\nerrors===undefined||\\nindex.throwRedacted`error errors not yet implemented in marshal-justin`;\\nreturn out.next(`${name}(${quote(message)})`);}\\n\\n\\ndefault:{\\nthrow assert.fail(\\nindex.redacted`unrecognized ${index.quote(encodeToCapData.QCLASS)} ${index.quote(qclass)}`,\\nTypeError);}}}else\\n\\n\\n\\nif(isArray(rawTree)){\\nconst{length}=rawTree;\\nif(length===0){\\nreturn out.next('[]');}else\\n{\\nout.open('[');\\nfor(let i=0;i<length;i+=1){\\nout.line();\\ndecode(rawTree[i]);\\nout.next(',');}\\n\\nreturn out.close(']');}}else\\n\\n{\\n/* rawTree is an `EncodingRecord` which only has string keys,*/\\n/* but since ownKeys is not generic, it can't propagate that*/\\nconst names=/** @type {string[]} */ownKeys(rawTree);\\nif(names.length===0){\\nreturn out.next('{}');}else\\n{\\nout.open('{');\\nfor(const name of names){\\ndecodeProperty(name,rawTree[name]);}\\n\\nreturn out.close('}');}}};\\n\\n\\n\\nprepare(encoding);\\ndecode(encoding);\\nreturn out.done();};\\n\\nharden(decodeToJustin);exports.decodeToJustin=decodeToJustin;\",\n \"node_modules/@endo/marshal/src/marshal-stringify.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var index=require('../../errors/index.js');var\\n\\n\\n\\n\\n\\n\\nmarshal=require('./marshal.js');/*/ <reference types=\\\"ses\\\"/>*/ /** @import {Passable} from '@endo/pass-style' */ /** @type {IMPORT('./types.js').ConvertValToSlot<any>} */\\nconst doNotConvertValToSlot=(val)=>\\nindex.throwRedacted`Marshal's stringify rejects presences and promises ${val}`;\\n\\n/** @type {IMPORT('./types.js').ConvertSlotToVal<any>} */\\nconst doNotConvertSlotToVal=(slot,_iface)=>\\nindex.throwRedacted`Marshal's parse must not encode any slots ${slot}`;\\n\\nconst badArrayHandler=harden({\\nget:(_target,name,_receiver)=>{\\nif(name==='length'){\\nreturn 0;}\\n\\n/* `throw` is noop since `Fail` throws. But linter confused*/\\nthrow index.throwRedacted`Marshal's parse must not encode any slot positions ${name}`;}});\\n\\n\\n\\nconst badArray=harden(new Proxy(harden([]),badArrayHandler));\\n\\nconst{serialize,unserialize}=marshal.makeMarshal(\\ndoNotConvertValToSlot,\\ndoNotConvertSlotToVal,\\n{\\nerrorTagging:'off',\\n/* TODO fix tests to works with smallcaps.*/\\nserializeBodyFormat:'capdata'});\\n\\n\\n\\n/**\\n * @param {Passable} val\\n * @returns {string}\\n */\\nconst stringify=(val)=>serialize(val).body;\\nharden(stringify);\\n\\n/**\\n * @param {string} str\\n * @returns {unknown}\\n */\\nconst parse=(str)=>\\nunserialize(\\nharden({\\nbody:str,\\nslots:badArray}));\\n\\n\\nharden(parse);exports.parse=parse;exports.stringify=stringify;\",\n \"node_modules/@endo/marshal/src/marshal.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var index$1=require('../../nat/src/index.js');require('../../pass-style/index.js');var index=require('../../errors/index.js');var objectMap=require('../../common/object-map.js');var encodeToCapData=require('./encodeToCapData.js');var encodeToSmallcaps=require('./encodeToSmallcaps.js');var remotable=require('../../pass-style/src/remotable.js');var error=require('../../pass-style/src/error.js');var passStyleOf=require('../../pass-style/src/passStyleOf.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\npassStyleHelpers=require('../../pass-style/src/passStyle-helpers.js');/*/ <reference types=\\\"ses\\\"/>*/ /**\\n * @import {ConvertSlotToVal, ConvertValToSlot, FromCapData, MakeMarshalOptions, ToCapData} from './types.js';\\n * @import {Passable, PassableCap, RemotableObject} from '@endo/pass-style';\\n * @import {InterfaceSpec} from '@endo/pass-style';\\n * @import {Encoding} from './types.js';\\n */\\n\\nconst{defineProperties}=Object;\\nconst{isArray}=Array;\\nconst{ownKeys}=Reflect;\\n\\n/** @type {ConvertValToSlot<any>} */\\nconst defaultValToSlotFn=(x)=>x;\\n/** @type {ConvertSlotToVal<any>} */\\nconst defaultSlotToValFn=(x,_)=>x;\\n\\n/**\\n * @template Slot\\n * @param {ConvertValToSlot<Slot>} [convertValToSlot]\\n * @param {ConvertSlotToVal<Slot>} [convertSlotToVal]\\n * @param {MakeMarshalOptions} options\\n */\\nconst makeMarshal=(\\nconvertValToSlot=defaultValToSlotFn,\\nconvertSlotToVal=defaultSlotToValFn,\\n{\\nerrorTagging='on',\\nmarshalName='anon-marshal',\\n/* TODO Temporary hack.*/\\n/* See https://github.com/Agoric/agoric-sdk/issues/2780*/\\nerrorIdNum=10000,\\n/* We prefer that the caller instead log to somewhere hidden*/\\n/* to be revealed when correlating with the received error.*/\\nmarshalSaveError=(err)=>\\nconsole.log('Temporary logging of sent error',err),\\n/* Default to 'capdata' because it was implemented first.*/\\n/* Sometimes, ontogeny does recapitulate phylogeny ;)*/\\nserializeBodyFormat='capdata'}=\\n{})=>\\n{\\nassert.typeof(marshalName,'string');\\nerrorTagging==='on'||\\nerrorTagging==='off'||\\nindex.throwRedacted`The errorTagging option can only be \\\"on\\\" or \\\"off\\\" ${errorTagging}`;\\nconst nextErrorId=()=>{\\nerrorIdNum+=1;\\nreturn`error:${marshalName}#${errorIdNum}`;};\\n\\n\\n/**\\n * @type {ToCapData<Slot>}\\n */\\nconst toCapData=(root)=>{\\nconst slots=[];\\n/* maps val (promise or remotable) to index of slots[]*/\\nconst slotMap=new Map();\\n\\n/**\\n * @param {PassableCap} passable\\n * @returns {{index: number, repeat: boolean}}\\n */\\nconst encodeSlotCommon=(passable)=>{\\nlet index=slotMap.get(passable);\\nif(index!==undefined){\\n/* TODO assert that it's the same iface as before*/\\nassert.typeof(index,'number');\\nreturn harden({index,repeat:true});}\\n\\n\\nindex=slots.length;\\nconst slot=convertValToSlot(passable);\\nslots.push(slot);\\nslotMap.set(passable,index);\\nreturn harden({index,repeat:false});};\\n\\n\\n/**\\n * Even if an Error is not actually passable, we'd rather send\\n * it anyway because the diagnostic info carried by the error\\n * is more valuable than diagnosing why the error isn't\\n * passable. See comments in isErrorLike.\\n *\\n * @param {Error} err\\n * @param {(p: Passable) => unknown} encodeRecur\\n * @returns {{errorId?: string, message: string, name: string}}\\n */\\nconst encodeErrorCommon=(err,encodeRecur)=>{\\nconst message=encodeRecur(`${err.message}`);\\nassert.typeof(message,'string');\\nconst name=encodeRecur(`${err.name}`);\\nassert.typeof(name,'string');\\n/* TODO Must encode `cause`, `errors`, but*/\\n/* only once all possible counterparty decoders are tolerant of*/\\n/* receiving them.*/\\nif(errorTagging==='on'){\\n/* We deliberately do not share the stack, but it would*/\\n/* be useful to log the stack locally so someone who has*/\\n/* privileged access to the throwing Vat can correlate*/\\n/* the problem with the remote Vat that gets this*/\\n/* summary. If we do that, we could allocate some random*/\\n/* identifier and include it in the message, to help*/\\n/* with the correlation.*/\\nconst errorId=encodeRecur(nextErrorId());\\nassert.typeof(errorId,'string');\\nindex.note(err,index.redacted`Sent as ${errorId}`);\\nmarshalSaveError(err);\\nreturn harden({errorId,message,name});}else\\n{\\nreturn harden({message,name});}};\\n\\n\\n\\nif(serializeBodyFormat==='capdata'){\\n/**\\n * @param {PassableCap} passable\\n * @param {InterfaceSpec} [iface]\\n * @returns {Encoding}\\n */\\nconst encodeSlotToCapData=(passable,iface=undefined)=>{\\nconst{index,repeat}=encodeSlotCommon(passable);\\n\\nif(repeat===true||iface===undefined){\\nreturn harden({[encodeToCapData.QCLASS]:'slot',index});}else\\n{\\nreturn harden({[encodeToCapData.QCLASS]:'slot',iface,index});}};\\n\\n\\n\\n/** @type {(promise: RemotableObject, encodeRecur: (p: Passable) => Encoding) => Encoding} */\\nconst encodeRemotableToCapData=(val,_encodeRecur)=>\\nencodeSlotToCapData(val,remotable.getInterfaceOf(val));\\n\\n/** @type {(promise: Promise, encodeRecur: (p: Passable) => Encoding) => Encoding} */\\nconst encodePromiseToCapData=(promise,_encodeRecur)=>\\nencodeSlotToCapData(promise);\\n\\n/**\\n * Even if an Error is not actually passable, we'd rather send\\n * it anyway because the diagnostic info carried by the error\\n * is more valuable than diagnosing why the error isn't\\n * passable. See comments in isErrorLike.\\n *\\n * @param {Error} err\\n * @param {(p: Passable) => Encoding} encodeRecur\\n * @returns {Encoding}\\n */\\nconst encodeErrorToCapData=(err,encodeRecur)=>{\\nconst errData=encodeErrorCommon(err,encodeRecur);\\nreturn harden({[encodeToCapData.QCLASS]:'error',...errData});};\\n\\n\\nconst encodeToCapData$1=encodeToCapData.makeEncodeToCapData({\\nencodeRemotableToCapData,\\nencodePromiseToCapData,\\nencodeErrorToCapData});\\n\\n\\nconst encoded=encodeToCapData$1(root);\\nconst body=JSON.stringify(encoded);\\nreturn harden({\\nbody,\\nslots});}else\\n\\nif(serializeBodyFormat==='smallcaps'){\\n/**\\n * @param {string} prefix\\n * @param {PassableCap} passable\\n * @param {InterfaceSpec} [iface]\\n * @returns {string}\\n */\\nconst encodeSlotToSmallcaps=(prefix,passable,iface=undefined)=>{\\nconst{index,repeat}=encodeSlotCommon(passable);\\n\\n/* TODO explore removing this special case*/\\nif(repeat===true||iface===undefined){\\nreturn`${prefix}${index}`;}\\n\\nreturn`${prefix}${index}.${iface}`;};\\n\\n\\nconst encodeRemotableToSmallcaps=(remotable$1,_encodeRecur)=>\\nencodeSlotToSmallcaps('$',remotable$1,remotable.getInterfaceOf(remotable$1));\\n\\nconst encodePromiseToSmallcaps=(promise,_encodeRecur)=>\\nencodeSlotToSmallcaps('&',promise);\\n\\nconst encodeErrorToSmallcaps=(err,encodeRecur)=>{\\nconst errData=encodeErrorCommon(err,encodeRecur);\\nconst{message,...rest}=errData;\\nreturn harden({'#error':message,...rest});};\\n\\n\\nconst encodeToSmallcaps$1=encodeToSmallcaps.makeEncodeToSmallcaps({\\nencodeRemotableToSmallcaps,\\nencodePromiseToSmallcaps,\\nencodeErrorToSmallcaps});\\n\\n\\nconst encoded=encodeToSmallcaps$1(root);\\nconst smallcapsBody=JSON.stringify(encoded);\\nreturn harden({\\n/* Valid JSON cannot begin with a '#', so this is a valid signal*/\\n/* indicating smallcaps format.*/\\nbody:`#${smallcapsBody}`,\\nslots});}else\\n\\n{\\n/* The `throw` is a noop since `Fail` throws. Added for confused linters.*/\\nthrow index.throwRedacted`Unrecognized serializeBodyFormat: ${index.quote(serializeBodyFormat)}`;}};\\n\\n\\n\\nconst makeFullRevive=(slots)=>{\\n/** @type {Map<number>} */\\nconst valMap=new Map();\\n\\n/**\\n * @param {{iface?: string, index: number}} slotData\\n * @returns {PassableCap}\\n */\\nconst decodeSlotCommon=(slotData)=>{\\nconst{iface=undefined,index:index$2,...rest}=slotData;\\nownKeys(rest).length===0||\\nindex.throwRedacted`unexpected encoded slot properties ${index.quote(ownKeys(rest))}`;\\nconst extant=valMap.get(index$2);\\nif(extant){\\nreturn extant;}\\n\\n/* TODO SECURITY HAZARD: must enfoce that remotable vs promise*/\\n/* is according to the encoded string.*/\\nconst slot=slots[Number(index$1.Nat(index$2))];\\nconst val=convertSlotToVal(slot,iface);\\nvalMap.set(index$2,val);\\nreturn val;};\\n\\n\\n/**\\n * @param {{\\n * errorId?: string,\\n * message: string,\\n * name: string,\\n * cause: unknown,\\n * errors: unknown,\\n * }} errData\\n * @param {(e: unknown) => Passable} decodeRecur\\n * @returns {Error}\\n */\\nconst decodeErrorCommon=(errData,decodeRecur)=>{\\nconst{\\nerrorId=undefined,\\nmessage,\\nname,\\ncause=undefined,\\nerrors=undefined,\\n...rest}=\\nerrData;\\n/* See https://github.com/endojs/endo/pull/2052*/\\n/* capData does not transform strings. The immediately following calls*/\\n/* to `decodeRecur` are for reuse by other encodings that do,*/\\n/* such as smallcaps.*/\\nconst dName=decodeRecur(name);\\nconst dMessage=decodeRecur(message);\\n/* errorId is a late addition so be tolerant of its absence.*/\\nconst dErrorId=/** @type {string} */errorId&&decodeRecur(errorId);\\nif(typeof dName!=='string'){\\nthrow index.throwRedacted`invalid error name typeof ${index.quote(typeof dName)}`;}\\n\\nif(typeof dMessage!=='string'){\\nthrow index.throwRedacted`invalid error message typeof ${index.quote(typeof dMessage)}`;}\\n\\nconst errConstructor=error.getErrorConstructor(dName)||Error;\\nconst errorName=\\ndErrorId===undefined?\\n`Remote${errConstructor.name}`:\\n`Remote${errConstructor.name}(${dErrorId})`;\\nconst options={\\nerrorName,\\nsanitize:false};\\n\\nif(cause){\\noptions.cause=decodeRecur(cause);}\\n\\nif(errors){\\noptions.errors=decodeRecur(errors);}\\n\\nconst rawError=index.makeError(dMessage,errConstructor,options);\\n/* Note that this does not decodeRecur rest's property names.*/\\n/* This would be inconsistent with smallcaps' expected handling,*/\\n/* but is fine here since it is only used for `annotateError`,*/\\n/* which is for diagnostic info that is otherwise unobservable.*/\\nconst descs=objectMap.objectMap(rest,(data)=>({\\nvalue:decodeRecur(data),\\nwritable:false,\\nenumerable:false,\\nconfigurable:false}));\\n\\ndefineProperties(rawError,descs);\\nharden(rawError);\\nreturn passStyleOf.toPassableError(rawError);};\\n\\n\\n/* The current encoding does not give the decoder enough into to distinguish*/\\n/* whether a slot represents a promise or a remotable. As an implementation*/\\n/* restriction until this is fixed, if either is provided, both must be*/\\n/* provided and they must be the same.*/\\n/* See https://github.com/Agoric/agoric-sdk/issues/4334*/\\nconst decodeRemotableOrPromiseFromCapData=(rawTree,_decodeRecur)=>{\\nconst{[encodeToCapData.QCLASS]:_,...slotData}=rawTree;\\nreturn decodeSlotCommon(slotData);};\\n\\n\\nconst decodeErrorFromCapData=(rawTree,decodeRecur)=>{\\nconst{[encodeToCapData.QCLASS]:_,...errData}=rawTree;\\nreturn decodeErrorCommon(errData,decodeRecur);};\\n\\n\\nconst reviveFromCapData=encodeToCapData.makeDecodeFromCapData({\\ndecodeRemotableFromCapData:decodeRemotableOrPromiseFromCapData,\\ndecodePromiseFromCapData:decodeRemotableOrPromiseFromCapData,\\ndecodeErrorFromCapData});\\n\\n\\nconst makeDecodeSlotFromSmallcaps=(prefix)=>{\\n/**\\n * @param {string} stringEncoding\\n * @param {(e: unknown) => PassableCap} _decodeRecur\\n * @returns {RemotableObject | Promise}\\n */\\nreturn(stringEncoding,_decodeRecur)=>{\\nassert(stringEncoding.charAt(0)===prefix);\\n/* slots: $slotIndex.iface or $slotIndex*/\\nconst i=stringEncoding.indexOf('.');\\nconst index=Number(stringEncoding.slice(1,i<0?undefined:i));\\n/* i < 0 means there was no iface included.*/\\nconst iface=i<0?undefined:stringEncoding.slice(i+1);\\nreturn decodeSlotCommon({iface,index});};};\\n\\n\\nconst decodeRemotableFromSmallcaps=makeDecodeSlotFromSmallcaps('$');\\nconst decodePromiseFromSmallcaps=makeDecodeSlotFromSmallcaps('&');\\n\\nconst decodeErrorFromSmallcaps=(encoding,decodeRecur)=>{\\nconst{'#error':message,...restErrData}=encoding;\\n!passStyleHelpers.hasOwnPropertyOf(restErrData,'message')||\\nindex.throwRedacted`unexpected encoded error property ${index.quote('message')}`;\\nreturn decodeErrorCommon({message,...restErrData},decodeRecur);};\\n\\n\\nconst reviveFromSmallcaps=encodeToSmallcaps.makeDecodeFromSmallcaps({\\n/* @ts-ignore XXX SmallCapsEncoding*/\\ndecodeRemotableFromSmallcaps,\\n/* @ts-ignore XXX SmallCapsEncoding*/\\ndecodePromiseFromSmallcaps,\\ndecodeErrorFromSmallcaps});\\n\\n\\nreturn harden({reviveFromCapData,reviveFromSmallcaps});};\\n\\n\\n/**\\n * @type {FromCapData<Slot>}\\n */\\nconst fromCapData=(data)=>{\\nconst{body,slots}=data;\\ntypeof body==='string'||\\nindex.throwRedacted`unserialize() given non-capdata (.body is ${body}, not string)`;\\nisArray(data.slots)||\\nindex.throwRedacted`unserialize() given non-capdata (.slots are not Array)`;\\nconst{reviveFromCapData,reviveFromSmallcaps}=makeFullRevive(slots);\\nlet result;\\n/* JSON cannot begin with a '#', so this is an unambiguous signal.*/\\nif(body.charAt(0)==='#'){\\nconst smallcapsBody=body.slice(1);\\nconst encoding=harden(JSON.parse(smallcapsBody));\\nresult=harden(reviveFromSmallcaps(encoding));}else\\n{\\nconst rawTree=harden(JSON.parse(body));\\nresult=harden(reviveFromCapData(rawTree));}\\n\\n/* See https://github.com/Agoric/agoric-sdk/issues/4337*/\\n/* which should be considered fixed once we've completed the switch*/\\n/* to smallcaps.*/\\npassStyleOf.assertPassable(result);\\nreturn(/** @type {PassableCap} */result);};\\n\\n\\nreturn harden({\\ntoCapData,\\nfromCapData,\\n\\n/* for backwards compatibility*/\\n/** @deprecated use toCapData */\\nserialize:toCapData,\\n/** @deprecated use fromCapData */\\nunserialize:fromCapData});};exports.makeMarshal=makeMarshal;\",\n \"node_modules/@endo/marshal/src/rankOrder.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../pass-style/index.js');var index=require('../../errors/index.js');var encodePassable=require('./encodePassable.js');var passStyleOf=require('../../pass-style/src/passStyleOf.js');var passStyleHelpers=require('../../pass-style/src/passStyle-helpers.js');var\\n\\n\\n\\n\\n\\n\\n\\nsymbol=require('../../pass-style/src/symbol.js');/**\\n * @import {Passable, PassStyle} from '@endo/pass-style'\\n * @import {FullCompare, RankCompare, RankCover} from './types.js'\\n */\\n\\nconst{entries,fromEntries,setPrototypeOf,is}=Object;\\n\\n/**\\n * @typedef {object} RankComparatorKit\\n * @property {RankCompare} comparator\\n * @property {RankCompare} antiComparator\\n */\\n\\n/**\\n * @typedef {object} FullComparatorKit\\n * @property {FullCompare} comparator\\n * @property {FullCompare} antiComparator\\n */\\n\\n/**\\n * @typedef {[number, number]} IndexCover\\n */\\n\\n/**\\n * This is the equality comparison used by JavaScript's Map and Set\\n * abstractions, where NaN is the same as NaN and -0 is the same as\\n * 0. Marshal serializes -0 as zero, so the semantics of our distributed\\n * object system does not distinguish 0 from -0.\\n *\\n * `sameValueZero` is the EcmaScript spec name for this equality comparison,\\n * but TODO we need a better name for the API.\\n *\\n * @param {any} x\\n * @param {any} y\\n * @returns {boolean}\\n */\\nconst sameValueZero=(x,y)=>x===y||is(x,y);\\n\\nconst trivialComparator=(left,right)=>\\n/* eslint-disable-next-line no-nested-ternary, @endo/restrict-comparison-operands*/\\nleft<right?-1:left===right?0:1;\\n\\n/**\\n * @typedef {Record<PassStyle, { index: number, cover: RankCover }>} PassStyleRanksRecord\\n */\\n\\nconst passStyleRanks=/** @type {PassStyleRanksRecord} */\\nfromEntries(\\nentries(encodePassable.passStylePrefixes)\\n/* Sort entries by ascending prefix.*/.\\nsort(([_leftStyle,leftPrefixes],[_rightStyle,rightPrefixes])=>{\\nreturn trivialComparator(leftPrefixes,rightPrefixes);}).\\n\\nmap(([passStyle,prefixes],index$1)=>{\\n/* Cover all strings that start with any character in `prefixes`,*/\\n/* verifying that it is sorted so that is*/\\n/* all s such that prefixes.at(0) ≤ s < successor(prefixes.at(-1)).*/\\nprefixes===[...prefixes].sort().join('')||\\nindex.throwRedacted`unsorted prefixes for passStyle ${index.quote(passStyle)}: ${index.quote(prefixes)}`;\\nconst cover=[\\nprefixes.charAt(0),\\nString.fromCharCode(prefixes.charCodeAt(prefixes.length-1)+1)];\\n\\nreturn[passStyle,{index:index$1,cover}];}));\\n\\n\\n\\nsetPrototypeOf(passStyleRanks,null);\\nharden(passStyleRanks);\\n\\n/**\\n * Associate with each passStyle a RankCover that may be an overestimate,\\n * and whose results therefore need to be filtered down. For example, because\\n * there is not a smallest or biggest bigint, bound it by `NaN` (the last place\\n * number) and `''` (the empty string, which is the first place string). Thus,\\n * a range query using this range may include these values, which would then\\n * need to be filtered out.\\n *\\n * @param {PassStyle} passStyle\\n * @returns {RankCover}\\n */\\nconst getPassStyleCover=(passStyle)=>passStyleRanks[passStyle].cover;\\nharden(getPassStyleCover);\\n\\n/**\\n * @type {WeakMap<RankCompare,WeakSet<Passable[]>>}\\n */\\nconst memoOfSorted=new WeakMap();\\n\\n/**\\n * @type {WeakMap<RankCompare,RankCompare>}\\n */\\nconst comparatorMirrorImages=new WeakMap();\\n\\n/**\\n * @param {RankCompare=} compareRemotables\\n * An option to create a comparator in which an internal order is\\n * assigned to remotables. This defaults to a comparator that\\n * always returns `0`, meaning that all remotables are tied\\n * for the same rank.\\n * @returns {RankComparatorKit}\\n */\\nconst makeComparatorKit=(compareRemotables=(_x,_y)=>0)=>{\\n/** @type {RankCompare} */\\nconst comparator=(left,right)=>{\\nif(sameValueZero(left,right)){\\nreturn 0;}\\n\\nconst leftStyle=passStyleOf.passStyleOf(left);\\nconst rightStyle=passStyleOf.passStyleOf(right);\\nif(leftStyle!==rightStyle){\\nreturn trivialComparator(\\npassStyleRanks[leftStyle].index,\\npassStyleRanks[rightStyle].index);}\\n\\n\\n/* eslint-disable @endo/restrict-comparison-operands --\\n * We know `left` and `right` are comparable.\\n */\\nswitch(leftStyle){\\ncase'remotable':{\\nreturn compareRemotables(left,right);}\\n\\ncase'undefined':\\ncase'null':\\ncase'error':\\ncase'promise':{\\n/* For each of these passStyles, all members of that passStyle are tied*/\\n/* for the same rank.*/\\nreturn 0;}\\n\\ncase'boolean':\\ncase'bigint':\\ncase'string':{\\n/* Within each of these passStyles, the rank ordering agrees with*/\\n/* JavaScript's relational operators `<` and `>`.*/\\nif(left<right){\\nreturn-1;}else\\n{\\nassert(left>right);\\nreturn 1;}}\\n\\n\\ncase'symbol':{\\nreturn comparator(\\nsymbol.nameForPassableSymbol(left),\\nsymbol.nameForPassableSymbol(right));}\\n\\n\\ncase'number':{\\n/* `NaN`'s rank is after all other numbers.*/\\nif(Number.isNaN(left)){\\nassert(!Number.isNaN(right));\\nreturn 1;}else\\nif(Number.isNaN(right)){\\nreturn-1;}\\n\\n/* The rank ordering of non-NaN numbers agrees with JavaScript's*/\\n/* relational operators '<' and '>'.*/\\nif(left<right){\\nreturn-1;}else\\n{\\nassert(left>right);\\nreturn 1;}}\\n\\n\\ncase'copyRecord':{\\n/* Lexicographic by inverse sorted order of property names, then*/\\n/* lexicographic by corresponding values in that same inverse*/\\n/* order of their property names. Comparing names by themselves first,*/\\n/* all records with the exact same set of property names sort next to*/\\n/* each other in a rank-sort of copyRecords.*/\\n\\n/* The copyRecord invariants enforced by passStyleOf ensure that*/\\n/* all the property names are strings. We need the reverse sorted order*/\\n/* of these names, which we then compare lexicographically. This ensures*/\\n/* that if the names of record X are a subset of the names of record Y,*/\\n/* then record X will have an earlier rank and sort to the left of Y.*/\\nconst leftNames=encodePassable.recordNames(left);\\nconst rightNames=encodePassable.recordNames(right);\\n\\nconst result=comparator(leftNames,rightNames);\\nif(result!==0){\\nreturn result;}\\n\\nreturn comparator(\\nencodePassable.recordValues(left,leftNames),\\nencodePassable.recordValues(right,rightNames));}\\n\\n\\ncase'copyArray':{\\n/* Lexicographic*/\\nconst len=Math.min(left.length,right.length);\\nfor(let i=0;i<len;i+=1){\\nconst result=comparator(left[i],right[i]);\\nif(result!==0){\\nreturn result;}}\\n\\n\\n/* If all matching elements were tied, then according to their lengths.*/\\n/* If array X is a prefix of array Y, then X has an earlier rank than Y.*/\\nreturn comparator(left.length,right.length);}\\n\\ncase'tagged':{\\n/* Lexicographic by `[Symbol.toStringTag]` then `.payload`.*/\\nconst labelComp=comparator(passStyleHelpers.getTag(left),passStyleHelpers.getTag(right));\\nif(labelComp!==0){\\nreturn labelComp;}\\n\\nreturn comparator(left.payload,right.payload);}\\n\\ndefault:{\\nthrow index.throwRedacted`Unrecognized passStyle: ${index.quote(leftStyle)}`;}}\\n\\n\\n/* eslint-enable */};\\n\\n\\n/** @type {RankCompare} */\\nconst antiComparator=(x,y)=>comparator(y,x);\\n\\nmemoOfSorted.set(comparator,new WeakSet());\\nmemoOfSorted.set(antiComparator,new WeakSet());\\ncomparatorMirrorImages.set(comparator,antiComparator);\\ncomparatorMirrorImages.set(antiComparator,comparator);\\n\\nreturn harden({comparator,antiComparator});};\\n\\n/**\\n * @param {RankCompare} comparator\\n * @returns {RankCompare=}\\n */\\nconst comparatorMirrorImage=(comparator)=>\\ncomparatorMirrorImages.get(comparator);\\n\\n/**\\n * @param {Passable[]} passables\\n * @param {RankCompare} compare\\n * @returns {boolean}\\n */\\nconst isRankSorted=(passables,compare)=>{\\nconst subMemoOfSorted=memoOfSorted.get(compare);\\nassert(subMemoOfSorted!==undefined);\\nif(subMemoOfSorted.has(passables)){\\nreturn true;}\\n\\nassert(passStyleOf.passStyleOf(passables)==='copyArray');\\nfor(let i=1;i<passables.length;i+=1){\\nif(compare(passables[i-1],passables[i])>=1){\\nreturn false;}}\\n\\n\\nsubMemoOfSorted.add(passables);\\nreturn true;};\\n\\nharden(isRankSorted);\\n\\n/**\\n * @param {Passable[]} sorted\\n * @param {RankCompare} compare\\n */\\nconst assertRankSorted=(sorted,compare)=>\\nisRankSorted(sorted,compare)||\\n/* TODO assert on bug could lead to infinite recursion. Fix.*/\\n/* eslint-disable-next-line no-use-before-define*/\\nindex.throwRedacted`Must be rank sorted: ${sorted} vs ${sortByRank(sorted,compare)}`;\\nharden(assertRankSorted);\\n\\n/**\\n * TODO SECURITY BUG: https://github.com/Agoric/agoric-sdk/issues/4260\\n * sortByRank currently uses `Array.prototype.sort` directly, and\\n * so only works correctly when given a `compare` function that considers\\n * `undefined` strictly bigger (`>`) than everything else. This is\\n * because `Array.prototype.sort` bizarrely moves all `undefined`s to\\n * the end of the array regardless, without consulting the `compare`\\n * function. This is a genuine bug for us NOW because sometimes we sort\\n * in reverse order by passing a reversed rank comparison function.\\n *\\n * @template {Passable} T\\n * @param {Iterable<T>} passables\\n * @param {RankCompare} compare\\n * @returns {T[]}\\n */\\nconst sortByRank=(passables,compare)=>{\\nif(Array.isArray(passables)){\\nharden(passables);\\n/* Calling isRankSorted gives it a chance to get memoized for*/\\n/* this `compare` function even if it was already memoized for a different*/\\n/* `compare` function.*/\\nif(isRankSorted(passables,compare)){\\nreturn passables;}}\\n\\n\\nconst unsorted=[...passables];\\nunsorted.forEach(harden);\\nconst sorted=harden(unsorted.sort(compare));\\nconst subMemoOfSorted=memoOfSorted.get(compare);\\nassert(subMemoOfSorted!==undefined);\\nsubMemoOfSorted.add(sorted);\\nreturn sorted;};\\n\\nharden(sortByRank);\\n\\n/**\\n * See\\n * https://en.wikipedia.org/wiki/Binary_search_algorithm#Procedure_for_finding_the_leftmost_element\\n *\\n * @param {Passable[]} sorted\\n * @param {RankCompare} compare\\n * @param {Passable} key\\n * @param {(\\\"leftMost\\\" | \\\"rightMost\\\")=} bias\\n * @returns {number}\\n */\\nconst rankSearch=(sorted,compare,key,bias='leftMost')=>{\\nassertRankSorted(sorted,compare);\\nlet left=0;\\nlet right=sorted.length;\\nwhile(left<right){\\nconst m=Math.floor((left+right)/2);\\nconst comp=compare(sorted[m],key);\\nif(comp<=-1||comp===0&&bias==='rightMost'){\\nleft=m+1;}else\\n{\\nassert(comp>=1||comp===0&&bias==='leftMost');\\nright=m;}}\\n\\n\\nreturn bias==='leftMost'?left:right-1;};\\n\\n\\n/**\\n * @param {Passable[]} sorted\\n * @param {RankCompare} compare\\n * @param {RankCover} rankCover\\n * @returns {IndexCover}\\n */\\nconst getIndexCover=(sorted,compare,[leftKey,rightKey])=>{\\nassertRankSorted(sorted,compare);\\nconst leftIndex=rankSearch(sorted,compare,leftKey,'leftMost');\\nconst rightIndex=rankSearch(sorted,compare,rightKey,'rightMost');\\nreturn[leftIndex,rightIndex];};\\n\\nharden(getIndexCover);\\n\\n/** @type {RankCover} */\\nconst FullRankCover=harden(['','{']);\\n\\n/**\\n * @param {Passable[]} sorted\\n * @param {IndexCover} indexCover\\n * @returns {Iterable<[number, Passable]>}\\n */\\nconst coveredEntries=(sorted,[leftIndex,rightIndex])=>{\\n/** @type {Iterable<[number, Passable]>} */\\nconst iterable=harden({\\n[Symbol.iterator]:()=>{\\nlet i=leftIndex;\\nreturn harden({\\nnext:()=>{\\nif(i<=rightIndex){\\nconst element=sorted[i];\\ni+=1;\\nreturn harden({value:[i,element],done:false});}else\\n{\\nreturn harden({value:undefined,done:true});}}});}});\\n\\n\\n\\n\\n\\nreturn iterable;};\\n\\nharden(coveredEntries);\\n\\n/**\\n * @template {Passable} T\\n * @param {RankCompare} compare\\n * @param {T} a\\n * @param {T} b\\n * @returns {T}\\n */\\nconst maxRank=(compare,a,b)=>compare(a,b)>=0?a:b;\\n\\n/**\\n * @template {Passable} T\\n * @param {RankCompare} compare\\n * @param {T} a\\n * @param {T} b\\n * @returns {T}\\n */\\nconst minRank=(compare,a,b)=>compare(a,b)<=0?a:b;\\n\\n/**\\n * @param {RankCompare} compare\\n * @param {RankCover[]} covers\\n * @returns {RankCover}\\n */\\nconst unionRankCovers=(compare,covers)=>{\\n/**\\n * @param {RankCover} a\\n * @param {RankCover} b\\n * @returns {RankCover}\\n */\\nconst unionRankCoverPair=([leftA,rightA],[leftB,rightB])=>[\\nminRank(compare,leftA,leftB),\\nmaxRank(compare,rightA,rightB)];\\n\\nreturn covers.reduce(unionRankCoverPair,['{','']);};\\n\\nharden(unionRankCovers);\\n\\n/**\\n * @param {RankCompare} compare\\n * @param {RankCover[]} covers\\n * @returns {RankCover}\\n */\\nconst intersectRankCovers=(compare,covers)=>{\\n/**\\n * @param {RankCover} a\\n * @param {RankCover} b\\n * @returns {RankCover}\\n */\\nconst intersectRankCoverPair=([leftA,rightA],[leftB,rightB])=>[\\nmaxRank(compare,leftA,leftB),\\nminRank(compare,rightA,rightB)];\\n\\nreturn covers.reduce(intersectRankCoverPair,['','{']);};\\n\\n\\nconst{comparator:compareRank,antiComparator:compareAntiRank}=\\nmakeComparatorKit();\\n\\n/**\\n * Create a comparator kit in which remotables are fully ordered\\n * by the order in which they are first seen by *this* comparator kit.\\n * BEWARE: This is observable mutable state, so such a comparator kit\\n * should never be shared among subsystems that should not be able\\n * to communicate.\\n *\\n * Note that this order does not meet the requirements for store\\n * ordering, since it has no memory of deleted keys.\\n *\\n * These full order comparator kit is strictly more precise that the\\n * rank order comparator kits above. As a result, any array which is\\n * sorted by such a full order will pass the isRankSorted test with\\n * a corresponding rank order.\\n *\\n * An array which is sorted by a *fresh* full order comparator, i.e.,\\n * one that has not yet seen any remotables, will of course remain\\n * sorted by according to *that* full order comparator. An array *of\\n * scalars* sorted by a fresh full order will remain sorted even\\n * according to a new fresh full order comparator, since it will see\\n * the remotables in the same order again. Unfortunately, this is\\n * not true of arrays of passables in general.\\n *\\n * @param {boolean=} longLived\\n * @returns {FullComparatorKit}\\n */\\nconst makeFullOrderComparatorKit=(longLived=false)=>{\\nlet numSeen=0;\\n/* When dynamically created with short lifetimes (the default) a WeakMap*/\\n/* would perform poorly, and the leak created by a Map only lasts as long*/\\n/* as the Map.*/\\nconst MapConstructor=longLived?WeakMap:Map;\\nconst seen=new MapConstructor();\\nconst tag=(r)=>{\\nif(seen.has(r)){\\nreturn seen.get(r);}\\n\\nnumSeen+=1;\\nseen.set(r,numSeen);\\nreturn numSeen;};\\n\\nconst compareRemotables=(x,y)=>compareRank(tag(x),tag(y));\\nreturn makeComparatorKit(compareRemotables);};\\n\\nharden(makeFullOrderComparatorKit);exports.FullRankCover=FullRankCover;exports.assertRankSorted=assertRankSorted;exports.comparatorMirrorImage=comparatorMirrorImage;exports.compareAntiRank=compareAntiRank;exports.compareRank=compareRank;exports.coveredEntries=coveredEntries;exports.getIndexCover=getIndexCover;exports.getPassStyleCover=getPassStyleCover;exports.intersectRankCovers=intersectRankCovers;exports.isRankSorted=isRankSorted;exports.makeComparatorKit=makeComparatorKit;exports.makeFullOrderComparatorKit=makeFullOrderComparatorKit;exports.sortByRank=sortByRank;exports.trivialComparator=trivialComparator;exports.unionRankCovers=unionRankCovers;\",\n \"node_modules/@endo/marshal/src/types.js\": \"\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n'use strict';/* @ts-check*/ /** @import {Passable, PassableCap} from '@endo/pass-style' */ /**\\n * @template Slot\\n * @template {PassableCap} [Value=any]\\n * @callback ConvertValToSlot\\n * @param {Value} val\\n * @returns {Slot}\\n */ /**\\n * @template Slot\\n * @template {PassableCap} [Value=any]\\n * @callback ConvertSlotToVal\\n * @param {Slot} slot\\n * @param {string} [iface]\\n * @returns {Value}\\n */ /**\\n * @template T\\n * @typedef {{ '@qclass': T }} EncodingClass\\n */ /**\\n * @typedef {EncodingClass<'NaN'> |\\n * EncodingClass<'undefined'> |\\n * EncodingClass<'Infinity'> |\\n * EncodingClass<'-Infinity'> |\\n * EncodingClass<'bigint'> & { digits: string } |\\n * EncodingClass<'@@asyncIterator'> |\\n * EncodingClass<'symbol'> & { name: string } |\\n * EncodingClass<'error'> & { name: string,\\n * message: string,\\n * errorId?: string,\\n * cause?: Encoding,\\n * errors?: Encoding[],\\n * } |\\n * EncodingClass<'slot'> & { index: number,\\n * iface?: string\\n * } |\\n * EncodingClass<'hilbert'> & { original: Encoding,\\n * rest?: Encoding\\n * } |\\n * EncodingClass<'tagged'> & { tag: string,\\n * payload: Encoding\\n * }\\n * } EncodingUnion\\n *\\n * Note that the '@@asyncIterator' encoding is deprecated. Use 'symbol' instead.\\n *\\n * The 'hilbert' encoding is a reference to the Hilbert Hotel\\n * of https://www.ias.edu/ideas/2016/pires-hilbert-hotel .\\n * It represents data that has its own '@qclass' property by separately storing\\n * the `original` value of that property and\\n * a `rest` record containing all other properties.\\n */ /**\\n * @typedef {boolean | number | null | string | EncodingUnion} EncodingElement\\n */ /**\\n * @template T\\n * @typedef {T | { [x: PropertyKey]: TreeOf<T> }} TreeOf\\n */ /**\\n * @typedef {TreeOf<EncodingElement>} Encoding\\n *\\n * The JSON-representable structure describing the complete shape and\\n * pass-by-copy data of a Passable (i.e., everything except the contents of its\\n * PassableCap leafs, which are marshalled into referenced Slots).\\n *\\n * '@qclass' is a privileged property name in our encoding scheme, so\\n * it is disallowed in encoding records and any data that has such a property\\n * must instead use the 'hilbert' encoding described above.\\n */ /**\\n * @template Slot\\n * @typedef {object} CapData\\n * @property {string} body A JSON.stringify of an Encoding\\n * @property {Slot[]} slots\\n */ /**\\n * @template Slot\\n * @callback ToCapData\\n * @param {Passable} val\\n * @returns {CapData<Slot>}\\n */ /**\\n * @template Slot\\n * @callback FromCapData\\n * @param {CapData<Slot>} data\\n * @returns {any} a Passable\\n */ /**\\n * @template Slot\\n * @typedef {object} Marshal\\n * @property {ToCapData<Slot>} serialize use toCapData\\n * @property {FromCapData<Slot>} unserialize use fromCapData\\n * @property {ToCapData<Slot>} toCapData\\n * @property {FromCapData<Slot>} fromCapData\\n */ /**\\n * @typedef {object} MakeMarshalOptions\\n * @property {'on'|'off'} [errorTagging] controls whether serialized errors\\n * also carry tagging information, made from `marshalName` and numbers\\n * generated (currently by counting) starting at `errorIdNum`. The\\n * `errorTagging` option defaults to `'on'`. Serialized\\n * errors are also logged to `marshalSaveError` only if tagging is `'on'`.\\n * @property {string=} marshalName Used to identify sent errors.\\n * @property {number=} errorIdNum Ascending numbers staring from here\\n * identify the sending of errors relative to this marshal instance.\\n * @property {(err: Error) => void=} marshalSaveError If `errorTagging` is\\n * `'on'`, then errors serialized by this marshal instance are also\\n * logged by calling `marshalSaveError` *after* `annotateError` associated\\n * that error with its errorId. Thus, if `marshalSaveError` in turn logs\\n * to the normal console, which is the default, then the console will\\n * show that note showing the associated errorId.\\n * @property {'capdata'|'smallcaps'} [serializeBodyFormat]\\n * Formatting to use in the \\\"body\\\" property in objects returned from\\n * `serialize`. The body string for each case:\\n * * 'capdata' - a JSON string, from an encoding of passables\\n * into JSON, where some values are represented as objects with a\\n * `'@qclass` property.\\n * * 'smallcaps' - a JSON string prefixed with `'#'`, which is\\n * an unambiguous signal since a valid JSON string cannot begin with\\n * `'#'`.\\n */ /**\\n * @typedef {[string, string]} RankCover\\n * RankCover represents the inclusive lower bound and *inclusive* upper bound\\n * of a string-comparison range that covers all possible encodings for\\n * a set of values.\\n */ /**\\n * @typedef {-1 | 0 | 1} RankComparison\\n * The result of a `RankCompare` function that defines a rank-order, i.e.,\\n * a total preorder in which different elements are always comparable but\\n * can be tied for the same rank. See `RankCompare`.\\n */ /**\\n * @callback RankCompare\\n * Returns `-1`, `0`, or `1` depending on whether the rank of `left`\\n * is respectively before, tied-with, or after the rank of `right`.\\n *\\n * This comparison function is valid as argument to\\n * `Array.prototype.sort`. This is sometimes described as a \\\"total order\\\"\\n * but, depending on your definitions, this is technically incorrect because\\n * it may return `0` to indicate that two distinguishable elements such as\\n * `-0` and `0` are tied (i.e., are in the same equivalence class\\n * for the purposes of this ordering). If each such equivalence class is\\n * a *rank* and ranks are disjoint, then this \\\"rank order\\\" is a\\n * true total order over these ranks. In mathematics this goes by several\\n * other names such as \\\"total preorder\\\".\\n *\\n * This function establishes a total rank order over all passables.\\n * To do so it makes arbitrary choices, such as that all strings\\n * are after all numbers. Thus, this order is not intended to be\\n * used directly as a comparison with useful semantics. However, it must be\\n * closely enough related to such comparisons to aid in implementing\\n * lookups based on those comparisons. For example, in order to get a total\\n * order among ranks, we put `NaN` after all other JavaScript \\\"number\\\" values\\n * (i.e., IEEE 754 floating-point values). But otherwise, we rank JavaScript\\n * numbers by signed magnitude, with `0` and `-0` tied. A semantically useful\\n * ordering would also compare magnitudes, and so agree with the rank ordering\\n * of all values other than `NaN`. An array sorted by rank would enable range\\n * queries by magnitude.\\n * @param {any} left\\n * @param {any} right\\n * @returns {RankComparison}\\n */ /**\\n * @typedef {RankCompare} FullCompare\\n * A `FullCompare` function satisfies all the invariants stated below for\\n * `RankCompare`'s relation with KeyCompare.\\n * In addition, its equality is as precise as the `KeyCompare`\\n * comparison defined below, in that, for all Keys `x` and `y`,\\n * `FullCompare(x, y) === 0` iff `KeyCompare(x, y) === 0`.\\n *\\n * For non-keys a `FullCompare` should be exactly as imprecise as\\n * `RankCompare`. For example, both will treat all errors as in the same\\n * equivalence class. Both will treat all promises as in the same\\n * equivalence class. Both will order taggeds the same way, which is admittedly\\n * weird, as some taggeds will be considered keys and other taggeds will be\\n * considered non-keys.\\n */\",\n \"node_modules/@endo/nat/src/index.js\": \"'use strict';\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nObject.defineProperty(exports,'__esModule',{value:true});/* Copyright (C) 2011 Google Inc.*/ /* Copyright (C) 2018 Agoric*/ /**/ /* Licensed under the Apache License, Version 2.0 (the \\\"License\\\");*/ /* you may not use this file except in compliance with the License.*/ /* You may obtain a copy of the License at*/ /**/ /* http://www.apache.org/licenses/LICENSE-2.0*/ /**/ /* Unless required by applicable law or agreed to in writing, software*/ /* distributed under the License is distributed on an \\\"AS IS\\\" BASIS,*/ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.*/ /* See the License for the specific language governing permissions and*/ /* limitations under the License.*/ /* @ts-check*/ /**\\n * Is `allegedNum` a number in the [contiguous range of exactly and\\n * unambiguously\\n * representable](https://esdiscuss.org/topic/more-numeric-constants-please-especially-epsilon#content-14)\\n * natural numbers (non-negative integers)?\\n *\\n * To qualify `allegedNum` must either be a\\n * non-negative `bigint`, or a non-negative `number` representing an integer\\n * within range of [integers safely representable in\\n * floating point](https://tc39.es/ecma262/#sec-number.issafeinteger).\\n *\\n * @param {unknown} allegedNum\\n * @returns {boolean}\\n */\\nfunction isNat(allegedNum){\\nif(typeof allegedNum==='bigint'){\\nreturn allegedNum>=0;}\\n\\nif(typeof allegedNum!=='number'){\\nreturn false;}\\n\\n\\nreturn Number.isSafeInteger(allegedNum)&&allegedNum>=0;}\\n\\n\\n/**\\n * If `allegedNumber` passes the `isNat` test, then return it as a bigint.\\n * Otherwise throw an appropriate error.\\n *\\n * If `allegedNum` is neither a bigint nor a number, `Nat` throws a `TypeError`.\\n * Otherwise, if it is not a [safely\\n * representable](https://esdiscuss.org/topic/more-numeric-constants-please-especially-epsilon#content-14)\\n * non-negative integer, `Nat` throws a `RangeError`.\\n * Otherwise, it is converted to a bigint if necessary and returned.\\n *\\n * @param {unknown} allegedNum\\n * @returns {bigint}\\n */\\nfunction Nat(allegedNum){\\nif(typeof allegedNum==='bigint'){\\nif(allegedNum<0){\\nthrow RangeError(`${allegedNum} is negative`);}\\n\\nreturn allegedNum;}\\n\\n\\nif(typeof allegedNum==='number'){\\nif(!Number.isSafeInteger(allegedNum)){\\nthrow RangeError(`${allegedNum} not a safe integer`);}\\n\\nif(allegedNum<0){\\nthrow RangeError(`${allegedNum} is negative`);}\\n\\nreturn BigInt(allegedNum);}\\n\\n\\nthrow TypeError(\\n`${allegedNum} is a ${typeof allegedNum} but must be a bigint or a number`);}exports.Nat=Nat;exports.isNat=isNat;\",\n \"node_modules/@endo/pass-style/index.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var iterHelpers=require('./src/iter-helpers.js');var passStyleHelpers=require('./src/passStyle-helpers.js');var error=require('./src/error.js');var remotable=require('./src/remotable.js');var symbol=require('./src/symbol.js');var string=require('./src/string.js');var passStyleOf=require('./src/passStyleOf.js');var makeTagged=require('./src/makeTagged.js');var makeFar=require('./src/make-far.js');var typeGuards=require('./src/typeGuards.js');require('./src/types.js');exports.filterIterable=iterHelpers.filterIterable;exports.mapIterable=iterHelpers.mapIterable;exports.PASS_STYLE=passStyleHelpers.PASS_STYLE;exports.assertChecker=passStyleHelpers.assertChecker;exports.getTag=passStyleHelpers.getTag;exports.hasOwnPropertyOf=passStyleHelpers.hasOwnPropertyOf;exports.isObject=passStyleHelpers.isObject;exports.getErrorConstructor=error.getErrorConstructor;exports.isErrorLike=error.isErrorLike;exports.getInterfaceOf=remotable.getInterfaceOf;exports.assertPassableSymbol=symbol.assertPassableSymbol;exports.isPassableSymbol=symbol.isPassableSymbol;exports.nameForPassableSymbol=symbol.nameForPassableSymbol;exports.passableSymbolForName=symbol.passableSymbolForName;exports.assertPassableString=string.assertPassableString;exports.assertWellFormedString=string.assertWellFormedString;exports.isWellFormedString=string.isWellFormedString;exports.assertPassable=passStyleOf.assertPassable;exports.isPassable=passStyleOf.isPassable;exports.passStyleOf=passStyleOf.passStyleOf;exports.toPassableError=passStyleOf.toPassableError;exports.toThrowable=passStyleOf.toThrowable;exports.makeTagged=makeTagged.makeTagged;exports.Far=makeFar.Far;exports.GET_METHOD_NAMES=makeFar.GET_METHOD_NAMES;exports.Remotable=makeFar.Remotable;exports.ToFarFunction=makeFar.ToFarFunction;exports.assertCopyArray=typeGuards.assertCopyArray;exports.assertRecord=typeGuards.assertRecord;exports.assertRemotable=typeGuards.assertRemotable;exports.isCopyArray=typeGuards.isCopyArray;exports.isRecord=typeGuards.isRecord;exports.isRemotable=typeGuards.isRemotable;\",\n \"node_modules/@endo/pass-style/src/copyArray.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var index=require('../../errors/index.js');var passStyleHelpers=require('./passStyle-helpers.js');/*/ <reference types=\\\"ses\\\"/>*/\\n\\n\\n\\n\\nconst{getPrototypeOf}=Object;\\nconst{ownKeys}=Reflect;\\nconst{isArray,prototype:arrayPrototype}=Array;\\n\\n/**\\n * @param {unknown} candidate\\n * @param {IMPORT('./types.js').Checker} [check]\\n * @returns {boolean}\\n */\\nconst canBeValid=(candidate,check=undefined)=>\\nisArray(candidate)||\\n!!check&&check(false,index.redacted`Array expected: ${candidate}`);\\n\\n/**\\n *\\n * @type {IMPORT('./internal-types.js').PassStyleHelper}\\n */\\nconst CopyArrayHelper=harden({\\nstyleName:'copyArray',\\n\\ncanBeValid,\\n\\nassertValid:(candidate,passStyleOfRecur)=>{\\ncanBeValid(candidate,passStyleHelpers.assertChecker);\\ngetPrototypeOf(candidate)===arrayPrototype||\\nassert.fail(index.redacted`Malformed array: ${candidate}`,TypeError);\\n/* Since we're already ensured candidate is an array, it should not be*/\\n/* possible for the following test to fail*/\\npassStyleHelpers.checkNormalProperty(candidate,'length',false,passStyleHelpers.assertChecker);\\nconst len=/** @type {unknown[]} */candidate.length;\\nfor(let i=0;i<len;i+=1){\\npassStyleHelpers.checkNormalProperty(candidate,i,true,passStyleHelpers.assertChecker);}\\n\\n/* +1 for the 'length' property itself.*/\\nownKeys(candidate).length===len+1||\\nassert.fail(index.redacted`Arrays must not have non-indexes: ${candidate}`,TypeError);\\n/* Recursively validate that each member is passable.*/\\ncandidate.every((v)=>!!passStyleOfRecur(v));}});exports.CopyArrayHelper=CopyArrayHelper;\",\n \"node_modules/@endo/pass-style/src/copyRecord.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var index=require('../../errors/index.js');var passStyleHelpers=require('./passStyle-helpers.js');/*/ <reference types=\\\"ses\\\"/>*/\\n\\n\\n\\n\\n\\n\\n\\n\\nconst{ownKeys}=Reflect;\\nconst{getPrototypeOf,values,prototype:objectPrototype}=Object;\\n\\n/**\\n *\\n * @type {IMPORT('./internal-types.js').PassStyleHelper}\\n */\\nconst CopyRecordHelper=harden({\\nstyleName:'copyRecord',\\n\\ncanBeValid:(candidate,check=undefined)=>{\\nconst reject=!!check&&((T,...subs)=>check(false,index.redacted(T,...subs)));\\nif(getPrototypeOf(candidate)!==objectPrototype){\\nreturn(\\nreject&&\\nreject`Records must inherit from Object.prototype: ${candidate}`);}\\n\\n\\n\\nreturn ownKeys(candidate).every((key)=>{\\nreturn(\\n(typeof key==='string'||\\nreject&&\\nreject`Records can only have string-named properties: ${candidate}`)&&(\\n!passStyleHelpers.canBeMethod(candidate[key])||\\nreject&&\\n/* TODO: Update message now that there is no such thing as \\\"implicit Remotable\\\".*/\\nreject`Records cannot contain non-far functions because they may be methods of an implicit Remotable: ${candidate}`));});},\\n\\n\\n\\n\\nassertValid:(candidate,passStyleOfRecur)=>{\\nCopyRecordHelper.canBeValid(candidate,passStyleHelpers.assertChecker);\\nfor(const name of ownKeys(candidate)){\\npassStyleHelpers.checkNormalProperty(candidate,name,true,passStyleHelpers.assertChecker);}\\n\\n/* Recursively validate that each member is passable.*/\\nfor(const val of values(candidate)){\\npassStyleOfRecur(val);}}});exports.CopyRecordHelper=CopyRecordHelper;\",\n \"node_modules/@endo/pass-style/src/error.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var index=require('../../errors/index.js');var\\n\\n\\n\\n\\n\\npassStyleHelpers=require('./passStyle-helpers.js');/*/ <reference types=\\\"ses\\\"/>*/ /** @import {PassStyleHelper} from './internal-types.js' */ /** @import {Checker, PassStyle, PassStyleOf} from './types.js' */\\n\\nconst{getPrototypeOf,getOwnPropertyDescriptors,hasOwn,entries}=Object;\\n\\n/* TODO: Maintenance hazard: Coordinate with the list of errors in the SES*/\\n/* whilelist.*/\\nconst errorConstructors=new Map(\\n/* Cast because otherwise TS is confused by AggregateError*/\\n/* See https://github.com/endojs/endo/pull/2042#discussion_r1484933028*/\\n/** @type {Array<[string, IMPORT('ses').GenericErrorConstructor]>} */\\n[\\n['Error',Error],\\n['EvalError',EvalError],\\n['RangeError',RangeError],\\n['ReferenceError',ReferenceError],\\n['SyntaxError',SyntaxError],\\n['TypeError',TypeError],\\n['URIError',URIError]\\n\\n/* https://github.com/endojs/endo/issues/550*/\\n/* To accommodate platforms prior to AggregateError, we comment out the*/\\n/* following line and instead conditionally add it to the map below.*/\\n/* ['AggregateError', AggregateError],*/]);\\n\\n\\n\\nif(typeof AggregateError!=='undefined'){\\n/* Conditional, to accommodate platforms prior to AggregateError*/\\nerrorConstructors.set('AggregateError',AggregateError);}\\n\\n\\n/**\\n * Because the error constructor returned by this function might be\\n * `AggregateError`, which has different construction parameters\\n * from the other error constructors, do not use it directly to try\\n * to make an error instance. Rather, use `makeError` which encapsulates\\n * this non-uniformity.\\n *\\n * @param {string} name\\n * @returns {IMPORT('ses').GenericErrorConstructor | undefined}\\n */\\nconst getErrorConstructor=(name)=>errorConstructors.get(name);\\nharden(getErrorConstructor);\\n\\n/**\\n * @param {unknown} candidate\\n * @param {Checker} [check]\\n * @returns {boolean}\\n */\\nconst checkErrorLike=(candidate,check=undefined)=>{\\nconst reject=!!check&&((T,...subs)=>check(false,index.redacted(T,...subs)));\\n/* TODO: Need a better test than instanceof*/\\nreturn(\\ncandidate instanceof Error||\\nreject&&reject`Error expected: ${candidate}`);};\\n\\n\\nharden(checkErrorLike);\\n/*/ <reference types=\\\"ses\\\"/>*/\\n\\n/**\\n * Validating error objects are passable raises a tension between security\\n * vs preserving diagnostic information. For errors, we need to remember\\n * the error itself exists to help us diagnose a bug that's likely more\\n * pressing than a validity bug in the error itself. Thus, whenever it is safe\\n * to do so, we prefer to let the error-like test succeed and to couch these\\n * complaints as notes on the error.\\n *\\n * To resolve this, such a malformed error object will still pass\\n * `isErrorLike` so marshal can use this for top level error to report from,\\n * even if it would not actually validate.\\n * Instead, the diagnostics that `assertError` would have reported are\\n * attached as notes to the malformed error. Thus, a malformed\\n * error is passable by itself, but not as part of a passable structure.\\n *\\n * @param {unknown} candidate\\n * @returns {boolean}\\n */\\nconst isErrorLike=(candidate)=>checkErrorLike(candidate);\\nharden(isErrorLike);\\n\\n/**\\n * @param {string} propName\\n * @param {PropertyDescriptor} desc\\n * @param {(val: any) => PassStyle} passStyleOfRecur\\n * @param {Checker} [check]\\n * @returns {boolean}\\n */\\nconst checkRecursivelyPassableErrorPropertyDesc=(\\npropName,\\ndesc,\\npassStyleOfRecur,\\ncheck=undefined)=>\\n{\\nconst reject=!!check&&((T,...subs)=>check(false,index.redacted(T,...subs)));\\nif(desc.enumerable){\\nreturn(\\nreject&&\\nreject`Passable Error ${index.quote(\\npropName)\\n} own property must not be enumerable: ${desc}`);}\\n\\n\\nif(!hasOwn(desc,'value')){\\nreturn(\\nreject&&\\nreject`Passable Error ${index.quote(\\npropName)\\n} own property must be a data property: ${desc}`);}\\n\\n\\nconst{value}=desc;\\nswitch(propName){\\ncase'message':\\ncase'stack':{\\nreturn(\\ntypeof value==='string'||\\nreject&&\\nreject`Passable Error ${index.quote(\\npropName)\\n} own property must be a string: ${value}`);}\\n\\n\\ncase'cause':{\\n/* eslint-disable-next-line no-use-before-define*/\\nreturn checkRecursivelyPassableError(value,passStyleOfRecur,check);}\\n\\ncase'errors':{\\nif(!Array.isArray(value)||passStyleOfRecur(value)!=='copyArray'){\\nreturn(\\nreject&&\\nreject`Passable Error ${index.quote(\\npropName)\\n} own property must be a copyArray: ${value}`);}\\n\\n\\nreturn value.every((err)=>\\n/* eslint-disable-next-line no-use-before-define*/\\ncheckRecursivelyPassableError(err,passStyleOfRecur,check));}\\n\\n\\ndefault:{\\nbreak;}}\\n\\n\\nreturn(\\nreject&&reject`Passable Error has extra unpassed property ${index.quote(propName)}`);};\\n\\n\\nharden(checkRecursivelyPassableErrorPropertyDesc);\\n\\n/**\\n * @param {unknown} candidate\\n * @param {(val: any) => PassStyle} passStyleOfRecur\\n * @param {Checker} [check]\\n * @returns {boolean}\\n */\\nconst checkRecursivelyPassableError=(\\ncandidate,\\npassStyleOfRecur,\\ncheck=undefined)=>\\n{\\nconst reject=!!check&&((T,...subs)=>check(false,index.redacted(T,...subs)));\\nif(!checkErrorLike(candidate,check)){\\nreturn false;}\\n\\nconst proto=getPrototypeOf(candidate);\\nconst{name}=proto;\\nconst errConstructor=getErrorConstructor(name);\\nif(errConstructor===undefined||errConstructor.prototype!==proto){\\nreturn(\\nreject&&\\nreject`Passable Error must inherit from an error class .prototype: ${candidate}`);}\\n\\n\\nconst descs=getOwnPropertyDescriptors(candidate);\\nif(!('message'in descs)){\\nreturn(\\nreject&&\\nreject`Passable Error must have an own \\\"message\\\" string property: ${candidate}`);}\\n\\n\\n\\nreturn entries(descs).every(([propName,desc])=>\\ncheckRecursivelyPassableErrorPropertyDesc(\\npropName,\\ndesc,\\npassStyleOfRecur,\\ncheck));};\\n\\n\\n\\nharden(checkRecursivelyPassableError);\\n\\n/**\\n * @type {PassStyleHelper}\\n */\\nconst ErrorHelper=harden({\\nstyleName:'error',\\n\\ncanBeValid:checkErrorLike,\\n\\nassertValid:(candidate,passStyleOfRecur)=>\\ncheckRecursivelyPassableError(candidate,passStyleOfRecur,passStyleHelpers.assertChecker)});exports.ErrorHelper=ErrorHelper;exports.checkRecursivelyPassableError=checkRecursivelyPassableError;exports.checkRecursivelyPassableErrorPropertyDesc=checkRecursivelyPassableErrorPropertyDesc;exports.getErrorConstructor=getErrorConstructor;exports.isErrorLike=isErrorLike;\",\n \"node_modules/@endo/pass-style/src/iter-helpers.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var\\n\\nmakeFar=require('./make-far.js');/**\\n * The result iterator has as many elements as the `baseIterator` and\\n * have the same termination -- the same completion value or failure\\n * reason. But the non-final values are the corresponding non-final\\n * values from `baseIterator` as transformed by `func`.\\n *\\n * @template T,U\\n * @param {Iterable<T>} baseIterable\\n * @param {(value: T) => U} func\\n * @returns {Iterable<U>}\\n */\\nconst mapIterable=(baseIterable,func)=>\\n/** @type {Iterable<U>} */\\nmakeFar.Far('mapped iterable',{\\n[Symbol.iterator]:()=>{\\nconst baseIterator=baseIterable[Symbol.iterator]();\\nreturn makeFar.Far('mapped iterator',{\\nnext:()=>{\\nconst{value:baseValue,done}=baseIterator.next();\\nconst value=done?baseValue:func(baseValue);\\nreturn harden({value,done});}});}});\\n\\n\\n\\n\\nharden(mapIterable);\\n\\n/**\\n * The result iterator has a subset of the non-final values from the\\n * `baseIterator` --- those for which `pred(value)` was truthy. The result\\n * has the same termination as the `baseIterator` -- the same completion value\\n * or failure reason.\\n *\\n * @template T\\n * @param {Iterable<T>} baseIterable\\n * @param {(value: T) => boolean} pred\\n * @returns {Iterable<T>}\\n */\\nconst filterIterable=(baseIterable,pred)=>\\n/** @type {Iterable<U>} */\\nmakeFar.Far('filtered iterable',{\\n[Symbol.iterator]:()=>{\\nconst baseIterator=baseIterable[Symbol.iterator]();\\nreturn makeFar.Far('filtered iterator',{\\nnext:()=>{\\nfor(;;){\\nconst result=baseIterator.next();\\nconst{value,done}=result;\\nif(done||pred(value)){\\nreturn result;}}}});}});\\n\\n\\n\\n\\n\\n\\nharden(filterIterable);exports.filterIterable=filterIterable;exports.mapIterable=mapIterable;\",\n \"node_modules/@endo/pass-style/src/make-far.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../eventual-send/utils.js');var index=require('../../errors/index.js');var passStyleHelpers=require('./passStyle-helpers.js');var remotable=require('./remotable.js');var\\n\\n\\n\\n\\n\\n\\n\\nlocal=require('../../eventual-send/src/local.js');/*/ <reference types=\\\"ses\\\"/>*/ /** @import {RemotableBrand} from '@endo/eventual-send' */ /** @import {InterfaceSpec, RemotableObject} from './types.js' */\\n\\nconst{prototype:functionPrototype}=Function;\\nconst{\\ngetPrototypeOf,\\nsetPrototypeOf,\\ncreate,\\nisFrozen,\\nprototype:objectPrototype}=\\nObject;\\n\\n/**\\n * Now that the remotableProto does not provide its own `toString` method,\\n * ensure it always inherits from something. The original prototype of\\n * `remotable` if there was one, or `Object.prototype` otherwise.\\n *\\n * @param {object} remotable\\n * @param {InterfaceSpec} iface\\n * @returns {object}\\n */\\nconst makeRemotableProto=(remotable,iface)=>{\\nlet oldProto=getPrototypeOf(remotable);\\nif(typeof remotable==='object'){\\nif(oldProto===null){\\noldProto=objectPrototype;}\\n\\noldProto===objectPrototype||\\nindex.throwRedacted`For now, remotables cannot inherit from anything unusual, in ${remotable}`;}else\\nif(typeof remotable==='function'){\\noldProto!==null||\\nindex.throwRedacted`Original function must not inherit from null: ${remotable}`;\\noldProto===functionPrototype||\\ngetPrototypeOf(oldProto)===functionPrototype||\\nindex.throwRedacted`Far functions must originally inherit from Function.prototype, in ${remotable}`;}else\\n{\\nindex.throwRedacted`unrecognized typeof ${remotable}`;}\\n\\nreturn harden(\\ncreate(oldProto,{\\n[passStyleHelpers.PASS_STYLE]:{value:'remotable'},\\n[Symbol.toStringTag]:{value:iface}}));};\\n\\n\\n\\n\\nconst assertCanBeRemotable=(candidate)=>\\nremotable.RemotableHelper.canBeValid(candidate,passStyleHelpers.assertChecker);\\n\\n/**\\n * Create and register a Remotable. After this, getInterfaceOf(remotable)\\n * returns iface.\\n *\\n * // https://github.com/Agoric/agoric-sdk/issues/804\\n *\\n * @template {{}} T\\n * @template {InterfaceSpec} I\\n * @param {I} [iface] The interface specification for\\n * the remotable. For now, a string iface must be \\\"Remotable\\\" or begin with\\n * \\\"Alleged: \\\" or \\\"DebugName: \\\", to serve as the alleged name. More\\n * general ifaces are not yet implemented. This is temporary. We include the\\n * \\\"Alleged\\\" or \\\"DebugName\\\" as a reminder that we do not yet have SwingSet\\n * or Comms Vat\\n * support for ensuring this is according to the vat hosting the object.\\n * Currently, Alice can tell Bob about Carol, where VatA (on Alice's behalf)\\n * misrepresents Carol's `iface`. VatB and therefore Bob will then see\\n * Carol's `iface` as misrepresented by VatA.\\n * @param {undefined} [props] Currently may only be undefined.\\n * That plan is that own-properties are copied to the remotable\\n * @param {T} [remotable] The object used as the remotable\\n * @returns {T & RemotableObject<I> & RemotableBrand<{}, T>}} remotable, modified for debuggability\\n */\\nconst Remotable=(\\n/* @ts-expect-error I could have different subtype than string*/\\niface='Remotable',\\nprops=undefined,\\nremotable$1=/** @type {T} */{})=>\\n{\\nremotable.assertIface(iface);\\nassert(iface);\\n/* TODO: When iface is richer than just string, we need to get the allegedName*/\\n/* in a different way.*/\\nprops===undefined||index.throwRedacted`Remotable props not yet implemented ${props}`;\\n\\n/* Fail fast: check that the unmodified object is able to become a Remotable.*/\\nassertCanBeRemotable(remotable$1);\\n\\n/* Ensure that the remotable isn't already marked.*/\\n!(passStyleHelpers.PASS_STYLE in remotable$1)||\\nindex.throwRedacted`Remotable ${remotable$1} is already marked as a ${index.quote(\\nremotable$1[passStyleHelpers.PASS_STYLE])\\n}`;\\n/* `isFrozen` always returns true with a fake `harden`, but we want that case*/\\n/* to succeed anyway. Faking `harden` is only correctness preserving*/\\n/* if the code in question contains no bugs that the real `harden` would*/\\n/* have caught.*/\\n/* @ts-ignore `isFake` purposely not in the type*/\\nharden.isFake||\\n/* Ensure that the remotable isn't already frozen.*/\\n!isFrozen(remotable$1)||\\nindex.throwRedacted`Remotable ${remotable$1} is already frozen`;\\nconst remotableProto=makeRemotableProto(remotable$1,iface);\\n\\n/* Take a static copy of the enumerable own properties as data properties.*/\\n/* const propDescs = getOwnPropertyDescriptors({ ...props });*/\\nconst mutateHardenAndCheck=(target)=>{\\n/* defineProperties(target, propDescs);*/\\nsetPrototypeOf(target,remotableProto);\\nharden(target);\\nassertCanBeRemotable(target);};\\n\\n\\n/* Fail fast: check a fresh remotable to see if our rules fit.*/\\nmutateHardenAndCheck({});\\n\\n/* Actually finish the new remotable.*/\\nmutateHardenAndCheck(remotable$1);\\n\\n/* COMMITTED!*/\\n/* We're committed, so keep the interface for future reference.*/\\nassert(iface!==undefined);/* To make TypeScript happy*/\\nreturn(/** @type {any} */remotable$1);};\\n\\nharden(Remotable);\\n\\n/**\\n * The name of the automatically added default meta-method for obtaining a\\n * list of all methods of an object declared with `Far`, or an object that\\n * inherits from an object declared with `Far`.\\n *\\n * Modeled on `GET_INTERFACE_GUARD` from `@endo/exo`.\\n *\\n * TODO Name to be bikeshed. Perhaps even whether it is a\\n * string or symbol to be bikeshed. See\\n * https://github.com/endojs/endo/pull/1809#discussion_r1388052454\\n *\\n * HAZARD: Beware that an exo's interface can change across an upgrade,\\n * so remotes that cache it can become stale.\\n */\\nconst GET_METHOD_NAMES='__getMethodNames__';\\n\\n/**\\n * Note that `getMethodNamesMethod` is a thisful method! It must be so that\\n * it works as expected with far-object inheritance.\\n *\\n * @returns {(string|symbol)[]}\\n */\\nconst getMethodNamesMethod=harden({\\n[GET_METHOD_NAMES](){\\nreturn local.getMethodNames(this);}})[\\n\\nGET_METHOD_NAMES];\\n\\nconst getMethodNamesDescriptor=harden({\\nvalue:getMethodNamesMethod,\\nenumerable:false,\\nconfigurable:false,\\nwritable:false});\\n\\n\\n/**\\n * Mark an object to be exposed for remote interaction\\n * and give it a suggestive interface name for debugging.\\n *\\n * All properties of the object have to be methods, not data.\\n *\\n * The object must not be hardened before it is marked.\\n * It will be hardened after marking.\\n *\\n * For far objects (as opposed to far functions), also adds\\n * `__getMethodNames__` method that returns an array of all the method names,\\n * if there is not yet any method named `__getMethodNames__`.\\n *\\n * @example\\n * Far('Employee', { getManager })\\n * @template {{}} T\\n * @param {string} farName This name will be prepended with `Alleged: `\\n * for now to form the `Remotable` `iface` argument.\\n * @param {T} [remotable] The object to be marked as remotable\\n */\\nconst Far=(farName,remotable=undefined)=>{\\nconst r=remotable===undefined?/** @type {T} */{}:remotable;\\nif(typeof r==='object'&&!(GET_METHOD_NAMES in r)){\\n/* This test excludes far functions, since we currently consider them*/\\n/* to only have a call-behavior, with no callable methods.*/\\n/* Beware: Mutates the input argument! But `Remotable`*/\\n/* * requires the object to be mutable*/\\n/* * does further mutations,*/\\n/* * hardens the mutated object before returning it.*/\\n/* so this mutation is not unprecedented. But it is surprising!*/\\nObject.defineProperty(r,GET_METHOD_NAMES,getMethodNamesDescriptor);}\\n\\nreturn Remotable(`Alleged: ${farName}`,undefined,r);};\\n\\nharden(Far);\\n\\n/**\\n * Coerce `func` to a far function that preserves its call behavior.\\n * If it is already a far function, return it. Otherwise make and return a\\n * new far function that wraps `func` and forwards calls to it. This\\n * works even if `func` is already frozen. `ToFarFunction` is to be used\\n * when the function comes from elsewhere under less control. For functions\\n * you author in place, better to use `Far` on their function literal directly.\\n *\\n * @template {(...args: any[]) => any} F\\n * @param {string} farName to be used only if `func` is not already a\\n * far function.\\n * @param {F} func\\n * @returns {F & RemotableObject & RemotableBrand<{}, F>}\\n */\\nconst ToFarFunction=(farName,func)=>{\\nif(remotable.getInterfaceOf(func)!==undefined){\\n/* @ts-expect-error checked cast*/\\nreturn func;}\\n\\n/* @ts-expect-error could be different subtype*/\\nreturn Far(farName,(...args)=>func(...args));};\\n\\nharden(ToFarFunction);exports.Far=Far;exports.GET_METHOD_NAMES=GET_METHOD_NAMES;exports.Remotable=Remotable;exports.ToFarFunction=ToFarFunction;\",\n \"node_modules/@endo/pass-style/src/makeTagged.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var index=require('../../errors/index.js');var passStyleHelpers=require('./passStyle-helpers.js');var passStyleOf=require('./passStyleOf.js');/*/ <reference types=\\\"ses\\\"/>*/\\n\\n\\n\\n\\n\\nconst{create,prototype:objectPrototype}=Object;\\n\\n/**\\n * @template {string} T\\n * @template {IMPORT('./types.js').Passable} P\\n * @param {T} tag\\n * @param {P} payload\\n * @returns {IMPORT('./types.js').CopyTagged<T,P>}\\n */\\nconst makeTagged=(tag,payload)=>{\\ntypeof tag==='string'||\\nindex.throwRedacted`The tag of a tagged record must be a string: ${tag}`;\\npassStyleOf.assertPassable(harden(payload));\\nreturn harden(\\ncreate(objectPrototype,{\\n[passStyleHelpers.PASS_STYLE]:{value:'tagged'},\\n[Symbol.toStringTag]:{value:tag},\\npayload:{value:payload,enumerable:true}}));};\\n\\n\\n\\nharden(makeTagged);exports.makeTagged=makeTagged;\",\n \"node_modules/@endo/pass-style/src/passStyle-helpers.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var index=require('../../errors/index.js');/*/ <reference types=\\\"ses\\\"/>*/\\n\\n\\n\\n\\n\\n\\nconst{isArray}=Array;\\nconst{prototype:functionPrototype}=Function;\\nconst{\\ngetOwnPropertyDescriptor,\\ngetPrototypeOf,\\nhasOwnProperty:objectHasOwnProperty,\\nisFrozen,\\nprototype:objectPrototype}=\\nObject;\\nconst{apply}=Reflect;\\nconst{toStringTag:toStringTagSymbol}=Symbol;\\n\\nconst typedArrayPrototype=getPrototypeOf(Uint8Array.prototype);\\nconst typedArrayToStringTagDesc=getOwnPropertyDescriptor(\\ntypedArrayPrototype,\\ntoStringTagSymbol);\\n\\nassert(typedArrayToStringTagDesc);\\nconst getTypedArrayToStringTag=typedArrayToStringTagDesc.get;\\nassert(typeof getTypedArrayToStringTag==='function');\\n\\nconst hasOwnPropertyOf=(obj,prop)=>\\napply(objectHasOwnProperty,obj,[prop]);\\nharden(hasOwnPropertyOf);\\n\\n/* TODO try typing this; `=> val is {} too narrow, implies no properties*/\\nconst isObject=(val)=>Object(val)===val;\\nharden(isObject);\\n\\n/**\\n * Duplicates packages/ses/src/make-hardener.js to avoid a dependency.\\n *\\n * @param {unknown} object\\n */\\nconst isTypedArray=(object)=>{\\n/* The object must pass a brand check or toStringTag will return undefined.*/\\nconst tag=apply(getTypedArrayToStringTag,object,[]);\\nreturn tag!==undefined;};\\n\\nharden(isTypedArray);\\n\\nconst PASS_STYLE=Symbol.for('passStyle');\\n\\n/**\\n * For a function to be a valid method, it must not be passable.\\n * Otherwise, we risk confusing pass-by-copy data carrying\\n * far functions with attempts at far objects with methods.\\n *\\n * TODO HAZARD Because we check this on the way to hardening a remotable,\\n * we cannot yet check that `func` is hardened. However, without\\n * doing so, it's inheritance might change after the `PASS_STYLE`\\n * check below.\\n *\\n * @param {any} func\\n * @returns {boolean}\\n */\\nconst canBeMethod=(func)=>\\ntypeof func==='function'&&!(PASS_STYLE in func);\\nharden(canBeMethod);\\n\\n/**\\n * Below we have a series of predicate functions and their (curried) assertion\\n * functions. The semantics of the assertion function is just to assert that\\n * the corresponding predicate function would have returned true. But it\\n * reproduces the internal tests so failures can give a better error message.\\n *\\n * @type {Checker}\\n */\\nconst assertChecker=(cond,details)=>{\\nassert(cond,details);\\nreturn true;};\\n\\nharden(assertChecker);\\n\\n/**\\n * Checks for the presence and enumerability of an own data property.\\n *\\n * @param {object} candidate\\n * @param {string|number|symbol} propertyName\\n * @param {boolean} shouldBeEnumerable\\n * @param {Checker} [check]\\n * @returns {boolean}\\n */\\nconst checkNormalProperty=(\\ncandidate,\\npropertyName,\\nshouldBeEnumerable,\\ncheck)=>\\n{\\nconst reject=!!check&&((T,...subs)=>check(false,index.redacted(T,...subs)));\\nconst desc=getOwnPropertyDescriptor(candidate,propertyName);\\nif(desc===undefined){\\nreturn reject&&reject`${index.quote(propertyName)} property expected: ${candidate}`;}\\n\\nreturn(\\n(hasOwnPropertyOf(desc,'value')||\\nreject&&\\nreject`${index.quote(\\npropertyName)\\n} must not be an accessor property: ${candidate}`)&&(\\nshouldBeEnumerable?\\ndesc.enumerable||\\nreject&&\\nreject`${index.quote(\\npropertyName)\\n} must be an enumerable property: ${candidate}`:\\n!desc.enumerable||\\nreject&&\\nreject`${index.quote(\\npropertyName)\\n} must not be an enumerable property: ${candidate}`));};\\n\\n\\nharden(checkNormalProperty);\\n\\n/**\\n * @template {IMPORT('./types.js').InterfaceSpec} T\\n * @param {IMPORT('./types.js').PassStyled<any, T>} tagRecord\\n * @returns {T}\\n */\\nconst getTag=(tagRecord)=>tagRecord[Symbol.toStringTag];\\nharden(getTag);\\n\\nconst checkPassStyle=(obj,expectedPassStyle,check)=>{\\nconst reject=!!check&&((T,...subs)=>check(false,index.redacted(T,...subs)));\\nconst actual=obj[PASS_STYLE];\\nreturn(\\nactual===expectedPassStyle||\\nreject&&\\nreject`Expected ${index.quote(expectedPassStyle)}, not ${index.quote(actual)}: ${obj}`);};\\n\\n\\nharden(checkPassStyle);\\n\\nconst makeCheckTagRecord=(checkProto)=>{\\n/**\\n * @param {IMPORT('./types.js').PassStyled<any, any>} tagRecord\\n * @param {PassStyle} passStyle\\n * @param {Checker} [check]\\n * @returns {boolean}\\n */\\nconst checkTagRecord=(tagRecord,passStyle,check)=>{\\nconst reject=!!check&&((T,...subs)=>check(false,index.redacted(T,...subs)));\\nreturn(\\n(isObject(tagRecord)||\\nreject&&reject`A non-object cannot be a tagRecord: ${tagRecord}`)&&(\\nisFrozen(tagRecord)||\\nreject&&reject`A tagRecord must be frozen: ${tagRecord}`)&&(\\n!isArray(tagRecord)||\\nreject&&reject`An array cannot be a tagRecord: ${tagRecord}`)&&\\ncheckNormalProperty(tagRecord,PASS_STYLE,false,check)&&\\ncheckPassStyle(tagRecord,passStyle,check)&&\\ncheckNormalProperty(tagRecord,Symbol.toStringTag,false,check)&&(\\ntypeof getTag(tagRecord)==='string'||\\nreject&&\\nreject`A [Symbol.toStringTag]-named property must be a string: ${tagRecord}`)&&\\ncheckProto(tagRecord,getPrototypeOf(tagRecord),check));};\\n\\n\\nreturn harden(checkTagRecord);};\\n\\n\\nconst checkTagRecord=makeCheckTagRecord(\\n(val,proto,check)=>\\nproto===objectPrototype||\\n!!check&&\\ncheck(false,index.redacted`A tagRecord must inherit from Object.prototype: ${val}`));\\n\\nharden(checkTagRecord);\\n\\nconst checkFunctionTagRecord=makeCheckTagRecord(\\n(val,proto,check)=>\\nproto===functionPrototype||\\nproto!==null&&getPrototypeOf(proto)===functionPrototype||\\n!!check&&\\ncheck(\\nfalse,\\nindex.redacted`For functions, a tagRecord must inherit from Function.prototype: ${val}`));\\n\\n\\nharden(checkFunctionTagRecord);exports.PASS_STYLE=PASS_STYLE;exports.assertChecker=assertChecker;exports.canBeMethod=canBeMethod;exports.checkFunctionTagRecord=checkFunctionTagRecord;exports.checkNormalProperty=checkNormalProperty;exports.checkPassStyle=checkPassStyle;exports.checkTagRecord=checkTagRecord;exports.getTag=getTag;exports.hasOwnPropertyOf=hasOwnPropertyOf;exports.isObject=isObject;exports.isTypedArray=isTypedArray;\",\n \"node_modules/@endo/pass-style/src/passStyleOf.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../promise-kit/index.js');var index=require('../../errors/index.js');var passStyleHelpers=require('./passStyle-helpers.js');var copyArray=require('./copyArray.js');var copyRecord=require('./copyRecord.js');var tagged=require('./tagged.js');var error=require('./error.js');var remotable=require('./remotable.js');var symbol=require('./symbol.js');var safePromise=require('./safe-promise.js');var string=require('./string.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nisPromise=require('../../promise-kit/src/is-promise.js');/* global globalThis */ /** @import {PassStyleHelper} from './internal-types.js' */ /** @import {CopyArray, CopyRecord, CopyTagged, Passable} from './types.js' */ /** @import {PassStyle} from './types.js' */ /** @import {PassStyleOf} from './types.js' */ /** @import {PrimitiveStyle} from './types.js' */ /** @typedef {Exclude<PassStyle, PrimitiveStyle | \\\"promise\\\">} HelperPassStyle */\\n\\nconst{ownKeys}=Reflect;\\nconst{isFrozen,getOwnPropertyDescriptors,values}=Object;\\n\\n/**\\n * @param {PassStyleHelper[]} passStyleHelpers\\n * @returns {Record<HelperPassStyle, PassStyleHelper> }\\n */\\n\\nconst makeHelperTable=(passStyleHelpers)=>{\\n/** @type {Record<HelperPassStyle, any> & {__proto__: null}} */\\nconst HelperTable={\\n__proto__:null,\\ncopyArray:undefined,\\ncopyRecord:undefined,\\ntagged:undefined,\\nerror:undefined,\\nremotable:undefined};\\n\\nfor(const helper of passStyleHelpers){\\nconst{styleName}=helper;\\nstyleName in HelperTable||index.throwRedacted`Unrecognized helper: ${index.quote(styleName)}`;\\nHelperTable[styleName]===undefined||\\nindex.throwRedacted`conflicting helpers for ${index.quote(styleName)}`;\\nHelperTable[styleName]=helper;}\\n\\nfor(const styleName of ownKeys(HelperTable)){\\nHelperTable[styleName]!==undefined||\\nindex.throwRedacted`missing helper for ${index.quote(styleName)}`;}\\n\\n\\nreturn harden(HelperTable);};\\n\\n\\n/**\\n * @param {PassStyleHelper[]} passStyleHelpers The passStyleHelpers to register,\\n * in priority order.\\n * NOTE These must all be \\\"trusted\\\",\\n * complete, and non-colliding. `makePassStyleOf` may *assume* that each helper\\n * does what it is supposed to do. `makePassStyleOf` is not trying to defend\\n * itself against malicious helpers, though it does defend against some\\n * accidents.\\n * @returns {PassStyleOf}\\n */\\nconst makePassStyleOf=(passStyleHelpers$1)=>{\\nconst HelperTable=makeHelperTable(passStyleHelpers$1);\\nconst remotableHelper=HelperTable.remotable;\\n\\n/**\\n * Purely for performance. However it is mutable static state, and\\n * it does have some observability on proxies. TODO need to assess\\n * whether this creates a static communications channel.\\n *\\n * passStyleOf does a full recursive walk of pass-by-copy\\n * structures, in order to validate that they are acyclic. In addition\\n * it is used by other algorithms to recursively walk these pass-by-copy\\n * structures, so without this cache, these algorithms could be\\n * O(N**2) or worse.\\n *\\n * @type {WeakMap<WeakKey, PassStyle>}\\n */\\nconst passStyleMemo=new WeakMap();\\n\\n/**\\n * @type {PassStyleOf}\\n */\\n/* @ts-expect-error cast*/\\nconst passStyleOf=(passable)=>{\\n/* Even when a WeakSet is correct, when the set has a shorter lifetime*/\\n/* than its keys, we prefer a Set due to expected implementation*/\\n/* tradeoffs.*/\\nconst inProgress=new Set();\\n\\nconst passStyleOfRecur=(inner)=>{\\nconst innerIsObject=passStyleHelpers.isObject(inner);\\nif(innerIsObject){\\nconst innerStyle=passStyleMemo.get(inner);\\nif(innerStyle){\\nreturn innerStyle;}\\n\\n!inProgress.has(inner)||\\nindex.throwRedacted`Pass-by-copy data cannot be cyclic ${inner}`;\\ninProgress.add(inner);}\\n\\n/* eslint-disable-next-line no-use-before-define*/\\nconst passStyle=passStyleOfInternal(inner);\\nif(innerIsObject){\\npassStyleMemo.set(inner,passStyle);\\ninProgress.delete(inner);}\\n\\nreturn passStyle;};\\n\\n\\nconst passStyleOfInternal=(inner)=>{\\nconst typestr=typeof inner;\\nswitch(typestr){\\ncase'undefined':\\ncase'boolean':\\ncase'number':\\ncase'bigint':{\\nreturn typestr;}\\n\\ncase'string':{\\nstring.assertPassableString(inner);\\nreturn'string';}\\n\\ncase'symbol':{\\nsymbol.assertPassableSymbol(inner);\\nreturn'symbol';}\\n\\ncase'object':{\\nif(inner===null){\\nreturn'null';}\\n\\nif(!isFrozen(inner)){\\nassert.fail(\\n/* TypedArrays get special treatment in harden()*/\\n/* and a corresponding special error message here.*/\\npassStyleHelpers.isTypedArray(inner)?\\nindex.redacted`Cannot pass mutable typed arrays like ${inner}.`:\\nindex.redacted`Cannot pass non-frozen objects like ${inner}. Use harden()`);}\\n\\n\\nif(isPromise.isPromise(inner)){\\nsafePromise.assertSafePromise(inner);\\nreturn'promise';}\\n\\ntypeof inner.then!=='function'||\\nindex.throwRedacted`Cannot pass non-promise thenables`;\\nconst passStyleTag=inner[passStyleHelpers.PASS_STYLE];\\nif(passStyleTag!==undefined){\\nassert.typeof(passStyleTag,'string');\\nconst helper=HelperTable[passStyleTag];\\nhelper!==undefined||\\nindex.throwRedacted`Unrecognized PassStyle: ${index.quote(passStyleTag)}`;\\nhelper.assertValid(inner,passStyleOfRecur);\\nreturn(/** @type {PassStyle} */passStyleTag);}\\n\\nfor(const helper of passStyleHelpers$1){\\nif(helper.canBeValid(inner)){\\nhelper.assertValid(inner,passStyleOfRecur);\\nreturn helper.styleName;}}\\n\\n\\nremotableHelper.assertValid(inner,passStyleOfRecur);\\nreturn'remotable';}\\n\\ncase'function':{\\nisFrozen(inner)||\\nindex.throwRedacted`Cannot pass non-frozen objects like ${inner}. Use harden()`;\\ntypeof inner.then!=='function'||\\nindex.throwRedacted`Cannot pass non-promise thenables`;\\nremotableHelper.assertValid(inner,passStyleOfRecur);\\nreturn'remotable';}\\n\\ndefault:{\\nthrow assert.fail(index.redacted`Unrecognized typeof ${index.quote(typestr)}`,TypeError);}}};\\n\\n\\n\\n\\nreturn passStyleOfRecur(passable);};\\n\\nreturn harden(passStyleOf);};\\n\\n\\nconst PassStyleOfEndowmentSymbol=Symbol.for('@endo passStyleOf');\\n\\n/**\\n * If there is already a PassStyleOfEndowmentSymbol property on the global,\\n * then presumably it was endowed for us by liveslots with a `passStyleOf`\\n * function, so we should use and export that one instead.\\n * Other software may have left it for us here,\\n * but it would require write access to our global, or the ability to\\n * provide endowments to our global, both of which seems adequate as a test of\\n * whether it is authorized to serve the same role as liveslots.\\n *\\n * NOTE HAZARD: This use by liveslots does rely on `passStyleOf` being\\n * deterministic. If it is not, then in a liveslot-like virtualized\\n * environment, it can be used to detect GC.\\n *\\n * @type {PassStyleOf}\\n */\\nconst passStyleOf=\\nglobalThis&&globalThis[PassStyleOfEndowmentSymbol]||\\nmakePassStyleOf([\\ncopyArray.CopyArrayHelper,\\ncopyRecord.CopyRecordHelper,\\ntagged.TaggedHelper,\\nerror.ErrorHelper,\\nremotable.RemotableHelper]);\\n\\n\\nconst assertPassable=(val)=>{\\npassStyleOf(val);/* throws if val is not a passable*/};\\n\\nharden(assertPassable);\\n\\n/**\\n * Is `specimen` Passable? This returns true iff `passStyleOf(specimen)`\\n * returns a string. This returns `false` iff `passStyleOf(specimen)` throws.\\n * Under no normal circumstance should `isPassable(specimen)` throw.\\n *\\n * TODO Deprecate and ultimately delete @agoric/base-zone's `isPassable' in\\n * favor of this one.\\n * See https://github.com/endojs/endo/issues/2096\\n *\\n * TODO implement an isPassable that does not rely on try/catch.\\n * This implementation is just a standin until then.\\n * See https://github.com/endojs/endo/issues/2096\\n *\\n * @param {any} specimen\\n * @returns {specimen is Passable}\\n */\\nconst isPassable=(specimen)=>{\\ntry{\\n/* In fact, it never returns undefined. It either returns a*/\\n/* string or throws.*/\\nreturn passStyleOf(specimen)!==undefined;}\\ncatch(_){\\nreturn false;}};\\n\\n\\nharden(isPassable);\\n\\n/**\\n * @param {string} name\\n * @param {PropertyDescriptor} desc\\n * @returns {boolean}\\n */\\nconst isPassableErrorPropertyDesc=(name,desc)=>\\nerror.checkRecursivelyPassableErrorPropertyDesc(name,desc,passStyleOf);\\n\\n/**\\n * After hardening, if `err` is a passable error, return it.\\n *\\n * Otherwise, return a new passable error that propagates the diagnostic\\n * info of the original, and is linked to the original as a note.\\n *\\n * TODO Adopt a more flexible notion of passable error, in which\\n * a passable error can contain other own data properties with\\n * throwable values.\\n *\\n * @param {Error} err\\n * @returns {Error}\\n */\\nconst toPassableError=(err)=>{\\nharden(err);\\nif(error.checkRecursivelyPassableError(err,passStyleOf)){\\nreturn err;}\\n\\nconst{name,message}=err;\\nconst{cause:causeDesc,errors:errorsDesc}=\\ngetOwnPropertyDescriptors(err);\\nlet cause;\\nlet errors;\\nif(causeDesc&&isPassableErrorPropertyDesc('cause',causeDesc)){\\ncause=causeDesc.value;}\\n\\nif(errorsDesc&&isPassableErrorPropertyDesc('errors',errorsDesc)){\\nerrors=errorsDesc.value;}\\n\\n\\nconst errConstructor=error.getErrorConstructor(`${name}`)||Error;\\nconst newError=index.makeError(`${message}`,errConstructor,{\\n/* @ts-ignore Assuming cause is Error | undefined*/\\ncause,\\nerrors});\\n\\n/* Still needed, because `makeError` only does a shallow freeze.*/\\nharden(newError);\\n/* Even the cleaned up error copy, if sent to the console, should*/\\n/* cause hidden diagnostic information of the original error*/\\n/* to be logged.*/\\nindex.note(newError,index.redacted`copied from error ${err}`);\\npassStyleOf(newError)==='error'||\\nindex.throwRedacted`Expected ${newError} to be a passable error`;\\nreturn newError;};\\n\\nharden(toPassableError);\\n\\n/**\\n * After hardening, if `specimen` is throwable, return it.\\n * A specimen is throwable iff it is Passable and contains no PassableCaps,\\n * i.e., no Remotables or Promises.\\n * IOW, if it contains only copy-data and passable errors.\\n *\\n * Otherwise, if `specimen` is *almost* throwable, for example, it is\\n * an error that can be made throwable by `toPassableError`, then\\n * return `specimen` converted to a throwable.\\n *\\n * Otherwise, throw a diagnostic indicating a failure to coerce.\\n *\\n * This is in support of the exo boundary throwing only throwables, to ease\\n * security review.\\n *\\n * TODO Adopt a more flexitble notion of throwable, in which\\n * data containers containing non-passable errors can themselves be coerced\\n * to throwable by coercing to a similar containers containing\\n * the results of coercing those errors to passable errors.\\n *\\n * @param {unknown} specimen\\n * @returns {Passable<never, Error>}\\n */\\nconst toThrowable=(specimen)=>{\\nharden(specimen);\\nif(error.isErrorLike(specimen)){\\nreturn toPassableError(/** @type {Error} */specimen);}\\n\\n/* Note that this step will fail if `specimen` would be a passable container*/\\n/* except that it contains non-passable errors that could be converted.*/\\n/* This will need to be fixed to do the TODO above.*/\\nconst passStyle=passStyleOf(specimen);\\nif(passStyleHelpers.isObject(specimen)){\\nswitch(passStyle){\\ncase'copyArray':{\\nconst elements=/** @type {CopyArray} */specimen;\\nfor(const element of elements){\\nelement===toThrowable(element)||\\nindex.throwRedacted`nested toThrowable coercion not yet supported ${element}`;}\\n\\nbreak;}\\n\\ncase'copyRecord':{\\nconst rec=/** @type {CopyRecord} */specimen;\\nfor(const val of values(rec)){\\nval===toThrowable(val)||\\nindex.throwRedacted`nested toThrowable coercion not yet supported ${val}`;}\\n\\nbreak;}\\n\\ncase'tagged':{\\nconst tg=/** @type {CopyTagged} */specimen;\\nconst{payload}=tg;\\npayload===toThrowable(payload)||\\nindex.throwRedacted`nested toThrowable coercion not yet supported ${payload}`;\\nbreak;}\\n\\ncase'error':{\\nconst er=/** @type {Error} */specimen;\\ner===toThrowable(er)||\\nindex.throwRedacted`nested toThrowable coercion not yet supported ${er}`;\\nbreak;}\\n\\ndefault:{\\nthrow index.throwRedacted`A ${index.quote(passStyle)} is not throwable: ${specimen}`;}}}\\n\\n\\n\\nreturn(/** @type {Passable<never,never>} */specimen);};\\n\\nharden(toThrowable);exports.PassStyleOfEndowmentSymbol=PassStyleOfEndowmentSymbol;exports.assertPassable=assertPassable;exports.isPassable=isPassable;exports.passStyleOf=passStyleOf;exports.toPassableError=toPassableError;exports.toThrowable=toThrowable;\",\n \"node_modules/@endo/pass-style/src/remotable.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var index=require('../../errors/index.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\npassStyleHelpers=require('./passStyle-helpers.js');/*/ <reference types=\\\"ses\\\"/>*/ /**\\n * @import {Checker} from './types.js'\\n * @import {InterfaceSpec, PassStyled} from './types.js'\\n * @import {PassStyleHelper} from './internal-types.js'\\n * @import {RemotableObject as Remotable} from './types.js'\\n */\\n\\nconst{ownKeys}=Reflect;\\nconst{isArray}=Array;\\nconst{\\ngetPrototypeOf,\\nisFrozen,\\nprototype:objectPrototype,\\ngetOwnPropertyDescriptors}=\\nObject;\\n\\n/**\\n * @param {InterfaceSpec} iface\\n * @param {Checker} [check]\\n */\\nconst checkIface=(iface,check)=>{\\nconst reject=!!check&&((T,...subs)=>check(false,index.redacted(T,...subs)));\\nreturn(\\n/* TODO other possible ifaces, once we have third party veracity*/\\n(typeof iface==='string'||\\nreject&&\\nreject`For now, interface ${iface} must be a string; unimplemented`)&&(\\niface==='Remotable'||\\niface.startsWith('Alleged: ')||\\niface.startsWith('DebugName: ')||\\nreject&&\\nreject`For now, iface ${index.quote(\\niface)\\n} must be \\\"Remotable\\\" or begin with \\\"Alleged: \\\" or \\\"DebugName: \\\"; unimplemented`));};\\n\\n\\n\\n/**\\n * An `iface` must be pure. Right now it must be a string, which is pure.\\n * Later we expect to include some other values that qualify as `PureData`,\\n * which is a pass-by-copy superstructure ending only in primitives or\\n * empty pass-by-copy composites. No remotables, promises, or errors.\\n * We *assume* for now that the pass-by-copy superstructure contains no\\n * proxies.\\n *\\n * @param {InterfaceSpec} iface\\n */\\nconst assertIface=(iface)=>checkIface(iface,passStyleHelpers.assertChecker);\\nharden(assertIface);\\n\\n/**\\n * @param {object | Function} original\\n * @param {Checker} [check]\\n * @returns {boolean}\\n */\\nconst checkRemotableProtoOf=(original,check)=>{\\nconst reject=!!check&&((T,...subs)=>check(false,index.redacted(T,...subs)));\\npassStyleHelpers.isObject(original)||\\nindex.throwRedacted`Remotables must be objects or functions: ${original}`;\\n\\n/* A valid remotable object must inherit from a \\\"tag record\\\" -- a*/\\n/* plain-object prototype consisting of only*/\\n/* a `PASS_STYLE` property with value \\\"remotable\\\" and a suitable `Symbol.toStringTag`*/\\n/* property. The remotable could inherit directly from such a tag record, or*/\\n/* it could inherit from another valid remotable, that therefore itself*/\\n/* inherits directly or indirectly from such a tag record.*/\\n/**/\\n/* TODO: It would be nice to typedef this shape, but we can't declare a type*/\\n/* with PASS_STYLE from JSDoc.*/\\n/**/\\n/* @type {{ [PASS_STYLE]: string,*/\\n/* [Symbol.toStringTag]: string,*/\\n/* }}*/\\n/**/\\nconst proto=getPrototypeOf(original);\\nif(\\nproto===objectPrototype||\\nproto===null||\\nproto===Function.prototype)\\n{\\nreturn(\\nreject&&reject`Remotables must be explicitly declared: ${index.quote(original)}`);}\\n\\n\\n\\nif(typeof original==='object'){\\nconst protoProto=getPrototypeOf(proto);\\nif(protoProto!==objectPrototype&&protoProto!==null){\\n/* eslint-disable-next-line no-use-before-define*/\\nreturn checkRemotable(proto,check);}\\n\\nif(!passStyleHelpers.checkTagRecord(proto,'remotable',check)){\\nreturn false;}}else\\n\\nif(typeof original==='function'){\\nif(!passStyleHelpers.checkFunctionTagRecord(proto,'remotable',check)){\\nreturn false;}}\\n\\n\\n\\n/* Typecasts needed due to https://github.com/microsoft/TypeScript/issues/1863*/\\nconst passStyleKey=/** @type {unknown} */passStyleHelpers.PASS_STYLE;\\nconst tagKey=/** @type {unknown} */Symbol.toStringTag;\\nconst{\\n/* checkTagRecord already verified PASS_STYLE and Symbol.toStringTag own data properties.*/\\n[/** @type {string} */passStyleKey]:_passStyleDesc,\\n[/** @type {string} */tagKey]:{value:iface},\\n...restDescs}=\\ngetOwnPropertyDescriptors(proto);\\n\\nreturn(\\n(ownKeys(restDescs).length===0||\\nreject&&\\nreject`Unexpected properties on Remotable Proto ${ownKeys(\\nrestDescs)\\n}`)&&\\ncheckIface(iface,check));};\\n\\n\\n\\n/**\\n * Keep a weak set of confirmed remotables for marshal performance\\n * (without which we would incur a redundant verification in\\n * getInterfaceOf).\\n * We don't remember rejections because they are possible to correct\\n * with e.g. `harden`.\\n *\\n * @type {WeakSet<Remotable>}\\n */\\nconst confirmedRemotables=new WeakSet();\\n\\n/**\\n * @param {any} val\\n * @param {Checker} [check]\\n * @returns {val is Remotable}\\n */\\nconst checkRemotable=(val,check)=>{\\nif(confirmedRemotables.has(val)){\\nreturn true;}\\n\\nconst reject=!!check&&((T,...subs)=>check(false,index.redacted(T,...subs)));\\nif(!isFrozen(val)){\\nreturn reject&&reject`cannot serialize non-frozen objects like ${val}`;}\\n\\n/* eslint-disable-next-line no-use-before-define*/\\nif(!RemotableHelper.canBeValid(val,check)){\\nreturn false;}\\n\\nconst result=checkRemotableProtoOf(val,check);\\nif(result){\\nconfirmedRemotables.add(val);}\\n\\nreturn result;};\\n\\n\\n/**\\n * Simple semantics, just tell what interface spec a Remotable has,\\n * or undefined if not deemed to be a Remotable.\\n *\\n * @type {{\\n * <T extends string>(val: PassStyled<any, T>): T;\\n * (val: any): InterfaceSpec | undefined;\\n * }}\\n */\\nconst getInterfaceOf=(val)=>{\\nif(\\n!passStyleHelpers.isObject(val)||\\nval[passStyleHelpers.PASS_STYLE]!=='remotable'||\\n!checkRemotable(val))\\n{\\n/* @ts-expect-error narrowed*/\\nreturn undefined;}\\n\\n/* @ts-expect-error narrowed*/\\nreturn passStyleHelpers.getTag(val);};\\n\\nharden(getInterfaceOf);\\n\\n/**\\n *\\n * @type {PassStyleHelper}\\n */\\nconst RemotableHelper=harden({\\nstyleName:'remotable',\\n\\ncanBeValid:(candidate,check=undefined)=>{\\nconst reject=!!check&&((T,...subs)=>check(false,index.redacted(T,...subs)));\\nconst validType=\\n(passStyleHelpers.isObject(candidate)||\\nreject&&\\nreject`cannot serialize non-objects as Remotable ${candidate}`)&&(\\n!isArray(candidate)||\\nreject&&reject`cannot serialize arrays as Remotable ${candidate}`);\\nif(!validType){\\nreturn false;}\\n\\n\\nconst descs=getOwnPropertyDescriptors(candidate);\\nif(typeof candidate==='object'){\\n/* Every own property (regardless of enumerability)*/\\n/* must have a function value.*/\\nreturn ownKeys(descs).every((key)=>{\\nreturn(\\n/* Typecast needed due to https://github.com/microsoft/TypeScript/issues/1863*/\\n(passStyleHelpers.hasOwnPropertyOf(descs[/** @type {string} */key],'value')||\\nreject&&\\nreject`cannot serialize Remotables with accessors like ${index.quote(\\nString(key))\\n} in ${candidate}`)&&(\\nkey===Symbol.toStringTag&&checkIface(candidate[key],check)||\\n(passStyleHelpers.canBeMethod(candidate[key])||\\nreject&&\\nreject`cannot serialize Remotables with non-methods like ${index.quote(\\nString(key))\\n} in ${candidate}`)&&(\\nkey!==passStyleHelpers.PASS_STYLE||\\nreject&&\\nreject`A pass-by-remote cannot shadow ${index.quote(passStyleHelpers.PASS_STYLE)}`)));});}else\\n\\n\\nif(typeof candidate==='function'){\\n/* Far functions cannot be methods, and cannot have methods.*/\\n/* They must have exactly expected `.name` and `.length` properties*/\\nconst{\\nname:nameDesc,\\nlength:lengthDesc,\\n/* @ts-ignore TS doesn't like symbols as computed indexes??*/\\n[Symbol.toStringTag]:toStringTagDesc,\\n...restDescs}=\\ndescs;\\nconst restKeys=ownKeys(restDescs);\\nreturn(\\n(nameDesc&&typeof nameDesc.value==='string'||\\nreject&&\\nreject`Far function name must be a string, in ${candidate}`)&&(\\nlengthDesc&&typeof lengthDesc.value==='number'||\\nreject&&\\nreject`Far function length must be a number, in ${candidate}`)&&(\\ntoStringTagDesc===undefined||\\n(typeof toStringTagDesc.value==='string'||\\nreject&&\\nreject`Far function @@toStringTag must be a string, in ${candidate}`)&&\\ncheckIface(toStringTagDesc.value,check))&&(\\nrestKeys.length===0||\\nreject&&\\nreject`Far functions unexpected properties besides .name and .length ${restKeys}`));}\\n\\n\\nreturn reject&&reject`unrecognized typeof ${candidate}`;},\\n\\n\\nassertValid:(candidate)=>checkRemotable(candidate,passStyleHelpers.assertChecker),\\n\\nevery:(_passable,_fn)=>true});exports.RemotableHelper=RemotableHelper;exports.assertIface=assertIface;exports.getInterfaceOf=getInterfaceOf;\",\n \"node_modules/@endo/pass-style/src/safe-promise.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../promise-kit/index.js');var index=require('../../errors/index.js');var passStyleHelpers=require('./passStyle-helpers.js');var\\n\\n\\n\\n\\n\\nisPromise=require('../../promise-kit/src/is-promise.js');/*/ <reference types=\\\"ses\\\"/>*/ /** @import {Checker} from './types.js' */\\n\\nconst{isFrozen,getPrototypeOf,getOwnPropertyDescriptor}=Object;\\nconst{ownKeys}=Reflect;\\nconst{toStringTag}=Symbol;\\n\\n/**\\n * @param {Promise} pr The value to examine\\n * @param {Checker} check\\n * @returns {pr is Promise} Whether it is a safe promise\\n */\\nconst checkPromiseOwnKeys=(pr,check)=>{\\nconst reject=(T,...subs)=>check(false,index.redacted(T,...subs));\\nconst keys=ownKeys(pr);\\n\\nif(keys.length===0){\\nreturn true;}\\n\\n\\n/**\\n * This excludes those symbol-named own properties that are also found on\\n * `Promise.prototype`, so that overrides of these properties can be\\n * explicitly tolerated if they pass the `checkSafeOwnKey` check below.\\n * In particular, we wish to tolerate\\n * * An overriding `toStringTag` non-enumerable data property\\n * with a string value.\\n * * Those own properties that might be added by Node's async_hooks.\\n */\\nconst unknownKeys=keys.filter(\\n(key)=>typeof key!=='symbol'||!passStyleHelpers.hasOwnPropertyOf(Promise.prototype,key));\\n\\n\\nif(unknownKeys.length!==0){\\nreturn reject`${pr} - Must not have any own properties: ${index.quote(unknownKeys)}`;}\\n\\n\\n/**\\n * Explicitly tolerate a `toStringTag` symbol-named non-enumerable\\n * data property whose value is a string. Otherwise, tolerate those\\n * symbol-named properties that might be added by NodeJS's async_hooks,\\n * if they obey the expected safety properties.\\n *\\n * At the time of this writing, Node's async_hooks contains the\\n * following code, which we can safely tolerate\\n *\\n * ```js\\n * function destroyTracking(promise, parent) {\\n * trackPromise(promise, parent);\\n * const asyncId = promise[async_id_symbol];\\n * const destroyed = { destroyed: false };\\n * promise[destroyedSymbol] = destroyed;\\n * registerDestroyHook(promise, asyncId, destroyed);\\n * }\\n * ```\\n *\\n * @param {string|symbol} key\\n */\\nconst checkSafeOwnKey=(key)=>{\\nif(key===toStringTag){\\n/* TODO should we also enforce anything on the contents of the string,*/\\n/* such as that it must start with `'Promise'`?*/\\nconst tagDesc=getOwnPropertyDescriptor(pr,toStringTag);\\nassert(tagDesc!==undefined);\\nreturn(\\n(passStyleHelpers.hasOwnPropertyOf(tagDesc,'value')||\\nreject`Own @@toStringTag must be a data property, not an accessor: ${index.quote(\\ntagDesc)\\n}`)&&(\\ntypeof tagDesc.value==='string'||\\nreject`Own @@toStringTag value must be a string: ${index.quote(\\ntagDesc.value)\\n}`)&&(\\n!tagDesc.enumerable||\\nreject`Own @@toStringTag must not be enumerable: ${index.quote(tagDesc)}`));}\\n\\n\\nconst val=pr[key];\\nif(val===undefined||typeof val==='number'){\\nreturn true;}\\n\\nif(\\ntypeof val==='object'&&\\nval!==null&&\\nisFrozen(val)&&\\ngetPrototypeOf(val)===Object.prototype)\\n{\\nconst subKeys=ownKeys(val);\\nif(subKeys.length===0){\\nreturn true;}\\n\\n\\nif(\\nsubKeys.length===1&&\\nsubKeys[0]==='destroyed'&&\\nval.destroyed===false)\\n{\\nreturn true;}}\\n\\n\\nreturn reject`Unexpected Node async_hooks additions to promise: ${pr}.${index.quote(\\nString(key))\\n} is ${val}`;};\\n\\n\\nreturn keys.every(checkSafeOwnKey);};\\n\\n\\n/**\\n * Under Hardened JS a promise is \\\"safe\\\" if its `then` method can be called\\n * synchronously without giving the promise an opportunity for a\\n * reentrancy attack during that call.\\n *\\n * https://github.com/Agoric/agoric-sdk/issues/9\\n * raises the issue of testing that a specimen is a safe promise\\n * such that the test also does not give the specimen a\\n * reentrancy opportunity. That is well beyond the ambition here.\\n * TODO Though if we figure out a nice solution, it might be good to\\n * use it here as well.\\n *\\n * @param {unknown} pr The value to examine\\n * @param {Checker} check\\n * @returns {pr is Promise} Whether it is a safe promise\\n */\\nconst checkSafePromise=(pr,check)=>{\\nconst reject=(T,...subs)=>check(false,index.redacted(T,...subs));\\nreturn(\\n(isFrozen(pr)||reject`${pr} - Must be frozen`)&&(\\nisPromise.isPromise(pr)||reject`${pr} - Must be a promise`)&&(\\ngetPrototypeOf(pr)===Promise.prototype||\\nreject`${pr} - Must inherit from Promise.prototype: ${index.quote(\\ngetPrototypeOf(pr))\\n}`)&&\\ncheckPromiseOwnKeys(/** @type {Promise} */pr,check));};\\n\\n\\nharden(checkSafePromise);\\n\\n/**\\n * Determine if the argument is a Promise.\\n *\\n * @param {unknown} pr The value to examine\\n * @returns {pr is Promise} Whether it is a promise\\n */\\nconst isSafePromise=(pr)=>checkSafePromise(pr,(x)=>x);\\nharden(isSafePromise);\\n\\nconst assertSafePromise=(pr)=>checkSafePromise(pr,passStyleHelpers.assertChecker);exports.assertSafePromise=assertSafePromise;exports.isSafePromise=isSafePromise;\",\n \"node_modules/@endo/pass-style/src/string.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../env-options/index.js');var index=require('../../errors/index.js');var\\n\\n\\n\\nenvOptions=require('../../env-options/src/env-options.js');/* @ts-expect-error TS builtin `String` type does not yet*/ /* know about`isWellFormed`*/\\nconst hasWellFormedStringMethod=!!String.prototype.isWellFormed;\\n\\n/**\\n * Is the argument a well-formed string?\\n *\\n * Unfortunately, the\\n * [standard built-in `String.prototype.isWellFormed`](https://github.com/tc39/proposal-is-usv-string)\\n * does a ToString on its input, causing it to judge non-strings to be\\n * well-formed strings if they coerce to a well-formed strings. This\\n * recapitulates the mistake in having the global `isNaN` coerce its inputs,\\n * causing it to judge non-string to be NaN if they coerce to NaN.\\n *\\n * This `isWellFormedString` function only judges well-formed strings to be\\n * well-formed strings. For all non-strings it returns false.\\n *\\n * @param {unknown} str\\n * @returns {str is string}\\n */\\nconst isWellFormedString=hasWellFormedStringMethod?\\n/* @ts-expect-error TS does not yet know about `isWellFormed`*/\\n(str)=>typeof str==='string'&&str.isWellFormed():\\n(str)=>{\\nif(typeof str!=='string'){\\nreturn false;}\\n\\nfor(const ch of str){\\n/* The string iterator iterates by Unicode code point, not*/\\n/* UTF16 code unit. But if it encounters an unpaired surrogate,*/\\n/* it will produce it.*/\\nconst cp=/** @type {number} */ch.codePointAt(0);\\nif(cp>=0xd800&&cp<=0xdfff){\\n/* All surrogates are in this range. The string iterator only*/\\n/* produces a character in this range for unpaired surrogates,*/\\n/* which only happens if the string is not well-formed.*/\\nreturn false;}}\\n\\n\\nreturn true;};\\n\\nharden(isWellFormedString);\\n\\n/**\\n * Returns normally when `isWellFormedString(str)` would return true.\\n * Throws a diagnostic error when `isWellFormedString(str)` would return false.\\n *\\n * @param {unknown} str\\n * @returns {asserts str is string}\\n */\\nconst assertWellFormedString=(str)=>{\\nisWellFormedString(str)||index.throwRedacted`Expected well-formed unicode string: ${str}`;};\\n\\nharden(assertWellFormedString);\\n\\nconst ONLY_WELL_FORMED_STRINGS_PASSABLE=\\nenvOptions.getEnvironmentOption('ONLY_WELL_FORMED_STRINGS_PASSABLE','disabled',[\\n'enabled'])===\\n'enabled';\\n\\n/**\\n * For now,\\n * if `ONLY_WELL_FORMED_STRINGS_PASSABLE` environment option is `'enabled'`,\\n * then `assertPassableString` is the same as `assertWellFormedString`.\\n * Otherwise `assertPassableString` just asserts that `str` is a string.\\n *\\n * Currently, `ONLY_WELL_FORMED_STRINGS_PASSABLE` defaults to `'disabled'`\\n * because we do not yet know the performance impact. Later, if we decide we\\n * can afford it, we'll first change the default to `'enabled'` and ultimately\\n * remove the switch altogether. Be prepared for these changes.\\n *\\n * TODO once the switch is removed, simplify `assertPassableString` to\\n * simply be `assertWellFormedString`.\\n *\\n * TODO update https://github.com/Agoric/agoric-sdk/blob/master/docs/env.md\\n * which is unfortunately in the wrong repo to be updated in the same change.\\n *\\n * @param { unknown } str\\n * @returns {asserts str is string }\\n */\\nconst assertPassableString=(str)=>{\\ntypeof str==='string'||index.throwRedacted`Expected string ${str}`;\\n!ONLY_WELL_FORMED_STRINGS_PASSABLE||assertWellFormedString(str);};\\n\\nharden(assertPassableString);exports.assertPassableString=assertPassableString;exports.assertWellFormedString=assertWellFormedString;exports.isWellFormedString=isWellFormedString;\",\n \"node_modules/@endo/pass-style/src/symbol.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var index=require('../../errors/index.js');\\n\\nconst{ownKeys}=Reflect;\\n\\n/**\\n * The well known symbols are static symbol values on the `Symbol` constructor.\\n */\\nconst wellKnownSymbolNames=new Map(\\nownKeys(Symbol).\\nfilter(\\n(name)=>typeof name==='string'&&typeof Symbol[name]==='symbol').\\n\\nfilter((name)=>{\\n/* @ts-expect-error It doesn't know name cannot be a symbol*/\\n!name.startsWith('@@')||\\nindex.throwRedacted`Did not expect Symbol to have a symbol-valued property name starting with \\\"@@\\\" ${index.quote(\\nname)\\n}`;\\nreturn true;})\\n\\n/* @ts-ignore It doesn't know name cannot be a symbol*/.\\nmap((name)=>[Symbol[name],`@@${name}`]));\\n\\n\\n/**\\n * The passable symbols are the well known symbols (the symbol values\\n * of static properties of the `Symbol` constructor) and the registered\\n * symbols.\\n *\\n * @param {any} sym\\n * @returns {boolean}\\n */\\nconst isPassableSymbol=(sym)=>\\ntypeof sym==='symbol'&&(\\ntypeof Symbol.keyFor(sym)==='string'||wellKnownSymbolNames.has(sym));\\nharden(isPassableSymbol);\\n\\nconst assertPassableSymbol=(sym)=>\\nisPassableSymbol(sym)||\\nindex.throwRedacted`Only registered symbols or well-known symbols are passable: ${index.quote(sym)}`;\\nharden(assertPassableSymbol);\\n\\n/**\\n * If `sym` is a passable symbol, return a string that uniquely identifies this\\n * symbol. If `sym` is a non-passable symbol, return `undefined`.\\n *\\n * The passable symbols are the well known symbols (the symbol values\\n * of static properties of the `Symbol` constructor) and the registered\\n * symbols. Since the registration string of a registered symbol can be any\\n * string, if we simply used that to identify those symbols, there would not\\n * be any remaining strings left over to identify the well-known symbols.\\n * Instead, we reserve strings beginning with `\\\"@@\\\"` for purposes of this\\n * encoding. We identify a well known symbol such as `Symbol.iterator`\\n * by prefixing the property name with `\\\"@@\\\"`, such as `\\\"@@iterator\\\"`.\\n * For registered symbols whose name happens to begin with `\\\"@@\\\"`, such\\n * as `Symbol.for('@@iterator')` or `Symbol.for('@@foo')`, we identify\\n * them by prefixing them with an extra `\\\"@@\\\"`, such as\\n * `\\\"@@@@iterator\\\"` or `\\\"@@@@foo\\\"`. (This is the Hilbert Hotel encoding\\n * technique.)\\n *\\n * @param {symbol} sym\\n * @returns {string=}\\n */\\nconst nameForPassableSymbol=(sym)=>{\\nconst name=Symbol.keyFor(sym);\\nif(name===undefined){\\nreturn wellKnownSymbolNames.get(sym);}\\n\\nif(name.startsWith('@@')){\\nreturn`@@${name}`;}\\n\\nreturn name;};\\n\\nharden(nameForPassableSymbol);\\n\\nconst AtAtPrefixPattern=/^@@(.*)$/;\\nharden(AtAtPrefixPattern);\\n\\n/**\\n * If `name` is a string that could have been produced by\\n * `nameForPassableSymbol`, return the symbol argument it was produced to\\n * represent.\\n *\\n * If `name` does not begin with `\\\"@@\\\"`, then just the corresponding\\n * registered symbol, `Symbol.for(name)`.\\n * If `name` is `\\\"@@\\\"` followed by a well known symbol's property name on\\n * `Symbol` such `\\\"@@iterator\\\", return that well known symbol such as\\n * `Symbol.iterator`\\n * If `name` begins with `\\\"@@@@\\\"` it encodes the registered symbol whose\\n * name begins with `\\\"@@\\\"` instead.\\n * Otherwise, if name begins with `\\\"@@\\\"` it may encode a registered symbol\\n * from a future version of JavaScript, but it is not one we can decode\\n * yet, so throw.\\n *\\n * @param {string} name\\n * @returns {symbol=}\\n */\\nconst passableSymbolForName=(name)=>{\\nif(typeof name!=='string'){\\nreturn undefined;}\\n\\nconst match=AtAtPrefixPattern.exec(name);\\nif(match){\\nconst suffix=match[1];\\nif(suffix.startsWith('@@')){\\nreturn Symbol.for(suffix);}else\\n{\\nconst sym=Symbol[suffix];\\nif(typeof sym==='symbol'){\\nreturn sym;}\\n\\nindex.throwRedacted`Reserved for well known symbol ${index.quote(suffix)}: ${index.quote(name)}`;}}\\n\\n\\nreturn Symbol.for(name);};\\n\\nharden(passableSymbolForName);exports.assertPassableSymbol=assertPassableSymbol;exports.isPassableSymbol=isPassableSymbol;exports.nameForPassableSymbol=nameForPassableSymbol;exports.passableSymbolForName=passableSymbolForName;\",\n \"node_modules/@endo/pass-style/src/tagged.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var index=require('../../errors/index.js');var passStyleHelpers=require('./passStyle-helpers.js');/*/ <reference types=\\\"ses\\\"/>*/\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nconst{ownKeys}=Reflect;\\nconst{getOwnPropertyDescriptors}=Object;\\n\\n/**\\n *\\n * @type {IMPORT('./internal-types.js').PassStyleHelper}\\n */\\nconst TaggedHelper=harden({\\nstyleName:'tagged',\\n\\ncanBeValid:(candidate,check=undefined)=>\\npassStyleHelpers.checkPassStyle(candidate,'tagged',check),\\n\\nassertValid:(candidate,passStyleOfRecur)=>{\\npassStyleHelpers.checkTagRecord(candidate,'tagged',passStyleHelpers.assertChecker);\\n\\n/* Typecasts needed due to https://github.com/microsoft/TypeScript/issues/1863*/\\nconst passStyleKey=/** @type {unknown} */passStyleHelpers.PASS_STYLE;\\nconst tagKey=/** @type {unknown} */Symbol.toStringTag;\\nconst{\\n/* checkTagRecord already verified PASS_STYLE and Symbol.toStringTag own data properties.*/\\n[/** @type {string} */passStyleKey]:_passStyleDesc,\\n[/** @type {string} */tagKey]:_labelDesc,\\npayload:_payloadDesc,/* value checked by recursive walk at the end*/\\n...restDescs}=\\ngetOwnPropertyDescriptors(candidate);\\nownKeys(restDescs).length===0||\\nindex.throwRedacted`Unexpected properties on tagged record ${ownKeys(restDescs)}`;\\n\\npassStyleHelpers.checkNormalProperty(candidate,'payload',true,passStyleHelpers.assertChecker);\\n\\n/* Recursively validate that each member is passable.*/\\npassStyleOfRecur(candidate.payload);}});exports.TaggedHelper=TaggedHelper;\",\n \"node_modules/@endo/pass-style/src/typeGuards.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var index=require('../../errors/index.js');var\\n\\n\\n\\n\\npassStyleOf=require('./passStyleOf.js');/** @import {CopyArray, CopyRecord, Passable, RemotableObject} from './types.js' */ /**\\n * Check whether the argument is a pass-by-copy array, AKA a \\\"copyArray\\\"\\n * in @endo/marshal terms\\n *\\n * @param {any} arr\\n * @returns {arr is CopyArray<any>}\\n */\\nconst isCopyArray=(arr)=>passStyleOf.passStyleOf(arr)==='copyArray';\\nharden(isCopyArray);\\n\\n/**\\n * Check whether the argument is a pass-by-copy record, AKA a\\n * \\\"copyRecord\\\" in @endo/marshal terms\\n *\\n * @param {any} record\\n * @returns {record is CopyRecord<any>}\\n */\\nconst isRecord=(record)=>passStyleOf.passStyleOf(record)==='copyRecord';\\nharden(isRecord);\\n\\n/**\\n * Check whether the argument is a remotable.\\n *\\n * @param {Passable} remotable\\n * @returns {remotable is RemotableObject}\\n */\\nconst isRemotable=(remotable)=>passStyleOf.passStyleOf(remotable)==='remotable';\\nharden(isRemotable);\\n\\n/**\\n * @param {any} array\\n * @param {string=} optNameOfArray\\n * @returns {asserts array is CopyArray<any>}\\n */\\nconst assertCopyArray=(array,optNameOfArray='Alleged array')=>{\\nconst passStyle=passStyleOf.passStyleOf(array);\\npassStyle==='copyArray'||\\nindex.throwRedacted`${index.quote(optNameOfArray)} ${array} must be a pass-by-copy array, not ${index.quote(\\npassStyle)\\n}`;};\\n\\nharden(assertCopyArray);\\n\\n/**\\n * @param {any} record\\n * @param {string=} optNameOfRecord\\n * @returns {asserts record is CopyRecord<any>}\\n */\\nconst assertRecord=(record,optNameOfRecord='Alleged record')=>{\\nconst passStyle=passStyleOf.passStyleOf(record);\\npassStyle==='copyRecord'||\\nindex.throwRedacted`${index.quote(optNameOfRecord)} ${record} must be a pass-by-copy record, not ${index.quote(\\npassStyle)\\n}`;};\\n\\nharden(assertRecord);\\n\\n/**\\n * @param {Passable} remotable\\n * @param {string=} optNameOfRemotable\\n * @returns {asserts remotable is RemotableObject}\\n */\\nconst assertRemotable=(\\nremotable,\\noptNameOfRemotable='Alleged remotable')=>\\n{\\nconst passStyle=passStyleOf.passStyleOf(remotable);\\npassStyle==='remotable'||\\nindex.throwRedacted`${index.quote(optNameOfRemotable)} ${remotable} must be a remotable, not ${index.quote(\\npassStyle)\\n}`;};\\n\\nharden(assertRemotable);exports.assertCopyArray=assertCopyArray;exports.assertRecord=assertRecord;exports.assertRemotable=assertRemotable;exports.isCopyArray=isCopyArray;exports.isRecord=isRecord;exports.isRemotable=isRemotable;\",\n \"node_modules/@endo/pass-style/src/types.js\": \"'use strict';/** @file Empty twin for .d.ts */\",\n \"node_modules/@endo/patterns/index.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var checkKey=require('./src/keys/checkKey.js');var copySet=require('./src/keys/copySet.js');var copyBag=require('./src/keys/copyBag.js');var compareKeys=require('./src/keys/compareKeys.js');var mergeSetOperators=require('./src/keys/merge-set-operators.js');var mergeBagOperators=require('./src/keys/merge-bag-operators.js');var patternMatchers=require('./src/patterns/patternMatchers.js');var getGuardPayloads=require('./src/patterns/getGuardPayloads.js');require('./src/types.js');var listDifference=require('../common/list-difference.js');var objectMap=require('../common/object-map.js');exports.assertCopyBag=checkKey.assertCopyBag;exports.assertCopyMap=checkKey.assertCopyMap;exports.assertCopySet=checkKey.assertCopySet;exports.assertKey=checkKey.assertKey;exports.assertScalarKey=checkKey.assertScalarKey;exports.getCopyBagEntries=checkKey.getCopyBagEntries;exports.getCopyMapEntries=checkKey.getCopyMapEntries;exports.getCopySetKeys=checkKey.getCopySetKeys;exports.isCopyBag=checkKey.isCopyBag;exports.isCopyMap=checkKey.isCopyMap;exports.isCopySet=checkKey.isCopySet;exports.isKey=checkKey.isKey;exports.makeCopyBag=checkKey.makeCopyBag;exports.makeCopyBagFromElements=checkKey.makeCopyBagFromElements;exports.makeCopyMap=checkKey.makeCopyMap;exports.makeCopySet=checkKey.makeCopySet;exports.coerceToElements=copySet.coerceToElements;exports.coerceToBagEntries=copyBag.coerceToBagEntries;exports.bagCompare=compareKeys.bagCompare;exports.compareKeys=compareKeys.compareKeys;exports.keyEQ=compareKeys.keyEQ;exports.keyGT=compareKeys.keyGT;exports.keyGTE=compareKeys.keyGTE;exports.keyLT=compareKeys.keyLT;exports.keyLTE=compareKeys.keyLTE;exports.setCompare=compareKeys.setCompare;exports.elementsCompare=mergeSetOperators.elementsCompare;exports.elementsDisjointSubtract=mergeSetOperators.elementsDisjointSubtract;exports.elementsDisjointUnion=mergeSetOperators.elementsDisjointUnion;exports.elementsIntersection=mergeSetOperators.elementsIntersection;exports.elementsIsDisjoint=mergeSetOperators.elementsIsDisjoint;exports.elementsIsSuperset=mergeSetOperators.elementsIsSuperset;exports.elementsUnion=mergeSetOperators.elementsUnion;exports.setDisjointSubtract=mergeSetOperators.setDisjointSubtract;exports.setDisjointUnion=mergeSetOperators.setDisjointUnion;exports.setIntersection=mergeSetOperators.setIntersection;exports.setIsDisjoint=mergeSetOperators.setIsDisjoint;exports.setIsSuperset=mergeSetOperators.setIsSuperset;exports.setUnion=mergeSetOperators.setUnion;exports.bagDisjointSubtract=mergeBagOperators.bagDisjointSubtract;exports.bagIntersection=mergeBagOperators.bagIntersection;exports.bagIsSuperbag=mergeBagOperators.bagIsSuperbag;exports.bagUnion=mergeBagOperators.bagUnion;exports.M=patternMatchers.M;exports.assertAwaitArgGuard=patternMatchers.assertAwaitArgGuard;exports.assertInterfaceGuard=patternMatchers.assertInterfaceGuard;exports.assertMethodGuard=patternMatchers.assertMethodGuard;exports.assertPattern=patternMatchers.assertPattern;exports.assertRawGuard=patternMatchers.assertRawGuard;exports.getRankCover=patternMatchers.getRankCover;exports.isAwaitArgGuard=patternMatchers.isAwaitArgGuard;exports.isPattern=patternMatchers.isPattern;exports.isRawGuard=patternMatchers.isRawGuard;exports.kindOf=patternMatchers.kindOf;exports.matches=patternMatchers.matches;exports.mustMatch=patternMatchers.mustMatch;exports.getAwaitArgGuardPayload=getGuardPayloads.getAwaitArgGuardPayload;exports.getInterfaceGuardPayload=getGuardPayloads.getInterfaceGuardPayload;exports.getInterfaceMethodKeys=getGuardPayloads.getInterfaceMethodKeys;exports.getMethodGuardPayload=getGuardPayloads.getMethodGuardPayload;exports.listDifference=listDifference.listDifference;exports.objectMap=objectMap.objectMap;\",\n \"node_modules/@endo/patterns/src/keys/checkKey.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../../marshal/index.js');var identChecker=require('../../../common/ident-checker.js');var index=require('../../../errors/index.js');var copySet=require('./copySet.js');var copyBag=require('./copyBag.js');var passStyleHelpers=require('../../../pass-style/src/passStyle-helpers.js');var passStyleOf=require('../../../pass-style/src/passStyleOf.js');var rankOrder=require('../../../marshal/src/rankOrder.js');var makeFar=require('../../../pass-style/src/make-far.js');var makeTagged=require('../../../pass-style/src/makeTagged.js');/*/ <reference types=\\\"ses\\\"/>*/\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nconst{ownKeys}=Reflect;\\n\\n/**\\n * @import {Passable, Primitive} from '@endo/pass-style'\\n * @import {Checker} from '@endo/marshal'\\n * @import {CopyBag, CopyMap, CopySet, Key, ScalarKey} from '../types.js'\\n */\\n\\n/* ////////////////// Primitive and Scalar keys ////////////////////////////////*/\\n\\n/**\\n * @param {Passable} val\\n * @param {Checker} check\\n * @returns {boolean}\\n */\\nconst checkPrimitiveKey=(val,check)=>{\\nif(passStyleHelpers.isObject(val)){\\nreturn(\\ncheck!==identChecker.identChecker&&\\ncheck(false,index.redacted`A ${index.quote(typeof val)} cannot be a primitive: ${val}`));}\\n\\n\\n/* TODO There is not yet a checkPassable, but perhaps there should be.*/\\n/* If that happens, we should call it here instead.*/\\npassStyleOf.assertPassable(val);\\nreturn true;};\\n\\n\\n/**\\n * @param {any} val\\n * @returns {val is Primitive}\\n */\\nconst isPrimitiveKey=(val)=>checkPrimitiveKey(val,identChecker.identChecker);\\nharden(isPrimitiveKey);\\n\\n/**\\n * @param {Passable} val\\n * @returns {asserts val is Primitive}\\n */\\nconst assertPrimitiveKey=(val)=>{\\ncheckPrimitiveKey(val,passStyleHelpers.assertChecker);};\\n\\nharden(assertPrimitiveKey);\\n\\n/**\\n * @param {any} val\\n * @param {Checker} check\\n * @returns {boolean}\\n */\\nconst checkScalarKey=(val,check)=>{\\nif(isPrimitiveKey(val)){\\nreturn true;}\\n\\nconst passStyle=passStyleOf.passStyleOf(val);\\nif(passStyle==='remotable'){\\nreturn true;}\\n\\nreturn check(false,index.redacted`A ${index.quote(passStyle)} cannot be a scalar key: ${val}`);};\\n\\n\\n/**\\n * @param {any} val\\n * @returns {val is ScalarKey}\\n */\\nconst isScalarKey=(val)=>checkScalarKey(val,identChecker.identChecker);\\nharden(isScalarKey);\\n\\n/**\\n * @param {Passable} val\\n * @returns {asserts val is ScalarKey}\\n */\\nconst assertScalarKey=(val)=>{\\ncheckScalarKey(val,passStyleHelpers.assertChecker);};\\n\\nharden(assertScalarKey);\\n\\n/* ////////////////////////////// Keys /////////////////////////////////////////*/\\n\\n/* @ts-expect-error Key does not satisfy WeakKey*/\\n/** @type {WeakSet<Key>} */\\n/* @ts-expect-error Key does not satisfy WeakKey*/\\nconst keyMemo=new WeakSet();\\n\\n/**\\n * @param {unknown} val\\n * @param {Checker} check\\n * @returns {boolean}\\n */\\nconst checkKey=(val,check)=>{\\nif(!passStyleHelpers.isObject(val)){\\n/* TODO There is not yet a checkPassable, but perhaps there should be.*/\\n/* If that happens, we should call it here instead.*/\\npassStyleOf.assertPassable(val);\\nreturn true;}\\n\\n/* @ts-expect-error narrowed*/\\nif(keyMemo.has(val)){\\nreturn true;}\\n\\n/* eslint-disable-next-line no-use-before-define*/\\nconst result=checkKeyInternal(val,check);\\nif(result){\\n/* Don't cache the undefined cases, so that if it is tried again*/\\n/* with `assertChecker` it'll throw a diagnostic again*/\\n/* @ts-expect-error narrowed*/\\nkeyMemo.add(val);}\\n\\n/* Note that we do not memoize a negative judgement, so that if it is tried*/\\n/* again with a checker, it will still produce a useful diagnostic.*/\\nreturn result;};\\n\\nharden(checkKey);\\n\\n/**\\n * @type {{\\n * (val: Passable): val is Key;\\n * (val: any): boolean;\\n * }}\\n */\\nconst isKey=(val)=>checkKey(val,identChecker.identChecker);\\nharden(isKey);\\n\\n/**\\n * @param {Key} val\\n * @returns {asserts val is Key}\\n */\\nconst assertKey=(val)=>{\\ncheckKey(val,passStyleHelpers.assertChecker);};\\n\\nharden(assertKey);\\n\\n/* //////////////////////////// CopySet ////////////////////////////////////////*/\\n\\n/* Moved to here so they can check that the copySet contains only keys*/\\n/* without creating an import cycle.*/\\n\\n/** @type {WeakSet<CopySet>} */\\nconst copySetMemo=new WeakSet();\\n\\n/**\\n * @param {any} s\\n * @param {Checker} check\\n * @returns {boolean}\\n */\\nconst checkCopySet=(s,check)=>{\\nif(copySetMemo.has(s)){\\nreturn true;}\\n\\nconst result=\\n(passStyleOf.passStyleOf(s)==='tagged'&&passStyleHelpers.getTag(s)==='copySet'||\\ncheck(false,index.redacted`Not a copySet: ${s}`))&&\\ncopySet.checkElements(s.payload,check)&&\\ncheckKey(s.payload,check);\\nif(result){\\ncopySetMemo.add(s);}\\n\\nreturn result;};\\n\\nharden(checkCopySet);\\n\\n/**\\n * @param {any} s\\n * @returns {s is CopySet}\\n */\\nconst isCopySet=(s)=>checkCopySet(s,identChecker.identChecker);\\nharden(isCopySet);\\n\\n/**\\n * @callback AssertCopySet\\n * @param {Passable} s\\n * @returns {asserts s is CopySet}\\n */\\n\\n/** @type {AssertCopySet} */\\nconst assertCopySet=(s)=>{\\ncheckCopySet(s,passStyleHelpers.assertChecker);};\\n\\nharden(assertCopySet);\\n\\n/**\\n * @template {Key} K\\n * @param {CopySet<K>} s\\n * @returns {K[]}\\n */\\nconst getCopySetKeys=(s)=>{\\nassertCopySet(s);\\nreturn s.payload;};\\n\\nharden(getCopySetKeys);\\n\\n/**\\n * @template {Key} K\\n * @param {CopySet<K>} s\\n * @param {(key: K, index: number) => boolean} fn\\n * @returns {boolean}\\n */\\nconst everyCopySetKey=(s,fn)=>\\ngetCopySetKeys(s).every((key,index)=>fn(key,index));\\nharden(everyCopySetKey);\\n\\n/**\\n * @template {Key} K\\n * @param {Iterable<K>} elementIter\\n * @returns {CopySet<K>}\\n */\\nconst makeCopySet=(elementIter)=>{\\nconst result=copySet.makeSetOfElements(elementIter);\\nassertCopySet(result);\\nreturn result;};\\n\\nharden(makeCopySet);\\n\\n/* //////////////////////////// CopyBag ////////////////////////////////////////*/\\n\\n/* Moved to here so they can check that the copyBag contains only keys*/\\n/* without creating an import cycle.*/\\n\\n/** @type {WeakSet<CopyBag>} */\\nconst copyBagMemo=new WeakSet();\\n\\n/**\\n * @param {any} b\\n * @param {Checker} check\\n * @returns {boolean}\\n */\\nconst checkCopyBag=(b,check)=>{\\nif(copyBagMemo.has(b)){\\nreturn true;}\\n\\nconst result=\\n(passStyleOf.passStyleOf(b)==='tagged'&&passStyleHelpers.getTag(b)==='copyBag'||\\ncheck(false,index.redacted`Not a copyBag: ${b}`))&&\\ncopyBag.checkBagEntries(b.payload,check)&&\\ncheckKey(b.payload,check);\\nif(result){\\ncopyBagMemo.add(b);}\\n\\nreturn result;};\\n\\nharden(checkCopyBag);\\n\\n/**\\n * @param {any} b\\n * @returns {b is CopyBag}\\n */\\nconst isCopyBag=(b)=>checkCopyBag(b,identChecker.identChecker);\\nharden(isCopyBag);\\n\\n/**\\n * @callback AssertCopyBag\\n * @param {Passable} b\\n * @returns {asserts b is CopyBag}\\n */\\n\\n/** @type {AssertCopyBag} */\\nconst assertCopyBag=(b)=>{\\ncheckCopyBag(b,passStyleHelpers.assertChecker);};\\n\\nharden(assertCopyBag);\\n\\n/**\\n * @template {Key} K\\n * @param {CopyBag<K>} b\\n * @returns {CopyBag<K>['payload']}\\n */\\nconst getCopyBagEntries=(b)=>{\\nassertCopyBag(b);\\nreturn b.payload;};\\n\\nharden(getCopyBagEntries);\\n\\n/**\\n * @template {Key} K\\n * @param {CopyBag<K>} b\\n * @param {(entry: [K, bigint], index: number) => boolean} fn\\n * @returns {boolean}\\n */\\nconst everyCopyBagEntry=(b,fn)=>\\ngetCopyBagEntries(b).every((entry,index)=>fn(entry,index));\\nharden(everyCopyBagEntry);\\n\\n/**\\n * @template {Key} K\\n * @param {Iterable<[K,bigint]>} bagEntryIter\\n * @returns {CopyBag<K>}\\n */\\nconst makeCopyBag=(bagEntryIter)=>{\\nconst result=copyBag.makeBagOfEntries(bagEntryIter);\\nassertCopyBag(result);\\nreturn result;};\\n\\nharden(makeCopyBag);\\n\\n/**\\n * @template {Key} K\\n * @param {Iterable<K>} elementIter\\n * @returns {CopyBag<K>}\\n */\\nconst makeCopyBagFromElements=(elementIter)=>{\\n/* This fullOrder contains history dependent state. It is specific*/\\n/* to this one call and does not survive it.*/\\nconst fullCompare=rankOrder.makeFullOrderComparatorKit().antiComparator;\\nconst sorted=rankOrder.sortByRank(elementIter,fullCompare);\\n/** @type {[K,bigint][]} */\\nconst entries=[];\\nfor(let i=0;i<sorted.length;){\\nconst k=sorted[i];\\nlet j=i+1;\\nwhile(j<sorted.length&&fullCompare(k,sorted[j])===0){\\nj+=1;}\\n\\nentries.push([k,BigInt(j-i)]);\\ni=j;}\\n\\nreturn makeCopyBag(entries);};\\n\\nharden(makeCopyBagFromElements);\\n\\n/* //////////////////////////// CopyMap ////////////////////////////////////////*/\\n\\n/* Moved to here so they can check that the copyMap's keys contains only keys*/\\n/* without creating an import cycle.*/\\n\\n/** @type {WeakSet<CopyMap>} */\\nconst copyMapMemo=new WeakSet();\\n\\n/**\\n * @param {any} m\\n * @param {Checker} check\\n * @returns {boolean}\\n */\\nconst checkCopyMap=(m,check)=>{\\nif(copyMapMemo.has(m)){\\nreturn true;}\\n\\nif(!(passStyleOf.passStyleOf(m)==='tagged'&&passStyleHelpers.getTag(m)==='copyMap')){\\nreturn check(false,index.redacted`Not a copyMap: ${m}`);}\\n\\nconst{payload}=m;\\nif(passStyleOf.passStyleOf(payload)!=='copyRecord'){\\nreturn check(false,index.redacted`A copyMap's payload must be a record: ${m}`);}\\n\\nconst{keys,values,...rest}=payload;\\nconst result=\\n(ownKeys(rest).length===0||\\ncheck(\\nfalse,\\nindex.redacted`A copyMap's payload must only have .keys and .values: ${m}`))&&\\n\\ncopySet.checkElements(keys,check)&&\\ncheckKey(keys,check)&&(\\npassStyleOf.passStyleOf(values)==='copyArray'||\\ncheck(false,index.redacted`A copyMap's .values must be a copyArray: ${m}`))&&(\\nkeys.length===values.length||\\ncheck(\\nfalse,\\nindex.redacted`A copyMap must have the same number of keys and values: ${m}`));\\n\\nif(result){\\ncopyMapMemo.add(m);}\\n\\nreturn result;};\\n\\nharden(checkCopyMap);\\n\\n/**\\n * @param {any} m\\n * @returns {m is CopyMap<Key, Passable>}\\n */\\nconst isCopyMap=(m)=>checkCopyMap(m,identChecker.identChecker);\\nharden(isCopyMap);\\n\\n/**\\n * @param {Passable} m\\n * @returns {asserts m is CopyMap<Key, Passable>}\\n */\\nconst assertCopyMap=(m)=>{\\ncheckCopyMap(m,passStyleHelpers.assertChecker);};\\n\\nharden(assertCopyMap);\\n\\n/**\\n * @template {Key} K\\n * @template {Passable} V\\n * @param {CopyMap<K,V>} m\\n * @returns {K[]}\\n */\\nconst getCopyMapKeys=(m)=>{\\nassertCopyMap(m);\\nreturn m.payload.keys;};\\n\\nharden(getCopyMapKeys);\\n\\n/**\\n * @template {Key} K\\n * @template {Passable} V\\n * @param {CopyMap<K,V>} m\\n * @returns {V[]}\\n */\\nconst getCopyMapValues=(m)=>{\\nassertCopyMap(m);\\nreturn m.payload.values;};\\n\\nharden(getCopyMapValues);\\n\\n/**\\n * Returns an array of a CopyMap's entries in storage order.\\n *\\n * @template {Key} K\\n * @template {Passable} V\\n * @param {CopyMap<K,V>} m\\n * @returns {Array<[K,V]>}\\n */\\nconst getCopyMapEntryArray=(m)=>{\\nassertCopyMap(m);\\nconst{\\npayload:{keys,values}}=\\nm;\\nreturn harden(keys.map((key,i)=>[key,values[i]]));};\\n\\nharden(getCopyMapEntryArray);\\n\\n/**\\n * @template {Key} K\\n * @template {Passable} V\\n * @param {CopyMap<K,V>} m\\n * @returns {Iterable<[K,V]>}\\n */\\nconst getCopyMapEntries=(m)=>{\\nassertCopyMap(m);\\nconst{\\npayload:{keys,values}}=\\nm;\\nconst{length}=/** @type {Array} */keys;\\nreturn makeFar.Far('CopyMap entries iterable',{\\n[Symbol.iterator]:()=>{\\nlet i=0;\\nreturn makeFar.Far('CopyMap entries iterator',{\\nnext:()=>{\\n/** @type {IteratorResult<[K,V],void>} */\\nlet result;\\nif(i<length){\\nresult=harden({done:false,value:[keys[i],values[i]]});\\ni+=1;\\nreturn result;}else\\n{\\nresult=harden({done:true,value:undefined});}\\n\\nreturn result;}});}});};\\n\\n\\n\\n\\n\\nharden(getCopyMapEntries);\\n\\n/**\\n * @template {Key} K\\n * @template {Passable} V\\n * @param {CopyMap<K,V>} m\\n * @param {(key: K, index: number) => boolean} fn\\n * @returns {boolean}\\n */\\nconst everyCopyMapKey=(m,fn)=>\\ngetCopyMapKeys(m).every((key,index)=>fn(key,index));\\nharden(everyCopyMapKey);\\n\\n/**\\n * @template {Key} K\\n * @template {Passable} V\\n * @param {CopyMap<K,V>} m\\n * @param {(value: V, index: number) => boolean} fn\\n * @returns {boolean}\\n */\\nconst everyCopyMapValue=(m,fn)=>\\ngetCopyMapValues(m).every((value,index)=>fn(value,index));\\nharden(everyCopyMapValue);\\n\\n/**\\n * @template {Key} K\\n * @template {Passable} V\\n * @param {CopyMap<K,V>} m\\n * @returns {CopySet<K>}\\n */\\nconst copyMapKeySet=(m)=>\\n/* A copyMap's keys are already in the internal form used by copySets.*/\\nmakeTagged.makeTagged('copySet',m.payload.keys);\\nharden(copyMapKeySet);\\n\\n/**\\n * @template {Key} K\\n * @template {Passable} V\\n * @param {Iterable<[K, V]>} entries\\n * @returns {CopyMap<K,V>}\\n */\\nconst makeCopyMap=(entries)=>{\\n/* This is weird, but reverse rank sorting the entries is a good first step*/\\n/* for getting the rank sorted keys together with the values*/\\n/* organized by those keys. Also, among values associated with*/\\n/* keys in the same equivalence class, those are rank sorted.*/\\n/* TODO This*/\\n/* could solve the copyMap cover issue explained in patternMatchers.js.*/\\n/* But only if we include this criteria in our validation of copyMaps,*/\\n/* which we currently do not.*/\\nconst sortedEntries=rankOrder.sortByRank(entries,rankOrder.compareAntiRank);\\nconst keys=sortedEntries.map(([k,_v])=>k);\\nconst values=sortedEntries.map(([_k,v])=>v);\\nconst result=makeTagged.makeTagged('copyMap',{keys,values});\\nassertCopyMap(result);\\nreturn result;};\\n\\nharden(makeCopyMap);\\n\\n/* //////////////////////// Keys Recur /////////////////////////////////////////*/\\n\\n/**\\n * @param {any} val\\n * @param {Checker} check\\n * @returns {boolean}\\n */\\nconst checkKeyInternal=(val,check)=>{\\nconst checkIt=(child)=>checkKey(child,check);\\n\\nconst passStyle=passStyleOf.passStyleOf(val);\\nswitch(passStyle){\\ncase'copyRecord':{\\n/* A copyRecord is a key iff all its children are keys*/\\nreturn Object.values(val).every(checkIt);}\\n\\ncase'copyArray':{\\n/* A copyArray is a key iff all its children are keys*/\\nreturn val.every(checkIt);}\\n\\ncase'tagged':{\\nconst tag=passStyleHelpers.getTag(val);\\nswitch(tag){\\ncase'copySet':{\\nreturn checkCopySet(val,check);}\\n\\ncase'copyBag':{\\nreturn checkCopyBag(val,check);}\\n\\ncase'copyMap':{\\nreturn(\\ncheckCopyMap(val,check)&&\\n/* For a copyMap to be a key, all its keys and values must*/\\n/* be keys. Keys already checked by `checkCopyMap` since*/\\n/* that's a copyMap requirement in general.*/\\neveryCopyMapValue(val,checkIt));}\\n\\n\\ndefault:{\\nreturn(\\ncheck!==identChecker.identChecker&&\\ncheck(false,index.redacted`A passable tagged ${index.quote(tag)} is not a key: ${val}`));}}}\\n\\n\\n\\n\\ncase'remotable':{\\n/* All remotables are keys.*/\\nreturn true;}\\n\\ncase'error':\\ncase'promise':{\\nreturn check(false,index.redacted`A ${index.quote(passStyle)} cannot be a key`);}\\n\\ndefault:{\\n/* Unexpected tags are just non-keys, but an unexpected passStyle*/\\n/* is always an error.*/\\nthrow index.throwRedacted`unexpected passStyle ${index.quote(passStyle)}: ${val}`;}}};exports.assertCopyBag=assertCopyBag;exports.assertCopyMap=assertCopyMap;exports.assertCopySet=assertCopySet;exports.assertKey=assertKey;exports.assertPrimitiveKey=assertPrimitiveKey;exports.assertScalarKey=assertScalarKey;exports.checkCopyBag=checkCopyBag;exports.checkCopyMap=checkCopyMap;exports.checkCopySet=checkCopySet;exports.checkKey=checkKey;exports.checkScalarKey=checkScalarKey;exports.copyMapKeySet=copyMapKeySet;exports.everyCopyBagEntry=everyCopyBagEntry;exports.everyCopyMapKey=everyCopyMapKey;exports.everyCopyMapValue=everyCopyMapValue;exports.everyCopySetKey=everyCopySetKey;exports.getCopyBagEntries=getCopyBagEntries;exports.getCopyMapEntries=getCopyMapEntries;exports.getCopyMapEntryArray=getCopyMapEntryArray;exports.getCopyMapKeys=getCopyMapKeys;exports.getCopyMapValues=getCopyMapValues;exports.getCopySetKeys=getCopySetKeys;exports.isCopyBag=isCopyBag;exports.isCopyMap=isCopyMap;exports.isCopySet=isCopySet;exports.isKey=isKey;exports.isPrimitiveKey=isPrimitiveKey;exports.isScalarKey=isScalarKey;exports.makeCopyBag=makeCopyBag;exports.makeCopyBagFromElements=makeCopyBagFromElements;exports.makeCopyMap=makeCopyMap;exports.makeCopySet=makeCopySet;\",\n \"node_modules/@endo/patterns/src/keys/compareKeys.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../../marshal/index.js');var index=require('../../../errors/index.js');var checkKey=require('./checkKey.js');var keycollectionOperators=require('./keycollection-operators.js');var rankOrder=require('../../../marshal/src/rankOrder.js');var passStyleOf=require('../../../pass-style/src/passStyleOf.js');var passStyleHelpers=require('../../../pass-style/src/passStyle-helpers.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nencodePassable=require('../../../marshal/src/encodePassable.js');/*/ <reference types=\\\"ses\\\"/>*/ /** @import {CopySet, Key, KeyCompare} from '../types.js' */ /**\\n * CopySet X is smaller than CopySet Y iff all of these conditions hold:\\n * 1. For every x in X, x is also in Y.\\n * 2. There is a y in Y that is not in X.\\n *\\n * X is equivalent to Y iff the condition 1 holds but condition 2 does not.\\n */\\nconst setCompare=keycollectionOperators.makeCompareCollection(\\n/** @type {<K extends Key>(s: CopySet<K>) => Array<[K, 1]>} */\\n(s)=>harden(checkKey.getCopySetKeys(s).map((key)=>[key,1])),\\n\\n0,\\nrankOrder.trivialComparator);\\n\\nharden(setCompare);\\n\\n/**\\n * CopyBag X is smaller than CopyBag Y iff all of these conditions hold\\n * (where `count(A, a)` is shorthand for the count associated with `a` in `A`):\\n * 1. For every x in X, x is also in Y and count(X, x) <= count(Y, x).\\n * 2. There is a y in Y such that y is not in X or count(X, y) < count(Y, y).\\n *\\n * X is equivalent to Y iff the condition 1 holds but condition 2 does not.\\n */\\nconst bagCompare=keycollectionOperators.makeCompareCollection(\\ncheckKey.getCopyBagEntries,\\n0n,\\nrankOrder.trivialComparator);\\n\\nharden(bagCompare);\\n\\n/* TODO The desired semantics for CopyMap comparison have not yet been decided.*/\\n/* See https://github.com/endojs/endo/pull/1737#pullrequestreview-1596595411*/\\n/* The below is a currently-unused extension of CopyBag semantics (i.e., absent*/\\n/* entries treated as present with a value that is smaller than everything).*/\\n/**\\n * A unique local value that is guaranteed to not exist in any inbound data\\n * structure (which would not be the case if we used `Symbol.for`).\\n */\\nconst ABSENT=Symbol('absent');\\n/**\\n * CopyMap X is smaller than CopyMap Y iff all of these conditions hold:\\n * 1. X and Y are both Keys (i.e., neither contains non-comparable data).\\n * 2. For every x in X, x is also in Y and X[x] is smaller than or equivalent to Y[x].\\n * 3. There is a y in Y such that y is not in X or X[y] is smaller than Y[y].\\n *\\n * X is equivalent to Y iff conditions 1 and 2 hold but condition 3 does not.\\n */\\n/* eslint-disable-next-line no-underscore-dangle*/\\nconst _mapCompare=keycollectionOperators.makeCompareCollection(\\ncheckKey.getCopyMapEntryArray,\\nABSENT,\\n(leftValue,rightValue)=>{\\nif(leftValue===ABSENT&&rightValue===ABSENT){\\nthrow index.throwRedacted`Internal: Unexpected absent entry pair`;}else\\nif(leftValue===ABSENT){\\nreturn-1;}else\\nif(rightValue===ABSENT){\\nreturn 1;}else\\n{\\n/* eslint-disable-next-line no-use-before-define*/\\nreturn compareKeys(leftValue,rightValue);}});\\n\\n\\n\\nharden(_mapCompare);\\n\\n/** @type {KeyCompare} */\\nconst compareKeys=(left,right)=>{\\ncheckKey.assertKey(left);\\ncheckKey.assertKey(right);\\nconst leftStyle=passStyleOf.passStyleOf(left);\\nconst rightStyle=passStyleOf.passStyleOf(right);\\nif(leftStyle!==rightStyle){\\n/* Different passStyles are incommensurate*/\\nreturn NaN;}\\n\\nswitch(leftStyle){\\ncase'undefined':\\ncase'null':\\ncase'boolean':\\ncase'bigint':\\ncase'string':\\ncase'symbol':{\\n/* for these, keys compare the same as rank*/\\nreturn rankOrder.compareRank(left,right);}\\n\\ncase'number':{\\nconst rankComp=rankOrder.compareRank(left,right);\\nif(rankComp===0){\\nreturn 0;}\\n\\nif(Number.isNaN(left)||Number.isNaN(right)){\\n/* NaN is equal to itself, but incommensurate with everything else*/\\nassert(!Number.isNaN(left)||!Number.isNaN(right));\\nreturn NaN;}\\n\\n/* Among non-NaN numbers, key order is the same as rank order. Note that*/\\n/* in both orders, `-0` is in the same equivalence class as `0`.*/\\nreturn rankComp;}\\n\\ncase'remotable':{\\nif(left===right){\\nreturn 0;}\\n\\n/* If two remotables are not identical, then as keys they are*/\\n/* incommensurate.*/\\nreturn NaN;}\\n\\ncase'copyArray':{\\n/* Lexicographic by key order. Rank order of arrays is lexicographic by*/\\n/* rank order.*/\\n/* Because the invariants above apply to the elements of the array,*/\\n/* they apply to the array as a whole.*/\\n/* @ts-expect-error narrowed*/\\nconst len=Math.min(left.length,right.length);\\nfor(let i=0;i<len;i+=1){\\n/* @ts-expect-error narrowed*/\\nconst result=compareKeys(left[i],right[i]);\\nif(result!==0){\\nreturn result;}}\\n\\n\\n/* If all matching elements are keyEQ, then according to their lengths.*/\\n/* Thus, if array X is a prefix of array Y, then X is smaller than Y.*/\\n/* @ts-expect-error narrowed*/\\nreturn rankOrder.compareRank(left.length,right.length);}\\n\\ncase'copyRecord':{\\n/* Pareto partial order comparison.*/\\n/* @ts-expect-error narrowed*/\\nconst leftNames=encodePassable.recordNames(left);\\n/* @ts-expect-error narrowed*/\\nconst rightNames=encodePassable.recordNames(right);\\n\\n/* eslint-disable-next-line no-use-before-define*/\\nif(!keyEQ(leftNames,rightNames)){\\n/* If they do not have exactly the same properties,*/\\n/* they are incommensurate.*/\\n/* Note that rank sorting of copyRecords groups all copyRecords with*/\\n/* the same keys together, enabling range searching over copyRecords*/\\n/* to avoid more irrelevant ones.*/\\nreturn NaN;}\\n\\n/* @ts-expect-error narrowed*/\\nconst leftValues=encodePassable.recordValues(left,leftNames);\\n/* @ts-expect-error narrowed*/\\nconst rightValues=encodePassable.recordValues(right,rightNames);\\n/* Presume that both copyRecords have the same key order*/\\n/* until encountering a property disproving that hypothesis.*/\\nlet result=0;\\nfor(let i=0;i<leftValues.length;i+=1){\\nconst comp=compareKeys(leftValues[i],rightValues[i]);\\nif(Number.isNaN(comp)){\\nreturn NaN;}\\n\\nif(result!==comp&&comp!==0){\\nif(result===0){\\nresult=comp;}else\\n{\\nassert(\\nresult===-1&&comp===1||result===1&&comp===-1);\\n\\nreturn NaN;}}}\\n\\n\\n\\n/* If copyRecord X is smaller than copyRecord Y, then they must have the*/\\n/* same property names and every value in X must be smaller or equal to*/\\n/* the corresponding value in Y (with at least one value smaller).*/\\n/* The rank order of X and Y is based on lexicographic rank order of*/\\n/* their values, as organized by reverse lexicographic order of their*/\\n/* property names.*/\\n/* Thus if compareKeys(X,Y) < 0 then compareRank(X,Y) < 0.*/\\nreturn result;}\\n\\ncase'tagged':{\\n/* @ts-expect-error narrowed*/\\nconst leftTag=passStyleHelpers.getTag(left);\\n/* @ts-expect-error narrowed*/\\nconst rightTag=passStyleHelpers.getTag(right);\\nif(leftTag!==rightTag){\\n/* different tags are incommensurate*/\\nreturn NaN;}\\n\\nswitch(leftTag){\\ncase'copySet':{\\n/* @ts-expect-error narrowed*/\\nreturn setCompare(left,right);}\\n\\ncase'copyBag':{\\n/* @ts-expect-error narrowed*/\\nreturn bagCompare(left,right);}\\n\\ncase'copyMap':{\\n/* TODO The desired semantics for CopyMap comparison have not yet been decided.*/\\n/* See https://github.com/endojs/endo/pull/1737#pullrequestreview-1596595411*/\\nthrow index.throwRedacted`Map comparison not yet implemented: ${left} vs ${right}`;}\\n\\ndefault:{\\nthrow index.throwRedacted`unexpected tag ${index.quote(leftTag)}: ${left}`;}}}\\n\\n\\n\\ndefault:{\\nthrow index.throwRedacted`unexpected passStyle ${index.quote(leftStyle)}: ${left}`;}}};\\n\\n\\n\\nharden(compareKeys);\\n\\nconst keyLT=(left,right)=>compareKeys(left,right)<0;\\nharden(keyLT);\\n\\nconst keyLTE=(left,right)=>compareKeys(left,right)<=0;\\nharden(keyLTE);\\n\\nconst keyEQ=(left,right)=>compareKeys(left,right)===0;\\nharden(keyEQ);\\n\\nconst keyGTE=(left,right)=>compareKeys(left,right)>=0;\\nharden(keyGTE);\\n\\nconst keyGT=(left,right)=>compareKeys(left,right)>0;\\nharden(keyGT);exports.bagCompare=bagCompare;exports.compareKeys=compareKeys;exports.keyEQ=keyEQ;exports.keyGT=keyGT;exports.keyGTE=keyGTE;exports.keyLT=keyLT;exports.keyLTE=keyLTE;exports.setCompare=setCompare;\",\n \"node_modules/@endo/patterns/src/keys/copyBag.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../../marshal/index.js');var index=require('../../../errors/index.js');var rankOrder=require('../../../marshal/src/rankOrder.js');var passStyleHelpers=require('../../../pass-style/src/passStyle-helpers.js');var passStyleOf=require('../../../pass-style/src/passStyleOf.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nmakeTagged=require('../../../pass-style/src/makeTagged.js');/**\\n * @import {Passable} from '@endo/pass-style'\\n * @import {Checker} from '@endo/marshal'\\n * @import {CopyBag, Key, FullCompare} from '../types.js'\\n */ /**\\n * @template {Key} T\\n * @param {[T,bigint][]} bagEntries\\n * @param {FullCompare | undefined} fullCompare If provided and `bagEntries` is already\\n * known to be sorted by this `fullCompare`, then we should get a memo hit\\n * rather than a resorting. However, currently, we still enumerate the entire\\n * array each time.\\n *\\n * TODO: If doing this reduntantly turns out to be expensive, we\\n * could memoize this no-duplicate-keys finding as well, independent\\n * of the `fullOrder` use to reach this finding.\\n * @param {Checker} check\\n * @returns {boolean}\\n */const checkNoDuplicateKeys=(bagEntries,fullCompare,check)=>{/* This fullOrder contains history dependent state. It is specific*/ /* to this one call and does not survive it.*/ /* TODO Once all our tooling is ready for `&&=`, the following*/\\n/* line should be rewritten using it.*/\\nfullCompare=fullCompare||rankOrder.makeFullOrderComparatorKit().antiComparator;\\n\\n/* Since the key is more significant than the value (the count),*/\\n/* sorting by fullOrder is guaranteed to make duplicate keys*/\\n/* adjacent independent of their counts.*/\\nbagEntries=rankOrder.sortByRank(bagEntries,fullCompare);\\nconst{length}=bagEntries;\\nfor(let i=1;i<length;i+=1){\\nconst k0=bagEntries[i-1][0];\\nconst k1=bagEntries[i][0];\\nif(fullCompare(k0,k1)===0){\\nreturn check(false,index.redacted`value has duplicate keys: ${k0}`);}}\\n\\n\\nreturn true;};\\n\\n\\n/**\\n * @template {Key} T\\n * @param {[T,bigint][]} bagEntries\\n * @param {FullCompare} [fullCompare]\\n * @returns {void}\\n */\\nconst assertNoDuplicateKeys=(bagEntries,fullCompare=undefined)=>{\\ncheckNoDuplicateKeys(bagEntries,fullCompare,passStyleHelpers.assertChecker);};\\n\\n\\n/**\\n * @param {[Passable,bigint][]} bagEntries\\n * @param {Checker} check\\n * @returns {boolean}\\n */\\nconst checkBagEntries=(bagEntries,check)=>{\\nif(passStyleOf.passStyleOf(bagEntries)!=='copyArray'){\\nreturn check(\\nfalse,\\nindex.redacted`The entries of a copyBag must be a copyArray: ${bagEntries}`);}\\n\\n\\nif(!rankOrder.isRankSorted(bagEntries,rankOrder.compareAntiRank)){\\nreturn check(\\nfalse,\\nindex.redacted`The entries of a copyBag must be sorted in reverse rank order: ${bagEntries}`);}\\n\\n\\nfor(const entry of bagEntries){\\nif(\\npassStyleOf.passStyleOf(entry)!=='copyArray'||\\nentry.length!==2||\\ntypeof entry[1]!=='bigint')\\n{\\nreturn check(\\nfalse,\\nindex.redacted`Each entry of a copyBag must be pair of a key and a bigint representing a count: ${entry}`);}\\n\\n\\nif(entry[1]<1){\\nreturn check(\\nfalse,\\nindex.redacted`Each entry of a copyBag must have a positive count: ${entry}`);}}\\n\\n\\n\\n/* @ts-expect-error XXX Key types*/\\nreturn checkNoDuplicateKeys(bagEntries,undefined,check);};\\n\\nharden(checkBagEntries);\\n\\n/* eslint-disable-next-line jsdoc/require-returns-check -- doesn't understand asserts*/\\n/**\\n * @param {[Passable,bigint][]} bagEntries\\n * @returns {asserts bagEntries is [Passable,bigint][]}\\n */\\nconst assertBagEntries=(bagEntries)=>{\\ncheckBagEntries(bagEntries,passStyleHelpers.assertChecker);};\\n\\nharden(assertBagEntries);\\n\\n/**\\n * @template {Key} K\\n * @param {Iterable<[K, bigint]>} bagEntriesList\\n */\\nconst coerceToBagEntries=(bagEntriesList)=>{\\nconst bagEntries=rankOrder.sortByRank(bagEntriesList,rankOrder.compareAntiRank);\\nassertBagEntries(bagEntries);\\nreturn bagEntries;};\\n\\nharden(coerceToBagEntries);\\n\\n/**\\n * @template {Key} K\\n * @param {Iterable<[K, bigint]>} bagEntryIter\\n * @returns {CopyBag<K>}\\n */\\nconst makeBagOfEntries=(bagEntryIter)=>\\nmakeTagged.makeTagged('copyBag',coerceToBagEntries(bagEntryIter));\\nharden(makeBagOfEntries);exports.assertBagEntries=assertBagEntries;exports.assertNoDuplicateKeys=assertNoDuplicateKeys;exports.checkBagEntries=checkBagEntries;exports.coerceToBagEntries=coerceToBagEntries;exports.makeBagOfEntries=makeBagOfEntries;\",\n \"node_modules/@endo/patterns/src/keys/copySet.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../../marshal/index.js');var index=require('../../../errors/index.js');var rankOrder=require('../../../marshal/src/rankOrder.js');var passStyleHelpers=require('../../../pass-style/src/passStyle-helpers.js');var passStyleOf=require('../../../pass-style/src/passStyleOf.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nmakeTagged=require('../../../pass-style/src/makeTagged.js');/**\\n * @import {Passable} from '@endo/pass-style'\\n * @import {Checker} from '@endo/marshal'\\n * @import {CopySet, FullCompare, Key} from '../types.js'\\n */ /**\\n * @template {Passable} T\\n * @param {T[]} elements\\n * @param {FullCompare | undefined} fullCompare If provided and `elements` is already known\\n * to be sorted by this `fullCompare`, then we should get a memo hit rather\\n * than a resorting. However, currently, we still enumerate the entire array\\n * each time.\\n *\\n * TODO: If doing this reduntantly turns out to be expensive, we\\n * could memoize this no-duplicate finding as well, independent\\n * of the `fullOrder` use to reach this finding.\\n * @param {Checker} check\\n * @returns {boolean}\\n */const checkNoDuplicates=(elements,fullCompare,check)=>{/* This fullOrder contains history dependent state. It is specific*/ /* to this one call and does not survive it.*/ /* TODO Once all our tooling is ready for `&&=`, the following*/\\n/* line should be rewritten using it.*/\\nfullCompare=fullCompare||rankOrder.makeFullOrderComparatorKit().antiComparator;\\n\\nelements=rankOrder.sortByRank(elements,fullCompare);\\nconst{length}=elements;\\nfor(let i=1;i<length;i+=1){\\nconst k0=elements[i-1];\\nconst k1=elements[i];\\nif(fullCompare(k0,k1)===0){\\nreturn check(false,index.redacted`value has duplicate keys: ${k0}`);}}\\n\\n\\nreturn true;};\\n\\n\\n/**\\n * @template {Passable} T\\n * @param {T[]} elements\\n * @param {FullCompare} [fullCompare]\\n * @returns {void}\\n */\\nconst assertNoDuplicates=(elements,fullCompare=undefined)=>{\\ncheckNoDuplicates(elements,fullCompare,passStyleHelpers.assertChecker);};\\n\\n\\n/**\\n * @param {Passable[]} elements\\n * @param {Checker} check\\n * @returns {boolean}\\n */\\nconst checkElements=(elements,check)=>{\\nif(passStyleOf.passStyleOf(elements)!=='copyArray'){\\nreturn check(\\nfalse,\\nindex.redacted`The keys of a copySet or copyMap must be a copyArray: ${elements}`);}\\n\\n\\nif(!rankOrder.isRankSorted(elements,rankOrder.compareAntiRank)){\\nreturn check(\\nfalse,\\nindex.redacted`The keys of a copySet or copyMap must be sorted in reverse rank order: ${elements}`);}\\n\\n\\nreturn checkNoDuplicates(elements,undefined,check);};\\n\\nharden(checkElements);\\n\\nconst assertElements=(elements)=>{\\ncheckElements(elements,passStyleHelpers.assertChecker);};\\n\\nharden(assertElements);\\n\\n/**\\n * @template {Key} K\\n * @param {Iterable<K>} elementsList\\n */\\nconst coerceToElements=(elementsList)=>{\\nconst elements=rankOrder.sortByRank(elementsList,rankOrder.compareAntiRank);\\nassertElements(elements);\\nreturn elements;};\\n\\nharden(coerceToElements);\\n\\n/**\\n * @template {Key} K\\n * @param {Iterable<K>} elementIter\\n * @returns {CopySet<K>}\\n */\\nconst makeSetOfElements=(elementIter)=>\\nmakeTagged.makeTagged('copySet',coerceToElements(elementIter));\\nharden(makeSetOfElements);exports.assertElements=assertElements;exports.assertNoDuplicates=assertNoDuplicates;exports.checkElements=checkElements;exports.coerceToElements=coerceToElements;exports.makeSetOfElements=makeSetOfElements;\",\n \"node_modules/@endo/patterns/src/keys/keycollection-operators.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../../marshal/index.js');var makeIterator=require('../../../common/make-iterator.js');var makeArrayIterator=require('../../../common/make-array-iterator.js');var index=require('../../../errors/index.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nrankOrder=require('../../../marshal/src/rankOrder.js');/* @ts-check*/ /**\\n * Refines a sequence of entries that is already sorted over its keys by the\\n * `rankCompare` preorder, where there may be internal runs tied for the same\\n * rank, into an iterable that resolves those ties using `fullCompare`.\\n *\\n * @template [V=unknown]\\n * @param {Array<[Key, V]>} entries\\n * @param {RankCompare} rankCompare\\n * @param {FullCompare} fullCompare\\n * @returns {IterableIterator<[Key, V]>}\\n */\\nconst generateFullSortedEntries=(entries,rankCompare,fullCompare)=>{\\n/* @ts-expect-error XXX Key types*/\\nrankOrder.assertRankSorted(entries,rankCompare);\\nconst{length}=entries;\\nlet i=0;\\nlet sameRankIterator;\\nreturn makeIterator.makeIterator(()=>{\\nif(sameRankIterator){\\nconst result=sameRankIterator.next();\\nif(!result.done){\\nreturn result;}\\n\\nsameRankIterator=undefined;}\\n\\nif(i<length){\\nconst entry=entries[i];\\n/* Look ahead for same-rank ties.*/\\nlet j=i+1;\\nwhile(j<length&&rankCompare(entry[0],entries[j][0])===0){\\nj+=1;}\\n\\nif(j===i+1){\\n/* No ties found.*/\\ni=j;\\nreturn harden({done:false,value:entry});}\\n\\nconst ties=entries.slice(i,j);\\ni=j;\\n\\n/* Sort the ties by `fullCompare`, enforce key uniqueness, and delegate to*/\\n/* a sub-iterator.*/\\n/* @ts-expect-error XXX Key types*/\\nconst sortedTies=rankOrder.sortByRank(ties,fullCompare);\\nfor(let k=1;k<sortedTies.length;k+=1){\\n/* @ts-expect-error XXX Key types*/\\nconst[key0]=sortedTies[k-1];\\nconst[key1]=sortedTies[k];\\nMath.sign(fullCompare(key0,key1))||\\nindex.throwRedacted`Duplicate entry key: ${key0}`;}\\n\\nsameRankIterator=makeArrayIterator.makeArrayIterator(sortedTies);\\nreturn sameRankIterator.next();}\\n\\nreturn harden({done:true,value:undefined});});};\\n\\n\\nharden(generateFullSortedEntries);\\n\\n/**\\n * Returns an iterator that merges reverse-rank-sorted [key, value] entries of\\n * two KeyCollections into a reverse-full-sorted [key, value1, value2] entries\\n * by the key they have in common, representing the value for an absent entry in\\n * either collection as `absentValue`.\\n *\\n * @template [C=KeyCollection]\\n * @template [V=unknown]\\n * @param {C} c1\\n * @param {C} c2\\n * @param {(collection: C) => Array<[Key, V]>} getEntries\\n * @param {any} absentValue\\n * @returns {IterableIterator<[Key, V | absentValue, V | absentValue]>}\\n */\\nconst generateCollectionPairEntries=(\\nc1,\\nc2,\\ngetEntries,\\nabsentValue)=>\\n{\\nconst e1=getEntries(c1);\\nconst e2=getEntries(c2);\\n\\n/* Establish a history-dependent comparison scoped to the active invocation*/\\n/* and use it to map reverse-preordered entries into an iterator with a*/\\n/* narrower total order.*/\\nconst fullCompare=rankOrder.makeFullOrderComparatorKit().antiComparator;\\nconst x=generateFullSortedEntries(e1,rankOrder.compareAntiRank,fullCompare);\\nconst y=generateFullSortedEntries(e2,rankOrder.compareAntiRank,fullCompare);\\n\\n/* Maintain a single-result { done, key, value } buffer for each iterator*/\\n/* so they can be merged.*/\\nlet xDone;\\nlet xKey;\\nlet xValue;\\nlet yDone;\\nlet yKey;\\nlet yValue;\\nconst nonEntry=[undefined,undefined];\\nconst nextX=()=>{\\n!xDone||index.throwRedacted`Internal: nextX must not be called once done`;\\nconst result=xValue;\\n({done:xDone,value:[xKey,xValue]=nonEntry}=x.next());\\nreturn result;};\\n\\nnextX();\\nconst nextY=()=>{\\n!yDone||index.throwRedacted`Internal: nextY must not be called once done`;\\nconst result=yValue;\\n({done:yDone,value:[yKey,yValue]=nonEntry}=y.next());\\nreturn result;};\\n\\nnextY();\\nreturn makeIterator.makeIterator(()=>{\\nlet done=false;\\n/** @type {[Key, V | absentValue, V | absentValue]} */\\nlet value;\\nif(xDone&&yDone){\\ndone=true;\\nvalue=[undefined,absentValue,absentValue];}else\\nif(xDone){\\nvalue=[yKey,absentValue,nextY()];}else\\nif(yDone){\\nvalue=[xKey,nextX(),absentValue];}else\\n{\\n/* Compare the keys to determine if we should return a merged result*/\\n/* or a one-sided result.*/\\nconst comp=fullCompare(xKey,yKey);\\nif(comp===0){\\nvalue=[xKey,nextX(),nextY()];}else\\nif(comp<0){\\nvalue=[xKey,nextX(),absentValue];}else\\nif(comp>0){\\nvalue=[yKey,absentValue,nextY()];}else\\n{\\nthrow index.throwRedacted`Unexpected key comparison ${index.quote(comp)} for ${xKey} vs ${yKey}`;}}\\n\\n\\nreturn harden({done,value});});};\\n\\n\\nharden(generateCollectionPairEntries);\\n\\n/**\\n * Returns a function for comparing two KeyCollections of the same type using\\n * the provided entries factory and same-key entry value comparator (where the\\n * value for an absent entry in one collection is `absentValue`).\\n *\\n * If the corresponding entries for any single key are incomparable or the\\n * comparison result has the opposite sign of the result for a different key,\\n * then the KeyCollections are incomparable. Otherwise, the collections compare\\n * by the result of any non-equal entry comparison, or compare equal if there is\\n * no non-equal entry comparison result.\\n * For example, given CopyBags X and Y and a value comparator that goes by count\\n * (defaulting absent keys to a count of 0), X is smaller than Y (`result < 0`)\\n * iff there are no keys in X that are either absent from Y\\n * (`compareValues(xCount, absentValue) > 0`) or present in Y with a lower count\\n * (`compareValues(xCount, yCount) > 0`) AND there is at least one key in Y that\\n * is either absent from X (`compareValues(absentValue, yCount) < 0`) or present\\n * with a lower count (`compareValues(xCount, yCount) < 0`).\\n *\\n * This can be generalized to virtual collections in the future by replacing\\n * `getEntries => Array` with `generateEntries => IterableIterator`.\\n *\\n * @template [C=KeyCollection]\\n * @template [V=unknown]\\n * @param {(collection: C) => Array<[Key, V]>} getEntries\\n * @param {any} absentValue\\n * @param {KeyCompare} compareValues\\n * @returns {(left: C, right: C) => KeyComparison}\\n */\\nconst makeCompareCollection=(getEntries,absentValue,compareValues)=>\\nharden((left,right)=>{\\nconst merged=generateCollectionPairEntries(\\nleft,\\nright,\\ngetEntries,\\nabsentValue);\\n\\nlet leftIsBigger=false;\\nlet rightIsBigger=false;\\nfor(const[_key,leftValue,rightValue]of merged){\\nconst comp=compareValues(leftValue,rightValue);\\nif(comp===0){\\n/* eslint-disable-next-line no-continue*/\\ncontinue;}else\\nif(comp<0){\\n/* Based on this key, left < right.*/\\nrightIsBigger=true;}else\\nif(comp>0){\\n/* Based on this key, left > right.*/\\nleftIsBigger=true;}else\\n{\\nNumber.isNaN(comp)||\\n/* prettier-ignore*/\\nindex.throwRedacted`Unexpected value comparison ${index.quote(comp)} for ${leftValue} vs ${rightValue}`;\\nreturn NaN;}\\n\\nif(leftIsBigger&&rightIsBigger){\\nreturn NaN;}}\\n\\n\\n/* eslint-disable-next-line no-nested-ternary*/\\nreturn leftIsBigger?1:rightIsBigger?-1:0;});\\n\\nharden(makeCompareCollection);exports.generateCollectionPairEntries=generateCollectionPairEntries;exports.makeCompareCollection=makeCompareCollection;\",\n \"node_modules/@endo/patterns/src/keys/merge-bag-operators.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../../marshal/index.js');var index=require('../../../errors/index.js');var copyBag=require('./copyBag.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nrankOrder=require('../../../marshal/src/rankOrder.js');/**\\n * @import {Passable} from '@endo/pass-style';\\n * @import {RankCompare} from '@endo/marshal'\\n * @import {FullCompare, Key} from '../types.js'\\n */ /* Based on merge-set-operators.js, but altered for the bag representation.*/ /* TODO share more code with that file and keycollection-operators.js.*/ /**\\n * Asserts that `bagEntries` is already rank sorted by `rankCompare`, where\\n * there\\n * may be contiguous regions of bagEntries whose keys are tied for the same\\n * rank.\\n * Returns an iterable that will enumerate all the bagEntries in order\\n * according to `fullOrder`, which should differ from `rankOrder` only\\n * by being more precise.\\n *\\n * This should be equivalent to resorting the entire `bagEntries` array\\n * according\\n * to `fullOrder`. However, it optimizes for the case where these contiguous\\n * runs that need to be resorted are either absent or small.\\n *\\n * @template {Key} T\\n * @param {[T,bigint][]} bagEntries\\n * @param {RankCompare} rankCompare\\n * @param {FullCompare} fullCompare\\n * @returns {Iterable<[T,bigint]>}\\n */const bagWindowResort=(bagEntries,rankCompare,fullCompare)=>{rankOrder.assertRankSorted(bagEntries,rankCompare);const{length}=bagEntries;let i=0;\\nlet optInnerIterator;\\nreturn harden({\\n[Symbol.iterator]:()=>\\nharden({\\nnext:()=>{\\nif(optInnerIterator){\\nconst result=optInnerIterator.next();\\nif(result.done){\\noptInnerIterator=undefined;\\n/* fall through*/}else\\n{\\nreturn result;}}\\n\\n\\nif(i<length){\\nconst entry=bagEntries[i];\\nlet j=i+1;\\nwhile(\\nj<length&&\\nrankCompare(entry[0],bagEntries[j][0])===0)\\n{\\nj+=1;}\\n\\nif(j===i+1){\\ni=j;\\nreturn harden({done:false,value:entry});}\\n\\nconst similarRun=bagEntries.slice(i,j);\\ni=j;\\nconst resorted=rankOrder.sortByRank(similarRun,fullCompare);\\n/* Providing the same `fullCompare` should cause a memo hit*/\\n/* within `assertNoDuplicates` enabling it to avoid a*/\\n/* redundant resorting.*/\\ncopyBag.assertNoDuplicateKeys(resorted,fullCompare);\\n/* This is the raw JS array iterator whose `.next()` method*/\\n/* does not harden the IteratorResult, in violation of our*/\\n/* conventions. Fixing this is expensive and I'm confident the*/\\n/* unfrozen value does not escape this file, so I'm leaving this*/\\n/* as is.*/\\noptInnerIterator=resorted[Symbol.iterator]();\\nreturn optInnerIterator.next();}else\\n{\\nreturn harden({done:true,value:[null,0n]});}}})});};\\n\\n\\n\\n\\n\\n\\n/**\\n * Returns an iterable whose iteration results are [key, xCount, yCount] tuples\\n * representing the next key in the local full order, as well as how many\\n * times it occurred in the x input iterator and the y input iterator.\\n *\\n * For sets, these counts are always 0 or 1, but this representation\\n * generalizes nicely for bags.\\n *\\n * @template {Key} T\\n * @param {[T,bigint][]} xbagEntries\\n * @param {[T,bigint][]} ybagEntries\\n * @returns {Iterable<[T,bigint,bigint]>}\\n */\\nconst merge=(xbagEntries,ybagEntries)=>{\\n/* This fullOrder contains history dependent state. It is specific*/\\n/* to this one `merge` call and does not survive it.*/\\nconst fullCompare=rankOrder.makeFullOrderComparatorKit().antiComparator;\\n\\nconst xs=bagWindowResort(xbagEntries,rankOrder.compareAntiRank,fullCompare);\\nconst ys=bagWindowResort(ybagEntries,rankOrder.compareAntiRank,fullCompare);\\nreturn harden({\\n[Symbol.iterator]:()=>{\\n/* These six `let` variables are buffering one ahead from the underlying*/\\n/* iterators. Each iteration reports one or the other or both, and*/\\n/* then refills the buffers of those it advanced.*/\\n/** @type {T} */\\nlet x;\\nlet xc;\\nlet xDone;\\n/** @type {T} */\\nlet y;\\nlet yc;\\nlet yDone;\\n\\nconst xi=xs[Symbol.iterator]();\\nconst nextX=()=>{\\n!xDone||index.throwRedacted`Internal: nextX should not be called once done`;\\n({\\ndone:xDone,\\nvalue:[x,xc]}=\\nxi.next());};\\n\\nnextX();\\n\\nconst yi=ys[Symbol.iterator]();\\nconst nextY=()=>{\\n!yDone||index.throwRedacted`Internal: nextY should not be called once done`;\\n({\\ndone:yDone,\\nvalue:[y,yc]}=\\nyi.next());};\\n\\nnextY();\\n\\nreturn harden({\\nnext:()=>{\\n/** @type {boolean} */\\nlet done=false;\\n/** @type {[T,bigint,bigint]} */\\nlet value;\\nif(xDone&&yDone){\\ndone=true;\\n/* @ts-expect-error Because the terminating value does not matter*/\\nvalue=[null,0n,0n];}else\\nif(xDone){\\n/* only ys are left*/\\nvalue=[y,0n,yc];\\nnextY();}else\\nif(yDone){\\n/* only xs are left*/\\nvalue=[x,xc,0n];\\nnextX();}else\\n{\\nconst comp=fullCompare(x,y);\\nif(comp===0){\\n/* x and y are equivalent, so report both*/\\nvalue=[x,xc,yc];\\nnextX();\\nnextY();}else\\nif(comp<0){\\n/* x is earlier, so report it*/\\nvalue=[x,xc,0n];\\nnextX();}else\\n{\\n/* y is earlier, so report it*/\\ncomp>0||index.throwRedacted`Internal: Unexpected comp ${index.quote(comp)}`;\\nvalue=[y,0n,yc];\\nnextY();}}\\n\\n\\nreturn harden({done,value});}});}});};\\n\\n\\n\\n\\n\\nharden(merge);\\n\\n/* We should be able to use this for iterIsSuperset as well.*/\\n/* The generalization is free.*/\\n/**\\n * @template T\\n * @param {Iterable<[T,bigint,bigint]>} xyi\\n * @returns {boolean}\\n */\\nconst bagIterIsSuperbag=(xyi)=>{\\nfor(const[_m,xc,yc]of xyi){\\nif(xc<yc){\\n/* something in y is not in x, so x is not a superbag of y*/\\nreturn false;}}\\n\\n\\nreturn true;};\\n\\n\\n/* We should be able to use this for iterIsDisjoint as well.*/\\n/* The code is identical.*/\\n/**\\n * @template T\\n * @param {Iterable<[T,bigint,bigint]>} xyi\\n * @returns {boolean}\\n */\\nconst bagIterIsDisjoint=(xyi)=>{\\nfor(const[_m,xc,yc]of xyi){\\nif(xc>=1n&&yc>=1n){\\n/* Something in both, so not disjoint*/\\nreturn false;}}\\n\\n\\nreturn true;};\\n\\n\\n/**\\n * @template T\\n * @param {[T,bigint,bigint][]} xyi\\n * @returns {[T,bigint][]}\\n */\\nconst bagIterUnion=(xyi)=>{\\n/** @type {[T,bigint][]} */\\nconst result=[];\\nfor(const[m,xc,yc]of xyi){\\nresult.push([m,xc+yc]);}\\n\\nreturn result;};\\n\\n\\n/**\\n * @template T\\n * @param {Iterable<[T,bigint,bigint]>} xyi\\n * @returns {[T,bigint][]}\\n */\\nconst bagIterIntersection=(xyi)=>{\\n/** @type {[T,bigint][]} */\\nconst result=[];\\nfor(const[m,xc,yc]of xyi){\\nconst mc=xc<=yc?xc:yc;\\nresult.push([m,mc]);}\\n\\nreturn result;};\\n\\n\\n/**\\n * @template T\\n * @param {Iterable<[T,bigint,bigint]>} xyi\\n * @returns {[T,bigint][]}\\n */\\nconst bagIterDisjointSubtract=(xyi)=>{\\n/** @type {[T,bigint][]} */\\nconst result=[];\\nfor(const[m,xc,yc]of xyi){\\nconst mc=xc-yc;\\nmc>=0n||index.throwRedacted`right element ${m} was not in left`;\\nif(mc>=1n){\\n/* the x was not in y*/\\nresult.push([m,mc]);}}\\n\\n\\nreturn result;};\\n\\n\\nconst mergeify=(bagIterOp)=>(xbagEntries,ybagEntries)=>\\nbagIterOp(merge(xbagEntries,ybagEntries));\\n\\nconst bagEntriesIsSuperbag=mergeify(bagIterIsSuperbag);\\nconst bagEntriesIsDisjoint=mergeify(bagIterIsDisjoint);\\nconst bagEntriesUnion=mergeify(bagIterUnion);\\nconst bagEntriesIntersection=mergeify(bagIterIntersection);\\nconst bagEntriesDisjointSubtract=mergeify(bagIterDisjointSubtract);\\n\\nconst rawBagify=(bagEntriesOp)=>(xbag,ybag)=>\\nbagEntriesOp(xbag.payload,ybag.payload);\\n\\nconst bagify=(bagEntriesOp)=>(xbag,ybag)=>\\ncopyBag.makeBagOfEntries(bagEntriesOp(xbag.payload,ybag.payload));\\n\\nconst bagIsSuperbag=rawBagify(bagEntriesIsSuperbag);\\nconst bagIsDisjoint=rawBagify(bagEntriesIsDisjoint);\\nconst bagUnion=bagify(bagEntriesUnion);\\nconst bagIntersection=bagify(bagEntriesIntersection);\\nconst bagDisjointSubtract=bagify(bagEntriesDisjointSubtract);exports.bagDisjointSubtract=bagDisjointSubtract;exports.bagIntersection=bagIntersection;exports.bagIsDisjoint=bagIsDisjoint;exports.bagIsSuperbag=bagIsSuperbag;exports.bagUnion=bagUnion;\",\n \"node_modules/@endo/patterns/src/keys/merge-set-operators.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../../marshal/index.js');var index=require('../../../errors/index.js');var copySet=require('./copySet.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nrankOrder=require('../../../marshal/src/rankOrder.js');/**\\n * @import {Passable} from '@endo/pass-style';\\n * @import {RankCompare} from '@endo/marshal'\\n * @import {FullCompare, KeyComparison} from '../types.js'\\n */ /* TODO share more code with keycollection-operators.js.*/ /**\\n * Asserts that `elements` is already rank sorted by `rankCompare`, where there\\n * may be contiguous regions of elements tied for the same rank.\\n * Returns an iterable that will enumerate all the elements in order\\n * according to `fullOrder`, which should differ from `rankOrder` only\\n * by being more precise.\\n *\\n * This should be equivalent to resorting the entire `elements` array according\\n * to `fullOrder`. However, it optimizes for the case where these contiguous\\n * runs that need to be resorted are either absent or small.\\n *\\n * @template {Passable} T\\n * @param {T[]} elements\\n * @param {RankCompare} rankCompare\\n * @param {FullCompare} fullCompare\\n * @returns {Iterable<T>}\\n */const windowResort=(elements,rankCompare,fullCompare)=>{rankOrder.assertRankSorted(elements,rankCompare);const{length}=elements;let i=0;\\nlet optInnerIterator;\\nreturn harden({\\n[Symbol.iterator]:()=>\\nharden({\\nnext:()=>{\\nif(optInnerIterator){\\nconst result=optInnerIterator.next();\\nif(result.done){\\noptInnerIterator=undefined;\\n/* fall through*/}else\\n{\\nreturn result;}}\\n\\n\\nif(i<length){\\nconst value=elements[i];\\nlet j=i+1;\\nwhile(j<length&&rankCompare(value,elements[j])===0){\\nj+=1;}\\n\\nif(j===i+1){\\ni=j;\\nreturn harden({done:false,value});}\\n\\nconst similarRun=elements.slice(i,j);\\ni=j;\\nconst resorted=rankOrder.sortByRank(similarRun,fullCompare);\\n/* Providing the same `fullCompare` should cause a memo hit*/\\n/* within `assertNoDuplicates` enabling it to avoid a*/\\n/* redundant resorting.*/\\ncopySet.assertNoDuplicates(resorted,fullCompare);\\n/* This is the raw JS array iterator whose `.next()` method*/\\n/* does not harden the IteratorResult, in violation of our*/\\n/* conventions. Fixing this is expensive and I'm confident the*/\\n/* unfrozen value does not escape this file, so I'm leaving this*/\\n/* as is.*/\\noptInnerIterator=resorted[Symbol.iterator]();\\nreturn optInnerIterator.next();}else\\n{\\nreturn harden({done:true,value:null});}}})});};\\n\\n\\n\\n\\n\\n\\n/**\\n * Returns an iterable whose iteration results are [key, xCount, yCount] tuples\\n * representing the next key in the local full order, as well as how many\\n * times it occurred in the x input iterator and the y input iterator.\\n *\\n * For sets, these counts are always 0 or 1, but this representation\\n * generalizes nicely for bags.\\n *\\n * @template {Passable} T\\n * @param {T[]} xelements\\n * @param {T[]} yelements\\n * @returns {Iterable<[T,bigint,bigint]>}\\n */\\nconst merge=(xelements,yelements)=>{\\n/* This fullOrder contains history dependent state. It is specific*/\\n/* to this one `merge` call and does not survive it.*/\\nconst fullCompare=rankOrder.makeFullOrderComparatorKit().antiComparator;\\n\\nconst xs=windowResort(xelements,rankOrder.compareAntiRank,fullCompare);\\nconst ys=windowResort(yelements,rankOrder.compareAntiRank,fullCompare);\\nreturn harden({\\n[Symbol.iterator]:()=>{\\n/* These four `let` variables are buffering one ahead from the underlying*/\\n/* iterators. Each iteration reports one or the other or both, and*/\\n/* then refills the buffers of those it advanced.*/\\n/** @type {T} */\\nlet x;\\nlet xDone;\\n/** @type {T} */\\nlet y;\\nlet yDone;\\n\\nconst xi=xs[Symbol.iterator]();\\nconst nextX=()=>{\\n!xDone||index.throwRedacted`Internal: nextX should not be called once done`;\\n({done:xDone,value:x}=xi.next());};\\n\\nnextX();\\n\\nconst yi=ys[Symbol.iterator]();\\nconst nextY=()=>{\\n!yDone||index.throwRedacted`Internal: nextY should not be called once done`;\\n({done:yDone,value:y}=yi.next());};\\n\\nnextY();\\n\\nreturn harden({\\nnext:()=>{\\n/** @type {boolean} */\\nlet done=false;\\n/** @type {[T,bigint,bigint]} */\\nlet value;\\nif(xDone&&yDone){\\ndone=true;\\n/* @ts-expect-error Because the terminating value does not matter*/\\nvalue=[null,0n,0n];}else\\nif(xDone){\\n/* only ys are left*/\\nvalue=[y,0n,1n];\\nnextY();}else\\nif(yDone){\\n/* only xs are left*/\\nvalue=[x,1n,0n];\\nnextX();}else\\n{\\nconst comp=fullCompare(x,y);\\nif(comp===0){\\n/* x and y are equivalent, so report both*/\\nvalue=[x,1n,1n];\\nnextX();\\nnextY();}else\\nif(comp<0){\\n/* x is earlier, so report it*/\\nvalue=[x,1n,0n];\\nnextX();}else\\n{\\n/* y is earlier, so report it*/\\ncomp>0||index.throwRedacted`Internal: Unexpected comp ${index.quote(comp)}`;\\nvalue=[y,0n,1n];\\nnextY();}}\\n\\n\\nreturn harden({done,value});}});}});};\\n\\n\\n\\n\\n\\nharden(merge);\\n\\nconst iterIsSuperset=(xyi)=>{\\nfor(const[_m,xc,_yc]of xyi){\\nif(xc===0n){\\n/* something in y is not in x, so x is not a superset of y*/\\nreturn false;}}\\n\\n\\nreturn true;};\\n\\n\\n/**\\n * @template T\\n * @param {Iterable<[T,bigint,bigint]>} xyi\\n * @returns {boolean}\\n */\\nconst iterIsDisjoint=(xyi)=>{\\nfor(const[_m,xc,yc]of xyi){\\nif(xc>=1n&&yc>=1n){\\n/* Something in both, so not disjoint*/\\nreturn false;}}\\n\\n\\nreturn true;};\\n\\n\\n/**\\n * @template T\\n * @param {Iterable<[T,bigint,bigint]>} xyi\\n * @returns {KeyComparison}\\n */\\nconst iterCompare=(xyi)=>{\\nlet loneY=false;\\nlet loneX=false;\\nfor(const[_m,xc,yc]of xyi){\\nif(xc===0n){\\n/* something in y is not in x, so x is not a superset of y*/\\nloneY=true;}\\n\\nif(yc===0n){\\n/* something in x is not in y, so y is not a superset of x*/\\nloneX=true;}\\n\\nif(loneX&&loneY){\\nreturn NaN;}}\\n\\n\\nif(loneX){\\nreturn 1;}else\\nif(loneY){\\nreturn-1;}else\\n{\\n!loneX&&!loneY||\\nindex.throwRedacted`Internal: Unexpected lone pair ${index.quote([loneX,loneY])}`;\\nreturn 0;}};\\n\\n\\n\\n/**\\n * @template T\\n * @param {Iterable<[T,bigint,bigint]>} xyi\\n * @returns {T[]}\\n */\\nconst iterUnion=(xyi)=>{\\nconst result=[];\\nfor(const[m,xc,yc]of xyi){\\nif(xc>=0n){\\nresult.push(m);}else\\n{\\nyc>=0n||index.throwRedacted`Internal: Unexpected count ${index.quote(yc)}`;\\n/* if x and y were both ready, then they were equivalent and*/\\n/* above clause already took care of it. Otherwise push here.*/\\nresult.push(m);}}\\n\\n\\nreturn result;};\\n\\n\\n/**\\n * @template T\\n * @param {Iterable<[T,bigint,bigint]>} xyi\\n * @returns {T[]}\\n */\\nconst iterDisjointUnion=(xyi)=>{\\nconst result=[];\\nfor(const[m,xc,yc]of xyi){\\nxc===0n||yc===0n||index.throwRedacted`Sets must not have common elements: ${m}`;\\nif(xc>=1n){\\nresult.push(m);}else\\n{\\nyc>=1n||index.throwRedacted`Internal: Unexpected count ${index.quote(yc)}`;\\nresult.push(m);}}\\n\\n\\nreturn result;};\\n\\n\\n/**\\n * @template T\\n * @param {Iterable<[T,bigint,bigint]>} xyi\\n * @returns {T[]}\\n */\\nconst iterIntersection=(xyi)=>{\\nconst result=[];\\nfor(const[m,xc,yc]of xyi){\\nif(xc>=1n&&yc>=1n){\\n/* If they are both present, then they were equivalent*/\\nresult.push(m);}}\\n\\n\\nreturn result;};\\n\\n\\n/**\\n * @template T\\n * @param {Iterable<[T,bigint,bigint]>} xyi\\n * @returns {T[]}\\n */\\nconst iterDisjointSubtract=(xyi)=>{\\nconst result=[];\\nfor(const[m,xc,yc]of xyi){\\nxc>=1n||index.throwRedacted`right element ${m} was not in left`;\\nif(yc===0n){\\n/* the x was not in y*/\\nresult.push(m);}}\\n\\n\\nreturn result;};\\n\\n\\nconst mergeify=(iterOp)=>(xelements,yelements)=>\\niterOp(merge(xelements,yelements));\\n\\nconst elementsIsSuperset=mergeify(iterIsSuperset);\\nconst elementsIsDisjoint=mergeify(iterIsDisjoint);\\nconst elementsCompare=mergeify(iterCompare);\\nconst elementsUnion=mergeify(iterUnion);\\nconst elementsDisjointUnion=mergeify(iterDisjointUnion);\\nconst elementsIntersection=mergeify(iterIntersection);\\nconst elementsDisjointSubtract=mergeify(iterDisjointSubtract);\\n\\nconst rawSetify=(elementsOp)=>(xset,yset)=>\\nelementsOp(xset.payload,yset.payload);\\n\\nconst setify=(elementsOp)=>(xset,yset)=>\\ncopySet.makeSetOfElements(elementsOp(xset.payload,yset.payload));\\n\\nconst setIsSuperset=rawSetify(elementsIsSuperset);\\nconst setIsDisjoint=rawSetify(elementsIsDisjoint);\\nconst setUnion=setify(elementsUnion);\\nconst setDisjointUnion=setify(elementsDisjointUnion);\\nconst setIntersection=setify(elementsIntersection);\\nconst setDisjointSubtract=setify(elementsDisjointSubtract);exports.elementsCompare=elementsCompare;exports.elementsDisjointSubtract=elementsDisjointSubtract;exports.elementsDisjointUnion=elementsDisjointUnion;exports.elementsIntersection=elementsIntersection;exports.elementsIsDisjoint=elementsIsDisjoint;exports.elementsIsSuperset=elementsIsSuperset;exports.elementsUnion=elementsUnion;exports.setDisjointSubtract=setDisjointSubtract;exports.setDisjointUnion=setDisjointUnion;exports.setIntersection=setIntersection;exports.setIsDisjoint=setIsDisjoint;exports.setIsSuperset=setIsSuperset;exports.setUnion=setUnion;\",\n \"node_modules/@endo/patterns/src/patterns/getGuardPayloads.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var objectMap=require('../../../common/object-map.js');var patternMatchers=require('./patternMatchers.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\ncheckKey=require('../keys/checkKey.js');/**\\n * @import {AwaitArgGuard, AwaitArgGuardPayload, InterfaceGuard, InterfaceGuardPayload, MethodGuard, MethodGuardPayload} from '../types.js'\\n */ /* The get*GuardPayload functions exist to adapt to the worlds both*/ /* before and after https://github.com/endojs/endo/pull/1712 . When*/ /* given something that would be the expected guard in either world,*/ /* it returns a *GuardPayload that is valid in the current world. Thus*/ /* it helps new consumers of these guards cope with old code that*/ /* would construct and send these guards.*/ /* Because the main use case for this legacy adaptation is in @endo/exo*/ /* or packages that depend on it, the tests for this legacy adaptation*/ /* are found in the @endo/exo `test-legacy-guard-tolerance.js`.*/ /* Unlike LegacyAwaitArgGuardShape, LegacyMethodGuardShape,*/ /* and LegacyInterfaceGuardShape, there is no need for a*/ /* LegacyRawGuardShape, because raw guards were introduced at*/ /* https://github.com/endojs/endo/pull/1831 , which was merged well after*/ /* https://github.com/endojs/endo/pull/1712 . Thus, there was never a*/ /* `klass:` form of the raw guard.*/ /* TODO At such a time that we decide we no longer need to support code*/ /* preceding https://github.com/endojs/endo/pull/1712 or guard data*/ /* generated by that code, all the adaptation complexity in this file*/ /* should be deleted.*/ /* TODO manually maintain correspondence with AwaitArgGuardPayloadShape*/ /* because this one needs to be stable and accommodate nested legacy,*/ /* when that's an issue.*/const LegacyAwaitArgGuardShape=harden({klass:'awaitArg',\\nargGuard:patternMatchers.M.pattern()});\\n\\n\\n/**\\n * By using this abstraction rather than accessing the properties directly,\\n * we smooth the transition to https://github.com/endojs/endo/pull/1712,\\n * tolerating both the legacy and current guard shapes.\\n *\\n * Note that technically, tolerating the old LegacyAwaitArgGuardShape\\n * is an exploitable bug, in that a record that matches this\\n * shape is also a valid parameter pattern that should allow\\n * an argument that matches that pattern, i.e., a copyRecord argument that\\n * at least contains a `klass: 'awaitArgGuard'` property.\\n *\\n * @param {AwaitArgGuard} awaitArgGuard\\n * @returns {AwaitArgGuardPayload}\\n */\\nconst getAwaitArgGuardPayload=(awaitArgGuard)=>{\\nif(patternMatchers.matches(awaitArgGuard,LegacyAwaitArgGuardShape)){\\n/* @ts-expect-error Legacy adaptor can be ill typed*/\\nconst{klass:_,...payload}=awaitArgGuard;\\n/* @ts-expect-error Legacy adaptor can be ill typed*/\\nreturn payload;}\\n\\npatternMatchers.assertAwaitArgGuard(awaitArgGuard);\\nreturn awaitArgGuard.payload;};\\n\\nharden(getAwaitArgGuardPayload);\\n\\n/* TODO manually maintain correspondence with SyncMethodGuardPayloadShape*/\\n/* because this one needs to be stable and accommodate nested legacy,*/\\n/* when that's an issue.*/\\nconst LegacySyncMethodGuardShape=patternMatchers.M.splitRecord(\\n{\\nklass:'methodGuard',\\ncallKind:'sync',\\nargGuards:patternMatchers.SyncValueGuardListShape,\\nreturnGuard:patternMatchers.SyncValueGuardShape},\\n\\n{\\noptionalArgGuards:patternMatchers.SyncValueGuardListShape,\\nrestArgGuard:patternMatchers.SyncValueGuardShape});\\n\\n\\n\\n/* TODO manually maintain correspondence with ArgGuardShape*/\\n/* because this one needs to be stable and accommodate nested legacy,*/\\n/* when that's an issue.*/\\nconst LegacyArgGuardShape=patternMatchers.M.or(\\npatternMatchers.RawGuardShape,\\npatternMatchers.AwaitArgGuardShape,\\nLegacyAwaitArgGuardShape,\\npatternMatchers.M.pattern());\\n\\n/* TODO manually maintain correspondence with ArgGuardListShape*/\\n/* because this one needs to be stable and accommodate nested legacy,*/\\n/* when that's an issue.*/\\nconst LegacyArgGuardListShape=patternMatchers.M.arrayOf(LegacyArgGuardShape);\\n\\n/* TODO manually maintain correspondence with AsyncMethodGuardPayloadShape*/\\n/* because this one needs to be stable and accommodate nested legacy,*/\\n/* when that's an issue.*/\\nconst LegacyAsyncMethodGuardShape=patternMatchers.M.splitRecord(\\n{\\nklass:'methodGuard',\\ncallKind:'async',\\nargGuards:LegacyArgGuardListShape,\\nreturnGuard:patternMatchers.SyncValueGuardShape},\\n\\n{\\noptionalArgGuards:patternMatchers.ArgGuardListShape,\\nrestArgGuard:patternMatchers.SyncValueGuardShape});\\n\\n\\n\\n/* TODO manually maintain correspondence with MethodGuardPayloadShape*/\\n/* because this one needs to be stable and accommodate nested legacy,*/\\n/* when that's an issue.*/\\nconst LegacyMethodGuardShape=patternMatchers.M.or(\\nLegacySyncMethodGuardShape,\\nLegacyAsyncMethodGuardShape);\\n\\n\\nconst adaptLegacyArgGuard=(argGuard)=>\\npatternMatchers.matches(argGuard,LegacyAwaitArgGuardShape)?\\npatternMatchers.M.await(getAwaitArgGuardPayload(argGuard).argGuard):\\nargGuard;\\n\\n/**\\n * By using this abstraction rather than accessing the properties directly,\\n * we smooth the transition to https://github.com/endojs/endo/pull/1712,\\n * tolerating both the legacy and current guard shapes.\\n *\\n * Unlike LegacyAwaitArgGuardShape, tolerating LegacyMethodGuardShape\\n * does not seem like a currently exploitable bug, because there is not\\n * currently any context where either a methodGuard or a copyRecord would\\n * both be meaningful.\\n *\\n * @param {MethodGuard} methodGuard\\n * @returns {MethodGuardPayload}\\n */\\nconst getMethodGuardPayload=(methodGuard)=>{\\nif(patternMatchers.matches(methodGuard,patternMatchers.MethodGuardShape)){\\nreturn methodGuard.payload;}\\n\\npatternMatchers.mustMatch(methodGuard,LegacyMethodGuardShape,'legacyMethodGuard');\\nconst{\\n/* @ts-expect-error Legacy adaptor can be ill typed*/\\nklass:_,\\n/* @ts-expect-error Legacy adaptor can be ill typed*/\\ncallKind,\\n/* @ts-expect-error Legacy adaptor can be ill typed*/\\nreturnGuard,\\n/* @ts-expect-error Legacy adaptor can be ill typed*/\\nrestArgGuard}=\\nmethodGuard;\\nlet{\\n/* @ts-expect-error Legacy adaptor can be ill typed*/\\nargGuards,\\n/* @ts-expect-error Legacy adaptor can be ill typed*/\\noptionalArgGuards}=\\nmethodGuard;\\nif(callKind==='async'){\\nargGuards=argGuards.map(adaptLegacyArgGuard);\\noptionalArgGuards=\\noptionalArgGuards&&optionalArgGuards.map(adaptLegacyArgGuard);}\\n\\nconst payload=harden({\\ncallKind,\\nargGuards,\\noptionalArgGuards,\\nrestArgGuard,\\nreturnGuard});\\n\\n/* ensure the adaptation succeeded.*/\\npatternMatchers.mustMatch(payload,patternMatchers.MethodGuardPayloadShape,'internalMethodGuardAdaptor');\\nreturn payload;};\\n\\nharden(getMethodGuardPayload);\\n\\n/* TODO manually maintain correspondence with InterfaceGuardPayloadShape*/\\n/* because this one needs to be stable and accommodate nested legacy,*/\\n/* when that's an issue.*/\\nconst LegacyInterfaceGuardShape=patternMatchers.M.splitRecord(\\n{\\nklass:'Interface',\\ninterfaceName:patternMatchers.M.string(),\\nmethodGuards:patternMatchers.M.recordOf(\\npatternMatchers.M.string(),\\npatternMatchers.M.or(patternMatchers.MethodGuardShape,LegacyMethodGuardShape))},\\n\\n\\n{\\ndefaultGuards:patternMatchers.M.or(patternMatchers.M.undefined(),'passable','raw'),\\nsloppy:patternMatchers.M.boolean(),\\n/* There is no need to accommodate LegacyMethodGuardShape in*/\\n/* this position, since `symbolMethodGuards happened*/\\n/* after https://github.com/endojs/endo/pull/1712*/\\nsymbolMethodGuards:patternMatchers.M.mapOf(patternMatchers.M.symbol(),patternMatchers.MethodGuardShape)});\\n\\n\\n\\nconst adaptMethodGuard=(methodGuard)=>{\\nif(patternMatchers.matches(methodGuard,LegacyMethodGuardShape)){\\nconst{\\ncallKind,\\nargGuards,\\noptionalArgGuards=[],\\nrestArgGuard=patternMatchers.M.any(),\\nreturnGuard}=\\ngetMethodGuardPayload(methodGuard);\\nconst mCall=callKind==='sync'?patternMatchers.M.call:patternMatchers.M.callWhen;\\nreturn mCall(...argGuards).\\noptional(...optionalArgGuards).\\nrest(restArgGuard).\\nreturns(returnGuard);}\\n\\nreturn methodGuard;};\\n\\n\\n/**\\n * By using this abstraction rather than accessing the properties directly,\\n * we smooth the transition to https://github.com/endojs/endo/pull/1712,\\n * tolerating both the legacy and current guard shapes.\\n *\\n * Unlike LegacyAwaitArgGuardShape, tolerating LegacyInterfaceGuardShape\\n * does not seem like a currently exploitable bug, because there is not\\n * currently any context where either an interfaceGuard or a copyRecord would\\n * both be meaningful.\\n *\\n * @template {Record<PropertyKey, MethodGuard>} [T=Record<PropertyKey, MethodGuard>]\\n * @param {InterfaceGuard<T>} interfaceGuard\\n * @returns {InterfaceGuardPayload<T>}\\n */\\nconst getInterfaceGuardPayload=(interfaceGuard)=>{\\nif(patternMatchers.matches(interfaceGuard,patternMatchers.InterfaceGuardShape)){\\nreturn interfaceGuard.payload;}\\n\\npatternMatchers.mustMatch(interfaceGuard,LegacyInterfaceGuardShape,'legacyInterfaceGuard');\\n/* @ts-expect-error Legacy adaptor can be ill typed*/\\n/* eslint-disable-next-line prefer-const*/\\nlet{klass:_,interfaceName,methodGuards,...rest}=interfaceGuard;\\nmethodGuards=objectMap.objectMap(methodGuards,adaptMethodGuard);\\nconst payload=harden({\\ninterfaceName,\\nmethodGuards,\\n...rest});\\n\\npatternMatchers.mustMatch(\\npayload,\\npatternMatchers.InterfaceGuardPayloadShape,\\n'internalInterfaceGuardAdaptor');\\n\\nreturn payload;};\\n\\nharden(getInterfaceGuardPayload);\\n\\nconst emptyCopyMap=checkKey.makeCopyMap([]);\\n\\n/**\\n * @param {InterfaceGuard} interfaceGuard\\n * @returns {(string | symbol)[]}\\n */\\nconst getInterfaceMethodKeys=(interfaceGuard)=>{\\nconst{methodGuards,symbolMethodGuards=emptyCopyMap}=\\ngetInterfaceGuardPayload(interfaceGuard);\\n/** @type {(string | symbol)[]} */\\n/* TODO at-ts-expect-error works locally but not from @endo/exo*/\\n/* @ts-ignore inference is too weak to see this is ok*/\\nreturn harden([\\n...Reflect.ownKeys(methodGuards),\\n...checkKey.getCopyMapKeys(symbolMethodGuards)]);};\\n\\n\\nharden(getInterfaceMethodKeys);exports.getAwaitArgGuardPayload=getAwaitArgGuardPayload;exports.getInterfaceGuardPayload=getInterfaceGuardPayload;exports.getInterfaceMethodKeys=getInterfaceMethodKeys;exports.getMethodGuardPayload=getMethodGuardPayload;\",\n \"node_modules/@endo/patterns/src/patterns/patternMatchers.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../../marshal/index.js');var identChecker=require('../../../common/ident-checker.js');var applyLabelingError=require('../../../common/apply-labeling-error.js');var fromUniqueEntries=require('../../../common/from-unique-entries.js');var listDifference=require('../../../common/list-difference.js');var index=require('../../../errors/index.js');var compareKeys=require('../keys/compareKeys.js');var checkKey=require('../keys/checkKey.js');var keycollectionOperators=require('../keys/keycollection-operators.js');var passStyleOf=require('../../../pass-style/src/passStyleOf.js');var passStyleHelpers=require('../../../pass-style/src/passStyle-helpers.js');var encodePassable=require('../../../marshal/src/encodePassable.js');var rankOrder=require('../../../marshal/src/rankOrder.js');var makeFar=require('../../../pass-style/src/make-far.js');var symbol=require('../../../pass-style/src/symbol.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nmakeTagged=require('../../../pass-style/src/makeTagged.js');/* @ts-nocheck So many errors that the suppressions hamper readability.*/ /**\\n * @import {Checker, CopyRecord, CopyTagged, Passable} from '@endo/pass-style'\\n * @import {ArgGuard, AwaitArgGuard, CheckPattern, GetRankCover, InterfaceGuard, MatcherNamespace, MethodGuard, MethodGuardMaker, Pattern, RawGuard, SyncValueGuard, Kind, Limits, AllLimits, Key, DefaultGuardType} from '../types.js'\\n * @import {MatchHelper, PatternKit} from './types.js'\\n */\\n\\nconst{entries,values}=Object;\\nconst{ownKeys}=Reflect;\\n\\n/** @type {WeakSet<Pattern>} */\\nconst patternMemo=new WeakSet();\\n\\n/* /////////////////////// Match Helpers Helpers /////////////////////////////*/\\n\\n/** For forward references to `M` */\\nlet MM;\\n\\n/**\\n * The actual default values here are, at the present time, fairly\\n * arbitrary choices and may change before they settle down. Of course\\n * at some point we'll need to stop changing them. But we should first\\n * see how our system holds up with these choices. The main criteria\\n * is that they be big enough that \\\"normal\\\" innocent programs rarely\\n * encounter these limits.\\n *\\n * Exported primarily for testing.\\n */\\nconst defaultLimits=harden({\\ndecimalDigitsLimit:100,\\nstringLengthLimit:100_000,\\nsymbolNameLengthLimit:100,\\nnumPropertiesLimit:80,\\npropertyNameLengthLimit:100,\\narrayLengthLimit:10_000,\\nnumSetElementsLimit:10_000,\\nnumUniqueBagElementsLimit:10_000,\\nnumMapEntriesLimit:5000});\\n\\n\\n/**\\n * Use the result only to get the limits you need by destructuring.\\n * Thus, the result only needs to support destructuring. The current\\n * implementation uses inheritance as a cheap hack.\\n *\\n * @param {Limits} [limits]\\n * @returns {AllLimits}\\n */\\nconst limit=(limits={})=>\\n/** @type {AllLimits} */harden({__proto__:defaultLimits,...limits});\\n\\nconst checkIsWellFormedWithLimit=(\\npayload,\\nmainPayloadShape,\\ncheck,\\nlabel)=>\\n{\\nassert(Array.isArray(mainPayloadShape));\\nif(!Array.isArray(payload)){\\nreturn check(false,index.redacted`${index.quote(label)} payload must be an array: ${payload}`);}\\n\\n\\n/* Was the following, but its overuse of patterns caused an infinite regress*/\\n/* const payloadLimitShape = harden(*/\\n/* M.split(*/\\n/* mainPayloadShape,*/\\n/* M.partial(harden([M.recordOf(M.string(), M.number())]), harden([])),*/\\n/* ),*/\\n/* );*/\\n/* return checkMatches(payload, payloadLimitShape, check, label);*/\\n\\nconst mainLength=mainPayloadShape.length;\\nif(!(payload.length===mainLength||payload.length===mainLength+1)){\\nreturn check(false,index.redacted`${index.quote(label)} payload unexpected size: ${payload}`);}\\n\\nconst limits=payload[mainLength];\\npayload=harden(payload.slice(0,mainLength));\\n/* eslint-disable-next-line no-use-before-define*/\\nif(!checkMatches(payload,mainPayloadShape,check,label)){\\nreturn false;}\\n\\nif(limits===undefined){\\nreturn true;}\\n\\nreturn(\\n(passStyleOf.passStyleOf(limits)==='copyRecord'||\\ncheck(false,index.redacted`Limits must be a record: ${index.quote(limits)}`))&&\\nentries(limits).every(\\n([key,value])=>\\npassStyleOf.passStyleOf(value)==='number'||\\ncheck(false,index.redacted`Value of limit ${index.quote(key)} but be a number: ${index.quote(value)}`)));};\\n\\n\\n\\n\\n/**\\n * @param {unknown} specimen\\n * @param {number} decimalDigitsLimit\\n * @param {Checker} check\\n */\\nconst checkDecimalDigitsLimit=(specimen,decimalDigitsLimit,check)=>{\\nif(\\nMath.floor(Math.log10(Math.abs(Number(specimen))))+1<=\\ndecimalDigitsLimit)\\n{\\nreturn true;}\\n\\nreturn check(\\nfalse,\\nindex.redacted`bigint ${specimen} must not have more than ${decimalDigitsLimit} digits`);};\\n\\n\\n\\n/**\\n * @returns {PatternKit}\\n */\\nconst makePatternKit=()=>{\\n/**\\n * If this is a recognized match tag, return the MatchHelper.\\n * Otherwise result undefined.\\n *\\n * @param {string} tag\\n * @returns {MatchHelper | undefined}\\n */\\nconst maybeMatchHelper=(tag)=>\\n/* eslint-disable-next-line no-use-before-define*/\\nHelpersByMatchTag[tag];\\n\\n/**\\n * Note that this function indicates absence by returning `undefined`,\\n * even though `undefined` is a valid pattern. To evade this confusion,\\n * to register a payload shape with that meaning, use `MM.undefined()`.\\n *\\n * @param {string} tag\\n * @returns {Pattern | undefined}\\n */\\nconst maybePayloadShape=(tag)=>\\n/* eslint-disable-next-line no-use-before-define*/\\nGuardPayloadShapes[tag];\\n\\n/** @type {Map<Kind, unknown>} */\\nconst singletonKinds=new Map([\\n['null',null],\\n['undefined',undefined]]);\\n\\n\\n/**\\n * @type {WeakMap<CopyTagged, Kind>}\\n * Only for tagged records of recognized kinds whose store-level invariants\\n * have already been checked.\\n */\\nconst tagMemo=new WeakMap();\\n\\n/**\\n * Checks only recognized tags, and only if the tagged\\n * passes the invariants associated with that recognition.\\n *\\n * @param {Passable} tagged\\n * @param {Kind} tag\\n * @param {Checker} check\\n * @returns {boolean}\\n */\\nconst checkTagged=(tagged,tag,check)=>{\\nconst matchHelper=maybeMatchHelper(tag);\\nif(matchHelper){\\n/* Buried here is the important case, where we process*/\\n/* the various patternNodes*/\\nreturn matchHelper.checkIsWellFormed(tagged.payload,check);}else\\n{\\nconst payloadShape=maybePayloadShape(tag);\\nif(payloadShape!==undefined){\\n/* eslint-disable-next-line no-use-before-define*/\\nreturn checkMatches(tagged.payload,payloadShape,check,tag);}}\\n\\n\\nswitch(tag){\\ncase'copySet':{\\nreturn checkKey.checkCopySet(tagged,check);}\\n\\ncase'copyBag':{\\nreturn checkKey.checkCopyBag(tagged,check);}\\n\\ncase'copyMap':{\\nreturn checkKey.checkCopyMap(tagged,check);}\\n\\ndefault:{\\nreturn check(\\nfalse,\\nindex.redacted`cannot check unrecognized tag ${index.quote(tag)}: ${tagged}`);}}};\\n\\n\\n\\n\\n\\n/**\\n * Returns only a recognized kind, and only if the specimen passes the\\n * invariants associated with that recognition.\\n * Otherwise, `check(false, ...)` and returns undefined\\n *\\n * @param {any} specimen\\n * @param {Checker} [check]\\n * @returns {Kind | undefined}\\n */\\nconst kindOf=(specimen,check=identChecker.identChecker)=>{\\nconst passStyle=passStyleOf.passStyleOf(specimen);\\nif(passStyle!=='tagged'){\\nreturn passStyle;}\\n\\n/* At this point we know that specimen is well formed*/\\n/* as a tagged record, which is defined at the marshal level of abstraction,*/\\n/* since `passStyleOf` checks those invariants.*/\\nif(tagMemo.has(specimen)){\\nreturn tagMemo.get(specimen);}\\n\\nconst tag=passStyleHelpers.getTag(specimen);\\nif(checkTagged(specimen,tag,check)){\\ntagMemo.set(specimen,tag);\\nreturn tag;}\\n\\nif(check!==identChecker.identChecker){\\ncheck(false,index.redacted`cannot check unrecognized tag ${index.quote(tag)}`);}\\n\\nreturn undefined;};\\n\\nharden(kindOf);\\n\\n/**\\n * Checks only recognized kinds, and only if the specimen\\n * passes the invariants associated with that recognition.\\n *\\n * @param {any} specimen\\n * @param {Kind} kind\\n * @param {Checker} check\\n * @returns {boolean}\\n */\\nconst checkKind=(specimen,kind,check)=>{\\n/* check null and undefined as Keys*/\\nif(singletonKinds.has(kind)){\\n/* eslint-disable-next-line no-use-before-define*/\\nreturn checkAsKeyPatt(specimen,singletonKinds.get(kind),check);}\\n\\n\\nconst realKind=kindOf(specimen,check);\\nif(kind===realKind){\\nreturn true;}\\n\\nif(check!==identChecker.identChecker){\\n/* `kind` and `realKind` can be embedded without quotes*/\\n/* because they are drawn from the enumerated collection of known Kinds.*/\\ncheck(false,index.redacted`${index.bare(realKind)} ${specimen} - Must be a ${index.bare(kind)}`);}\\n\\nreturn false;};\\n\\n\\n/**\\n * Checks only recognized kinds, and only if the specimen\\n * passes the invariants associated with that recognition.\\n *\\n * @param {any} specimen\\n * @param {Kind} kind\\n * @returns {boolean}\\n */\\nconst isKind=(specimen,kind)=>checkKind(specimen,kind,identChecker.identChecker);\\n\\n/**\\n * @param {any} specimen\\n * @param {Key} keyAsPattern\\n * @param {Checker} check\\n * @returns {boolean}\\n */\\nconst checkAsKeyPatt=(specimen,keyAsPattern,check)=>{\\nif(checkKey.isKey(specimen)&&compareKeys.keyEQ(specimen,keyAsPattern)){\\nreturn true;}\\n\\nreturn(\\ncheck!==identChecker.identChecker&&\\n/* When the mismatch occurs against a key used as a pattern,*/\\n/* the pattern should still be redacted.*/\\ncheck(false,index.redacted`${specimen} - Must be: ${keyAsPattern}`));};\\n\\n\\n\\n/* /////////////////////// isPattern /////////////////////////////////////////*/\\n\\n/** @type {CheckPattern} */\\nconst checkPattern=(patt,check)=>{\\nif(checkKey.isKey(patt)){\\n/* All keys are patterns. For these, the keyMemo will do.*/\\n/* All primitives that are patterns are also keys, which this*/\\n/* also takes care of without memo. The rest of our checking logic*/\\n/* is only concerned with non-key patterns.*/\\nreturn true;}\\n\\nif(patternMemo.has(patt)){\\nreturn true;}\\n\\n/* eslint-disable-next-line no-use-before-define*/\\nconst result=checkPatternInternal(patt,check);\\nif(result){\\npatternMemo.add(patt);}\\n\\nreturn result;};\\n\\n\\n/**\\n * @param {Passable} patt - known not to be a key, and therefore known\\n * not to be primitive.\\n * @param {Checker} check\\n * @returns {boolean}\\n */\\nconst checkPatternInternal=(patt,check)=>{\\n/* Purposely parallels checkKey. TODO reuse more logic between them.*/\\n/* Most of the text of the switch below not dealing with matchers is*/\\n/* essentially identical.*/\\nconst checkIt=(child)=>checkPattern(child,check);\\n\\nconst kind=kindOf(patt,check);\\nswitch(kind){\\ncase undefined:{\\nreturn false;}\\n\\ncase'copyRecord':{\\n/* A copyRecord is a pattern iff all its children are*/\\n/* patterns*/\\nreturn values(patt).every(checkIt);}\\n\\ncase'copyArray':{\\n/* A copyArray is a pattern iff all its children are*/\\n/* patterns*/\\nreturn patt.every(checkIt);}\\n\\ncase'copyMap':{\\n/* A copyMap's keys are keys and therefore already known to be*/\\n/* patterns.*/\\n/* A copyMap is a pattern if its values are patterns.*/\\nreturn checkPattern(patt.values,check);}\\n\\ncase'error':\\ncase'promise':{\\nreturn check(false,index.redacted`A ${index.quote(kind)} cannot be a pattern`);}\\n\\ndefault:{\\nif(maybeMatchHelper(kind)!==undefined){\\nreturn true;}\\n\\nreturn check(\\nfalse,\\nindex.redacted`A passable of kind ${index.quote(kind)} is not a pattern: ${patt}`);}}};\\n\\n\\n\\n\\n\\n/**\\n * @param {Passable} patt\\n * @returns {boolean}\\n */\\nconst isPattern=(patt)=>checkPattern(patt,identChecker.identChecker);\\n\\n/**\\n * @param {Pattern} patt\\n */\\nconst assertPattern=(patt)=>{\\ncheckPattern(patt,passStyleHelpers.assertChecker);};\\n\\n\\n/* /////////////////////// matches ///////////////////////////////////////////*/\\n\\n/**\\n * @param {any} specimen\\n * @param {Pattern} pattern\\n * @param {Checker} check\\n * @param {string|number} [label]\\n * @returns {boolean}\\n */\\nconst checkMatches=(specimen,pattern,check,label=undefined)=>\\n/* eslint-disable-next-line no-use-before-define*/\\napplyLabelingError.applyLabelingError(checkMatchesInternal,[specimen,pattern,check],label);\\n\\n/**\\n * @param {any} specimen\\n * @param {Pattern} patt\\n * @param {Checker} check\\n * @returns {boolean}\\n */\\nconst checkMatchesInternal=(specimen,patt,check)=>{\\n/* Worth being a bit verbose and repetitive in order to optimize*/\\nconst patternKind=kindOf(patt,check);\\nconst specimenKind=kindOf(specimen);/* may be undefined*/\\nswitch(patternKind){\\ncase undefined:{\\nreturn index.throwRedacted`pattern expected: ${patt}`;}\\n\\ncase'promise':{\\nreturn index.throwRedacted`promises cannot be patterns: ${patt}`;}\\n\\ncase'error':{\\nreturn index.throwRedacted`errors cannot be patterns: ${patt}`;}\\n\\ncase'undefined':\\ncase'null':\\ncase'boolean':\\ncase'number':\\ncase'bigint':\\ncase'string':\\ncase'symbol':\\ncase'copySet':\\ncase'copyBag':\\ncase'remotable':{\\n/* These kinds are necessarily keys*/\\nreturn checkAsKeyPatt(specimen,patt,check);}\\n\\ncase'copyArray':{\\nif(checkKey.isKey(patt)){\\n/* Takes care of patterns which are keys, so the rest of this*/\\n/* logic can assume patterns that are not keys.*/\\nreturn checkAsKeyPatt(specimen,patt,check);}\\n\\nif(specimenKind!=='copyArray'){\\nreturn check(\\nfalse,\\nindex.redacted`${specimen} - Must be a copyArray to match a copyArray pattern: ${index.quote(\\npatt)\\n}`);}\\n\\n\\nconst{length}=patt;\\nif(specimen.length!==length){\\nreturn check(\\nfalse,\\nindex.redacted`Array ${specimen} - Must be as long as copyArray pattern: ${index.quote(\\npatt)\\n}`);}\\n\\n\\nreturn patt.every((p,i)=>checkMatches(specimen[i],p,check,i));}\\n\\ncase'copyRecord':{\\nif(checkKey.isKey(patt)){\\n/* Takes care of patterns which are keys, so the rest of this*/\\n/* logic can assume patterns that are not keys.*/\\nreturn checkAsKeyPatt(specimen,patt,check);}\\n\\nif(specimenKind!=='copyRecord'){\\nreturn check(\\nfalse,\\nindex.redacted`${specimen} - Must be a copyRecord to match a copyRecord pattern: ${index.quote(\\npatt)\\n}`);}\\n\\n\\n/* TODO Detect and accumulate difference in one pass.*/\\n/* Rather than using two calls to `listDifference` to detect and*/\\n/* report if and how these lists differ, since they are already*/\\n/* in sorted order, we should instead use an algorithm like*/\\n/* `iterDisjointUnion` from merge-sort-operators.js*/\\nconst specimenNames=encodePassable.recordNames(specimen);\\nconst pattNames=encodePassable.recordNames(patt);\\nconst missing=listDifference.listDifference(pattNames,specimenNames);\\nif(missing.length>=1){\\nreturn check(\\nfalse,\\nindex.redacted`${specimen} - Must have missing properties ${index.quote(missing)}`);}\\n\\n\\nconst unexpected=listDifference.listDifference(specimenNames,pattNames);\\nif(unexpected.length>=1){\\nreturn check(\\nfalse,\\nindex.redacted`${specimen} - Must not have unexpected properties: ${index.quote(\\nunexpected)\\n}`);}\\n\\n\\nconst specimenValues=encodePassable.recordValues(specimen,specimenNames);\\nconst pattValues=encodePassable.recordValues(patt,pattNames);\\nreturn pattNames.every((label,i)=>\\ncheckMatches(specimenValues[i],pattValues[i],check,label));}\\n\\n\\ncase'copyMap':{\\nif(checkKey.isKey(patt)){\\n/* Takes care of patterns which are keys, so the rest of this*/\\n/* logic can assume patterns that are not keys.*/\\nreturn checkAsKeyPatt(specimen,patt,check);}\\n\\nif(specimenKind!=='copyMap'){\\nreturn check(\\nfalse,\\nindex.redacted`${specimen} - Must be a copyMap to match a copyMap pattern: ${index.quote(\\npatt)\\n}`);}\\n\\n\\n/* Compare keys as copySets*/\\nconst pattKeySet=checkKey.copyMapKeySet(patt);\\nconst specimenKeySet=checkKey.copyMapKeySet(specimen);\\nif(!checkMatches(specimenKeySet,pattKeySet,check)){\\nreturn false;}\\n\\n/* Compare values as copyArrays after applying a shared total order.*/\\n/* This is necessary because the antiRankOrder sorting of each map's*/\\n/* entries is a preorder that admits ties.*/\\nconst pattValues=[];\\nconst specimenValues=[];\\nconst entryPairs=keycollectionOperators.generateCollectionPairEntries(\\npatt,\\nspecimen,\\ncheckKey.getCopyMapEntryArray,\\nundefined);\\n\\nfor(const[_key,pattValue,specimenValue]of entryPairs){\\npattValues.push(pattValue);\\nspecimenValues.push(specimenValue);}\\n\\nreturn checkMatches(harden(specimenValues),harden(pattValues),check);}\\n\\ndefault:{\\nconst matchHelper=maybeMatchHelper(patternKind);\\nif(matchHelper){\\nreturn matchHelper.checkMatches(specimen,patt.payload,check);}\\n\\nthrow index.throwRedacted`internal: should have recognized ${index.quote(patternKind)} `;}}};\\n\\n\\n\\n\\n/**\\n * @param {any} specimen\\n * @param {Pattern} patt\\n * @returns {boolean}\\n */\\nconst matches=(specimen,patt)=>\\ncheckMatches(specimen,patt,identChecker.identChecker);\\n\\n/**\\n * Returning normally indicates success. Match failure is indicated by\\n * throwing.\\n *\\n * @param {any} specimen\\n * @param {Pattern} patt\\n * @param {string|number} [label]\\n */\\nconst mustMatch=(specimen,patt,label=undefined)=>{\\nlet innerError;\\ntry{\\nif(checkMatches(specimen,patt,identChecker.identChecker,undefined)){\\nreturn;}}\\n\\ncatch(er){\\ninnerError=er;}\\n\\n/* should only throw*/\\ncheckMatches(specimen,patt,passStyleHelpers.assertChecker,label);\\nconst outerError=index.makeError(\\nindex.redacted`internal: ${label}: inconsistent pattern match: ${index.quote(patt)}`);\\n\\nif(innerError!==undefined){\\nindex.note(outerError,index.redacted`caused by ${innerError}`);}\\n\\nthrow outerError;};\\n\\n\\n/* /////////////////////// getRankCover //////////////////////////////////////*/\\n\\n/** @type {GetRankCover} */\\nconst getRankCover=(patt,encodePassable)=>{\\nif(checkKey.isKey(patt)){\\nconst encoded=encodePassable(patt);\\nif(encoded!==undefined){\\nreturn[encoded,`${encoded}~`];}}\\n\\n\\nconst passStyle=passStyleOf.passStyleOf(patt);\\nswitch(passStyle){\\ncase'copyArray':{\\n/* XXX this doesn't get along with the world of cover === pair of*/\\n/* strings. In the meantime, fall through to the default which*/\\n/* returns a cover that covers all copyArrays.*/\\n/**/\\n/* const rankCovers = patt.map(p => getRankCover(p, encodePassable));*/\\n/* return harden([*/\\n/* rankCovers.map(([left, _right]) => left),*/\\n/* rankCovers.map(([_left, right]) => right),*/\\n/* ]);*/\\nbreak;}\\n\\ncase'copyRecord':{\\n/* XXX this doesn't get along with the world of cover === pair of*/\\n/* strings. In the meantime, fall through to the default which*/\\n/* returns a cover that covers all copyRecords.*/\\n/**/\\n/* const pattKeys = ownKeys(patt);*/\\n/* const pattEntries = harden(pattKeys.map(key => [key, patt[key]]));*/\\n/* const [leftEntriesLimit, rightEntriesLimit] =*/\\n/* getRankCover(pattEntries);*/\\n/* return harden([*/\\n/* fromUniqueEntries(leftEntriesLimit),*/\\n/* fromUniqueEntries(rightEntriesLimit),*/\\n/* ]);*/\\nbreak;}\\n\\ncase'tagged':{\\nconst tag=passStyleHelpers.getTag(patt);\\nconst matchHelper=maybeMatchHelper(tag);\\nif(matchHelper){\\n/* Buried here is the important case, where we process*/\\n/* the various patternNodes*/\\nreturn matchHelper.getRankCover(patt.payload,encodePassable);}\\n\\nswitch(tag){\\ncase'copySet':{\\n/* XXX this doesn't get along with the world of cover === pair of*/\\n/* strings. In the meantime, fall through to the default which*/\\n/* returns a cover that covers all copySets.*/\\n/**/\\n/* // Should already be validated by checkPattern. But because this*/\\n/* // is a check that may loosen over time, we also assert*/\\n/* // everywhere we still rely on the restriction.*/\\n/* ```js*/\\n/* patt.payload.length === 1 ||*/\\n/* Fail`Non-singleton copySets with matcher not yet implemented: ${patt}`;*/\\n/* ```*/\\n/**/\\n/* const [leftElementLimit, rightElementLimit] = getRankCover(*/\\n/* patt.payload[0],*/\\n/* );*/\\n/* return harden([*/\\n/* makeCopySet([leftElementLimit]),*/\\n/* makeCopySet([rightElementLimit]),*/\\n/* ]);*/\\nbreak;}\\n\\ncase'copyMap':{\\n/* XXX this doesn't get along with the world of cover === pair of*/\\n/* strings. In the meantime, fall through to the default which*/\\n/* returns a cover that covers all copyMaps.*/\\n/**/\\n/* // A matching copyMap must have the same keys, or at most one*/\\n/* // non-key key pattern. Thus we can assume that value positions*/\\n/* // match 1-to-1.*/\\n/* //*/\\n/* // TODO I may be overlooking that the less precise rankOrder*/\\n/* // equivalence class may cause values to be out of order,*/\\n/* // making this rankCover not actually cover. In that case, for*/\\n/* // all the values for keys at the same rank, we should union their*/\\n/* // rank covers. TODO POSSIBLE SILENT CORRECTNESS BUG*/\\n/* //*/\\n/* // If this is a bug, it probably affects the getRankCover*/\\n/* // cases of matchLTEHelper and matchGTEHelper on copyMap as*/\\n/* // well. See makeCopyMap for an idea on fixing*/\\n/* // this bug.*/\\n/* const [leftPayloadLimit, rightPayloadLimit] = getRankCover(*/\\n/* patt.payload,*/\\n/* encodePassable,*/\\n/* );*/\\n/* return harden([*/\\n/* makeTagged('copyMap', leftPayloadLimit),*/\\n/* makeTagged('copyMap', rightPayloadLimit),*/\\n/* ]);*/\\nbreak;}\\n\\ndefault:{\\nbreak;/* fall through to default*/}}\\n\\n\\nbreak;/* fall through to default*/}\\n\\ndefault:{\\nbreak;/* fall through to default*/}}\\n\\n\\nreturn rankOrder.getPassStyleCover(passStyle);};\\n\\n\\n/**\\n * @param {Passable[]} array\\n * @param {Pattern} patt\\n * @param {Checker} check\\n * @param {string} [labelPrefix]\\n * @returns {boolean}\\n */\\nconst arrayEveryMatchPattern=(array,patt,check,labelPrefix='')=>{\\nif(isKind(patt,'match:any')){\\n/* if the pattern is M.any(), we know its true*/\\nreturn true;}\\n\\nreturn array.every((el,i)=>\\ncheckMatches(el,patt,check,`${labelPrefix}[${i}]`));};\\n\\n\\n\\n/* /////////////////////// Match Helpers /////////////////////////////////////*/\\n\\n/** @type {MatchHelper} */\\nconst matchAnyHelper=makeFar.Far('match:any helper',{\\ncheckMatches:(_specimen,_matcherPayload,_check)=>true,\\n\\ncheckIsWellFormed:(matcherPayload,check)=>\\nmatcherPayload===undefined||\\ncheck(false,index.redacted`match:any payload: ${matcherPayload} - Must be undefined`),\\n\\ngetRankCover:(_matchPayload,_encodePassable)=>['','{']});\\n\\n\\n/** @type {MatchHelper} */\\nconst matchAndHelper=makeFar.Far('match:and helper',{\\ncheckMatches:(specimen,patts,check)=>{\\nreturn patts.every((patt)=>checkMatches(specimen,patt,check));},\\n\\n\\ncheckIsWellFormed:(allegedPatts,check)=>{\\nconst checkIt=(patt)=>checkPattern(patt,check);\\nreturn(\\n(passStyleOf.passStyleOf(allegedPatts)==='copyArray'||\\ncheck(false,index.redacted`Needs array of sub-patterns: ${index.quote(allegedPatts)}`))&&\\nallegedPatts.every(checkIt));},\\n\\n\\n\\ngetRankCover:(patts,encodePassable)=>\\nrankOrder.intersectRankCovers(\\nrankOrder.compareRank,\\npatts.map((p)=>getRankCover(p,encodePassable)))});\\n\\n\\n\\n/** @type {MatchHelper} */\\nconst matchOrHelper=makeFar.Far('match:or helper',{\\ncheckMatches:(specimen,patts,check)=>{\\nconst{length}=patts;\\nif(length===0){\\nreturn check(\\nfalse,\\nindex.redacted`${specimen} - no pattern disjuncts to match: ${index.quote(patts)}`);}\\n\\n\\nif(\\npatts.length===2&&\\n!matches(specimen,patts[0])&&\\nisKind(patts[0],'match:kind')&&\\npatts[0].payload==='undefined')\\n{\\n/* Worth special casing the optional pattern for*/\\n/* better error messages.*/\\nreturn checkMatches(specimen,patts[1],check);}\\n\\nif(patts.some((patt)=>matches(specimen,patt))){\\nreturn true;}\\n\\nreturn check(false,index.redacted`${specimen} - Must match one of ${index.quote(patts)}`);},\\n\\n\\ncheckIsWellFormed:matchAndHelper.checkIsWellFormed,\\n\\ngetRankCover:(patts,encodePassable)=>\\nrankOrder.unionRankCovers(\\nrankOrder.compareRank,\\npatts.map((p)=>getRankCover(p,encodePassable)))});\\n\\n\\n\\n/** @type {MatchHelper} */\\nconst matchNotHelper=makeFar.Far('match:not helper',{\\ncheckMatches:(specimen,patt,check)=>{\\nif(matches(specimen,patt)){\\nreturn check(\\nfalse,\\nindex.redacted`${specimen} - Must fail negated pattern: ${index.quote(patt)}`);}else\\n\\n{\\nreturn true;}},\\n\\n\\n\\ncheckIsWellFormed:checkPattern,\\n\\ngetRankCover:(_patt,_encodePassable)=>['','{']});\\n\\n\\n/** @type {MatchHelper} */\\nconst matchScalarHelper=makeFar.Far('match:scalar helper',{\\ncheckMatches:(specimen,_matcherPayload,check)=>\\ncheckKey.checkScalarKey(specimen,check),\\n\\ncheckIsWellFormed:matchAnyHelper.checkIsWellFormed,\\n\\ngetRankCover:(_matchPayload,_encodePassable)=>['a','z~']});\\n\\n\\n/** @type {MatchHelper} */\\nconst matchKeyHelper=makeFar.Far('match:key helper',{\\ncheckMatches:(specimen,_matcherPayload,check)=>\\ncheckKey.checkKey(specimen,check),\\n\\ncheckIsWellFormed:matchAnyHelper.checkIsWellFormed,\\n\\ngetRankCover:(_matchPayload,_encodePassable)=>['a','z~']});\\n\\n\\n/** @type {MatchHelper} */\\nconst matchPatternHelper=makeFar.Far('match:pattern helper',{\\ncheckMatches:(specimen,_matcherPayload,check)=>\\ncheckPattern(specimen,check),\\n\\ncheckIsWellFormed:matchAnyHelper.checkIsWellFormed,\\n\\ngetRankCover:(_matchPayload,_encodePassable)=>['a','z~']});\\n\\n\\n/** @type {MatchHelper} */\\nconst matchKindHelper=makeFar.Far('match:kind helper',{\\ncheckMatches:checkKind,\\n\\ncheckIsWellFormed:(allegedKeyKind,check)=>\\ntypeof allegedKeyKind==='string'||\\ncheck(\\nfalse,\\nindex.redacted`match:kind: payload: ${allegedKeyKind} - A kind name must be a string`),\\n\\n\\ngetRankCover:(kind,_encodePassable)=>{\\nlet style;\\nswitch(kind){\\ncase'copySet':\\ncase'copyMap':{\\nstyle='tagged';\\nbreak;}\\n\\ndefault:{\\nstyle=kind;\\nbreak;}}\\n\\n\\nreturn rankOrder.getPassStyleCover(style);}});\\n\\n\\n\\n/** @type {MatchHelper} */\\nconst matchTaggedHelper=makeFar.Far('match:tagged helper',{\\ncheckMatches:(specimen,[tagPatt,payloadPatt],check)=>{\\nif(passStyleOf.passStyleOf(specimen)!=='tagged'){\\nreturn check(\\nfalse,\\nindex.redacted`Expected tagged object, not ${index.quote(\\npassStyleOf.passStyleOf(specimen))\\n}: ${specimen}`);}\\n\\n\\nreturn(\\ncheckMatches(passStyleHelpers.getTag(specimen),tagPatt,check,'tag')&&\\ncheckMatches(specimen.payload,payloadPatt,check,'payload'));},\\n\\n\\n\\ncheckIsWellFormed:(payload,check)=>\\ncheckMatches(\\npayload,\\nharden([MM.pattern(),MM.pattern()]),\\ncheck,\\n'match:tagged payload'),\\n\\n\\ngetRankCover:(_kind,_encodePassable)=>rankOrder.getPassStyleCover('tagged')});\\n\\n\\n/** @type {MatchHelper} */\\nconst matchBigintHelper=makeFar.Far('match:bigint helper',{\\ncheckMatches:(specimen,[limits=undefined],check)=>{\\nconst{decimalDigitsLimit}=limit(limits);\\nreturn(\\ncheckKind(specimen,'bigint',check)&&\\ncheckDecimalDigitsLimit(specimen,decimalDigitsLimit,check));},\\n\\n\\n\\ncheckIsWellFormed:(payload,check)=>\\ncheckIsWellFormedWithLimit(\\npayload,\\nharden([]),\\ncheck,\\n'match:bigint payload'),\\n\\n\\ngetRankCover:(_matchPayload,_encodePassable)=>\\nrankOrder.getPassStyleCover('bigint')});\\n\\n\\n/** @type {MatchHelper} */\\nconst matchNatHelper=makeFar.Far('match:nat helper',{\\ncheckMatches:(specimen,[limits=undefined],check)=>{\\nconst{decimalDigitsLimit}=limit(limits);\\nreturn(\\ncheckKind(specimen,'bigint',check)&&\\ncheck(\\n/** @type {bigint} */specimen>=0n,\\nindex.redacted`${specimen} - Must be non-negative`)&&\\n\\ncheckDecimalDigitsLimit(specimen,decimalDigitsLimit,check));},\\n\\n\\n\\ncheckIsWellFormed:(payload,check)=>\\ncheckIsWellFormedWithLimit(\\npayload,\\nharden([]),\\ncheck,\\n'match:nat payload'),\\n\\n\\ngetRankCover:(_matchPayload,_encodePassable)=>\\n/* TODO Could be more precise*/\\nrankOrder.getPassStyleCover('bigint')});\\n\\n\\n/** @type {MatchHelper} */\\nconst matchStringHelper=makeFar.Far('match:string helper',{\\ncheckMatches:(specimen,[limits=undefined],check)=>{\\nconst{stringLengthLimit}=limit(limits);\\n/* prettier-ignore*/\\nreturn(\\ncheckKind(specimen,'string',check)&&(\\n/* eslint-disable-next-line @endo/restrict-comparison-operands*/\\n/** @type {string} */specimen.length<=stringLengthLimit||\\ncheck(\\nfalse,\\nindex.redacted`string ${specimen} must not be bigger than ${stringLengthLimit}`)));},\\n\\n\\n\\n\\ncheckIsWellFormed:(payload,check)=>\\ncheckIsWellFormedWithLimit(\\npayload,\\nharden([]),\\ncheck,\\n'match:string payload'),\\n\\n\\ngetRankCover:(_matchPayload,_encodePassable)=>\\nrankOrder.getPassStyleCover('string')});\\n\\n\\n/** @type {MatchHelper} */\\nconst matchSymbolHelper=makeFar.Far('match:symbol helper',{\\ncheckMatches:(specimen,[limits=undefined],check)=>{\\nconst{symbolNameLengthLimit}=limit(limits);\\nif(!checkKind(specimen,'symbol',check)){\\nreturn false;}\\n\\nconst symbolName=symbol.nameForPassableSymbol(specimen);\\n\\nif(typeof symbolName!=='string'){\\nthrow index.throwRedacted`internal: Passable symbol ${specimen} must have a passable name`;}\\n\\nreturn check(\\nsymbolName.length<=symbolNameLengthLimit,\\nindex.redacted`Symbol name ${index.quote(\\nsymbolName)\\n} must not be bigger than ${symbolNameLengthLimit}`);},\\n\\n\\n\\ncheckIsWellFormed:(payload,check)=>\\ncheckIsWellFormedWithLimit(\\npayload,\\nharden([]),\\ncheck,\\n'match:symbol payload'),\\n\\n\\ngetRankCover:(_matchPayload,_encodePassable)=>\\nrankOrder.getPassStyleCover('symbol')});\\n\\n\\n/** @type {MatchHelper} */\\nconst matchRemotableHelper=makeFar.Far('match:remotable helper',{\\ncheckMatches:(specimen,remotableDesc,check)=>{\\nif(isKind(specimen,'remotable')){\\nreturn true;}\\n\\nif(check===identChecker.identChecker){\\nreturn false;}\\n\\nconst{label}=remotableDesc;\\nconst passStyle=passStyleOf.passStyleOf(specimen);\\nconst kindDetails=\\npassStyle!=='tagged'?\\n/* Pass style can be embedded in details without quotes.*/\\nindex.bare(passStyle):\\n/* Tag must be quoted because it is potentially attacker-controlled*/\\n/* (unlike `kindOf`, this does not reject unrecognized tags).*/\\nindex.quote(passStyleHelpers.getTag(specimen));\\nreturn check(\\nfalse,\\n/* `label` can be embedded without quotes because it is provided by*/\\n/* local code like `M.remotable(\\\"...\\\")`.*/\\nindex.redacted`${specimen} - Must be a remotable ${index.bare(label)}, not ${kindDetails}`);},\\n\\n\\n\\ncheckIsWellFormed:(allegedRemotableDesc,check)=>\\ncheckMatches(\\nallegedRemotableDesc,\\nharden({label:MM.string()}),\\ncheck,\\n'match:remotable payload'),\\n\\n\\ngetRankCover:(_remotableDesc,_encodePassable)=>\\nrankOrder.getPassStyleCover('remotable')});\\n\\n\\n/** @type {MatchHelper} */\\nconst matchLTEHelper=makeFar.Far('match:lte helper',{\\ncheckMatches:(specimen,rightOperand,check)=>\\ncompareKeys.keyLTE(specimen,rightOperand)||\\ncheck(false,index.redacted`${specimen} - Must be <= ${rightOperand}`),\\n\\ncheckIsWellFormed:checkKey.checkKey,\\n\\ngetRankCover:(rightOperand,encodePassable)=>{\\nconst passStyle=passStyleOf.passStyleOf(rightOperand);\\n/* The prefer-const makes no sense when some of the variables need*/\\n/* to be `let`*/\\n/* eslint-disable-next-line prefer-const*/\\nlet[leftBound,rightBound]=rankOrder.getPassStyleCover(passStyle);\\nconst newRightBound=`${encodePassable(rightOperand)}~`;\\nif(newRightBound!==undefined){\\nrightBound=newRightBound;}\\n\\nreturn[leftBound,rightBound];}});\\n\\n\\n\\n/** @type {MatchHelper} */\\nconst matchLTHelper=makeFar.Far('match:lt helper',{\\ncheckMatches:(specimen,rightOperand,check)=>\\ncompareKeys.keyLT(specimen,rightOperand)||\\ncheck(false,index.redacted`${specimen} - Must be < ${rightOperand}`),\\n\\ncheckIsWellFormed:checkKey.checkKey,\\n\\ngetRankCover:matchLTEHelper.getRankCover});\\n\\n\\n/** @type {MatchHelper} */\\nconst matchGTEHelper=makeFar.Far('match:gte helper',{\\ncheckMatches:(specimen,rightOperand,check)=>\\ncompareKeys.keyGTE(specimen,rightOperand)||\\ncheck(false,index.redacted`${specimen} - Must be >= ${rightOperand}`),\\n\\ncheckIsWellFormed:checkKey.checkKey,\\n\\ngetRankCover:(rightOperand,encodePassable)=>{\\nconst passStyle=passStyleOf.passStyleOf(rightOperand);\\n/* The prefer-const makes no sense when some of the variables need*/\\n/* to be `let`*/\\n/* eslint-disable-next-line prefer-const*/\\nlet[leftBound,rightBound]=rankOrder.getPassStyleCover(passStyle);\\nconst newLeftBound=encodePassable(rightOperand);\\nif(newLeftBound!==undefined){\\nleftBound=newLeftBound;}\\n\\nreturn[leftBound,rightBound];}});\\n\\n\\n\\n/** @type {MatchHelper} */\\nconst matchGTHelper=makeFar.Far('match:gt helper',{\\ncheckMatches:(specimen,rightOperand,check)=>\\ncompareKeys.keyGT(specimen,rightOperand)||\\ncheck(false,index.redacted`${specimen} - Must be > ${rightOperand}`),\\n\\ncheckIsWellFormed:checkKey.checkKey,\\n\\ngetRankCover:matchGTEHelper.getRankCover});\\n\\n\\n/** @type {MatchHelper} */\\nconst matchRecordOfHelper=makeFar.Far('match:recordOf helper',{\\ncheckMatches:(\\nspecimen,\\n[keyPatt,valuePatt,limits=undefined],\\ncheck)=>\\n{\\nconst{numPropertiesLimit,propertyNameLengthLimit}=limit(limits);\\nreturn(\\ncheckKind(specimen,'copyRecord',check)&&\\ncheck(\\nownKeys(specimen).length<=numPropertiesLimit,\\nindex.redacted`Must not have more than ${index.quote(\\nnumPropertiesLimit)\\n} properties: ${specimen}`)&&\\n\\nentries(specimen).every(\\n([key,value])=>\\napplyLabelingError.applyLabelingError(\\ncheck,\\n[\\nkey.length<=propertyNameLengthLimit,\\nindex.redacted`Property name must not be longer than ${index.quote(\\npropertyNameLengthLimit)\\n}`],\\n\\nkey)&&\\n\\ncheckMatches(\\nharden([key,value]),\\nharden([keyPatt,valuePatt]),\\ncheck,\\nkey)));},\\n\\n\\n\\n\\n\\ncheckIsWellFormed:(payload,check)=>\\ncheckIsWellFormedWithLimit(\\npayload,\\nharden([MM.pattern(),MM.pattern()]),\\ncheck,\\n'match:recordOf payload'),\\n\\n\\ngetRankCover:(_entryPatt)=>rankOrder.getPassStyleCover('copyRecord')});\\n\\n\\n/** @type {MatchHelper} */\\nconst matchArrayOfHelper=makeFar.Far('match:arrayOf helper',{\\ncheckMatches:(specimen,[subPatt,limits=undefined],check)=>{\\nconst{arrayLengthLimit}=limit(limits);\\n/* prettier-ignore*/\\nreturn(\\ncheckKind(specimen,'copyArray',check)&&(\\n/** @type {Array} */specimen.length<=arrayLengthLimit||\\ncheck(\\nfalse,\\nindex.redacted`Array length ${specimen.length} must be <= limit ${arrayLengthLimit}`))&&\\n\\narrayEveryMatchPattern(specimen,subPatt,check));},\\n\\n\\n\\ncheckIsWellFormed:(payload,check)=>\\ncheckIsWellFormedWithLimit(\\npayload,\\nharden([MM.pattern()]),\\ncheck,\\n'match:arrayOf payload'),\\n\\n\\ngetRankCover:()=>rankOrder.getPassStyleCover('copyArray')});\\n\\n\\n/** @type {MatchHelper} */\\nconst matchSetOfHelper=makeFar.Far('match:setOf helper',{\\ncheckMatches:(specimen,[keyPatt,limits=undefined],check)=>{\\nconst{numSetElementsLimit}=limit(limits);\\nreturn(\\ncheckKind(specimen,'copySet',check)&&\\ncheck(\\n/** @type {Array} */specimen.payload.length<numSetElementsLimit,\\nindex.redacted`Set must not have more than ${index.quote(numSetElementsLimit)} elements: ${\\nspecimen.payload.length\\n}`)&&\\n\\narrayEveryMatchPattern(specimen.payload,keyPatt,check,'set elements'));},\\n\\n\\n\\ncheckIsWellFormed:(payload,check)=>\\ncheckIsWellFormedWithLimit(\\npayload,\\nharden([MM.pattern()]),\\ncheck,\\n'match:setOf payload'),\\n\\n\\ngetRankCover:()=>rankOrder.getPassStyleCover('tagged')});\\n\\n\\n/** @type {MatchHelper} */\\nconst matchBagOfHelper=makeFar.Far('match:bagOf helper',{\\ncheckMatches:(\\nspecimen,\\n[keyPatt,countPatt,limits=undefined],\\ncheck)=>\\n{\\nconst{numUniqueBagElementsLimit,decimalDigitsLimit}=limit(limits);\\nreturn(\\ncheckKind(specimen,'copyBag',check)&&\\ncheck(\\n/** @type {Array} */specimen.payload.length<=\\nnumUniqueBagElementsLimit,\\nindex.redacted`Bag must not have more than ${index.quote(\\nnumUniqueBagElementsLimit)\\n} unique elements: ${specimen}`)&&\\n\\nspecimen.payload.every(\\n([key,count],i)=>\\ncheckMatches(key,keyPatt,check,`bag keys[${i}]`)&&\\napplyLabelingError.applyLabelingError(\\ncheckDecimalDigitsLimit,\\n[count,decimalDigitsLimit,check],\\n`bag counts[${i}]`)&&\\n\\ncheckMatches(count,countPatt,check,`bag counts[${i}]`)));},\\n\\n\\n\\n\\ncheckIsWellFormed:(payload,check)=>\\ncheckIsWellFormedWithLimit(\\npayload,\\nharden([MM.pattern(),MM.pattern()]),\\ncheck,\\n'match:bagOf payload'),\\n\\n\\ngetRankCover:()=>rankOrder.getPassStyleCover('tagged')});\\n\\n\\n/** @type {MatchHelper} */\\nconst matchMapOfHelper=makeFar.Far('match:mapOf helper',{\\ncheckMatches:(\\nspecimen,\\n[keyPatt,valuePatt,limits=undefined],\\ncheck)=>\\n{\\nconst{numMapEntriesLimit}=limit(limits);\\nreturn(\\ncheckKind(specimen,'copyMap',check)&&\\ncheck(\\n/** @type {Array} */specimen.payload.keys.length<=\\nnumMapEntriesLimit,\\nindex.redacted`CopyMap must have no more than ${index.quote(\\nnumMapEntriesLimit)\\n} entries: ${specimen}`)&&\\n\\narrayEveryMatchPattern(\\nspecimen.payload.keys,\\nkeyPatt,\\ncheck,\\n'map keys')&&\\n\\narrayEveryMatchPattern(\\nspecimen.payload.values,\\nvaluePatt,\\ncheck,\\n'map values'));},\\n\\n\\n\\n\\ncheckIsWellFormed:(payload,check)=>\\ncheckIsWellFormedWithLimit(\\npayload,\\nharden([MM.pattern(),MM.pattern()]),\\ncheck,\\n'match:mapOf payload'),\\n\\n\\ngetRankCover:(_entryPatt)=>rankOrder.getPassStyleCover('tagged')});\\n\\n\\n/**\\n * @param {Passable[]} specimen\\n * @param {Pattern[]} requiredPatt\\n * @param {Pattern[]} optionalPatt\\n * @returns {{\\n * requiredSpecimen: Passable[],\\n * optionalSpecimen: Passable[],\\n * restSpecimen: Passable[]\\n * }}\\n */\\nconst splitArrayParts=(specimen,requiredPatt,optionalPatt)=>{\\nconst numRequired=requiredPatt.length;\\nconst numOptional=optionalPatt.length;\\nconst requiredSpecimen=specimen.slice(0,numRequired);\\nconst optionalSpecimen=specimen.slice(\\nnumRequired,\\nnumRequired+numOptional);\\n\\nconst restSpecimen=specimen.slice(numRequired+numOptional);\\nreturn harden({requiredSpecimen,optionalSpecimen,restSpecimen});};\\n\\n\\n/**\\n * Optional specimen elements which are `undefined` pass unconditionally.\\n * We encode this with the `M.or` pattern so it also produces a good\\n * compression distinguishing `undefined` from absence.\\n *\\n * @param {Pattern[]} optionalPatt\\n * @param {number} length\\n * @returns {Pattern[]} The partialPatt\\n */\\nconst adaptArrayPattern=(optionalPatt,length)=>\\nharden(optionalPatt.slice(0,length).map((patt)=>MM.opt(patt)));\\n\\n/** @type {MatchHelper} */\\nconst matchSplitArrayHelper=makeFar.Far('match:splitArray helper',{\\ncheckMatches:(\\nspecimen,\\n[requiredPatt,optionalPatt=[],restPatt=MM.any()],\\ncheck)=>\\n{\\nif(!checkKind(specimen,'copyArray',check)){\\nreturn false;}\\n\\nconst{requiredSpecimen,optionalSpecimen,restSpecimen}=\\nsplitArrayParts(specimen,requiredPatt,optionalPatt);\\nconst partialPatt=adaptArrayPattern(\\noptionalPatt,\\noptionalSpecimen.length);\\n\\nlet argNum=0;\\nreturn(\\n(requiredSpecimen.length===requiredPatt.length||\\ncheck(\\nfalse,\\nindex.redacted`Expected at least ${index.quote(\\nrequiredPatt.length)\\n} arguments: ${specimen}`))&&\\n\\nrequiredPatt.every((p,i)=>\\n/* eslint-disable-next-line no-plusplus*/\\ncheckMatches(requiredSpecimen[i],p,check,`arg ${argNum++}`))&&\\n\\npartialPatt.every((p,i)=>\\n/* eslint-disable-next-line no-plusplus*/\\ncheckMatches(optionalSpecimen[i],p,check,`arg ${argNum++}?`))&&\\n\\ncheckMatches(restSpecimen,restPatt,check,'...rest'));},\\n\\n\\n\\n/**\\n * @param {Array} splitArray\\n * @param {Checker} check\\n */\\ncheckIsWellFormed:(splitArray,check)=>{\\nif(\\npassStyleOf.passStyleOf(splitArray)==='copyArray'&&(\\nsplitArray.length>=1||splitArray.length<=3))\\n{\\nconst[requiredPatt,optionalPatt=undefined,restPatt=undefined]=\\nsplitArray;\\nif(\\nisPattern(requiredPatt)&&\\npassStyleOf.passStyleOf(requiredPatt)==='copyArray'&&(\\noptionalPatt===undefined||\\nisPattern(optionalPatt)&&\\npassStyleOf.passStyleOf(optionalPatt)==='copyArray')&&(\\nrestPatt===undefined||isPattern(restPatt)))\\n{\\nreturn true;}}\\n\\n\\nreturn check(\\nfalse,\\nindex.redacted`Must be an array of a requiredPatt array, an optional optionalPatt array, and an optional restPatt: ${index.quote(\\nsplitArray)\\n}`);},\\n\\n\\n\\ngetRankCover:([\\n_requiredPatt,\\n_optionalPatt=undefined,\\n_restPatt=undefined])=>\\nrankOrder.getPassStyleCover('copyArray')});\\n\\n\\n/**\\n * @param {CopyRecord<Passable>} specimen\\n * @param {CopyRecord<Pattern>} requiredPatt\\n * @param {CopyRecord<Pattern>} optionalPatt\\n * @returns {{\\n * requiredSpecimen: CopyRecord<Passable>,\\n * optionalSpecimen: CopyRecord<Passable>,\\n * restSpecimen: CopyRecord<Passable>\\n * }}\\n */\\nconst splitRecordParts=(specimen,requiredPatt,optionalPatt)=>{\\n/* Not frozen! Mutated in place*/\\n/** @type {[string, Passable][]} */\\nconst requiredEntries=[];\\n/** @type {[string, Passable][]} */\\nconst optionalEntries=[];\\n/** @type {[string, Passable][]} */\\nconst restEntries=[];\\nfor(const[name,value]of entries(specimen)){\\nif(passStyleHelpers.hasOwnPropertyOf(requiredPatt,name)){\\nrequiredEntries.push([name,value]);}else\\nif(passStyleHelpers.hasOwnPropertyOf(optionalPatt,name)){\\noptionalEntries.push([name,value]);}else\\n{\\nrestEntries.push([name,value]);}}\\n\\n\\nreturn harden({\\nrequiredSpecimen:fromUniqueEntries.fromUniqueEntries(requiredEntries),\\noptionalSpecimen:fromUniqueEntries.fromUniqueEntries(optionalEntries),\\nrestSpecimen:fromUniqueEntries.fromUniqueEntries(restEntries)});};\\n\\n\\n\\n/**\\n * Optional specimen values which are `undefined` pass unconditionally.\\n * We encode this with the `M.or` pattern so it also produces a good\\n * compression distinguishing `undefined` from absence.\\n *\\n * @param {CopyRecord<Pattern>} optionalPatt\\n * @param {string[]} names\\n * @returns {CopyRecord<Pattern>} The partialPatt\\n */\\nconst adaptRecordPattern=(optionalPatt,names)=>\\nfromUniqueEntries.fromUniqueEntries(names.map((name)=>[name,MM.opt(optionalPatt[name])]));\\n\\n/** @type {MatchHelper} */\\nconst matchSplitRecordHelper=makeFar.Far('match:splitRecord helper',{\\ncheckMatches:(\\nspecimen,\\n[requiredPatt,optionalPatt={},restPatt=MM.any()],\\ncheck)=>\\n{\\nif(!checkKind(specimen,'copyRecord',check)){\\nreturn false;}\\n\\nconst{requiredSpecimen,optionalSpecimen,restSpecimen}=\\nsplitRecordParts(specimen,requiredPatt,optionalPatt);\\n\\nconst partialNames=/** @type {string[]} */ownKeys(optionalSpecimen);\\nconst partialPatt=adaptRecordPattern(optionalPatt,partialNames);\\nreturn(\\ncheckMatches(requiredSpecimen,requiredPatt,check)&&\\npartialNames.every((name)=>\\ncheckMatches(\\noptionalSpecimen[name],\\npartialPatt[name],\\ncheck,\\n`${name}?`))&&\\n\\n\\ncheckMatches(restSpecimen,restPatt,check,'...rest'));},\\n\\n\\n\\n/**\\n * @param {Array} splitArray\\n * @param {Checker} check\\n */\\ncheckIsWellFormed:(splitArray,check)=>{\\nif(\\npassStyleOf.passStyleOf(splitArray)==='copyArray'&&(\\nsplitArray.length>=1||splitArray.length<=3))\\n{\\nconst[requiredPatt,optionalPatt=undefined,restPatt=undefined]=\\nsplitArray;\\nif(\\nisPattern(requiredPatt)&&\\npassStyleOf.passStyleOf(requiredPatt)==='copyRecord'&&(\\noptionalPatt===undefined||\\nisPattern(optionalPatt)&&\\npassStyleOf.passStyleOf(optionalPatt)==='copyRecord')&&(\\nrestPatt===undefined||isPattern(restPatt)))\\n{\\nreturn true;}}\\n\\n\\nreturn check(\\nfalse,\\nindex.redacted`Must be an array of a requiredPatt record, an optional optionalPatt record, and an optional restPatt: ${index.quote(\\nsplitArray)\\n}`);},\\n\\n\\n\\ngetRankCover:([\\nrequiredPatt,\\n_optionalPatt=undefined,\\n_restPatt=undefined])=>\\nrankOrder.getPassStyleCover(passStyleOf.passStyleOf(requiredPatt))});\\n\\n\\n/** @type {Record<string, MatchHelper>} */\\nconst HelpersByMatchTag=harden({\\n'match:any':matchAnyHelper,\\n'match:and':matchAndHelper,\\n'match:or':matchOrHelper,\\n'match:not':matchNotHelper,\\n\\n'match:scalar':matchScalarHelper,\\n'match:key':matchKeyHelper,\\n'match:pattern':matchPatternHelper,\\n'match:kind':matchKindHelper,\\n'match:tagged':matchTaggedHelper,\\n'match:bigint':matchBigintHelper,\\n'match:nat':matchNatHelper,\\n'match:string':matchStringHelper,\\n'match:symbol':matchSymbolHelper,\\n'match:remotable':matchRemotableHelper,\\n\\n'match:lt':matchLTHelper,\\n'match:lte':matchLTEHelper,\\n'match:gte':matchGTEHelper,\\n'match:gt':matchGTHelper,\\n\\n'match:arrayOf':matchArrayOfHelper,\\n'match:recordOf':matchRecordOfHelper,\\n'match:setOf':matchSetOfHelper,\\n'match:bagOf':matchBagOfHelper,\\n'match:mapOf':matchMapOfHelper,\\n'match:splitArray':matchSplitArrayHelper,\\n'match:splitRecord':matchSplitRecordHelper});\\n\\n\\nconst makeMatcher=(tag,payload)=>{\\nconst matcher=makeTagged.makeTagged(tag,payload);\\nassertPattern(matcher);\\nreturn matcher;};\\n\\n\\nconst makeKindMatcher=(kind)=>makeMatcher('match:kind',kind);\\n\\nconst AnyShape=makeMatcher('match:any',undefined);\\nconst ScalarShape=makeMatcher('match:scalar',undefined);\\nconst KeyShape=makeMatcher('match:key',undefined);\\nconst PatternShape=makeMatcher('match:pattern',undefined);\\nconst BooleanShape=makeKindMatcher('boolean');\\nconst NumberShape=makeKindMatcher('number');\\nconst BigIntShape=makeTagged.makeTagged('match:bigint',[]);\\nconst NatShape=makeTagged.makeTagged('match:nat',[]);\\nconst StringShape=makeTagged.makeTagged('match:string',[]);\\nconst SymbolShape=makeTagged.makeTagged('match:symbol',[]);\\nconst RecordShape=makeTagged.makeTagged('match:recordOf',[AnyShape,AnyShape]);\\nconst ArrayShape=makeTagged.makeTagged('match:arrayOf',[AnyShape]);\\nconst SetShape=makeTagged.makeTagged('match:setOf',[AnyShape]);\\nconst BagShape=makeTagged.makeTagged('match:bagOf',[AnyShape,AnyShape]);\\nconst MapShape=makeTagged.makeTagged('match:mapOf',[AnyShape,AnyShape]);\\nconst RemotableShape=makeKindMatcher('remotable');\\nconst ErrorShape=makeKindMatcher('error');\\nconst PromiseShape=makeKindMatcher('promise');\\nconst UndefinedShape=makeKindMatcher('undefined');\\n\\n/**\\n * For when the last element of the payload is the optional limits,\\n * so that when it is `undefined` it is dropped from the end of the\\n * payloads array.\\n *\\n * @param {string} tag\\n * @param {Passable[]} payload\\n */\\nconst makeLimitsMatcher=(tag,payload)=>{\\nif(payload[payload.length-1]===undefined){\\npayload=harden(payload.slice(0,payload.length-1));}\\n\\nreturn makeMatcher(tag,payload);};\\n\\n\\nconst makeRemotableMatcher=(label=undefined)=>\\nlabel===undefined?\\nRemotableShape:\\nmakeMatcher('match:remotable',harden({label}));\\n\\n/**\\n * @template T\\n * @param {T} empty\\n * @param {T} base\\n * @param {T} [optional]\\n * @param {T} [rest]\\n * @returns {T[]}\\n */\\nconst makeSplitPayload=(\\nempty,\\nbase,\\noptional=undefined,\\nrest=undefined)=>\\n{\\nif(rest){\\nreturn[base,optional||empty,rest];}\\n\\nif(optional){\\nreturn[base,optional];}\\n\\nreturn[base];};\\n\\n\\n/* //////////////////*/\\n\\n/** @type {MatcherNamespace} */\\nconst M=harden({\\nany:()=>AnyShape,\\nand:(...patts)=>makeMatcher('match:and',patts),\\nor:(...patts)=>makeMatcher('match:or',patts),\\nnot:(subPatt)=>makeMatcher('match:not',subPatt),\\n\\nscalar:()=>ScalarShape,\\nkey:()=>KeyShape,\\npattern:()=>PatternShape,\\nkind:makeKindMatcher,\\ntagged:(tagPatt=M.string(),payloadPatt=M.any())=>\\nmakeMatcher('match:tagged',harden([tagPatt,payloadPatt])),\\nboolean:()=>BooleanShape,\\nnumber:()=>NumberShape,\\nbigint:(limits=undefined)=>\\nlimits?makeLimitsMatcher('match:bigint',[limits]):BigIntShape,\\nnat:(limits=undefined)=>\\nlimits?makeLimitsMatcher('match:nat',[limits]):NatShape,\\nstring:(limits=undefined)=>\\nlimits?makeLimitsMatcher('match:string',[limits]):StringShape,\\nsymbol:(limits=undefined)=>\\nlimits?makeLimitsMatcher('match:symbol',[limits]):SymbolShape,\\nrecord:(limits=undefined)=>\\nlimits?M.recordOf(M.any(),M.any(),limits):RecordShape,\\narray:(limits=undefined)=>\\nlimits?M.arrayOf(M.any(),limits):ArrayShape,\\nset:(limits=undefined)=>limits?M.setOf(M.any(),limits):SetShape,\\nbag:(limits=undefined)=>\\nlimits?M.bagOf(M.any(),M.any(),limits):BagShape,\\nmap:(limits=undefined)=>\\nlimits?M.mapOf(M.any(),M.any(),limits):MapShape,\\nremotable:makeRemotableMatcher,\\nerror:()=>ErrorShape,\\npromise:()=>PromiseShape,\\nundefined:()=>UndefinedShape,\\nnull:()=>null,\\n\\nlt:(rightOperand)=>makeMatcher('match:lt',rightOperand),\\nlte:(rightOperand)=>makeMatcher('match:lte',rightOperand),\\neq:(key)=>{\\ncheckKey.assertKey(key);\\nreturn key===undefined?M.undefined():key;},\\n\\nneq:(key)=>M.not(M.eq(key)),\\ngte:(rightOperand)=>makeMatcher('match:gte',rightOperand),\\ngt:(rightOperand)=>makeMatcher('match:gt',rightOperand),\\n\\nrecordOf:(keyPatt=M.any(),valuePatt=M.any(),limits=undefined)=>\\nmakeLimitsMatcher('match:recordOf',[keyPatt,valuePatt,limits]),\\narrayOf:(subPatt=M.any(),limits=undefined)=>\\nmakeLimitsMatcher('match:arrayOf',[subPatt,limits]),\\nsetOf:(keyPatt=M.any(),limits=undefined)=>\\nmakeLimitsMatcher('match:setOf',[keyPatt,limits]),\\nbagOf:(keyPatt=M.any(),countPatt=M.any(),limits=undefined)=>\\nmakeLimitsMatcher('match:bagOf',[keyPatt,countPatt,limits]),\\nmapOf:(keyPatt=M.any(),valuePatt=M.any(),limits=undefined)=>\\nmakeLimitsMatcher('match:mapOf',[keyPatt,valuePatt,limits]),\\nsplitArray:(base,optional=undefined,rest=undefined)=>\\nmakeMatcher(\\n'match:splitArray',\\nmakeSplitPayload([],base,optional,rest)),\\n\\nsplitRecord:(base,optional=undefined,rest=undefined)=>\\nmakeMatcher(\\n'match:splitRecord',\\nmakeSplitPayload({},base,optional,rest)),\\n\\nsplit:(base,rest=undefined)=>{\\nif(passStyleOf.passStyleOf(harden(base))==='copyArray'){\\n/* TODO at-ts-expect-error works locally but not from @endo/exo*/\\n/* @ts-expect-error We know it should be an array*/\\nreturn M.splitArray(base,rest&&[],rest);}else\\n{\\nreturn M.splitRecord(base,rest&&{},rest);}},\\n\\n\\npartial:(base,rest=undefined)=>{\\nif(passStyleOf.passStyleOf(harden(base))==='copyArray'){\\n/* TODO at-ts-expect-error works locally but not from @endo/exo*/\\n/* @ts-expect-error We know it should be an array*/\\nreturn M.splitArray([],base,rest);}else\\n{\\nreturn M.splitRecord({},base,rest);}},\\n\\n\\n\\neref:(t)=>M.or(t,M.promise()),\\nopt:(t)=>M.or(M.undefined(),t),\\n\\ninterface:(interfaceName,methodGuards,options)=>\\n/* eslint-disable-next-line no-use-before-define*/\\nmakeInterfaceGuard(interfaceName,methodGuards,options),\\ncall:(...argPatterns)=>\\n/* eslint-disable-next-line no-use-before-define*/\\nmakeMethodGuardMaker('sync',argPatterns),\\ncallWhen:(...argGuards)=>\\n/* eslint-disable-next-line no-use-before-define*/\\nmakeMethodGuardMaker('async',argGuards),\\n\\nawait:(argPattern)=>\\n/* eslint-disable-next-line no-use-before-define*/\\nmakeAwaitArgGuard(argPattern),\\nraw:()=>\\n/* eslint-disable-next-line no-use-before-define*/\\nmakeRawGuard()});\\n\\n\\nreturn harden({\\ncheckMatches,\\nmatches,\\nmustMatch,\\nassertPattern,\\nisPattern,\\ngetRankCover,\\nM,\\nkindOf});};\\n\\n\\n\\n/* Only include those whose meaning is independent of an imputed sort order*/\\n/* of remotables, or of encoding of passable as sortable strings. Thus,*/\\n/* getRankCover is omitted. To get one, you'd need to instantiate*/\\n/* `makePatternKit()` yourself. Since there are currently no external*/\\n/* uses of `getRankCover`, for clarity during development, `makePatternKit`*/\\n/* is not currently exported.*/\\nconst{\\ncheckMatches,\\nmatches,\\nmustMatch,\\nassertPattern,\\nisPattern,\\ngetRankCover,\\nM,\\nkindOf}=\\nmakePatternKit();\\n\\nMM=M;\\n\\n/* //////////////////////////// Guards ///////////////////////////////////////*/\\n\\n/* M.await(...)*/\\nconst AwaitArgGuardPayloadShape=harden({\\nargGuard:M.pattern()});\\n\\n\\nconst AwaitArgGuardShape=M.kind('guard:awaitArgGuard');\\n\\n/**\\n * @param {any} specimen\\n * @returns {specimen is AwaitArgGuard}\\n */\\nconst isAwaitArgGuard=(specimen)=>\\nmatches(specimen,AwaitArgGuardShape);\\nharden(isAwaitArgGuard);\\n\\n/**\\n * @param {any} specimen\\n * @returns {asserts specimen is AwaitArgGuard}\\n */\\nconst assertAwaitArgGuard=(specimen)=>{\\nmustMatch(specimen,AwaitArgGuardShape,'awaitArgGuard');};\\n\\nharden(assertAwaitArgGuard);\\n\\n/**\\n * @param {Pattern} argPattern\\n * @returns {AwaitArgGuard}\\n */\\nconst makeAwaitArgGuard=(argPattern)=>{\\n/** @type {AwaitArgGuard} */\\nconst result=makeTagged.makeTagged('guard:awaitArgGuard',{\\nargGuard:argPattern});\\n\\nassertAwaitArgGuard(result);\\nreturn result;};\\n\\n\\n/* M.raw()*/\\n\\nconst RawGuardPayloadShape=M.record();\\n\\nconst RawGuardShape=M.kind('guard:rawGuard');\\n\\nconst isRawGuard=(specimen)=>matches(specimen,RawGuardShape);\\n\\nconst assertRawGuard=(specimen)=>\\nmustMatch(specimen,RawGuardShape,'rawGuard');\\n\\n/**\\n * @returns {RawGuard}\\n */\\nconst makeRawGuard=()=>makeTagged.makeTagged('guard:rawGuard',{});\\n\\n/* M.call(...)*/\\n/* M.callWhen(...)*/\\n\\nconst SyncValueGuardShape=M.or(RawGuardShape,M.pattern());\\n\\nconst SyncValueGuardListShape=M.arrayOf(SyncValueGuardShape);\\n\\nconst ArgGuardShape=M.or(RawGuardShape,AwaitArgGuardShape,M.pattern());\\nconst ArgGuardListShape=M.arrayOf(ArgGuardShape);\\n\\nconst SyncMethodGuardPayloadShape=harden({\\ncallKind:'sync',\\nargGuards:SyncValueGuardListShape,\\noptionalArgGuards:M.opt(SyncValueGuardListShape),\\nrestArgGuard:M.opt(SyncValueGuardShape),\\nreturnGuard:SyncValueGuardShape});\\n\\n\\nconst AsyncMethodGuardPayloadShape=harden({\\ncallKind:'async',\\nargGuards:ArgGuardListShape,\\noptionalArgGuards:M.opt(ArgGuardListShape),\\nrestArgGuard:M.opt(SyncValueGuardShape),\\nreturnGuard:SyncValueGuardShape});\\n\\n\\nconst MethodGuardPayloadShape=M.or(\\nSyncMethodGuardPayloadShape,\\nAsyncMethodGuardPayloadShape);\\n\\n\\nconst MethodGuardShape=M.kind('guard:methodGuard');\\n\\n/**\\n * @param {any} specimen\\n * @returns {asserts specimen is MethodGuard}\\n */\\nconst assertMethodGuard=(specimen)=>{\\nmustMatch(specimen,MethodGuardShape,'methodGuard');};\\n\\nharden(assertMethodGuard);\\n\\n/**\\n * @param {'sync'|'async'} callKind\\n * @param {ArgGuard[]} argGuards\\n * @param {ArgGuard[]} [optionalArgGuards]\\n * @param {SyncValueGuard} [restArgGuard]\\n * @returns {MethodGuardMaker}\\n */\\nconst makeMethodGuardMaker=(\\ncallKind,\\nargGuards,\\noptionalArgGuards=undefined,\\nrestArgGuard=undefined)=>\\n\\nharden({\\noptional:(...optArgGuards)=>{\\noptionalArgGuards===undefined||\\nindex.throwRedacted`Can only have one set of optional guards`;\\nrestArgGuard===undefined||\\nindex.throwRedacted`optional arg guards must come before rest arg`;\\nreturn makeMethodGuardMaker(callKind,argGuards,optArgGuards);},\\n\\nrest:(rArgGuard)=>{\\nrestArgGuard===undefined||index.throwRedacted`Can only have one rest arg`;\\nreturn makeMethodGuardMaker(\\ncallKind,\\nargGuards,\\noptionalArgGuards,\\nrArgGuard);},\\n\\n\\nreturns:(returnGuard=M.undefined())=>{\\n/** @type {MethodGuard} */\\nconst result=makeTagged.makeTagged('guard:methodGuard',{\\ncallKind,\\nargGuards,\\noptionalArgGuards,\\nrestArgGuard,\\nreturnGuard});\\n\\nassertMethodGuard(result);\\nreturn result;}});\\n\\n\\n\\nconst InterfaceGuardPayloadShape=M.splitRecord(\\n{\\ninterfaceName:M.string(),\\nmethodGuards:M.recordOf(M.string(),MethodGuardShape)},\\n\\n{\\ndefaultGuards:M.or(M.undefined(),'passable','raw'),\\nsloppy:M.boolean(),\\nsymbolMethodGuards:M.mapOf(M.symbol(),MethodGuardShape)});\\n\\n\\n\\nconst InterfaceGuardShape=M.kind('guard:interfaceGuard');\\n\\n/**\\n * @param {any} specimen\\n * @returns {asserts specimen is InterfaceGuard}\\n */\\nconst assertInterfaceGuard=(specimen)=>{\\nmustMatch(specimen,InterfaceGuardShape,'interfaceGuard');};\\n\\nharden(assertInterfaceGuard);\\n\\n/**\\n * @template {Record<PropertyKey, MethodGuard>} [M = Record<PropertyKey, MethodGuard>]\\n * @param {string} interfaceName\\n * @param {M} methodGuards\\n * @param {{ sloppy?: boolean, defaultGuards?: DefaultGuardType }} [options]\\n * @returns {InterfaceGuard<M>}\\n */\\nconst makeInterfaceGuard=(interfaceName,methodGuards,options={})=>{\\nconst{sloppy=false,defaultGuards=sloppy?'passable':undefined}=\\noptions;\\n/* For backwards compatibility, string-keyed method guards are represented in*/\\n/* a CopyRecord. But symbol-keyed methods cannot be, so we put those in a*/\\n/* CopyMap when present.*/\\n/** @type {Record<string, MethodGuard>} */\\nconst stringMethodGuards={};\\n/** @type {Array<[symbol, MethodGuard]>} */\\nconst symbolMethodGuardsEntries=[];\\nfor(const key of ownKeys(methodGuards)){\\nconst value=methodGuards[/** @type {string} */key];\\nif(typeof key==='symbol'){\\nsymbolMethodGuardsEntries.push([key,value]);}else\\n{\\nstringMethodGuards[key]=value;}}\\n\\n\\n/** @type {InterfaceGuard} */\\nconst result=makeTagged.makeTagged('guard:interfaceGuard',{\\ninterfaceName,\\nmethodGuards:stringMethodGuards,\\n...(symbolMethodGuardsEntries.length?\\n{symbolMethodGuards:checkKey.makeCopyMap(symbolMethodGuardsEntries)}:\\n{}),\\ndefaultGuards});\\n\\nassertInterfaceGuard(result);\\nreturn(/** @type {InterfaceGuard<M>} */result);};\\n\\n\\nconst GuardPayloadShapes=harden({\\n'guard:awaitArgGuard':AwaitArgGuardPayloadShape,\\n'guard:rawGuard':RawGuardPayloadShape,\\n'guard:methodGuard':MethodGuardPayloadShape,\\n'guard:interfaceGuard':InterfaceGuardPayloadShape});exports.ArgGuardListShape=ArgGuardListShape;exports.AwaitArgGuardShape=AwaitArgGuardShape;exports.InterfaceGuardPayloadShape=InterfaceGuardPayloadShape;exports.InterfaceGuardShape=InterfaceGuardShape;exports.M=M;exports.MethodGuardPayloadShape=MethodGuardPayloadShape;exports.MethodGuardShape=MethodGuardShape;exports.RawGuardShape=RawGuardShape;exports.SyncValueGuardListShape=SyncValueGuardListShape;exports.SyncValueGuardShape=SyncValueGuardShape;exports.assertAwaitArgGuard=assertAwaitArgGuard;exports.assertInterfaceGuard=assertInterfaceGuard;exports.assertMethodGuard=assertMethodGuard;exports.assertPattern=assertPattern;exports.assertRawGuard=assertRawGuard;exports.checkMatches=checkMatches;exports.defaultLimits=defaultLimits;exports.getRankCover=getRankCover;exports.isAwaitArgGuard=isAwaitArgGuard;exports.isPattern=isPattern;exports.isRawGuard=isRawGuard;exports.kindOf=kindOf;exports.matches=matches;exports.mustMatch=mustMatch;\",\n \"node_modules/@endo/patterns/src/types.js\": \"\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n'use strict';/*/ <reference types=\\\"ses\\\"/>*/ /* NB: as of TS 5.5 nightly, TS thinks RankCover and Checker \\\"is declared but never read\\\" but they are*/ /**\\n * @import {Checker, CopyArray, CopyRecord, CopyTagged, Passable, PassStyle, Primitive, RemotableObject} from '@endo/pass-style';\\n * @import {RankCompare, RankCover} from '@endo/marshal';\\n */ /**\\n * @typedef {Exclude<Passable<RemotableObject, never>, Error | Promise>} Key\\n *\\n * Keys are Passable arbitrarily-nested pass-by-copy containers\\n * (CopyArray, CopyRecord, CopySet, CopyBag, CopyMap) in which every\\n * non-container leaf is either a Passable primitive value or a Remotable (a\\n * remotely-accessible object or presence for a remote object), or such leaves\\n * in isolation with no container.\\n *\\n * Keys are so named because they can be used as keys in CopyMaps and\\n * [agoric-sdk Stores](https://github.com/Agoric/agoric-sdk/blob/master/packages/store/docs/store-taxonomy.md),\\n * and as elements in CopySets and CopyBags.\\n *\\n * Keys cannot contain promises or errors, as these do not have useful\\n * distributed equality semantics. Keys also cannot contain any CopyTagged\\n * except for those recognized as CopySets, CopyBags, and CopyMaps.\\n *\\n * Be aware that we may recognize more CopyTaggeds over time, including\\n * CopyTaggeds recognized as Keys.\\n *\\n * Distributed equality is location independent.\\n * The same two Keys, passed to another location, will be `keyEQ` there iff\\n * they are `keyEQ` here. (`keyEQ` tests equality according to the\\n * key distributed equality semantics.)\\n */ /**\\n * @typedef {Primitive | RemotableObject} ScalarKey\\n */ /**\\n * @callback GetRankCover\\n * @param {Passable} payload\\n * @param {KeyToDBKey} encodePassable\\n * @returns {RankCover}\\n */ /**\\n * @callback KeyToDBKey\\n * @param {Key} key\\n * @returns {string}\\n */ /**\\n * @typedef {Exclude<Passable, Error | Promise>} Pattern\\n *\\n * Patterns are Passable arbitrarily-nested pass-by-copy containers\\n * (CopyArray, CopyRecord, CopySet, CopyBag, CopyMap) in which every\\n * non-container leaf is either a Key or a Matcher, or such leaves in isolation\\n * with no container.\\n *\\n * A Pattern acts as a declarative total predicate over Passables, where each\\n * Passable is either matched or not matched by it. Every Key is also a Pattern\\n * that matches only \\\"itself\\\", i.e., Keys that are `keyEQ` to it according to\\n * the key distributed equality semantics.\\n *\\n * Patterns cannot contain promises or errors, as these do\\n * not have useful distributed equality or matching semantics. Likewise,\\n * no Pattern can distinguish among promises, or distinguish among errors.\\n * Patterns also cannot contain any CopyTaggeds except for those recognized as\\n * CopySets, CopyBags, CopyMaps, or Matchers.\\n *\\n * Be aware that we may recognize more CopyTaggeds over time, including\\n * CopyTaggeds recognized as Patterns.\\n *\\n * Whether a Passable is matched by a given Pattern is location independent.\\n * If a given Passable and Pattern are passed to another location,\\n * the Passable will be matched by the Pattern there iff the Passable is matched\\n * by the Pattern here.\\n *\\n * Patterns are often used in a type-like manner, to represent the category\\n * of Passables that the Pattern is intended* to match. To keep this\\n * distinction clear, we often use the suffix \\\"Shape\\\" rather than \\\"Pattern\\\"\\n * to avoid confusion when the Pattern itself represents\\n * some category of Pattern. For example, an \\\"AmountShape\\\" represents the\\n * category of Amounts. And \\\"AmountPatternShape\\\" represents the\\n * category of Patterns over Amounts.\\n *\\n * * We say \\\"intended\\\" above because Patterns, in order to be declarative\\n * and Passable, cannot have the generality of predicates written in a\\n * Turing-universal programming language. Rather, to represent the category of\\n * things intended to be a Foo, a FooShape should reliably\\n * accept all Foos and reject only non-Foos. However, a FooShape may also accept\\n * non-Foos that \\\"look like\\\" or \\\"have the same shape as\\\" genuine Foos.\\n * An accurate predicate for e.g. input validation would need to supplement the\\n * Pattern check with code to detect the residual cases.\\n * We hope the \\\"Shape\\\" metaphor helps remind us of this type-like imprecision\\n * of Patterns.\\n */ /* TODO parameterize CopyTagged to support these refinements*/ /**\\n * @template {Key} [K=Key]\\n * @typedef {CopyTagged<'copySet', K[]>} CopySet\\n *\\n * A Passable collection of Keys that are all mutually distinguishable\\n * according to the key distributed equality semantics exposed by `keyEQ`.\\n */ /**\\n * @template {Key} [K=Key]\\n * @typedef {CopyTagged<'copyBag', [K, bigint][]>} CopyBag\\n *\\n * A Passable collection of entries with Keys that are all mutually distinguishable\\n * according to the key distributed equality semantics exposed by `keyEQ`,\\n * each with a corresponding positive cardinality.\\n */ /**\\n * @template {Key} [K=Key]\\n * @template {Passable} [V=Passable]\\n * @typedef {CopyTagged<'copyMap', { keys: K[], values: V[] }>} CopyMap\\n *\\n * A Passable collection of entries with Keys that are all mutually distinguishable\\n * according to the key distributed equality semantics exposed by `keyEQ`,\\n * each with a corresponding Passable value.\\n */ /**\\n * @typedef {CopySet | CopyBag | CopyMap} KeyCollection\\n *\\n * CopySet, CopyBag, and CopyMap all store Keys in reverse rankOrder,\\n * which supports generalized utilities.\\n */ /* TODO: enumerate Matcher tag values?*/ /**\\n * @typedef {CopyTagged<`match:${string}`, Passable>} Matcher\\n *\\n * A Pattern representing the predicate characterizing a category of Passables,\\n * such as strings or 8-bit unsigned integer numbers or CopyArrays of Remotables.\\n */ /**\\n * @typedef {RankCompare} FullCompare\\n * A `FullCompare` function satisfies all the invariants stated below for\\n * `RankCompare`'s relation with KeyCompare.\\n * In addition, its equality is as precise as the `KeyCompare`\\n * comparison defined below, in that, for all Keys `x` and `y`,\\n * `FullCompare(x, y) === 0` iff `KeyCompare(x, y) === 0`.\\n *\\n * For non-Key inputs, a `FullCompare` should be exactly as imprecise as\\n * `RankCompare`. For example, both will treat all errors as in the same\\n * equivalence class. Both will treat all promises as in the same\\n * equivalence class. Both will order tagged records the same way, which is\\n * admittedly weird because some (such as CopySets, CopyBags, and CopyMaps)\\n * will be considered Keys while others will be considered non-Keys.\\n */ /**\\n * @typedef {object} RankComparatorKit\\n * @property {RankCompare} comparator\\n * @property {RankCompare} antiComparator\\n */ /**\\n * @typedef {object} FullComparatorKit\\n * @property {FullCompare} comparator\\n * @property {FullCompare} antiComparator\\n */ /**\\n * @typedef {-1 | 0 | 1 | NaN} KeyComparison\\n * The result of a `KeyCompare` function that defines a meaningful\\n * and meaningfully precise partial order of Key values. See `KeyCompare`.\\n */ /**\\n * @callback KeyCompare\\n * `compareKeys` implements a partial order over Keys --- it defines relative\\n * position between two Keys but leaves some pairs incomparable (for example,\\n * subsets over sets is a partial order in which {} precedes {x} and {y}, which\\n * are mutually incomparable but both precede {x, y}). As with the rank ordering\\n * produced by `compareRank`, -1, 0, and 1 respectively mean \\\"less than\\\",\\n * \\\"equivalent to\\\", and \\\"greater than\\\". NaN means \\\"incomparable\\\" --- the first\\n * key is not less, equivalent, or greater than the second.\\n *\\n * By using NaN for \\\"incomparable\\\", the normal equivalence for using\\n * the return value in a comparison is preserved.\\n * `compareKeys(left, right) >= 0` iff `left` is greater than or\\n * equivalent to `right` in the partial ordering.\\n *\\n * Key order (a partial order) and rank order (a total preorder) are\\n * co-designed to support efficient range search for Key-based queries\\n * (@see {@link ../README.md#rank-order-and-key-order}).\\n *\\n * @param {Key} left\\n * @param {Key} right\\n * @returns {KeyComparison}\\n */ /**\\n * @callback CheckPattern\\n * @param {Passable} allegedPattern\\n * @param {Checker} check\\n * @returns {boolean}\\n */ /**\\n * @typedef {object} AllLimits\\n * @property {number} decimalDigitsLimit\\n * @property {number} stringLengthLimit\\n * @property {number} symbolNameLengthLimit\\n * @property {number} numPropertiesLimit\\n * @property {number} propertyNameLengthLimit\\n * @property {number} arrayLengthLimit\\n * @property {number} numSetElementsLimit\\n * @property {number} numUniqueBagElementsLimit\\n * @property {number} numMapEntriesLimit\\n */ /**\\n * @typedef {Partial<AllLimits>} Limits\\n */ /**\\n * @typedef {Exclude<PassStyle, 'tagged'> |\\n * 'copySet' | 'copyBag' | 'copyMap' |\\n * `match:${any}` | `guard:${any}`\\n * } Kind\\n * It is either a PassStyle other than 'tagged', or, if the underlying\\n * PassStyle is 'tagged', then the `getTag` value for tags that are\\n * recognized at the @endo/patterns level of abstraction. For each of those\\n * tags, a tagged record only has that kind if it satisfies the invariants\\n * that the @endo/patterns level associates with that kind.\\n */ /**\\n * @typedef {object} PatternMatchers\\n *\\n * @property {() => Matcher} any\\n * Matches any Passable.\\n *\\n * @property {(...subPatts: Pattern[]) => Matcher} and\\n * Matches against the intersection of all sub-Patterns.\\n *\\n * @property {(...subPatts: Pattern[]) => Matcher} or\\n * Matches against the union of all sub-Patterns\\n * (requiring a successful match against at least one).\\n *\\n * @property {(subPatt: Pattern) => Matcher} not\\n * Matches against the negation of the sub-Pattern.\\n *\\n * @property {() => Matcher} scalar\\n * Matches any Passable primitive value or Remotable.\\n * All matched values are Keys.\\n *\\n * @property {() => Matcher} key\\n * Matches any value that can be a key in a CopyMap\\n * or an element in a CopySet or CopyBag.\\n * All matched values are also valid Patterns that match only themselves.\\n *\\n * @property {() => Matcher} pattern\\n * Matches any Pattern that can be used to characterize Passables.\\n * A Pattern cannot contain promises or errors,\\n * as these are not stable enough to usefully match.\\n *\\n * @property {(kind: PassStyle | string) => Matcher} kind\\n * When `kind` specifies a PassStyle other than \\\"tagged\\\",\\n * matches any value having that PassStyle.\\n * Otherwise, when `kind` specifies a known tagged record tag\\n * (such as 'copySet', 'copyBag', 'copyMap', or 'match:scalar'),\\n * matches any CopyTagged with that tag and a valid tag-specific payload.\\n * Otherwise, does not match any value.\\n * TODO: Reject attempts to create a kind matcher with unknown `kind`?\\n *\\n * @property {(tagPatt?: Pattern, payloadPatt?: Pattern) => Matcher} tagged\\n * For matching an arbitrary Passable Tagged object, whether it has a\\n * recognized kind or not. If `tagPatt` is omitted, it defaults to\\n * `M.string()`. If `payloadPatt` is omitted, it defaults to\\n * `M.any()`.\\n *\\n * @property {() => Matcher} boolean\\n * Matches `true` or `false`.\\n *\\n * @property {() => Matcher} number\\n * Matches any floating point number,\\n * including `NaN` and either signed Infinity.\\n *\\n * @property {(limits?: Limits) => Matcher} bigint\\n * Matches any bigint, subject to limits.\\n *\\n * @property {(limits?: Limits) => Matcher} nat\\n * Matches any non-negative bigint, subject to limits.\\n *\\n * @property {(limits?: Limits) => Matcher} string\\n * Matches any string, subject to limits.\\n *\\n * @property {(limits?: Limits) => Matcher} symbol\\n * Matches any registered or well-known symbol,\\n * subject to limits.\\n *\\n * @property {(limits?: Limits) => Matcher} record\\n * Matches any CopyRecord, subject to limits.\\n *\\n * @property {(limits?: Limits) => Matcher} array\\n * Matches any CopyArray, subject to limits.\\n *\\n * @property {(limits?: Limits) => Matcher} set\\n * Matches any CopySet, subject to limits.\\n *\\n * @property {(limits?: Limits) => Matcher} bag\\n * Matches any CopyBag, subject to limits.\\n *\\n * @property {(limits?: Limits) => Matcher} map\\n * Matches any CopyMap, subject to limits.\\n *\\n * @property {(label?: string) => Matcher} remotable\\n * Matches a far object or its remote presence.\\n * The optional `label` is purely for diagnostic purposes and does not\\n * add any constraints.\\n *\\n * @property {() => Matcher} error\\n * Matches any error object.\\n * Error objects are Passable, but are neither Keys nor Patterns.\\n * They do not have a useful identity.\\n *\\n * @property {() => Matcher} promise\\n * Matches any promise object.\\n * Promises are Passable, but are neither Keys nor Patterns.\\n * They do not have a useful identity.\\n *\\n * @property {() => Matcher} undefined\\n * Matches the exact value `undefined`.\\n * All keys including `undefined` are already valid Patterns and\\n * so can validly represent themselves.\\n * But optional Pattern arguments `(patt = undefined) => ...`\\n * treat explicit `undefined` as omission of the argument.\\n * Thus, when a passed Pattern does not also need to be a Key,\\n * we recommend passing `M.undefined()` rather than `undefined`.\\n *\\n * @property {() => null} null\\n * Returns `null`, which matches only itself.\\n *\\n * @property {(rightOperand :Key) => Matcher} lt\\n * Matches any value that compareKeys reports as less than rightOperand.\\n *\\n * @property {(rightOperand :Key) => Matcher} lte\\n * Matches any value that compareKeys reports as less than or equal to\\n * rightOperand.\\n *\\n * @property {(key :Key) => Matcher} eq\\n * Matches any value that is equal to key.\\n *\\n * @property {(key :Key) => Matcher} neq\\n * Matches any value that is not equal to key.\\n *\\n * @property {(rightOperand :Key) => Matcher} gte\\n * Matches any value that compareKeys reports as greater than or equal\\n * to rightOperand.\\n *\\n * @property {(rightOperand :Key) => Matcher} gt\\n * Matches any value that compareKeys reports as greater than\\n * rightOperand.\\n *\\n * @property {(subPatt?: Pattern, limits?: Limits) => Matcher} arrayOf\\n * Matches any CopyArray whose elements are all matched by `subPatt`\\n * if defined, subject to limits.\\n *\\n * @property {(keyPatt?: Pattern,\\n * valuePatt?: Pattern,\\n * limits?: Limits\\n * ) => Matcher} recordOf\\n * Matches any CopyRecord whose keys are all matched by `keyPatt`\\n * if defined and values are all matched by `valuePatt` if defined,\\n * subject to limits.\\n *\\n * @property {(keyPatt?: Pattern, limits?: Limits) => Matcher} setOf\\n * Matches any CopySet whose elements are all matched by `keyPatt`\\n * if defined, subject to limits.\\n *\\n * @property {(keyPatt?: Pattern,\\n * countPatt?: Pattern,\\n * limits?: Limits\\n * ) => Matcher} bagOf\\n * Matches any CopyBag whose elements are all matched by `keyPatt`\\n * if defined and the cardinality of each is matched by `countPatt`\\n * if defined, subject to limits.\\n * `countPatt` is expected to rarely be useful,\\n * but is provided to minimize surprise.\\n *\\n * @property {(keyPatt?: Pattern,\\n * valuePatt?: Pattern,\\n * limits?: Limits\\n * ) => Matcher} mapOf\\n * Matches any CopyMap whose keys are all matched by `keyPatt` if defined\\n * and values are all matched by `valuePatt` if defined,\\n * subject to limits.\\n *\\n * @property {(required: Pattern[],\\n * optional?: Pattern[],\\n * rest?: Pattern,\\n * ) => Matcher} splitArray\\n * Matches any array --- typically an arguments list --- consisting of\\n * - an initial portion matched by `required`, and\\n * - a middle portion of length up to the length of `optional` that is\\n * matched by the equal-length prefix of `optional` if `optional` is\\n * defined, and\\n * - a remainder that is matched by `rest` if `rest` is defined.\\n * The array must be at least as long as `required`\\n * but its remainder can be arbitrarily short.\\n * Any array elements beyond the summed length of `required` and `optional`\\n * are collected and matched against `rest`.\\n *\\n * @property {(required: CopyRecord<Pattern>,\\n * optional?: CopyRecord<Pattern>,\\n * rest?: Pattern,\\n * ) => Matcher} splitRecord\\n * Matches any CopyRecord that can be split into component CopyRecords\\n * as follows:\\n * - all properties corresponding with a property of `required`\\n * - all properties corresponding with a property of `optional`\\n * but not corresponding with a property of `required`\\n * - all other properties\\n * where the first component is matched by `required`,\\n * the second component is matched by the subset of `optional`\\n * corresponding with its properties if `optional` is defined, and\\n * the third component is matched by `rest` if defined.\\n * The CopyRecord must have all properties that appear on `required`,\\n * but may omit properties that appear on `optional`.\\n *\\n * @property {(basePatt: CopyRecord<any> | CopyArray<any>,\\n * rest?: Pattern,\\n * ) => Matcher} split\\n * Deprecated. Use `M.splitArray` or `M.splitRecord` instead.\\n * An array or record is split into the first part that is matched by\\n * `basePatt`, and the remainder, which is matched against `rest` if present.\\n *\\n * @property {(basePatt: CopyRecord<any> | CopyArray<any>,\\n * rest?: Pattern,\\n * ) => Matcher} partial\\n * Deprecated. Use `M.splitArray` or `M.splitRecord` instead.\\n * An array or record is split into the first part that is matched by\\n * `basePatt`, and the remainder, which is matched against `rest` if present.\\n * `M.partial` differs from `M.split` in the handling of data that is\\n * described in `basePatt` but absent in a provided specimen:\\n * - For a CopyRecord, `M.partial` ignores properties of `basePatt`\\n * that are not present on the specimen.\\n * - For a CopyArray, `M.partial` ignores elements of `basePatt`\\n * at indices beyond the maximum index of the specimen.\\n *\\n * @property {(subPatt: Pattern) => Pattern} eref\\n * Matches any Passable that is either matched by `subPatt` or is a promise object.\\n * Note that validation is immediate, so (unlike the TypeScript `ERef<T>`\\n * type) `M.eref` matches a promise object whose fulfillment value is\\n * _not_ matched by `subPatt`.\\n * For describing a top-level parameter,\\n * `M.callWhen(..., M.await(p), ...)` is preferred over `M.call(..., M.eref(p), ...)`\\n * because the former always checks against the sub-Pattern (awaiting fulfillment\\n * if necessary) while the latter bypasses such checks when the relevant argument\\n * is a promise.\\n *\\n * @property {(subPatt: Pattern) => Pattern} opt\\n * Matches any Passable that is matched by `subPatt` or is the exact value `undefined`.\\n */ /**\\n * @typedef {undefined | 'passable' | 'raw'} DefaultGuardType\\n */ /**\\n * @typedef {<M extends Record<PropertyKey, MethodGuard>>(\\n * interfaceName: string,\\n * methodGuards: M,\\n * options: {defaultGuards?: undefined, sloppy?: false }) => InterfaceGuard<M>\\n * } MakeInterfaceGuardStrict\\n */ /**\\n * @typedef {(\\n * interfaceName: string,\\n * methodGuards: any,\\n * options: {defaultGuards?: 'passable' | 'raw', sloppy?: true }) => InterfaceGuard<any>\\n * } MakeInterfaceGuardSloppy\\n */ /**\\n * @typedef {<M extends Record<PropertyKey, MethodGuard>>(\\n * interfaceName: string,\\n * methodGuards: M,\\n * options?: {defaultGuards?: DefaultGuardType, sloppy?: boolean}) => InterfaceGuard<M>\\n * } MakeInterfaceGuardGeneral\\n */ /** @typedef {MakeInterfaceGuardStrict & MakeInterfaceGuardSloppy & MakeInterfaceGuardGeneral} MakeInterfaceGuard */ /**\\n * @typedef {object} GuardMakers\\n *\\n * @property {MakeInterfaceGuard} interface\\n * Guard the interface of an exo object\\n *\\n * @property {(...argPatterns: SyncValueGuard[]) => MethodGuardMaker} call\\n * Guard a synchronous call. Arguments not guarded by `M.raw()` are\\n * automatically hardened and must be at least Passable.\\n *\\n * @property {(...argGuards: ArgGuard[]) => MethodGuardMaker} callWhen\\n * Guard an async call. Arguments not guarded by `M.raw()` are automatically\\n * hardened and must be at least Passable.\\n *\\n * @property {(argPattern: Pattern) => AwaitArgGuard} await\\n * Guard a positional parameter in `M.callWhen`, awaiting it and matching its\\n * fulfillment against the provided pattern.\\n * For example, `M.callWhen(M.await(M.nat())).returns()` will await the first\\n * argument, check that its fulfillment satisfies `M.nat()`, and only then call\\n * the guarded method with that fulfillment. If the argument is a non-promise\\n * value that already satisfies `M.nat()`, then the result of `await`ing it will\\n * still pass, and `M.callWhen` will still delay the guarded method call to a\\n * future turn.\\n * If the argument is a promise that rejects rather than fulfills, or if its\\n * fulfillment does not satisfy the nested pattern, then the call is rejected\\n * without ever invoking the guarded method.\\n *\\n * Any `AwaitArgGuard` may not appear as a rest pattern or a result pattern,\\n * only a top-level single parameter pattern.\\n *\\n * @property {() => RawGuard} raw\\n * In parameter position, pass this argument through without any hardening or checking.\\n * In rest position, pass the rest of the arguments through without any hardening or checking.\\n * In return position, return the result without any hardening or checking.\\n */ /**\\n * @typedef {PatternMatchers & GuardMakers} MatcherNamespace\\n */ /** @typedef {(...args: any[]) => any} Method */ /**\\n * @template {Record<PropertyKey, MethodGuard>} [T=Record<PropertyKey, MethodGuard>]\\n * @typedef {{\\n * interfaceName: string,\\n * methodGuards:\\n * Omit<T, symbol> & Partial<{ [K in Extract<keyof T, symbol>]: never }>,\\n * symbolMethodGuards?:\\n * CopyMap<Extract<keyof T, symbol>, T[Extract<keyof T, symbol>]>,\\n * defaultGuards?: DefaultGuardType,\\n * sloppy?: boolean,\\n * }} InterfaceGuardPayload\\n */ /**\\n * @template {Record<PropertyKey, MethodGuard>} [T=Record<PropertyKey, MethodGuard>]\\n * @typedef {CopyTagged<'guard:interfaceGuard', InterfaceGuardPayload<T>>} InterfaceGuard\\n */ /**\\n * @typedef {MethodGuardOptional & MethodGuardRestReturns} MethodGuardMaker\\n * A method name and parameter/return signature like:\\n * ```js\\n * foo(a, b, c = d, ...e) => f\\n * ```\\n * should be guarded by something like:\\n * ```js\\n * {\\n * ...otherMethodGuards,\\n * foo: M.call(AShape, BShape).optional(CShape).rest(EShape).returns(FShape),\\n * }\\n * ```\\n/**\\n * @typedef {object} MethodGuardReturns\\n * @property {(returnGuard?: SyncValueGuard) => MethodGuard} returns\\n * Arguments have been specified, now finish by creating a `MethodGuard`.\\n * If the return guard is not `M.raw()`, the return value is automatically\\n * hardened and must be Passable.\\n */ /**\\n * @typedef {object} MethodGuardRest\\n * @property {(restArgGuard: SyncValueGuard) => MethodGuardReturns} rest\\n * If the rest argument guard is not `M.raw()`, all rest arguments are\\n * automatically hardened and must be Passable.\\n */ /**\\n * @typedef {MethodGuardRest & MethodGuardReturns} MethodGuardRestReturns\\n * Mandatory and optional arguments have been specified, now specify `rest`, or\\n * finish with `returns`.\\n */ /**\\n * @typedef {object} MethodGuardOptional\\n * @property {(...optArgGuards: ArgGuard[]) => MethodGuardRestReturns} optional\\n * Optional arguments not guarded with `M.raw()` are automatically hardened and\\n * must be Passable.\\n */ /**\\n * @typedef {{\\n * callKind: 'sync' | 'async',\\n * argGuards: ArgGuard[],\\n * optionalArgGuards?: ArgGuard[],\\n * restArgGuard?: SyncValueGuard,\\n * returnGuard: SyncValueGuard,\\n * }} MethodGuardPayload\\n */ /**\\n * @typedef {CopyTagged<'guard:methodGuard', MethodGuardPayload>} MethodGuard\\n */ /**\\n * @typedef {{\\n * argGuard: Pattern\\n * }} AwaitArgGuardPayload\\n */ /**\\n * @typedef {CopyTagged<'guard:awaitArgGuard', AwaitArgGuardPayload>} AwaitArgGuard\\n */ /**\\n * @typedef {{}} RawGuardPayload\\n */ /**\\n * @typedef {CopyTagged<'guard:rawGuard', RawGuardPayload>} RawGuard\\n */ /** @typedef {RawGuard | Pattern} SyncValueGuard */ /** @typedef {AwaitArgGuard | RawGuard | Pattern} ArgGuard */\",\n \"node_modules/@endo/promise-kit/index.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var promiseExecutorKit=require('./src/promise-executor-kit.js');var memoRace=require('./src/memo-race.js');var isPromise=require('./src/is-promise.js');\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nrequire('./src/types.js');/* global globalThis */ /** @type {PromiseConstructor} */\\nconst BestPipelinablePromise=globalThis.HandledPromise||Promise;\\n\\n/**\\n * makePromiseKit() builds a Promise object, and returns a record\\n * containing the promise itself, as well as separate facets for resolving\\n * and rejecting it.\\n *\\n * @template T\\n * @returns {IMPORT('./src/types.js').PromiseKit<T>}\\n */\\nfunction makePromiseKit(){\\nconst{resolve,reject,executor}=promiseExecutorKit.makeReleasingExecutorKit();\\n\\nconst promise=new BestPipelinablePromise(executor);\\n\\nreturn harden({promise,resolve,reject});}\\n\\nharden(makePromiseKit);\\n\\n/* NB: Another implementation for Promise.race would be to use the releasing executor,*/\\n/* However while it would no longer leak the raced promise objects themselves, it would*/\\n/* still leak reactions on the non-resolved promises contending for the race.*/\\n\\n/**\\n * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved\\n * or rejected.\\n *\\n * Unlike `Promise.race` it cleans up after itself so a non-resolved value doesn't hold onto\\n * the result promise.\\n *\\n * @template T\\n * @param {Iterable<T>} values An iterable of Promises.\\n * @returns {Promise<Awaited<T>>} A new Promise.\\n */\\nfunction racePromises(values){\\nreturn harden(memoRace.memoRace.call(BestPipelinablePromise,values));}\\n\\nharden(racePromises);exports.isPromise=isPromise.isPromise;exports.makePromiseKit=makePromiseKit;exports.racePromises=racePromises;\",\n \"node_modules/@endo/promise-kit/src/is-promise.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});/**\\n * Determine if the argument is a Promise.\\n *\\n * @param {unknown} maybePromise The value to examine\\n * @returns {maybePromise is Promise} Whether it is a promise\\n */\\nfunction isPromise(maybePromise){\\nreturn Promise.resolve(maybePromise)===maybePromise;}\\n\\nharden(isPromise);exports.isPromise=isPromise;\",\n \"node_modules/@endo/promise-kit/src/memo-race.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});/* Initial version authored by Brian Kim:\\nhttps://github.com/nodejs/node/issues/17469#issuecomment-685216777\\n This is free and unencumbered software released into the public domain.\\n Anyone is free to copy, modify, publish, use, compile, sell, or\\ndistribute this software, either in source code form or as a compiled\\nbinary, for any purpose, commercial or non-commercial, and by any\\nmeans.\\n In jurisdictions that recognize copyright laws, the author or authors\\nof this software dedicate any and all copyright interest in the\\nsoftware to the public domain. We make this dedication for the benefit\\nof the public at large and to the detriment of our heirs and\\nsuccessors. We intend this dedication to be an overt act of\\nrelinquishment in perpetuity of all present and future rights to this\\nsoftware under copyright law.\\n THE SOFTWARE IS PROVIDED \\\"AS IS\\\", WITHOUT WARRANTY OF ANY KIND,\\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\\nIN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\\nOTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\\nARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\\nOTHER DEALINGS IN THE SOFTWARE.\\n For more information, please refer to <http://unlicense.org/>\\n*/\\n\\n\\n\\n\\n\\n\\n\\nconst isObject=(value)=>Object(value)===value;\\n\\n/**\\n * @template [T=any]\\n * @typedef {object} Deferred\\n * @property {(value?: IMPORT(\\\"./types.js\\\").ERef<T> ) => void} resolve\\n * @property {(err?: any ) => void} reject\\n */\\n\\n/**\\n * @typedef { never\\n * | {settled: false, deferreds: Set<Deferred>}\\n * | {settled: true, deferreds?: undefined}\\n * } PromiseMemoRecord\\n */\\n\\n/* Keys are the values passed to race, values are a record of data containing a*/\\n/* set of deferreds and whether the value has settled.*/\\n/** @type {WeakMap<object, PromiseMemoRecord>} */\\nconst knownPromises=new WeakMap();\\n\\n/**\\n * @param {PromiseMemoRecord | undefined} record\\n * @returns {Set<Deferred>}\\n */\\nconst markSettled=(record)=>{\\nif(!record||record.settled){\\nreturn new Set();}\\n\\n\\nconst{deferreds}=record;\\nObject.assign(record,{\\ndeferreds:undefined,\\nsettled:true});\\n\\nObject.freeze(record);\\nreturn deferreds;};\\n\\n\\n/**\\n *\\n * @param {any} value\\n * @returns {PromiseMemoRecord}\\n */\\nconst getMemoRecord=(value)=>{\\nif(!isObject(value)){\\n/* If the contender is a primitive, attempting to use it as a key in the*/\\n/* weakmap would throw an error. Luckily, it is safe to call*/\\n/* `Promise.resolve(contender).then` on a primitive value multiple times*/\\n/* because the promise fulfills immediately. So we fake a settled record.*/\\nreturn harden({settled:true});}\\n\\n\\nlet record=knownPromises.get(value);\\n\\nif(!record){\\nrecord={deferreds:new Set(),settled:false};\\nknownPromises.set(value,record);\\n/* This call to `then` happens once for the lifetime of the value.*/\\nPromise.resolve(value).then(\\n(val)=>{\\nfor(const{resolve}of markSettled(record)){\\nresolve(val);}},\\n\\n\\n(err)=>{\\nfor(const{reject}of markSettled(record)){\\nreject(err);}});}\\n\\n\\n\\n\\nreturn record;};\\n\\n\\nconst{race}={\\n/**\\n * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved\\n * or rejected.\\n *\\n * Unlike `Promise.race` it cleans up after itself so a non-resolved value doesn't hold onto\\n * the result promise.\\n *\\n * @template T\\n * @template {PromiseConstructor} [P=PromiseConstructor]\\n * @this {P}\\n * @param {Iterable<T>} values An iterable of Promises.\\n * @returns {Promise<Awaited<T>>} A new Promise.\\n */\\nrace(values){\\nlet deferred;\\n/** @type {T[]} */\\nconst cachedValues=[];\\nconst C=this;\\nconst result=new C((resolve,reject)=>{\\ndeferred={resolve,reject};\\nfor(const value of values){\\ncachedValues.push(value);\\nconst{settled,deferreds}=getMemoRecord(value);\\nif(settled){\\n/* If the contender is settled (including primitives), it is safe*/\\n/* to call `Promise.resolve(value).then` on it.*/\\nC.resolve(value).then(resolve,reject);}else\\n{\\ndeferreds.add(deferred);}}});\\n\\n\\n\\n\\n/* The finally callback executes when any value settles, preventing any of*/\\n/* the unresolved values from retaining a reference to the resolved value.*/\\nreturn result.finally(()=>{\\nfor(const value of cachedValues){\\nconst{deferreds}=getMemoRecord(value);\\nif(deferreds){\\ndeferreds.delete(deferred);}}});}};exports.memoRace=race;\",\n \"node_modules/@endo/promise-kit/src/promise-executor-kit.js\": \"'use strict';\\n\\n\\n\\n\\n\\n\\n\\n\\nObject.defineProperty(exports,'__esModule',{value:true});/*/ <reference types=\\\"ses\\\"/>*/ /**\\n * @template T\\n * @callback PromiseExecutor The promise executor\\n * @param {(value: IMPORT('./types.js').ERef<T>) => void} resolve\\n * @param {(reason: any) => void} reject\\n */ /**\\n * makeReleasingExecutorKit() builds resolve/reject functions which drop references\\n * to the resolve/reject functions gathered from an executor to be used with a\\n * promise constructor.\\n *\\n * @template T\\n * @returns {Pick<IMPORT('./types.js').PromiseKit<T>, 'resolve' | 'reject'> & { executor: PromiseExecutor<T>}}\\n */const makeReleasingExecutorKit=()=>{/** @type {null | undefined | ((value: IMPORT('./types.js').ERef<T>) => void)} */let internalResolve;/** @type {null | undefined | ((reason: unknown) => void)} */let internalReject;\\n\\n/** @param {IMPORT('./types.js').ERef<T>} value */\\nconst resolve=(value)=>{\\nif(internalResolve){\\ninternalResolve(value);\\ninternalResolve=null;\\ninternalReject=null;}else\\n{\\nassert(internalResolve===null);}};\\n\\n\\n\\n/** @param {unknown} reason */\\nconst reject=(reason)=>{\\nif(internalReject){\\ninternalReject(reason);\\ninternalResolve=null;\\ninternalReject=null;}else\\n{\\nassert(internalReject===null);}};\\n\\n\\n\\nconst executor=(res,rej)=>{\\nassert(internalResolve===undefined&&internalReject===undefined);\\ninternalResolve=res;\\ninternalReject=rej;};\\n\\n\\nreturn harden({resolve,reject,executor});};\\n\\nharden(makeReleasingExecutorKit);exports.makeReleasingExecutorKit=makeReleasingExecutorKit;\",\n \"node_modules/@endo/promise-kit/src/types.js\": \"'use strict';/**\\n * @template T\\n * @typedef {object} PromiseKit A reified Promise\\n * @property {(value: ERef<T>) => void} resolve\\n * @property {(reason: any) => void} reject\\n * @property {Promise<T>} promise\\n */\",\n \"node_modules/@endo/zip/index.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('./src/types.js');var reader=require('./src/reader.js');var writer=require('./src/writer.js');/* eslint-disable-next-line import/export*/exports.ZipReader=reader.ZipReader;exports.readZip=reader.readZip;exports.ZipWriter=writer.ZipWriter;exports.writeZip=writer.writeZip;\",\n \"node_modules/@endo/zip/src/buffer-reader.js\": \"'use strict';\\nObject.defineProperty(exports,'__esModule',{value:true});/* @ts-check*/ /* eslint no-bitwise: [\\\"off\\\"] */\\n\\nconst q=JSON.stringify;\\n\\n/**\\n * @typedef {object} BufferReaderState\\n * @property {Uint8Array} bytes\\n * @property {DataView} data\\n * @property {number} length\\n * @property {number} index\\n * @property {number} offset\\n */\\n\\n/** @type {WeakMap<BufferReader, BufferReaderState>} */\\nconst privateFields=new WeakMap();\\n\\n/** @type {(bufferReader: BufferReader) => BufferReaderState} */\\nconst privateFieldsGet=privateFields.get.bind(privateFields);\\n\\nclass BufferReader{\\n/**\\n * @param {ArrayBuffer} buffer\\n */\\nconstructor(buffer){\\nconst bytes=new Uint8Array(buffer);\\nconst data=new DataView(bytes.buffer);\\nprivateFields.set(this,{\\nbytes,\\ndata,\\nlength:bytes.length,\\nindex:0,\\noffset:0});}\\n\\n\\n\\n/**\\n * @returns {number}\\n */\\nget length(){\\nreturn privateFieldsGet(this).length;}\\n\\n\\n/**\\n * @returns {number}\\n */\\nget index(){\\nreturn privateFieldsGet(this).index;}\\n\\n\\n/**\\n * @param {number} index\\n */\\nset index(index){\\nthis.seek(index);}\\n\\n\\n/**\\n * @param {number} offset\\n */\\nset offset(offset){\\nconst fields=privateFieldsGet(this);\\nif(offset>fields.data.byteLength){\\nthrow Error('Cannot set offset beyond length of underlying data');}\\n\\nif(offset<0){\\nthrow Error('Cannot set negative offset');}\\n\\nfields.offset=offset;\\nfields.length=fields.data.byteLength-fields.offset;}\\n\\n\\n/**\\n * @param {number} index\\n * @returns {boolean} whether the read head can move to the given absolute\\n * index.\\n */\\ncanSeek(index){\\nconst fields=privateFieldsGet(this);\\nreturn index>=0&&fields.offset+index<=fields.length;}\\n\\n\\n/**\\n * @param {number} index the index to check.\\n * @throws {Error} an Error if the index is out of bounds.\\n */\\nassertCanSeek(index){\\nconst fields=privateFieldsGet(this);\\nif(!this.canSeek(index)){\\nthrow Error(\\n`End of data reached (data length = ${fields.length}, asked index ${index}`);}}\\n\\n\\n\\n\\n/**\\n * @param {number} index\\n * @returns {number} prior index\\n */\\nseek(index){\\nconst fields=privateFieldsGet(this);\\nconst restore=fields.index;\\nthis.assertCanSeek(index);\\nfields.index=index;\\nreturn restore;}\\n\\n\\n/**\\n * @param {number} size\\n * @returns {Uint8Array}\\n */\\npeek(size){\\nconst fields=privateFieldsGet(this);\\n/* Clamp size.*/\\nsize=Math.max(0,Math.min(fields.length-fields.index,size));\\nif(size===0){\\n/* in IE10, when using subarray(idx, idx), we get the array [0x00] instead of [].*/\\nreturn new Uint8Array(0);}\\n\\nconst result=fields.bytes.subarray(\\nfields.offset+fields.index,\\nfields.offset+fields.index+size);\\n\\nreturn result;}\\n\\n\\n/**\\n * @param {number} offset\\n */\\ncanRead(offset){\\nconst fields=privateFieldsGet(this);\\nreturn this.canSeek(fields.index+offset);}\\n\\n\\n/**\\n * Check that the offset will not go too far.\\n *\\n * @param {number} offset the additional offset to check.\\n * @throws {Error} an Error if the offset is out of bounds.\\n */\\nassertCanRead(offset){\\nconst fields=privateFieldsGet(this);\\nthis.assertCanSeek(fields.index+offset);}\\n\\n\\n/**\\n * Get raw data without conversion, <size> bytes.\\n *\\n * @param {number} size the number of bytes to read.\\n * @returns {Uint8Array} the raw data.\\n */\\nread(size){\\nconst fields=privateFieldsGet(this);\\nthis.assertCanRead(size);\\nconst result=this.peek(size);\\nfields.index+=size;\\nreturn result;}\\n\\n\\n/**\\n * @returns {number}\\n */\\nreadUint8(){\\nconst fields=privateFieldsGet(this);\\nthis.assertCanRead(1);\\nconst index=fields.offset+fields.index;\\nconst value=fields.data.getUint8(index);\\nfields.index+=1;\\nreturn value;}\\n\\n\\n/**\\n * @returns {number}\\n * @param {boolean=} littleEndian\\n */\\nreadUint16(littleEndian){\\nconst fields=privateFieldsGet(this);\\nthis.assertCanRead(2);\\nconst index=fields.offset+fields.index;\\nconst value=fields.data.getUint16(index,littleEndian);\\nfields.index+=2;\\nreturn value;}\\n\\n\\n/**\\n * @returns {number}\\n * @param {boolean=} littleEndian\\n */\\nreadUint32(littleEndian){\\nconst fields=privateFieldsGet(this);\\nthis.assertCanRead(4);\\nconst index=fields.offset+fields.index;\\nconst value=fields.data.getUint32(index,littleEndian);\\nfields.index+=4;\\nreturn value;}\\n\\n\\n/**\\n * @param {number} index\\n * @returns {number}\\n */\\nbyteAt(index){\\nconst fields=privateFieldsGet(this);\\nreturn fields.bytes[fields.offset+index];}\\n\\n\\n/**\\n * @param {number} offset\\n */\\nskip(offset){\\nconst fields=privateFieldsGet(this);\\nthis.seek(fields.index+offset);}\\n\\n\\n/**\\n * @param {Uint8Array} expected\\n * @returns {boolean}\\n */\\nexpect(expected){\\nconst fields=privateFieldsGet(this);\\nif(!this.matchAt(fields.index,expected)){\\nreturn false;}\\n\\nfields.index+=expected.length;\\nreturn true;}\\n\\n\\n/**\\n * @param {number} index\\n * @param {Uint8Array} expected\\n * @returns {boolean}\\n */\\nmatchAt(index,expected){\\nconst fields=privateFieldsGet(this);\\nif(index+expected.length>fields.length||index<0){\\nreturn false;}\\n\\nfor(let i=0;i<expected.length;i+=1){\\nif(expected[i]!==this.byteAt(index+i)){\\nreturn false;}}\\n\\n\\nreturn true;}\\n\\n\\n/**\\n * @param {Uint8Array} expected\\n */\\nassert(expected){\\nconst fields=privateFieldsGet(this);\\nif(!this.expect(expected)){\\nthrow Error(\\n`Expected ${q(expected)} at ${fields.index}, got ${this.peek(\\nexpected.length)\\n}`);}}\\n\\n\\n\\n\\n/**\\n * @param {Uint8Array} expected\\n * @returns {number}\\n */\\nfindLast(expected){\\nconst fields=privateFieldsGet(this);\\nlet index=fields.length-expected.length;\\nwhile(index>=0&&!this.matchAt(index,expected)){\\nindex-=1;}\\n\\nreturn index;}}exports.BufferReader=BufferReader;\",\n \"node_modules/@endo/zip/src/buffer-writer.js\": \"'use strict';\\n\\n\\nObject.defineProperty(exports,'__esModule',{value:true});/* @ts-check*/ /* eslint no-bitwise: [\\\"off\\\"] */ /**\\n * @type {WeakMap<BufferWriter, {\\n * length: number,\\n * index: number,\\n * bytes: Uint8Array,\\n * data: DataView,\\n * capacity: number,\\n * }>}\\n */\\nconst privateFields=new WeakMap();\\n\\n/**\\n * @param {BufferWriter} self\\n */\\nconst getPrivateFields=(self)=>{\\nconst fields=privateFields.get(self);\\nif(!fields){\\nthrow Error('BufferWriter fields are not initialized');}\\n\\nreturn fields;};\\n\\n\\nconst assertNatNumber=(n)=>{\\nif(Number.isSafeInteger(n)&&/** @type {number} */n>=0){\\nreturn;}\\n\\nthrow TypeError(`must be a non-negative integer, got ${n}`);};\\n\\n\\nclass BufferWriter{\\n/**\\n * @returns {number}\\n */\\nget length(){\\nreturn getPrivateFields(this).length;}\\n\\n\\n/**\\n * @returns {number}\\n */\\nget index(){\\nreturn getPrivateFields(this).index;}\\n\\n\\n/**\\n * @param {number} index\\n */\\nset index(index){\\nthis.seek(index);}\\n\\n\\n/**\\n * @param {number=} capacity\\n */\\nconstructor(capacity=16){\\nconst bytes=new Uint8Array(capacity);\\nconst data=new DataView(bytes.buffer);\\nprivateFields.set(this,{\\nbytes,\\ndata,\\nindex:0,\\nlength:0,\\ncapacity});}\\n\\n\\n\\n/**\\n * @param {number} required\\n */\\nensureCanSeek(required){\\nassertNatNumber(required);\\nconst fields=getPrivateFields(this);\\nlet capacity=fields.capacity;\\nwhile(capacity<required){\\ncapacity*=2;}\\n\\nconst bytes=new Uint8Array(capacity);\\nconst data=new DataView(bytes.buffer);\\nbytes.set(fields.bytes.subarray(0,fields.length));\\nfields.bytes=bytes;\\nfields.data=data;\\nfields.capacity=capacity;}\\n\\n\\n/**\\n * @param {number} index\\n */\\nseek(index){\\nconst fields=getPrivateFields(this);\\nthis.ensureCanSeek(index);\\nfields.index=index;\\nfields.length=Math.max(fields.index,fields.length);}\\n\\n\\n/**\\n * @param {number} size\\n */\\nensureCanWrite(size){\\nassertNatNumber(size);\\nconst fields=getPrivateFields(this);\\nthis.ensureCanSeek(fields.index+size);}\\n\\n\\n/**\\n * @param {Uint8Array} bytes\\n */\\nwrite(bytes){\\nconst fields=getPrivateFields(this);\\nthis.ensureCanWrite(bytes.byteLength);\\nfields.bytes.set(bytes,fields.index);\\nfields.index+=bytes.byteLength;\\nfields.length=Math.max(fields.index,fields.length);}\\n\\n\\n/**\\n * @param {number} start\\n * @param {number} end\\n */\\nwriteCopy(start,end){\\nassertNatNumber(start);\\nassertNatNumber(end);\\nconst fields=getPrivateFields(this);\\nconst size=end-start;\\nthis.ensureCanWrite(size);\\nfields.bytes.copyWithin(fields.index,start,end);\\nfields.index+=size;\\nfields.length=Math.max(fields.index,fields.length);}\\n\\n\\n/**\\n * @param {number} value\\n */\\nwriteUint8(value){\\nconst fields=getPrivateFields(this);\\nthis.ensureCanWrite(1);\\nfields.data.setUint8(fields.index,value);\\nfields.index+=1;\\nfields.length=Math.max(fields.index,fields.length);}\\n\\n\\n/**\\n * @param {number} value\\n * @param {boolean=} littleEndian\\n */\\nwriteUint16(value,littleEndian){\\nconst fields=getPrivateFields(this);\\nthis.ensureCanWrite(2);\\nconst index=fields.index;\\nfields.data.setUint16(index,value,littleEndian);\\nfields.index+=2;\\nfields.length=Math.max(fields.index,fields.length);}\\n\\n\\n/**\\n * @param {number} value\\n * @param {boolean=} littleEndian\\n */\\nwriteUint32(value,littleEndian){\\nconst fields=getPrivateFields(this);\\nthis.ensureCanWrite(4);\\nconst index=fields.index;\\nfields.data.setUint32(index,value,littleEndian);\\nfields.index+=4;\\nfields.length=Math.max(fields.index,fields.length);}\\n\\n\\n/**\\n * @param {number=} begin\\n * @param {number=} end\\n * @returns {Uint8Array}\\n */\\nsubarray(begin,end){\\nconst fields=getPrivateFields(this);\\nreturn fields.bytes.subarray(0,fields.length).subarray(begin,end);}\\n\\n\\n/**\\n * @param {number=} begin\\n * @param {number=} end\\n * @returns {Uint8Array}\\n */\\nslice(begin,end){\\nreturn this.subarray(begin,end).slice();}}exports.BufferWriter=BufferWriter;\",\n \"node_modules/@endo/zip/src/compression.js\": \"'use strict';\\n\\nObject.defineProperty(exports,'__esModule',{value:true});/* @ts-check*/ /* STORE is the magic number for \\\"not compressed\\\".*/\\nconst STORE=0;exports.STORE=STORE;\",\n \"node_modules/@endo/zip/src/crc32.js\": \"'use strict';\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nObject.defineProperty(exports,'__esModule',{value:true});/* @ts-check*/ /* eslint no-bitwise: [\\\"off\\\"] */ /**\\n * The following functions `makeTable` and `crc32` come from `pako`, from\\n * pako/lib/zlib/crc32.js released under the MIT license, see pako\\n * https://github.com/nodeca/pako/\\n */ /* Use ordinary array, since untyped makes no boost here*/ /**\\n * @returns {Array<number>}\\n */function makeTable(){let c;const table=[];\\nfor(let n=0;n<256;n+=1){\\nc=n;\\nfor(let k=0;k<8;k+=1){\\nc=c&1?0xedb88320^c>>>1:c>>>1;}\\n\\ntable[n]=c;}\\n\\n\\nreturn table;}\\n\\n\\n/* Initialize a table of 256 signed 32 bit integers.*/\\nconst table=makeTable();\\n\\n/**\\n * @param {Uint8Array} bytes\\n * @param {number} length\\n * @param {number} index\\n * @param {number} crc\\n */\\nfunction crc32(bytes,length=bytes.length,index=0,crc=0){\\nconst end=index+length;\\n\\ncrc^=-1;\\n\\nfor(let i=index;i<end;i+=1){\\ncrc=crc>>>8^table[(crc^bytes[i])&0xff];}\\n\\n\\nreturn(crc^-1)>>>0;}exports.crc32=crc32;\",\n \"node_modules/@endo/zip/src/format-reader.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('./types.js');var crc32=require('./crc32.js');var signature=require('./signature.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\ncompression=require('./compression.js');/* @ts-check*/ /* q, as in quote, for quoting strings in errors*/\\nconst q=JSON.stringify;\\n\\nconst MAX_VALUE_16BITS=65535;\\nconst MAX_VALUE_32BITS=4294967295;\\n\\nconst textDecoder=new TextDecoder();\\n\\n/**\\n * @param {number} bitFlag\\n * @returns {boolean}\\n */\\nfunction isEncrypted(bitFlag){\\nreturn(bitFlag&0x0001)===0x0001;}\\n\\n\\n/**\\n * @param {BufferReader} reader\\n * @returns {Date}\\n * @see http://www.delorie.com/djgpp/doc/rbinter/it/65/16.html\\n * @see http://www.delorie.com/djgpp/doc/rbinter/it/66/16.html\\n */\\nfunction readDosDateTime(reader){\\nconst dosTime=reader.readUint32(true);\\nreturn new Date(\\nDate.UTC(\\n(dosTime>>25&0x7f)+1980,/* year*/\\n(dosTime>>21&0x0f)-1,/* month*/\\ndosTime>>16&0x1f,/* day*/\\ndosTime>>11&0x1f,/* hour*/\\ndosTime>>5&0x3f,/* minute*/\\n(dosTime&0x1f)<<1/* second*/));}\\n\\n\\n\\n\\n/**\\n * @param {BufferReader} reader\\n * @returns {ArchiveHeaders}\\n */\\nfunction readHeaders(reader){\\nreturn{\\nversionNeeded:reader.readUint16(true),\\nbitFlag:reader.readUint16(true),\\ncompressionMethod:reader.readUint16(true),\\ndate:readDosDateTime(reader),\\ncrc32:reader.readUint32(true),\\ncompressedLength:reader.readUint32(true),\\nuncompressedLength:reader.readUint32(true)};}\\n\\n\\n\\n/**\\n * @param {BufferReader} reader\\n * @returns {CentralFileRecord}\\n */\\nfunction readCentralFileHeader(reader){\\nconst version=reader.readUint8();\\nconst madeBy=reader.readUint8();\\nconst headers=readHeaders(reader);\\nconst nameLength=reader.readUint16(true);\\nconst extraFieldsLength=reader.readUint16(true);\\nconst commentLength=reader.readUint16(true);\\nconst diskNumberStart=reader.readUint16(true);\\nconst internalFileAttributes=reader.readUint16(true);\\nconst externalFileAttributes=reader.readUint32(true);\\nconst fileStart=reader.readUint32(true);\\n\\nconst name=reader.read(nameLength);\\n/* TODO read extra fields, particularly Zip64*/\\nreader.skip(extraFieldsLength);\\n\\nif(headers.uncompressedLength===MAX_VALUE_32BITS){\\nthrow Error('Cannot read Zip64');}\\n\\nif(headers.compressedLength===MAX_VALUE_32BITS){\\nthrow Error('Cannot read Zip64');}\\n\\nif(fileStart===MAX_VALUE_32BITS){\\nthrow Error('Cannot read Zip64');}\\n\\nif(diskNumberStart===MAX_VALUE_32BITS){\\nthrow Error('Cannot read Zip64');}\\n\\n\\nconst comment=reader.read(commentLength);\\n\\nreturn{\\nname,\\nversion,\\nmadeBy,\\n...headers,\\ndiskNumberStart,\\ninternalFileAttributes,\\nexternalFileAttributes,\\nfileStart,\\ncomment};}\\n\\n\\n\\n/**\\n * @param {BufferReader} reader\\n * @param {CentralDirectoryLocator} locator\\n * @returns {Array<CentralFileRecord>}\\n */\\nfunction readCentralDirectory(reader,locator){\\nconst{centralDirectoryOffset,centralDirectoryRecords}=locator;\\nreader.seek(centralDirectoryOffset);\\n\\nconst entries=[];\\nwhile(reader.expect(signature.CENTRAL_FILE_HEADER)){\\nconst entry=readCentralFileHeader(reader);\\nentries.push(entry);}\\n\\n\\nif(centralDirectoryRecords!==entries.length){\\n/* We expected some records but couldn't find ANY.*/\\n/* This is really suspicious, as if something went wrong.*/\\nthrow Error(\\n`Corrupted zip or bug: expected ${centralDirectoryRecords} records in central dir, got ${entries.length}`);}\\n\\n\\n\\nreturn entries;}\\n\\n\\n/**\\n * @param {BufferReader} reader\\n * @returns {LocalFileRecord}\\n */\\nfunction readFile(reader){\\nreader.expect(signature.LOCAL_FILE_HEADER);\\nconst headers=readHeaders(reader);\\nconst nameLength=reader.readUint16(true);\\nconst extraFieldsLength=reader.readUint16(true);\\nconst name=reader.read(nameLength);\\nreader.skip(extraFieldsLength);\\nconst content=reader.read(headers.compressedLength);\\nreturn{name,...headers,content};}\\n\\n\\n/**\\n * @param {BufferReader} reader\\n * @param {Array<CentralFileRecord>} records\\n * @returns {Array<LocalFileRecord>}\\n */\\nfunction readLocalFiles(reader,records){\\nconst files=[];\\nfor(const record of records){\\nreader.seek(record.fileStart);\\nconst file=readFile(reader);\\nfiles.push(file);}\\n\\nreturn files;}\\n\\n\\n/**\\n * @param {BufferReader} reader\\n * @returns {CentralDirectoryLocator}\\n */\\nfunction readBlockEndOfCentral(reader){\\nif(!reader.expect(signature.CENTRAL_DIRECTORY_END)){\\nthrow Error(\\n'Corrupt zip file, or zip file containing an unsupported variable-width end-of-archive comment, or an unsupported zip file with 64 bit sizes');}\\n\\n\\nconst diskNumber=reader.readUint16(true);\\nconst diskWithCentralDirStart=reader.readUint16(true);\\nconst centralDirectoryRecordsOnThisDisk=reader.readUint16(true);\\nconst centralDirectoryRecords=reader.readUint16(true);\\nconst centralDirectorySize=reader.readUint32(true);\\nconst centralDirectoryOffset=reader.readUint32(true);\\nconst commentLength=reader.readUint16(true);\\n/* Warning: the encoding depends of the system locale.*/\\n/* On a Linux machine with LANG=en_US.utf8, this field is utf8 encoded.*/\\n/* On a Windows machine, this field is encoded with the localized Windows*/\\n/* code page.*/\\nconst comment=textDecoder.decode(reader.read(commentLength));\\nreturn{\\ndiskNumber,\\ndiskWithCentralDirStart,\\ncentralDirectoryRecordsOnThisDisk,\\ncentralDirectoryRecords,\\ncentralDirectorySize,\\ncentralDirectoryOffset,\\ncomment};}\\n\\n\\n\\n/**\\n * @param {BufferReader} reader\\n * @returns {CentralDirectoryLocator}\\n */\\nfunction readEndOfCentralDirectoryRecord(reader){\\n/* Zip files are permitted to have a variable-width comment at the end of the*/\\n/* \\\"end of central directory record\\\" and may have subsequent Zip64 headers.*/\\n/* The prescribed method of finding the beginning of the \\\"end of central*/\\n/* directory record\\\" is to seek the magic number:*/\\n/**/\\n/* reader.findLast(signature.CENTRAL_DIRECTORY_END);*/\\n/**/\\n/* This introduces a number of undesirable, attackable ambiguities*/\\n/* Agoric is not comfortable supporting, so we forbid the comment*/\\n/* and 64 bit zip support so we can seek a predictable length*/\\n/* from the end.*/\\nconst centralDirectoryEnd=reader.length-22;\\nif(centralDirectoryEnd<0){\\nthrow Error('Corrupted zip: not enough content');}\\n\\nreader.seek(centralDirectoryEnd);\\nconst locator=readBlockEndOfCentral(reader);\\n\\n/* Excerpt from the zip spec:*/\\n/* 4) If one of the fields in the end of central directory*/\\n/* record is too small to hold required data, the field*/\\n/* should be set to -1 (0xFFFF or 0xFFFFFFFF) and the*/\\n/* ZIP64 format record should be created.*/\\n/* 5) The end of central directory record and the*/\\n/* Zip64 end of central directory locator record must*/\\n/* reside on the same disk when splitting or spanning*/\\n/* an archive.*/\\nconst zip64=\\nlocator.diskNumber===MAX_VALUE_16BITS||\\nlocator.diskWithCentralDirStart===MAX_VALUE_16BITS||\\nlocator.centralDirectoryRecordsOnThisDisk===MAX_VALUE_16BITS||\\nlocator.centralDirectoryRecords===MAX_VALUE_16BITS||\\nlocator.centralDirectorySize===MAX_VALUE_32BITS||\\nlocator.centralDirectoryOffset===MAX_VALUE_32BITS;\\n\\nif(zip64){\\nthrow Error('Cannot read Zip64');}\\n\\n\\nconst{\\ncentralDirectoryOffset,\\ncentralDirectorySize\\n/* zip64EndOfCentralSize*/}=\\nlocator;\\n\\nconst expectedCentralDirectoryEnd=\\ncentralDirectoryOffset+centralDirectorySize;\\nconst extraBytes=centralDirectoryEnd-expectedCentralDirectoryEnd;\\n\\nreader.offset=extraBytes;\\n\\nreturn locator;}\\n\\n\\n/**\\n * @param {CentralFileRecord} centralRecord\\n * @param {LocalFileRecord} localRecord\\n * @param {string} archiveName\\n */\\nfunction checkRecords(centralRecord,localRecord,archiveName){\\nconst centralName=textDecoder.decode(centralRecord.name);\\nconst localName=textDecoder.decode(localRecord.name);\\n\\n/* In some zip files created on Windows, the filename stored in the central*/\\n/* dir contains \\\"\\\\\\\" instead of \\\"/\\\". Strangely, the file name in the local*/\\n/* directory uses \\\"/\\\" as specified:*/\\n/* http://www.info-zip.org/FAQ.html#backslashes or APPNOTE#4.4.17.1, \\\"All*/\\n/* slashes MUST be forward slashes '/'\\\") but there are a lot of bad zip*/\\n/* generators... Search \\\"unzip mismatching \\\"local\\\" filename continuing with*/\\n/* \\\"central\\\" filename version\\\".*/\\n/**/\\n/* The reasoning appears to be that the central directory is for*/\\n/* user display and may differ, though this opens the possibility*/\\n/* for spoofing attacks.*/\\n/* http://seclists.org/fulldisclosure/2009/Sep/394*/\\n/**/\\n/* We strike a compromise: the central directory name may vary from the local*/\\n/* name exactly and only by different slashes.*/\\nif(centralName.replace(/\\\\\\\\/g,'/')!==localName){\\nthrow Error(\\n`Zip integrity error: central record file name ${q(\\ncentralName)\\n} must match local file name ${q(localName)} in archive ${q(\\narchiveName)\\n}`);}\\n\\n\\n\\n/**\\n * @param {boolean} value\\n * @param {string} message\\n */\\nfunction check(value,message){\\nif(!value){\\nthrow Error(\\n`Zip integrity error: ${message} for file ${q(\\nlocalName)\\n} in archive ${q(archiveName)}`);}}\\n\\n\\n\\n\\ncheck(\\ncentralRecord.bitFlag===localRecord.bitFlag,\\n`Central record bit flag ${centralRecord.bitFlag.toString(\\n16)\\n} must match local record bit flag ${localRecord.bitFlag.toString(16)}`);\\n\\ncheck(\\ncentralRecord.compressionMethod===localRecord.compressionMethod,\\n`Central record compression method ${q(\\ncentralRecord.compressionMethod)\\n} must match local compression method ${q(localRecord.compressionMethod)}`);\\n\\n/* TODO Date integrity check would be easier on the original bytes.*/\\n/* Perhaps defer decoding the underlying bytes.*/\\ncheck(\\ncentralRecord.crc32===localRecord.crc32,\\n`Central record CRC-32 checksum ${centralRecord.crc32} must match local checksum ${localRecord.crc32}`);\\n\\ncheck(\\ncentralRecord.compressedLength===localRecord.compressedLength,\\n`Central record compressed size ${centralRecord.compressedLength} must match local ${localRecord.compressedLength}`);\\n\\ncheck(\\ncentralRecord.uncompressedLength===localRecord.uncompressedLength,\\n`Central record uncompressed size ${centralRecord.uncompressedLength} must match local ${localRecord.uncompressedLength}`);\\n\\n\\nconst checksum=crc32.crc32(localRecord.content);\\ncheck(\\nchecksum===localRecord.crc32,\\n`CRC-32 checksum mismatch, wanted ${localRecord.crc32} but actual content is ${checksum}`);}\\n\\n\\n\\n/**\\n * @param {number} externalFileAttributes\\n */\\nfunction modeForExternalAttributes(externalFileAttributes){\\nreturn externalFileAttributes>>16&0xffff;}\\n\\n\\n/**\\n * @param {CentralFileRecord} centralRecord\\n * @param {LocalFileRecord} localRecord\\n * @returns {CompressedFile}\\n */\\nfunction recordToFile(centralRecord,localRecord){\\nconst mode=modeForExternalAttributes(centralRecord.externalFileAttributes);\\nreturn{\\nname:centralRecord.name,\\nmode,\\ndate:centralRecord.date,\\ncrc32:centralRecord.crc32,\\ncompressionMethod:centralRecord.compressionMethod,\\ncompressedLength:centralRecord.compressedLength,\\nuncompressedLength:centralRecord.uncompressedLength,\\ncontent:localRecord.content,\\ncomment:centralRecord.comment};}\\n\\n\\n\\n/**\\n * @param {CompressedFile} file\\n * @returns {UncompressedFile}\\n */\\nfunction decompressFile(file){\\nif(file.compressionMethod!==compression.STORE){\\nthrow Error(\\n`Cannot find decompressor for compression method ${q(\\nfile.compressionMethod)\\n} for file ${file.name}`);}\\n\\n\\nreturn{\\nname:file.name,\\nmode:file.mode,\\ndate:file.date,\\ncontent:file.content,\\ncomment:file.comment};}\\n\\n\\n\\n/**\\n * @param {UncompressedFile} file\\n * @returns {ArchivedFile}\\n */\\nfunction decodeFile(file){\\nconst name=textDecoder.decode(file.name);\\nconst comment=textDecoder.decode(file.comment);\\nreturn{\\nname,\\ntype:'file',\\nmode:file.mode&0o777,\\ndate:file.date,\\ncontent:file.content,\\ncomment};}\\n\\n\\n\\n/**\\n * @param {BufferReader} reader\\n * @param {string} name\\n */\\nfunction readZip(reader,name='<unknown>'){\\nconst locator=readEndOfCentralDirectoryRecord(reader);\\nconst centralRecords=readCentralDirectory(reader,locator);\\nconst localRecords=readLocalFiles(reader,centralRecords);\\nconst files=new Map();\\n\\nfor(let i=0;i<centralRecords.length;i+=1){\\nconst centralRecord=centralRecords[i];\\nconst localRecord=localRecords[i];\\n\\ncheckRecords(centralRecord,localRecord,name);\\n\\nif(isEncrypted(centralRecord.bitFlag)){\\nthrow Error('Encrypted zip are not supported');}\\n\\n\\nconst isDir=(centralRecord.externalFileAttributes&0x0010)!==0;\\nif(!isDir){\\nconst compressedFile=recordToFile(centralRecord,localRecord);\\nconst decompressedFile=decompressFile(compressedFile);\\nconst decodedFile=decodeFile(decompressedFile);\\nfiles.set(decodedFile.name,decodedFile);}\\n\\n/* TODO handle explicit directory entries*/}\\n\\nreturn files;}exports.readZip=readZip;\",\n \"node_modules/@endo/zip/src/format-writer.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var crc32=require('./crc32.js');var signature=require('./signature.js');var compression=require('./compression.js');/* @ts-check*/\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nconst UNIX=3;\\nconst UNIX_VERSION=30;\\n\\nconst textEncoder=new TextEncoder();\\n\\n/**\\n * @param {BufferWriter} writer\\n * @param {Date?} date\\n * @see http://www.delorie.com/djgpp/doc/rbinter/it/65/16.html\\n * @see http://www.delorie.com/djgpp/doc/rbinter/it/66/16.html\\n */\\nfunction writeDosDateTime(writer,date){\\nconst dosTime=\\ndate!==undefined&&date!==null?\\n(date.getUTCFullYear()-1980&0x7f)<<25|/* year*/\\ndate.getUTCMonth()+1<<21|/* month*/\\ndate.getUTCDate()<<16|/* day*/\\ndate.getUTCHours()<<11|/* hour*/\\ndate.getUTCMinutes()<<5|/* minute*/\\ndate.getUTCSeconds()>>1/* second*/:\\n0;/* Epoch origin by default.*/\\nwriter.writeUint32(dosTime,true);}\\n\\n\\n/**\\n * @param {BufferWriter} writer\\n * @param {FileRecord} file\\n * @returns {LocalFileLocator}\\n */\\nfunction writeFile(writer,file){\\n/* Header*/\\nconst fileStart=writer.index;\\nwriter.write(signature.LOCAL_FILE_HEADER);\\nconst headerStart=writer.index;\\n/* Version needed to extract*/\\nwriter.writeUint16(10,true);\\nwriter.writeUint16(file.bitFlag,true);\\nwriter.writeUint16(file.compressionMethod,true);\\nwriteDosDateTime(writer,file.date);\\nwriter.writeUint32(file.crc32,true);\\nwriter.writeUint32(file.compressedLength,true);\\nwriter.writeUint32(file.uncompressedLength,true);\\nwriter.writeUint16(file.name.length,true);\\nconst headerEnd=writer.length;\\n\\n/* TODO count of extra fields length*/\\nwriter.writeUint16(0,true);\\nwriter.write(file.name);\\n/* TODO write extra fields*/\\nwriter.write(file.content);\\n\\nreturn{\\nfileStart,\\nheaderStart,\\nheaderEnd};}\\n\\n\\n\\n/**\\n * @param {BufferWriter} writer\\n * @param {FileRecord} file\\n * @param {LocalFileLocator} locator\\n */\\nfunction writeCentralFileHeader(writer,file,locator){\\nwriter.write(signature.CENTRAL_FILE_HEADER);\\nwriter.writeUint8(file.version);\\nwriter.writeUint8(file.madeBy);\\nwriter.writeCopy(locator.headerStart,locator.headerEnd);\\n/* TODO extra fields length*/\\nwriter.writeUint16(0,true);\\nwriter.writeUint16(file.comment.length,true);\\nwriter.writeUint16(file.diskNumberStart,true);\\nwriter.writeUint16(file.internalFileAttributes,true);\\nwriter.writeUint32(file.externalFileAttributes,true);\\nwriter.writeUint32(locator.fileStart,true);\\nwriter.write(file.centralName);\\n/* TODO extra fields*/\\nwriter.write(file.comment);}\\n\\n\\n/**\\n * @param {BufferWriter} writer\\n * @param {number} entriesCount\\n * @param {number} centralDirectoryStart\\n * @param {number} centralDirectoryLength\\n * @param {Uint8Array} commentBytes\\n */\\nfunction writeEndOfCentralDirectoryRecord(\\nwriter,\\nentriesCount,\\ncentralDirectoryStart,\\ncentralDirectoryLength,\\ncommentBytes)\\n{\\nwriter.write(signature.CENTRAL_DIRECTORY_END);\\nwriter.writeUint16(0,true);\\nwriter.writeUint16(0,true);\\nwriter.writeUint16(entriesCount,true);\\nwriter.writeUint16(entriesCount,true);\\nwriter.writeUint32(centralDirectoryLength,true);\\nwriter.writeUint32(centralDirectoryStart,true);\\nwriter.writeUint16(commentBytes.length,true);\\nwriter.write(commentBytes);}\\n\\n\\n/**\\n * @param {BufferWriter} writer\\n * @param {Array<FileRecord>} records\\n * @param {string} comment\\n */\\nfunction writeZipRecords(writer,records,comment=''){\\n/* Write records with local headers.*/\\nconst locators=[];\\nfor(let i=0;i<records.length;i+=1){\\nlocators.push(writeFile(writer,records[i]));}\\n\\n\\n/* writeCentralDirectory*/\\nconst centralDirectoryStart=writer.index;\\nfor(let i=0;i<locators.length;i+=1){\\nwriteCentralFileHeader(writer,records[i],locators[i]);}\\n\\nconst centralDirectoryLength=writer.index-centralDirectoryStart;\\n\\nconst commentBytes=textEncoder.encode(comment);\\n\\n/* Write central directory end.*/\\nwriteEndOfCentralDirectoryRecord(\\nwriter,\\nrecords.length,\\ncentralDirectoryStart,\\ncentralDirectoryLength,\\ncommentBytes);}\\n\\n\\n\\n/**\\n * @param {IMPORT('./types.js').ArchivedFile} file\\n * @returns {IMPORT('./types.js').UncompressedFile}\\n */\\nfunction encodeFile(file){\\nconst name=textEncoder.encode(file.name.replace(/\\\\\\\\/g,'/'));\\nconst comment=textEncoder.encode(file.comment);\\nreturn{\\nname,\\nmode:file.mode,\\ndate:file.date,\\ncontent:file.content,\\ncomment};}\\n\\n\\n\\n/**\\n * @param {IMPORT('./types.js').UncompressedFile} file\\n * @returns {IMPORT('./types.js').CompressedFile}\\n */\\nfunction compressFileWithStore(file){\\nreturn{\\nname:file.name,\\nmode:file.mode,\\ndate:file.date,\\ncrc32:crc32.crc32(file.content),\\ncompressionMethod:compression.STORE,\\ncompressedLength:file.content.length,\\nuncompressedLength:file.content.length,\\ncontent:file.content,\\ncomment:file.comment};}\\n\\n\\n\\n/**\\n * Computes Zip external file attributes field from a UNIX mode for a file.\\n *\\n * @param {number} mode\\n * @returns {number}\\n */\\nfunction externalFileAttributes(mode){\\nreturn(mode&0o777|0o100000)<<16;}\\n\\n\\n/* TODO Add support for directory records.*/\\n/* /***/\\n/* * @param {number} mode*/\\n/* * @return {number}*/\\n/* *X/*/\\n/* function externalDirectoryAttributes(mode) {*/\\n/* // The 0x10 is the DOS directory attribute, which is set regardless of platform.*/\\n/* return ((mode & 0o777) | 0o40000) << 16 | 0x10;*/\\n/* }*/\\n\\n/**\\n * @param {IMPORT('./types.js').CompressedFile} file\\n * @returns {FileRecord}\\n */\\nfunction makeFileRecord(file){\\nreturn{\\nname:file.name,\\ncentralName:file.name,\\nmadeBy:UNIX,\\nversion:UNIX_VERSION,\\nversionNeeded:0,/* TODO this is probably too lax.*/\\nbitFlag:0,\\ncompressionMethod:compression.STORE,\\ndate:file.date,\\ncrc32:file.crc32,\\ncompressedLength:file.compressedLength,\\nuncompressedLength:file.uncompressedLength,\\ndiskNumberStart:0,\\ninternalFileAttributes:0,\\nexternalFileAttributes:externalFileAttributes(file.mode),\\ncomment:file.comment,\\ncontent:file.content};}\\n\\n\\n\\n/**\\n * @param {BufferWriter} writer\\n * @param {Array<IMPORT('./types.js').ArchivedFile>} files\\n * @param {string} comment\\n */\\nfunction writeZip(writer,files,comment=''){\\nconst encodedFiles=files.map(encodeFile);\\nconst compressedFiles=encodedFiles.map(compressFileWithStore);\\n/* TODO collate directoryRecords from file bases.*/\\nconst fileRecords=compressedFiles.map(makeFileRecord);\\nwriteZipRecords(writer,fileRecords,comment);}exports.writeZip=writeZip;exports.writeZipRecords=writeZipRecords;\",\n \"node_modules/@endo/zip/src/reader.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var bufferReader=require('./buffer-reader.js');var formatReader=require('./format-reader.js');/* @ts-check*/\\n\\n\\n\\n\\nclass ZipReader{\\n/**\\n * @param {Uint8Array} data\\n * @param {object} [options]\\n * @param {string} [options.name]\\n */\\nconstructor(data,options={}){\\nconst{name='<unknown>'}=options;\\nconst reader=new bufferReader.BufferReader(data);\\nthis.files=formatReader.readZip(reader);\\nthis.name=name;}\\n\\n\\n/**\\n * @param {string} name\\n * @returns {Uint8Array}\\n */\\nread(name){\\nconst file=this.files.get(name);\\nif(file===undefined){\\nthrow Error(`Cannot find file ${name} in Zip file ${this.name}`);}\\n\\nreturn file.content;}\\n\\n\\n/**\\n * @param {string} name\\n * @returns {IMPORT('./types.js').ArchivedStat=}\\n */\\nstat(name){\\nconst file=this.files.get(name);\\nif(file===undefined){\\nreturn undefined;}\\n\\nreturn{\\ntype:file.type,\\nmode:file.mode,\\ndate:file.date,\\ncomment:file.comment};}}\\n\\n\\n\\n\\n/**\\n * @param {Uint8Array} data\\n * @param {string} location\\n * @returns {Promise<IMPORT('./types.js').ArchiveReader>}\\n */\\nconst readZip=async(data,location)=>{\\nconst reader=new ZipReader(data,{name:location});\\n/** @type {IMPORT('./types.js').ReadFn} */\\nconst read=async(path)=>reader.read(path);\\nreturn{read};};exports.ZipReader=ZipReader;exports.readZip=readZip;\",\n \"node_modules/@endo/zip/src/signature.js\": \"'use strict';\\n\\n\\nObject.defineProperty(exports,'__esModule',{value:true});/* @ts-check*/ /* eslint no-bitwise: [\\\"off\\\"] */ /**\\n * @param {string} string\\n * @returns {Uint8Array}\\n */\\nfunction u(string){\\nconst array=new Uint8Array(string.length);\\nfor(let i=0;i<string.length;i+=1){\\narray[i]=string.charCodeAt(i)&0xff;}\\n\\nreturn array;}\\n\\n\\nconst LOCAL_FILE_HEADER=u('PK\\\\x03\\\\x04');\\nconst CENTRAL_FILE_HEADER=u('PK\\\\x01\\\\x02');\\nconst CENTRAL_DIRECTORY_END=u('PK\\\\x05\\\\x06');\\nconst ZIP64_CENTRAL_DIRECTORY_LOCATOR=u('PK\\\\x06\\\\x07');\\nconst ZIP64_CENTRAL_DIRECTORY_END=u('PK\\\\x06\\\\x06');\\nconst DATA_DESCRIPTOR=u('PK\\\\x07\\\\x08');exports.CENTRAL_DIRECTORY_END=CENTRAL_DIRECTORY_END;exports.CENTRAL_FILE_HEADER=CENTRAL_FILE_HEADER;exports.DATA_DESCRIPTOR=DATA_DESCRIPTOR;exports.LOCAL_FILE_HEADER=LOCAL_FILE_HEADER;exports.ZIP64_CENTRAL_DIRECTORY_END=ZIP64_CENTRAL_DIRECTORY_END;exports.ZIP64_CENTRAL_DIRECTORY_LOCATOR=ZIP64_CENTRAL_DIRECTORY_LOCATOR;\",\n \"node_modules/@endo/zip/src/types.js\": \"\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n'use strict';/* @ts-check*/ /**\\n * @typedef {{\\n * mode: number,\\n * date: Date?,\\n * comment: string,\\n * type: \\\"file\\\" | \\\"directory\\\"\\n * }} ArchivedStat\\n *\\n * @typedef {{\\n * name: string,\\n * content: Uint8Array,\\n * } & ArchivedStat} ArchivedFile\\n *\\n * @typedef {{\\n * name: Uint8Array,\\n * mode: number,\\n * date: Date?,\\n * content: Uint8Array,\\n * comment: Uint8Array,\\n * }} UncompressedFile\\n *\\n * @typedef {{\\n * name: Uint8Array,\\n * mode: number,\\n * date: Date?,\\n * crc32: number,\\n * compressionMethod: number,\\n * compressedLength: number,\\n * uncompressedLength: number,\\n * content: Uint8Array,\\n * comment: Uint8Array,\\n * }} CompressedFile\\n *\\n * @typedef {{\\n * versionNeeded: number,\\n * bitFlag: number,\\n * compressionMethod: number,\\n * date: Date?,\\n * crc32: number,\\n * compressedLength: number,\\n * uncompressedLength: number,\\n * }} ArchiveHeaders\\n */ /**\\n * @typedef {object} ArchiveReader\\n * @property {ReadFn} read\\n */ /**\\n * @callback ReadFn\\n * @param {string} name\\n * @returns {Promise<Uint8Array>} bytes\\n */ /**\\n * @typedef {object} ArchiveWriter\\n * @property {WriteFn} write\\n * @property {SnapshotFn} snapshot\\n */ /**\\n * @callback WriteFn\\n * @param {string} name\\n * @param {Uint8Array} bytes\\n * @returns {Promise<void>}\\n */ /**\\n * @callback SnapshotFn\\n * @returns {Promise<Uint8Array>}\\n */\",\n \"node_modules/@endo/zip/src/writer.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var bufferWriter=require('./buffer-writer.js');var formatWriter=require('./format-writer.js');/* @ts-check*/\\n\\n\\n\\n\\nclass ZipWriter{\\n/**\\n * @param {{\\n * date: Date,\\n * }} options\\n */\\nconstructor(options={date:new Date()}){\\nconst{date}=options;\\n/** type {Map<string, ZFile>} */\\nthis.files=new Map();\\nthis.date=date;}\\n\\n\\n/**\\n * @param {string} name\\n * @param {Uint8Array} content\\n * @param {{\\n * mode?: number,\\n * date?: Date,\\n * comment?: string,\\n * }} [options]\\n */\\nwrite(name,content,options={}){\\nconst{mode=0o644,date=undefined,comment=''}=options;\\nif(!content){\\nthrow Error(`ZipWriter write requires content for ${name}`);}\\n\\nthis.files.set(name,{\\nname,\\nmode,\\ndate,\\ncontent,\\ncomment});}\\n\\n\\n\\n/**\\n * @returns {Uint8Array}\\n */\\nsnapshot(){\\nconst writer=new bufferWriter.BufferWriter();\\nformatWriter.writeZip(writer,Array.from(this.files.values()));\\nreturn writer.subarray();}}\\n\\n\\n\\n/**\\n * @returns {IMPORT('./types.js').ArchiveWriter}\\n */\\nconst writeZip=()=>{\\nconst writer=new ZipWriter();\\n/** @type {IMPORT('./types.js').WriteFn} */\\nconst write=async(path,data)=>{\\nwriter.write(path,data);};\\n\\n/** @type {IMPORT('./types.js').SnapshotFn} */\\nconst snapshot=async()=>writer.snapshot();\\nreturn{write,snapshot};};exports.ZipWriter=ZipWriter;exports.writeZip=writeZip;\",\n \"packages/assert/src/assert.js\": \"'use strict';\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nObject.defineProperty(exports,'__esModule',{value:true});/* global globalThis */ /* Copyright (C) 2019 Agoric, under Apache License 2.0*/ /* @ts-check*/ /* This module assumes the existence of a non-standard `assert` host object.*/ /* SES version 0.11.0 introduces this global object and entangles it*/ /* with the `console` host object in scope when it initializes,*/ /* allowing errors, particularly assertion errors, to hide their \\\"details\\\"*/ /* from callers that might catch those errors, then reveal them to the*/ /* underlying console.*/ /* To the extent that this `console` is considered a resource,*/ /* this module must be considered a resource module.*/ /* The assertions re-exported here are defined in*/ /* https://github.com/endojs/endo/blob/HEAD/packages/ses/src/error/assert.js*/ /* At https://github.com/Agoric/agoric-sdk/issues/2774*/ /* is a record of a failed attempt to remove '.types'.*/ /* To satisfy CI, not only do we need to keep the file,*/ /* but we need to import it here as well.*/ /*/ <reference path=\\\"./types-ambient.js\\\" />*/\\n\\nconst{freeze}=Object;\\n\\n/** @type {IMPORT('ses').Assert} */\\nconst globalAssert=globalThis.assert;\\n\\nif(globalAssert===undefined){\\nthrow Error(\\n`Cannot initialize @agoric/assert, missing globalThis.assert, import 'ses' before '@agoric/assert'`);}\\n\\n\\n\\nconst missing=/** @type {const} */[\\n'fail',\\n'equal',\\n'typeof',\\n'string',\\n'note',\\n'details',\\n'Fail',\\n'quote',\\n'makeAssert'].\\nfilter((name)=>globalAssert[name]===undefined);\\nif(missing.length>0){\\nthrow Error(\\n`Cannot initialize @agoric/assert, missing globalThis.assert methods ${missing.join(\\n', ')\\n}`);}\\n\\n\\n\\nconst{details,Fail,quote,makeAssert}=globalAssert;\\n\\n\\n\\n/**\\n * @template T\\n * @param {T | null | undefined} val\\n * @param {string} [optDetails]\\n * @returns {T}\\n */\\nconst NonNullish=(val,optDetails=`unexpected ${quote(val)}`)=>{\\nif(val!=null){\\n/* This `!= null` idiom checks that `val` is neither `null` nor `undefined`.*/\\nreturn val;}\\n\\nassert.fail(optDetails);};\\n\\nharden(NonNullish);\\n\\n/**\\n * Prepend the correct indefinite article onto a noun, typically a typeof result\\n * e.g., \\\"an Object\\\" vs. \\\"a Number\\\"\\n *\\n * @deprecated\\n * @param {string} str The noun to prepend\\n * @returns {string} The noun prepended with a/an\\n */\\nfunction an(str){\\nstr=`${str}`;\\nif(str.length>=1&&'aeiouAEIOU'.includes(str[0])){\\nreturn`an ${str}`;}\\n\\nreturn`a ${str}`;}\\n\\nfreeze(an);exports.Fail=Fail;exports.NonNullish=NonNullish;exports.an=an;exports.assert=globalAssert;exports.details=details;exports.makeAssert=makeAssert;exports.q=quote;exports.quote=quote;\",\n \"packages/store/src/index.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var scalarWeakSetStore=require('./stores/scalarWeakSetStore.js');var scalarSetStore=require('./stores/scalarSetStore.js');var scalarWeakMapStore=require('./stores/scalarWeakMapStore.js');var scalarMapStore=require('./stores/scalarMapStore.js');var storeUtils=require('./stores/store-utils.js');require('../../../node_modules/@endo/patterns/index.js');require('../../../node_modules/@endo/exo/index.js');var legacyMap=require('./legacy/legacyMap.js');var legacyWeakMap=require('./legacy/legacyWeakMap.js');require('./types.js');exports.makeScalarWeakSetStore=scalarWeakSetStore.makeScalarWeakSetStore;exports.makeScalarSetStore=scalarSetStore.makeScalarSetStore;exports.makeScalarWeakMapStore=scalarWeakMapStore.makeScalarWeakMapStore;exports.makeScalarMapStore=scalarMapStore.makeScalarMapStore;exports.provideLazy=storeUtils.provideLazy;exports.makeLegacyMap=legacyMap.makeLegacyMap;exports.makeLegacyWeakMap=legacyWeakMap.makeLegacyWeakMap;\",\n \"packages/store/src/legacy/legacyMap.js\": \"'use strict';\\n\\nObject.defineProperty(exports,'__esModule',{value:true});/** @import {LegacyMap, LegacyWeakMap} from '../types.js'; */ /* TODO, once migrated to endo, import from @endo/errors instead*/\\nconst{Fail,quote:q}=assert;\\n\\n/**\\n * This module and its fraternal sibling legacyWeakMap exist only to ease a\\n * transition to the modern `store` system, are deprecated, and will eventually\\n * disappear. They are needed for now to support some of the uses of the old\\n * behavior that are not compatible with the new. The constraint imposed by the\\n * new is that only passables can be used as values, and only keys (roughly,\\n * structures, aka comparables) can be used as values.\\n *\\n * See https://github.com/Agoric/agoric-sdk/pull/3567\\n *\\n * TODO Once that PR is merged, link to the documents rather than the PRs.\\n *\\n * Each of these non-conforming uses should be marked with a\\n *\\n * ```js\\n * // Legacy because...\\n * ```\\n *\\n * comment explaining the problem inhibiting conversion to the new system. Some\\n * of these problems as of this writing:\\n *\\n * - A promiseKit used as a value, even though a promiseKit is not a passable.\\n * Solutions are to make it a passable, or to convert the container back to a\\n * conventional JavaScript Map.\\n * - A mutable array used as a value, that is subsequently mutated. Freezing the\\n * array wouldn't work of course because it would break the subsequent\\n * mutation. Using a far object wrapping an array would likely work fine.\\n *\\n * @deprecated switch to ScalarMap if possible, Map otherwise\\n * @template K,V\\n * @param {string} [tag] - tag for debugging\\n * @returns {LegacyMap<K, V>}\\n */\\nconst makeLegacyMap=(tag='key')=>{\\nconst m=new Map();\\nconst assertKeyDoesNotExist=(key)=>\\n!m.has(key)||Fail`${q(tag)} already registered: ${key}`;\\nconst assertKeyExists=(key)=>\\nm.has(key)||Fail`${q(tag)} not found: ${key}`;\\nreturn harden({\\nhas:(key)=>{\\n/* Check if a key exists. The key can be any JavaScript value,*/\\n/* though the answer will always be false for keys that cannot be found*/\\n/* in this map.*/\\nreturn m.has(key);},\\n\\ninit:(key,value)=>{\\nassertKeyDoesNotExist(key);\\nm.set(key,value);},\\n\\nget:(key)=>{\\nassertKeyExists(key);\\nreturn m.get(key);},\\n\\nset:(key,value)=>{\\nassertKeyExists(key);\\nm.set(key,value);},\\n\\ndelete:(key)=>{\\nassertKeyExists(key);\\nm.delete(key);},\\n\\nkeys:()=>m.keys(),\\nvalues:()=>m.values(),\\nentries:()=>m.entries(),\\ngetSize:()=>m.size,\\nclear:()=>m.clear()});};\\n\\n\\nharden(makeLegacyMap);exports.makeLegacyMap=makeLegacyMap;\",\n \"packages/store/src/legacy/legacyWeakMap.js\": \"'use strict';\\n\\nObject.defineProperty(exports,'__esModule',{value:true});/** @import {LegacyWeakMap} from '../types.js'; */ /* TODO, once migrated to endo, import from @endo/errors instead*/\\nconst{Fail,quote:q}=assert;\\n\\n/**\\n * See doccomment in the closely related `legacyMap.js` module.\\n *\\n * @deprecated switch to ScalarWeakMap if possible, WeakMap otherwise\\n * @template K,V\\n * @param {string} [tag] - tag for debugging\\n * @returns {LegacyWeakMap<K, V>}\\n */\\nconst makeLegacyWeakMap=(tag='key')=>{\\n/** @type {WeakMap<K & object, V>} */\\nconst wm=new WeakMap();\\nconst assertKeyDoesNotExist=(key)=>\\n!wm.has(key)||Fail`${q(tag)} already registered: ${key}`;\\nconst assertKeyExists=(key)=>\\nwm.has(key)||Fail`${q(tag)} not found: ${key}`;\\nreturn harden({\\nhas:(key)=>{\\n/* Check if a key exists. The key can be any JavaScript value,*/\\n/* though the answer will always be false for keys that cannot be found*/\\n/* in this map.*/\\nreturn wm.has(key);},\\n\\ninit:(key,value)=>{\\nassertKeyDoesNotExist(key);\\nwm.set(key,value);},\\n\\nget:(key)=>{\\nassertKeyExists(key);\\n/* How to tell typescript I believe the `get` will succeed.*/\\nreturn(/** @type {V} */wm.get(key));},\\n\\nset:(key,value)=>{\\nassertKeyExists(key);\\nwm.set(key,value);},\\n\\ndelete:(key)=>{\\nassertKeyExists(key);\\nwm.delete(key);}});};\\n\\n\\n\\nharden(makeLegacyWeakMap);exports.makeLegacyWeakMap=makeLegacyWeakMap;\",\n \"packages/store/src/stores/scalarMapStore.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../../../node_modules/@endo/pass-style/index.js');require('../../../../node_modules/@endo/marshal/index.js');require('../../../../node_modules/@endo/patterns/index.js');var scalarWeakMapStore=require('./scalarWeakMapStore.js');var storeUtils=require('./store-utils.js');var rankOrder=require('../../../../node_modules/@endo/marshal/src/rankOrder.js');var patternMatchers=require('../../../../node_modules/@endo/patterns/src/patterns/patternMatchers.js');var iterHelpers=require('../../../../node_modules/@endo/pass-style/src/iter-helpers.js');var checkKey=require('../../../../node_modules/@endo/patterns/src/keys/checkKey.js');var passStyleOf=require('../../../../node_modules/@endo/pass-style/src/passStyleOf.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nmakeFar=require('../../../../node_modules/@endo/pass-style/src/make-far.js');/**\\n * @import {Passable} from '@endo/pass-style');\\n * @import {Key, Pattern} from '@endo/patterns');\\n * @import {MapStore, MapStoreMethods, StoreOptions} from '../types.js';\\n */\\n\\nconst{quote:q}=assert;\\n\\n/**\\n * @template {Key} K\\n * @template {Passable} V\\n * @param {Map<K, V>} jsmap\\n * @param {(k: K, v: V) => void} assertKVOkToAdd\\n * @param {(k: K, v: V) => void} assertKVOkToSet\\n * @param {(k: K) => void} [assertKeyOkToDelete]\\n * @param {string} [tag]\\n * @returns {MapStoreMethods<K, V>}\\n */\\nconst makeMapStoreMethods=(\\njsmap,\\nassertKVOkToAdd,\\nassertKVOkToSet,\\nassertKeyOkToDelete=undefined,\\ntag='key')=>\\n{\\nconst{assertUpdateOnAdd,assertUpdateOnDelete,iterableKeys}=\\nstoreUtils.makeCurrentKeysKit(\\n()=>jsmap.keys(),\\n(k)=>jsmap.has(k),\\nrankOrder.compareRank,\\nassertKVOkToAdd,\\nassertKeyOkToDelete,\\ntag);\\n\\n\\n/**\\n * @param {Pattern} [keyPatt]\\n * @param {Pattern} [valuePatt]\\n * @returns {Iterable<K>}\\n */\\nconst keys=(keyPatt=undefined,valuePatt=undefined)=>{\\nif(keyPatt===undefined&&valuePatt===undefined){\\nreturn iterableKeys;}\\n\\nconst filter=(k)=>{\\nif(keyPatt!==undefined&&!patternMatchers.matches(k,keyPatt)){\\nreturn false;}\\n\\n/* Uses the current jsmap value, since the iteratator survives `.set`*/\\nif(valuePatt!==undefined&&!patternMatchers.matches(jsmap.get(k),valuePatt)){\\nreturn false;}\\n\\nreturn true;};\\n\\nreturn iterHelpers.filterIterable(iterableKeys,filter);};\\n\\n\\n/**\\n * @param {Pattern} [keyPatt]\\n * @param {Pattern} [valuePatt]\\n * @returns {Iterable<V>}\\n */\\nconst values=(keyPatt=undefined,valuePatt=undefined)=>\\niterHelpers.mapIterable(keys(keyPatt,valuePatt),(k)=>/** @type {V} */jsmap.get(k));\\n\\n/**\\n * @param {Pattern} [keyPatt]\\n * @param {Pattern} [valuePatt]\\n * @returns {Iterable<[K, V]>}\\n */\\nconst entries=(keyPatt=undefined,valuePatt=undefined)=>\\niterHelpers.mapIterable(keys(keyPatt,valuePatt),(k)=>[\\nk,\\n/** @type {V} */jsmap.get(k)]);\\n\\n\\nreturn harden({\\n...scalarWeakMapStore.makeWeakMapStoreMethods(\\njsmap,\\n/** @type {(k: K, v: V) => void} */assertUpdateOnAdd,\\nassertKVOkToSet,\\nassertUpdateOnDelete,\\ntag),\\n\\nkeys,\\nvalues,\\nentries,\\n\\nsnapshot:(keyPatt=undefined,valuePatt=undefined)=>\\ncheckKey.makeCopyMap(entries(keyPatt,valuePatt)),\\n\\ngetSize:(keyPatt=undefined,valuePatt=undefined)=>\\nkeyPatt===undefined&&valuePatt===undefined?\\njsmap.size:\\n[...keys(keyPatt,valuePatt)].length,\\n\\nclear:(keyPatt=undefined,valuePatt=undefined)=>{\\nif(keyPatt===undefined&&valuePatt===undefined){\\njsmap.clear();}\\n\\nfor(const key of keys(keyPatt,valuePatt)){\\njsmap.delete(key);}}});};\\n\\n\\n\\n\\n\\n/**\\n * Distinguishes between adding a new key (init) and updating or referencing a\\n * key (get, set, delete).\\n *\\n * `init` is only allowed if the key does not already exist. `Get`, `set` and\\n * `delete` are only allowed if the key does already exist.\\n *\\n * This is a _scalar_ map in that the keys can only be atomic values, primitives\\n * or remotables. Other storeMaps will accept, for example, copyArrays and\\n * copyRecords, as keys and look them up based on equality of their contents.\\n *\\n * @param {string} [tag] - the column name for the key\\n * @param {StoreOptions} [options]\\n * @returns {MapStore<any, any>}\\n */\\nconst makeScalarMapStore=(\\ntag='key',\\n{keyShape=undefined,valueShape=undefined}={})=>\\n{\\nconst jsmap=new Map();\\nif(keyShape!==undefined){\\npatternMatchers.assertPattern(keyShape);}\\n\\nif(valueShape!==undefined){\\npatternMatchers.assertPattern(valueShape);}\\n\\n\\nconst assertKVOkToSet=(_key,value)=>{\\n/* TODO: Just a transition kludge. Remove when possible.*/\\n/* See https://github.com/Agoric/agoric-sdk/issues/3606*/\\nharden(value);\\n\\npassStyleOf.assertPassable(value);\\nif(valueShape!==undefined){\\npatternMatchers.mustMatch(value,valueShape,'mapStore value');}};\\n\\n\\n\\nconst assertKVOkToAdd=(key,value)=>{\\n/* TODO: Just a transition kludge. Remove when possible.*/\\n/* See https://github.com/Agoric/agoric-sdk/issues/3606*/\\nharden(key);\\n\\ncheckKey.assertScalarKey(key);\\nif(keyShape!==undefined){\\npatternMatchers.mustMatch(key,keyShape,'mapStore key');}\\n\\nassertKVOkToSet(key,value);};\\n\\n\\nreturn makeFar.Far(`scalar MapStore of ${q(tag)}`,{\\n...makeMapStoreMethods(\\njsmap,\\nassertKVOkToAdd,\\nassertKVOkToSet,\\nundefined,\\ntag)});};\\n\\n\\n\\nharden(makeScalarMapStore);exports.makeMapStoreMethods=makeMapStoreMethods;exports.makeScalarMapStore=makeScalarMapStore;\",\n \"packages/store/src/stores/scalarSetStore.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../../../node_modules/@endo/pass-style/index.js');require('../../../../node_modules/@endo/marshal/index.js');require('../../../../node_modules/@endo/patterns/index.js');var scalarWeakSetStore=require('./scalarWeakSetStore.js');var storeUtils=require('./store-utils.js');var rankOrder=require('../../../../node_modules/@endo/marshal/src/rankOrder.js');var iterHelpers=require('../../../../node_modules/@endo/pass-style/src/iter-helpers.js');var patternMatchers=require('../../../../node_modules/@endo/patterns/src/patterns/patternMatchers.js');var checkKey=require('../../../../node_modules/@endo/patterns/src/keys/checkKey.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nmakeFar=require('../../../../node_modules/@endo/pass-style/src/make-far.js');/**\\n * @import {Key, Pattern} from '@endo/patterns');\\n * @import {SetStore, SetStoreMethods, StoreOptions} from '../types.js';\\n */\\n\\nconst{quote:q}=assert;\\n\\n/**\\n * @template {Key} K\\n * @param {Set<K>} jsset\\n * @param {(k: K) => void} assertKeyOkToAdd\\n * @param {(k: K) => void} [assertKeyOkToDelete]\\n * @param {string} [keyName]\\n * @returns {SetStoreMethods<K>}\\n */\\nconst makeSetStoreMethods=(\\njsset,\\nassertKeyOkToAdd,\\nassertKeyOkToDelete=undefined,\\nkeyName='key')=>\\n{\\nconst{assertUpdateOnAdd,assertUpdateOnDelete,iterableKeys}=\\nstoreUtils.makeCurrentKeysKit(\\n()=>jsset.keys(),\\n(k)=>jsset.has(k),\\nrankOrder.compareRank,\\nassertKeyOkToAdd,\\nassertKeyOkToDelete,\\nkeyName);\\n\\n\\n/**\\n * @param {Pattern} [keyPatt]\\n * @returns {Iterable<K>}\\n */\\nconst keys=(keyPatt=undefined)=>\\nkeyPatt===undefined?\\niterableKeys:\\niterHelpers.filterIterable(iterableKeys,(k)=>patternMatchers.matches(k,keyPatt));\\n\\nreturn harden({\\n...scalarWeakSetStore.makeWeakSetStoreMethods(\\njsset,\\nassertUpdateOnAdd,\\nassertUpdateOnDelete,\\nkeyName),\\n\\n\\nkeys,\\n\\nvalues:keys,\\n\\nsnapshot:(keyPatt=undefined)=>checkKey.makeCopySet(keys(keyPatt)),\\n\\ngetSize:(keyPatt=undefined)=>\\nkeyPatt===undefined?jsset.size:[...keys(keyPatt)].length,\\n\\nclear:(keyPatt=undefined)=>{\\nif(keyPatt===undefined){\\njsset.clear();}\\n\\nfor(const key of keys(keyPatt)){\\njsset.delete(key);}}});};\\n\\n\\n\\n\\n\\n/**\\n * Distinguishes between adding a new key (init) and updating or referencing a\\n * key (get, set, delete).\\n *\\n * `init` is only allowed if the key does not already exist. `Get`, `set` and\\n * `delete` are only allowed if the key does already exist.\\n *\\n * This is a _scalar_ set in that the keys can only be atomic values, primitives\\n * or remotables. Other storeSets will accept, for example, copyArrays and\\n * copyRecords, as keys and look them up based on equality of their contents.\\n *\\n * @template K\\n * @param {string} [tag] - tag for debugging\\n * @param {StoreOptions} [options]\\n * @returns {SetStore<K>}\\n */\\nconst makeScalarSetStore=(\\ntag='key',\\n{keyShape=undefined}={})=>\\n{\\nconst jsset=new Set();\\nif(keyShape!==undefined){\\npatternMatchers.assertPattern(keyShape);}\\n\\n\\nconst assertKeyOkToAdd=(key)=>{\\n/* TODO: Just a transition kludge. Remove when possible.*/\\n/* See https://github.com/Agoric/agoric-sdk/issues/3606*/\\nharden(key);\\n\\ncheckKey.assertScalarKey(key);\\nif(keyShape!==undefined){\\npatternMatchers.mustMatch(key,keyShape,'setStore key');}};\\n\\n\\n\\nreturn makeFar.Far(`scalar SetStore of ${q(tag)}`,{\\n...makeSetStoreMethods(jsset,assertKeyOkToAdd,undefined,tag)});};\\n\\n\\nharden(makeScalarSetStore);exports.makeScalarSetStore=makeScalarSetStore;exports.makeSetStoreMethods=makeSetStoreMethods;\",\n \"packages/store/src/stores/scalarWeakMapStore.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../../../node_modules/@endo/pass-style/index.js');require('../../../../node_modules/@endo/patterns/index.js');var checkKey=require('../../../../node_modules/@endo/patterns/src/keys/checkKey.js');var patternMatchers=require('../../../../node_modules/@endo/patterns/src/patterns/patternMatchers.js');var passStyleOf=require('../../../../node_modules/@endo/pass-style/src/passStyleOf.js');var\\n\\n\\n\\n\\n\\n\\n\\nmakeFar=require('../../../../node_modules/@endo/pass-style/src/make-far.js');/**\\n * @import {Key} from '@endo/patterns';\\n * @import {Passable, RemotableObject} from '@endo/pass-style';\\n * @import {WeakMapStore, StoreOptions} from '../types.js';\\n */\\n\\nconst{quote:q,Fail}=assert;\\n\\n/**\\n * @template {Key} K\\n * @template {Passable} V\\n * @param {WeakMap<K & object, V>} jsmap\\n * @param {(k: K, v: V) => void} assertKVOkToAdd\\n * @param {(k: K, v: V) => void} assertKVOkToSet\\n * @param {(k: K) => void} [assertKeyOkToDelete]\\n * @param {string} [keyName]\\n * @returns {WeakMapStore<K, V>}\\n */\\nconst makeWeakMapStoreMethods=(\\njsmap,\\nassertKVOkToAdd,\\nassertKVOkToSet,\\nassertKeyOkToDelete=undefined,\\nkeyName='key')=>\\n{\\nconst assertKeyDoesNotExist=(key)=>\\n!jsmap.has(key)||Fail`${q(keyName)} already registered: ${key}`;\\n\\nconst assertKeyExists=(key)=>\\njsmap.has(key)||Fail`${q(keyName)} not found: ${key}`;\\n\\nreturn harden({\\nhas:(key)=>{\\n/* Check if a key exists. The key can be any JavaScript value,*/\\n/* though the answer will always be false for keys that cannot be found*/\\n/* in this map.*/\\nreturn jsmap.has(key);},\\n\\nget:(key)=>{\\nassertKeyExists(key);\\n/* How to tell typescript I believe the `get` will succeed.*/\\nreturn(/** @type {V} */jsmap.get(key));},\\n\\n\\ninit:(key,value)=>{\\nassertKeyDoesNotExist(key);\\nassertKVOkToAdd(key,value);\\njsmap.set(key,value);},\\n\\nset:(key,value)=>{\\nassertKeyExists(key);\\nassertKVOkToSet(key,value);\\njsmap.set(key,value);},\\n\\ndelete:(key)=>{\\nassertKeyExists(key);\\nif(assertKeyOkToDelete!==undefined){\\nassertKeyOkToDelete(key);}\\n\\njsmap.delete(key);},\\n\\n\\naddAll:(entries)=>{\\nif(typeof entries[Symbol.iterator]!=='function'){\\nif(Object.isFrozen(entries)&&checkKey.isCopyMap(entries)){\\n/* @ts-expect-error XXX*/\\nentries=checkKey.getCopyMapEntries(entries);}else\\n{\\nFail`provided data source is not iterable: ${entries}`;}}\\n\\n\\nfor(const[key,value]of/** @type {Iterable<[K, V]>} */entries){\\n/* Don't assert that the key either does or does not exist.*/\\nassertKVOkToAdd(key,value);\\njsmap.set(key,value);}}});};\\n\\n\\n\\n\\n\\n/**\\n * This is a _scalar_ mapStore in that the keys can only be atomic values:\\n * primitives or remotables. Other mapStores will accept, for example,\\n * copyArrays and copyRecords as keys and look them up based on equality of\\n * their contents.\\n *\\n * TODO For now, this scalarWeakMap accepts only remotables, reflecting the\\n * constraints of the underlying JavaScript WeakMap it uses internally. But it\\n * should accept the primitives as well, storing them in a separate internal\\n * map. What makes it \\\"weak\\\" is that it provides no API for enumerating what's\\n * there. Though note that this would only enables collection of the remotables,\\n * since the other primitives may always reappear.\\n *\\n * @template K,V\\n * @param {string} [tag] - tag for debugging\\n * @param {StoreOptions} [options]\\n * @returns {RemotableObject & WeakMapStore<K, V>}\\n */\\nconst makeScalarWeakMapStore=(\\ntag='key',\\n{longLived=true,keyShape=undefined,valueShape=undefined}={})=>\\n{\\nconst jsmap=new(longLived?WeakMap:Map)();\\nif(keyShape!==undefined){\\npatternMatchers.assertPattern(keyShape);}\\n\\nif(valueShape!==undefined){\\npatternMatchers.assertPattern(valueShape);}\\n\\n\\nconst assertKVOkToSet=(_key,value)=>{\\n/* TODO: Just a transition kludge. Remove when possible.*/\\n/* See https://github.com/Agoric/agoric-sdk/issues/3606*/\\nharden(value);\\n\\npassStyleOf.assertPassable(value);\\nif(valueShape!==undefined){\\npatternMatchers.mustMatch(value,valueShape,'weakMapStore value');}};\\n\\n\\n\\nconst assertKVOkToAdd=(key,value)=>{\\n/* TODO: Just a transition kludge. Remove when possible.*/\\n/* See https://github.com/Agoric/agoric-sdk/issues/3606*/\\nharden(key);\\npassStyleOf.passStyleOf(key)==='remotable'||\\nFail`Only remotables can be keys of scalar WeakMapStores: ${key}`;\\nif(keyShape!==undefined){\\npatternMatchers.mustMatch(key,keyShape,'weakMapStore key');}\\n\\nassertKVOkToSet(key,value);};\\n\\n\\nreturn makeFar.Far(`scalar WeakMapStore of ${q(tag)}`,{\\n...makeWeakMapStoreMethods(\\njsmap,\\nassertKVOkToAdd,\\nassertKVOkToSet,\\nundefined,\\ntag)});};\\n\\n\\n\\nharden(makeScalarWeakMapStore);exports.makeScalarWeakMapStore=makeScalarWeakMapStore;exports.makeWeakMapStoreMethods=makeWeakMapStoreMethods;\",\n \"packages/store/src/stores/scalarWeakSetStore.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../../../node_modules/@endo/pass-style/index.js');require('../../../../node_modules/@endo/patterns/index.js');var checkKey=require('../../../../node_modules/@endo/patterns/src/keys/checkKey.js');var patternMatchers=require('../../../../node_modules/@endo/patterns/src/patterns/patternMatchers.js');var passStyleOf=require('../../../../node_modules/@endo/pass-style/src/passStyleOf.js');var makeFar=require('../../../../node_modules/@endo/pass-style/src/make-far.js');\\n\\n\\n\\n\\n\\n\\n\\nconst{quote:q,Fail}=assert;\\n\\n/**\\n * @import {Key} from '@endo/patterns';\\n * @import {StoreOptions, WeakSetStore, WeakSetStoreMethods} from '@agoric/store';\\n */\\n\\n/**\\n * @template {Key} K\\n * @param {WeakSet<K & object>} jsset\\n * @param {(k: K) => void} assertKeyOkToAdd\\n * @param {(k: K) => void} [assertKeyOkToDelete]\\n * @param {string} [keyName]\\n * @returns {WeakSetStoreMethods<K>}\\n */\\nconst makeWeakSetStoreMethods=(\\njsset,\\nassertKeyOkToAdd,\\nassertKeyOkToDelete=undefined,\\nkeyName='key')=>\\n{\\nconst assertKeyExists=(key)=>\\njsset.has(key)||Fail`${q(keyName)} not found: ${key}`;\\n\\nreturn harden({\\nhas:(key)=>{\\n/* Check if a key exists. The key can be any JavaScript value,*/\\n/* though the answer will always be false for keys that cannot be found*/\\n/* in this set.*/\\nreturn jsset.has(key);},\\n\\n\\nadd:(key)=>{\\nassertKeyOkToAdd(key);\\njsset.add(key);},\\n\\ndelete:(key)=>{\\nassertKeyExists(key);\\nif(assertKeyOkToDelete!==undefined){\\nassertKeyOkToDelete(key);}\\n\\njsset.delete(key);},\\n\\n\\naddAll:(keys)=>{\\nif(typeof keys[Symbol.iterator]!=='function'){\\nif(Object.isFrozen(keys)&&checkKey.isCopySet(keys)){\\n/* @ts-expect-error XXX*/\\nkeys=checkKey.getCopySetKeys(keys);}else\\n{\\nFail`provided data source is not iterable: ${keys}`;}}\\n\\n\\nfor(const key of/** @type {Iterable<K>} */keys){\\nassertKeyOkToAdd(key);\\njsset.add(key);}}});};\\n\\n\\n\\n\\n\\n/**\\n * This is a _scalar_ set in that the keys can only be atomic values, primitives\\n * or remotables. Other storeSets will accept, for example, copyArrays and\\n * copyRecords, as keys and look them up based on equality of their contents.\\n *\\n * TODO For now, this scalarWeakSet accepts only remotables, reflecting the\\n * constraints of the underlying JavaScript WeakSet it uses internally. But it\\n * should accept the primitives as well, storing them in a separate internal\\n * set. What makes it \\\"weak\\\" is that it provides no API for enumerating what's\\n * there. Though note that this would only enables collection of the remotables,\\n * since the other primitives may always appear.\\n *\\n * @template K\\n * @param {string} [tag] - tag for debugging\\n * @param {StoreOptions} [options]\\n * @returns {WeakSetStore<K>}\\n */\\nconst makeScalarWeakSetStore=(\\ntag='key',\\n{longLived=true,keyShape=undefined}={})=>\\n{\\nconst jsset=new(longLived?WeakSet:Set)();\\nif(keyShape!==undefined){\\npatternMatchers.assertPattern(keyShape);}\\n\\n\\nconst assertKeyOkToAdd=(key)=>{\\n/* TODO: Just a transition kludge. Remove when possible.*/\\n/* See https://github.com/Agoric/agoric-sdk/issues/3606*/\\nharden(key);\\npassStyleOf.passStyleOf(key)==='remotable'||\\nFail`Only remotables can be keys of scalar WeakStores: ${key}`;\\nif(keyShape!==undefined){\\npatternMatchers.mustMatch(key,keyShape,'weakSetStore key');}};\\n\\n\\n\\nreturn makeFar.Far(`scalar WeakSetStore of ${q(tag)}`,{\\n...makeWeakSetStoreMethods(jsset,assertKeyOkToAdd,undefined,tag)});};\\n\\n\\nharden(makeScalarWeakSetStore);exports.makeScalarWeakSetStore=makeScalarWeakSetStore;exports.makeWeakSetStoreMethods=makeWeakSetStoreMethods;\",\n \"packages/store/src/stores/store-utils.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../../../node_modules/@endo/marshal/index.js');require('../../../../node_modules/@endo/patterns/index.js');var patternMatchers=require('../../../../node_modules/@endo/patterns/src/patterns/patternMatchers.js');var\\n\\n\\nmakeFar=require('../../../../node_modules/@endo/pass-style/src/make-far.js');/**\\n * @import {RankCompare} from '@endo/marshal';\\n * @import {MapStore, WeakMapStore} from '../types.js';\\n * @import {Passable} from '@endo/pass-style';\\n * @import {Key} from '@endo/patterns';\\n */\\n\\nconst{Fail,quote:q}=assert;\\n\\n/* TODO: Undate `@endo/patterns` to export the original, and delete the*/\\n/* reimplementation here.*/\\n/**\\n * Should behave identically to the one in `@endo/patterns`, but reimplemented\\n * for now because `@endo/patterns` forgot to export this one. This one is\\n * simple enough that I prefer a reimplementation to a deep import.\\n *\\n * @param {unknown} s\\n * @returns {s is CopySet}\\n */\\nconst isCopySet=(s)=>patternMatchers.matches(s,patternMatchers.M.set());\\n\\n/* TODO: Undate `@endo/patterns` to export the original, and delete the*/\\n/* reimplementation here.*/\\n/**\\n * Should behave identically to the one in `@endo/patterns`, but reimplemented\\n * for now because `@endo/patterns` forgot to export this one. This one is\\n * simple enough that I prefer a reimplementation to a deep import.\\n *\\n * @param {unknown} m\\n * @returns {m is CopyMap}\\n */\\nconst isCopyMap=(m)=>patternMatchers.matches(m,patternMatchers.M.map());\\n\\n/**\\n * @template {Key} K\\n * @template {Passable} V\\n * @typedef {object} CurrentKeysKit\\n * @property {(k: K, v?: V) => void} assertUpdateOnAdd\\n * @property {(k: K) => void} assertUpdateOnDelete\\n * @property {Iterable<K>} iterableKeys\\n */\\n\\n/**\\n * @template {Key} K\\n * @template {Passable} V\\n * @param {() => Iterable<K>} getRawKeys\\n * @param {(k: K) => boolean} checkHas\\n * @param {RankCompare} compare\\n * @param {(k: K, v?: V) => void} assertOkToAdd\\n * @param {(k: K) => void} [assertOkToDelete]\\n * @param {string} [keyName]\\n * @returns {CurrentKeysKit<K, V>}\\n */\\nconst makeCurrentKeysKit=(\\ngetRawKeys,\\ncheckHas,\\ncompare,\\nassertOkToAdd,\\nassertOkToDelete=undefined,\\nkeyName='key')=>\\n{\\nlet updateCount=0;\\nlet sortedKeysMemo;\\n\\nconst assertUpdateOnAdd=(k,v=undefined)=>{\\nassertOkToAdd(k,v);\\nupdateCount+=1;\\nsortedKeysMemo=undefined;};\\n\\n\\nconst assertUpdateOnDelete=(k)=>assertOkToDelete&&assertOkToDelete(k);\\n\\nconst getSortedKeys=()=>{\\nif(sortedKeysMemo===undefined){\\nsortedKeysMemo=harden([...getRawKeys()].sort(compare));}\\n\\nreturn sortedKeysMemo;};\\n\\n\\nconst iterableKeys=makeFar.Far('Iterable of keys',{\\n[Symbol.iterator]:()=>{\\nconst generation=updateCount;\\ngetSortedKeys();\\nconst len=sortedKeysMemo.length;\\nlet i=0;\\nreturn makeFar.Far('Iterator of keys',{\\nnext:()=>{\\ngeneration===updateCount||Fail`Store ${q(keyName)} cursor stale`;\\n/* If they're equal, then the sortedKeyMemo is the same one*/\\n/* we started with.*/\\nfor(;;){\\nif(i<len){\\nconst value=sortedKeysMemo[i];\\ni+=1;\\nif(checkHas(value)){\\nreturn harden({done:false,value});}}else\\n\\n{\\nreturn harden({done:true,value:undefined});}}}});}});\\n\\n\\n\\n\\n\\n\\n\\nreturn harden({\\nassertUpdateOnAdd,\\nassertUpdateOnDelete,\\niterableKeys});};\\n\\n\\nharden(makeCurrentKeysKit);\\n\\n/**\\n * Call `provideLazy` to get or make the value associated with the key. If there\\n * already is one, return that. Otherwise, call `makeValue(key)`, remember it as\\n * the value for that key, and return it.\\n *\\n * @template {Key} K\\n * @template {Passable} V\\n * @param {WeakMapStore<K, V>} mapStore\\n * @param {K} key\\n * @param {(key: K) => V} makeValue\\n * @returns {V}\\n */\\nconst provideLazy=(mapStore,key,makeValue)=>{\\nif(!mapStore.has(key)){\\nmapStore.init(key,makeValue(key));}\\n\\nreturn mapStore.get(key);};\\n\\nharden(provideLazy);\\n\\n/**\\n * Helper for use cases in which the maker function is async. For two\\n * provideLazy calls with the same key, one may be making when the other call\\n * starts and it would make again. (Then there'd be a collision when the second\\n * tries to store the key.) This prevents that race condition by immediately\\n * storing a Promise for the maker in an ephemeral store.\\n *\\n * When the `store` argument is durable storage, note that it's possible for\\n * termination to happen after the make completes and before it reaches durable\\n * storage.\\n *\\n * @template {Key} K\\n * @template {Passable} V\\n * @param {WeakMapStore<K, V>} store\\n */\\nconst makeAtomicProvider=(store)=>{\\n/** @type {Map<K, Promise<V>>} */\\nconst pending=new Map();\\n\\n/**\\n * Call `provideAsync` to get or make the value associated with the key, when\\n * the maker is asynchronous. If there already is one, return that. Otherwise,\\n * call `makeValue(key)`, remember it as the value for that key, and return\\n * it.\\n *\\n * @param {K} key\\n * @param {(key: K) => Promise<V>} makeValue make the value for the store if\\n * it hasn't been made yet or the last make failed\\n * @param {(key: K, value: V) => Promise<void>} [finishValue] runs exactly\\n * once after a new value is added to the store\\n * @returns {Promise<V>}\\n */\\nconst provideAsync=(key,makeValue,finishValue)=>{\\nif(store.has(key)){\\nreturn Promise.resolve(store.get(key));}\\n\\nif(!pending.has(key)){\\nconst valP=makeValue(key).\\nthen((v)=>{\\nstore.init(key,v);\\nreturn v;}).\\n\\nthen((v)=>{\\nif(finishValue){\\nreturn finishValue(key,v).then(()=>v);}\\n\\nreturn v;}).\\n\\nfinally(()=>{\\npending.delete(key);});\\n\\npending.set(key,valP);}\\n\\nconst valP=pending.get(key);\\nassert(valP);\\nreturn valP;};\\n\\n\\nreturn harden({provideAsync});};\\n\\nharden(makeAtomicProvider);\\n/**\\n * @template {Key} K\\n * @template {Passable} V\\n * @typedef {ReturnType<typeof makeAtomicProvider<K, V>>} AtomicProvider<K, V>\\n */\\n\\n/**\\n * @template {Key} K\\n * @template {Passable} V\\n * @param {MapStore<K, V[]>} mapStore\\n * @param {K} key\\n * @param {V} item\\n */\\nconst appendToStoredArray=(mapStore,key,item)=>{\\nif(mapStore.has(key)){\\nconst extant=mapStore.get(key);\\nmapStore.set(key,harden([...extant,item]));}else\\n{\\nmapStore.init(key,harden([item]));}};\\n\\n\\nharden(appendToStoredArray);exports.appendToStoredArray=appendToStoredArray;exports.isCopyMap=isCopyMap;exports.isCopySet=isCopySet;exports.makeAtomicProvider=makeAtomicProvider;exports.makeCurrentKeysKit=makeCurrentKeysKit;exports.provideLazy=provideLazy;\",\n \"packages/store/src/types.js\": \"\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n'use strict';/*/ <reference types=\\\"ses\\\" />*/ /**\\n * Note TODO https://github.com/endojs/endo/issues/1488\\n *\\n * @import {Passable, RemotableObject} from '@endo/pass-style'\\n * @import {CopySet, CopyMap, Pattern} from '@endo/patterns'\\n * @import {Key} from '@endo/patterns'\\n */ /**\\n * @typedef {object} StoreOptions Of the dimensions on which KeyedStores can\\n * differ, we only represent a few of them as standard options. A given store\\n * maker should document which options it supports, as well as its positions\\n * on dimensions for which it does not support options.\\n * @property {boolean} [longLived] Which way to optimize a weak store. True\\n * means that we expect this weak store to outlive most of its keys, in which\\n * case we internally may use a JavaScript `WeakMap`. Otherwise we internally\\n * may use a JavaScript `Map`. Defaults to true, so please mark short lived\\n * stores explicitly.\\n * @property {boolean} [durable] The contents of this store survive termination\\n * of its containing process, allowing for restart or upgrade but at the cost\\n * of forbidding storage of references to ephemeral data. Defaults to false.\\n * @property {boolean} [fakeDurable] This store pretends to be a durable store\\n * but does not enforce that the things stored in it actually be themselves\\n * durable (whereas an actual durable store would forbid storage of such\\n * items). This is in service of allowing incremental transition to use of\\n * durable stores, to enable normal operation and testing when some stuff\\n * intended to eventually be durable has not yet been made durable. A store\\n * marked as fakeDurable will appear to operate normally but any attempt to\\n * upgrade its containing vat will fail with an error. Defaults to false.\\n * @property {Pattern} [keyShape]\\n * @property {Pattern} [valueShape]\\n */ /**\\n * Most store methods are in one of three categories\\n *\\n * - lookup methods (`has`,`get`)\\n * - update methods (`add`,`init`,`set`,`delete`,`addAll`)\\n * - query methods (`snapshot`,`keys`,`values`,`entries`,`getSize`)\\n * - query-update methods (`clear`)\\n *\\n * WeakStores have the lookup and update methods but not the query or\\n * query-update methods. Non-weak Stores are like their corresponding\\n * WeakStores, but with the additional query and query-update methods.\\n */ /* TODO use Key for K*/ /**\\n * @template K\\n * @typedef {object} WeakSetStoreMethods\\n * @property {(key: K) => boolean} has Check if a key exists. The key can be any\\n * JavaScript value, though the answer will always be false for keys that\\n * cannot be found in this store.\\n * @property {(key: K) => void} add Add the key to the set if it is not already\\n * there. Do nothing silently if already there. The key must be one allowed by\\n * this store. For example a scalar store only allows primitives and\\n * remotables.\\n * @property {(key: K) => void} delete Remove the key. Throws if not found.\\n * @property {(keys: CopySet<any> | Iterable<K>) => void} addAll\\n */ /**\\n * @template K\\n * @typedef {RemotableObject & WeakSetStoreMethods<K>} WeakSetStore\\n */ /* TODO use Key for K*/ /**\\n * @template K\\n * @typedef {object} SetStoreMethods\\n * @property {(key: K) => boolean} has Check if a key exists. The key can be any\\n * JavaScript value, though the answer will always be false for keys that\\n * cannot be found in this store.\\n * @property {(key: K) => void} add Add the key to the set if it is not already\\n * there. Do nothing silently if already there. The key must be one allowed by\\n * this store. For example a scalar store only allows primitives and\\n * remotables.\\n * @property {(key: K) => void} delete Remove the key. Throws if not found.\\n * @property {(keys: CopySet<any> | Iterable<K>) => void} addAll\\n * @property {(keyPatt?: Pattern) => Iterable<K>} keys\\n * @property {(keyPatt?: Pattern) => Iterable<K>} values\\n * @property {(keyPatt?: Pattern) => CopySet<any>} snapshot\\n * @property {(keyPatt?: Pattern) => number} getSize\\n * @property {(keyPatt?: Pattern) => void} clear\\n */ /**\\n * @template K\\n * @typedef {RemotableObject & SetStoreMethods<K>} SetStore\\n */ /* TODO use Key for K*/ /* TODO use Passable for V*/ /**\\n * @template K\\n * @template V\\n * @typedef {object} WeakMapStore\\n * @property {(key: K) => boolean} has Check if a key exists. The key can be any\\n * JavaScript value, though the answer will always be false for keys that\\n * cannot be found in this store.\\n * @property {(key: K) => V} get Return a value for the key. Throws if not\\n * found.\\n * @property {(key: K, value: V) => void} init Initialize the key only if it\\n * doesn't already exist. The key must be one allowed by this store. For\\n * example a scalar store only allows primitives and remotables.\\n * @property {(key: K, value: V) => void} set Set the key. Throws if not found.\\n * @property {(key: K) => void} delete Remove the key. Throws if not found.\\n * @property {(entries: CopyMap<any, any> | Iterable<[K, V]>) => void} addAll\\n */ /* TODO use Key for K*/ /* TODO use Passable for V*/ /**\\n * @template K\\n * @template V\\n * @typedef {object} MapStoreMethods\\n * @property {(key: K) => boolean} has Check if a key exists. The key can be any\\n * JavaScript value, though the answer will always be false for keys that\\n * cannot be found in this map\\n * @property {(key: K) => V} get Return a value for the key. Throws if not\\n * found.\\n * @property {(key: K, value: V) => void} init Initialize the key only if it\\n * doesn't already exist. The key must be one allowed by this store. For\\n * example a scalar store only allows primitives and remotables.\\n * @property {(key: K, value: V) => void} set Set the key. Throws if not found.\\n * @property {(key: K) => void} delete Remove the key. Throws if not found.\\n * @property {(entries: CopyMap<any, Passable> | Iterable<[K, V]>) => void} addAll\\n * @property {(keyPatt?: Pattern, valuePatt?: Pattern) => Iterable<K>} keys\\n * @property {(keyPatt?: Pattern, valuePatt?: Pattern) => Iterable<V>} values\\n * @property {(keyPatt?: Pattern, valuePatt?: Pattern) => Iterable<[K, V]>} entries\\n * @property {(\\n * keyPatt?: Pattern,\\n * valuePatt?: Pattern,\\n * ) => CopyMap<any, Passable>} snapshot\\n * @property {(keyPatt?: Pattern, valuePatt?: Pattern) => number} getSize\\n * @property {(keyPatt?: Pattern, valuePatt?: Pattern) => void} clear\\n */ /**\\n * @template [K=any]\\n * @template [V=any]\\n * @typedef {RemotableObject & MapStoreMethods<K, V>} MapStore\\n */ /* ///////////////////////// Deprecated Legacy /////////////////////////////////*/ /**\\n * @template K\\n * @template V\\n * @typedef {object} LegacyWeakMap LegacyWeakMap is deprecated. Use WeakMapStore\\n * instead if possible.\\n * @property {(key: K) => boolean} has Check if a key exists\\n * @property {(key: K) => V} get Return a value for the key. Throws if not\\n * found.\\n * @property {(key: K, value: V) => void} init Initialize the key only if it\\n * doesn't already exist\\n * @property {(key: K, value: V) => void} set Set the key. Throws if not found.\\n * @property {(key: K) => void} delete Remove the key. Throws if not found.\\n */ /**\\n * @template K\\n * @template V\\n * @typedef {object} LegacyMap LegacyMap is deprecated. Use MapStore instead if\\n * possible.\\n * @property {(key: K) => boolean} has Check if a key exists\\n * @property {(key: K) => V} get Return a value for the key. Throws if not\\n * found.\\n * @property {(key: K, value: V) => void} init Initialize the key only if it\\n * doesn't already exist\\n * @property {(key: K, value: V) => void} set Set the key. Throws if not found.\\n * @property {(key: K) => void} delete Remove the key. Throws if not found.\\n * @property {() => Iterable<K>} keys\\n * @property {() => Iterable<V>} values\\n * @property {() => Iterable<[K, V]>} entries\\n * @property {() => number} getSize\\n * @property {() => void} clear\\n */\",\n \"packages/swingset-liveslots/src/cache.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nassert$1=require('../../assert/src/assert.js');/**\\n * @template V\\n * @callback CacheGet\\n * @param {string} key\\n * @returns {V | undefined}\\n */ /**\\n * @template V\\n * @callback CacheSet\\n * @param {string} key\\n * @param {V} value\\n * @returns {void}\\n */ /**\\n * @callback CacheDelete\\n * @param {string} key\\n * @returns {void}\\n *\\n * @callback CacheFlush\\n * @returns {void}\\n *\\n * @callback CacheInsistClear\\n * @returns {void}\\n */ /**\\n * @template V\\n * @typedef {object} Cache\\n * @property {CacheGet<V>} get\\n * @property {CacheSet<V>} set\\n * @property {CacheDelete} delete\\n * @property {CacheFlush} flush\\n * @property {CacheInsistClear} insistClear\\n */ /**\\n * Cache of virtual object/collection state\\n *\\n * This cache is empty between deliveries. Within a delivery, the\\n * first access to some data will cause vatstore reads to populate the\\n * cache, then the data is retained until end-of-delivery. Writes to\\n * data will update the cache entry and mark it as dirty. At\\n * end-of-delivery, we flush the cache, writing out any dirty entries,\\n * and deleting all entries.\\n *\\n * This needs RAM for everything read during a delivery (rather than\\n * having a fixed maximum size), but yields a simple (easy to debug)\\n * deterministic relationship between data access and reads/writes to\\n * the backing store.\\n *\\n * @template V\\n * @param {(key: string) => V} readBacking\\n * @param {(key: string, value: V) => void} writeBacking\\n * @param {(key: string) => void} deleteBacking\\n * @returns {Cache<V>}\\n *\\n * This cache is part of the virtual object manager and is not intended to be\\n * used independently; it is exported only for the benefit of test code.\\n */function makeCache(readBacking,writeBacking,deleteBacking){const stash=new Map();const dirtyKeys=new Set();/** @type {Cache<V>} */const cache={get:(key)=>{assert.typeof(key,'string');if(stash.has(key)){return stash.get(key);}else if(dirtyKeys.has(key)){/* Respect a pending deletion.*/return undefined;}const value=readBacking(key);stash.set(key,value);return value;},set:(key,value)=>{assert.typeof(key,'string');stash.set(key,value);dirtyKeys.add(key);},delete:(key)=>{assert.typeof(key,'string');stash.delete(key);dirtyKeys.add(key);},flush:()=>{const keys=[...dirtyKeys.keys()];\\nfor(const key of keys.sort()){\\nif(stash.has(key)){\\nwriteBacking(key,stash.get(key));}else\\n{\\ndeleteBacking(key);}}\\n\\n\\nstash.clear();\\ndirtyKeys.clear();},\\n\\ninsistClear:()=>{\\ndirtyKeys.size===0||assert$1.Fail`cache still has dirtyKeys`;\\nstash.size===0||assert$1.Fail`cache still has stash`;}};\\n\\n\\nreturn harden(cache);}exports.makeCache=makeCache;\",\n \"packages/swingset-liveslots/src/capdata.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var\\n\\nassert=require('../../assert/src/assert.js');/**\\n * Assert function to ensure that something expected to be a capdata object\\n * actually is. A capdata object should have a .body property that's a string\\n * and a .slots property that's an array of strings.\\n *\\n * @param {any} capdata The object to be tested\\n * @throws {Error} if, upon inspection, the parameter does not satisfy the above\\n * criteria.\\n * @returns {asserts capdata is IMPORT('./types.js').SwingSetCapData}\\n */\\nfunction insistCapData(capdata){\\ntypeof capdata.body==='string'||\\nassert.Fail`capdata has non-string .body ${capdata.body}`;\\nArray.isArray(capdata.slots)||\\nassert.Fail`capdata has non-Array slots ${capdata.slots}`;\\n/* TODO check that the .slots array elements are actually strings*/}exports.insistCapData=insistCapData;\",\n \"packages/swingset-liveslots/src/collectionManager.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var assert=require('../../assert/src/assert.js');require('../../../node_modules/@endo/far/src/index.js');require('../../../node_modules/@endo/marshal/index.js');require('../../../node_modules/@endo/patterns/index.js');require('../../store/src/index.js');var parseVatSlots=require('./parseVatSlots.js');var vatstoreIterators=require('./vatstore-iterators.js');var cache=require('./cache.js');var rankOrder=require('../../../node_modules/@endo/marshal/src/rankOrder.js');var patternMatchers=require('../../../node_modules/@endo/patterns/src/patterns/patternMatchers.js');var encodePassable=require('../../../node_modules/@endo/marshal/src/encodePassable.js');var passStyleOf=require('../../../node_modules/@endo/pass-style/src/passStyleOf.js');var checkKey=require('../../../node_modules/@endo/patterns/src/keys/checkKey.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nmakeFar=require('../../../node_modules/@endo/pass-style/src/make-far.js');/**\\n * @import {ToCapData, FromCapData} from '@endo/marshal';\\n */ /* XXX TODO: The following key length limit was put in place due to limitations*/ /* in LMDB. With the move away from LMDB, it is no longer relevant, but I'm*/ /* leaving it in place for the time being as a general defensive measure against*/ /* various kind of resource exhaustion mischief. Although the switch to a*/ /* database without the limitation that motivated this would enable this max*/ /* length value to be made larger, current code is already engineered with this*/ /* max in mind, so leaving it in place for the time being it should not pose any*/ /* new challenges. Later, when we have time to examine this more deeply, we*/ /* should consider relaxing or removing this cap.*/const MAX_DBKEY_LENGTH=220;\\nfunction pattEq(p1,p2){\\nreturn rankOrder.compareRank(p1,p2)===0;}\\n\\n\\nfunction matchAny(patt){\\nreturn patt===undefined||pattEq(patt,patternMatchers.M.any());}\\n\\n\\nfunction throwNotDurable(value,slotIndex,serializedValue){\\n/* prettier-ignore*/\\nassert.Fail`value is not durable: ${value} at slot ${assert.quote(slotIndex)} of ${serializedValue.body}`;}\\n\\n\\nfunction failNotFound(key,label){\\nassert.Fail`key ${key} not found in collection ${assert.quote(label)}`;}\\n\\n\\nfunction failNotIterable(value){\\nassert.Fail`provided data source is not iterable: ${value}`;}\\n\\n\\nfunction prefixc(collectionID,dbEntryKey){\\nreturn`vc.${collectionID}.${dbEntryKey}`;}\\n\\n\\n/**\\n * @typedef {object} SchemaCacheValue\\n * @property {Pattern} keyShape\\n * @property {Pattern} valueShape\\n * @property {string} label\\n * @property {object} schemataCapData\\n */\\n\\n/* * Build a cache that holds the schema for each collection.\\n *\\n * The cache maps collectionID to { keyShape, valueShape, label,\\n * schemataCapData }. These are initialized when the collection is\\n * first constructed, and never modified afterwards. The values live\\n * in the vatstore, inside two keys, one for the [keyShape,\\n * valueShape] schemata, another for the label.\\n */\\n\\nfunction makeSchemaCache(syscall,unserialize){\\n/** @type {(collectionID: string) => SchemaCacheValue} */\\nconst readBacking=(collectionID)=>{\\n/* this is only called once per crank*/\\nconst schemataKey=prefixc(collectionID,'|schemata');\\nconst schemataValue=syscall.vatstoreGet(schemataKey);\\nconst schemataCapData=JSON.parse(schemataValue);\\nconst{label,keyShape,valueShape}=unserialize(schemataCapData);\\nreturn harden({keyShape,valueShape,label,schemataCapData});};\\n\\n/** @type {(collectionID: string, value: SchemaCacheValue) => void } */\\nconst writeBacking=(collectionID,value)=>{\\nconst{schemataCapData}=value;\\nconst schemataKey=prefixc(collectionID,'|schemata');\\nconst schemataValue=JSON.stringify(schemataCapData);\\nsyscall.vatstoreSet(schemataKey,schemataValue);};\\n\\n/** @type {(collectionID: string) => void} */\\nconst deleteBacking=(collectionID)=>{\\nconst schemataKey=prefixc(collectionID,'|schemata');\\nsyscall.vatstoreDelete(schemataKey);};\\n\\nreturn cache.makeCache(readBacking,writeBacking,deleteBacking);}\\n\\n\\n/**\\n * @param {*} syscall\\n * @param {IMPORT('./virtualReferences.js').VirtualReferenceManager} vrm\\n * @param {() => number} allocateExportID\\n * @param {() => number} allocateCollectionID\\n * @param {(val: any) => string | undefined} convertValToSlot\\n * @param {*} convertSlotToVal\\n * @param {*} registerValue\\n * @param {ToCapData<string>} serialize\\n * @param {FromCapData<string>} unserialize\\n * @param {(capDatas: any) => void} assertAcceptableSyscallCapdataSize\\n */\\nfunction makeCollectionManager(\\nsyscall,\\nvrm,\\nallocateExportID,\\nallocateCollectionID,\\nconvertValToSlot,\\nconvertSlotToVal,\\nregisterValue,\\nserialize,\\nunserialize,\\nassertAcceptableSyscallCapdataSize)\\n{\\nconst storeKindIDToName=new Map();\\n\\n/** @type { IMPORT('./cache.js').Cache<SchemaCacheValue>} */\\nconst schemaCache=makeSchemaCache(syscall,unserialize);\\n\\nconst storeKindInfo={\\nscalarMapStore:{\\nhasWeakKeys:false,\\nkindID:0,\\n/* eslint-disable-next-line no-use-before-define*/\\nreanimator:reanimateMapStore,\\ndurable:false},\\n\\nscalarWeakMapStore:{\\nhasWeakKeys:true,\\nkindID:0,\\n/* eslint-disable-next-line no-use-before-define*/\\nreanimator:reanimateWeakMapStore,\\ndurable:false},\\n\\nscalarSetStore:{\\nhasWeakKeys:false,\\nkindID:0,\\n/* eslint-disable-next-line no-use-before-define*/\\nreanimator:reanimateSetStore,\\ndurable:false},\\n\\nscalarWeakSetStore:{\\nhasWeakKeys:true,\\nkindID:0,\\n/* eslint-disable-next-line no-use-before-define*/\\nreanimator:reanimateWeakSetStore,\\ndurable:false},\\n\\nscalarDurableMapStore:{\\nhasWeakKeys:false,\\nkindID:0,\\n/* eslint-disable-next-line no-use-before-define*/\\nreanimator:reanimateMapStore,\\ndurable:true},\\n\\nscalarDurableWeakMapStore:{\\nhasWeakKeys:true,\\nkindID:0,\\n/* eslint-disable-next-line no-use-before-define*/\\nreanimator:reanimateWeakMapStore,\\ndurable:true},\\n\\nscalarDurableSetStore:{\\nhasWeakKeys:false,\\nkindID:0,\\n/* eslint-disable-next-line no-use-before-define*/\\nreanimator:reanimateSetStore,\\ndurable:true},\\n\\nscalarDurableWeakSetStore:{\\nhasWeakKeys:true,\\nkindID:0,\\n/* eslint-disable-next-line no-use-before-define*/\\nreanimator:reanimateWeakSetStore,\\ndurable:true}};\\n\\n\\n\\nfunction initializeStoreKindInfo(){\\nlet storeKindIDs={};\\nconst rawTable=syscall.vatstoreGet('storeKindIDTable');\\nif(rawTable){\\nstoreKindIDs=JSON.parse(rawTable);}\\n\\nfor(const kind of Object.getOwnPropertyNames(storeKindInfo)){\\nlet kindID=storeKindIDs[kind];\\nif(!kindID){\\nkindID=allocateExportID();\\nstoreKindIDs[kind]=kindID;}\\n\\nstoreKindInfo[kind].kindID=kindID;\\nstoreKindIDToName.set(`${kindID}`,kind);\\nvrm.registerKind(\\nkindID,\\nstoreKindInfo[kind].reanimator,\\n/* eslint-disable-next-line no-use-before-define*/\\ndeleteCollection,\\nstoreKindInfo[kind].durable);}\\n\\n\\nsyscall.vatstoreSet('storeKindIDTable',JSON.stringify(storeKindIDs));}\\n\\n\\nfunction obtainStoreKindID(kindName){\\nreturn storeKindInfo[kindName].kindID;}\\n\\n\\n/* Now that it's only used for this purpose, what should it be called?*/\\n/* TODO Should we be using the new encodeBigInt scheme instead, anyway?*/\\nconst BIGINT_TAG_LEN=10;\\n\\n/**\\n * Delete an entry from a collection as part of garbage collecting the entry's key.\\n *\\n * @param {string} collectionID - the collection from which the entry is to be deleted\\n * @param {string} vobjID - the entry key being removed\\n *\\n * @returns {boolean} true if this removal possibly introduces a further GC opportunity\\n */\\nfunction deleteCollectionEntry(collectionID,vobjID){\\nconst ordinalKey=prefixc(collectionID,`|${vobjID}`);\\nconst ordinalString=syscall.vatstoreGet(ordinalKey);\\nsyscall.vatstoreDelete(ordinalKey);\\nconst ordinalTag=encodePassable.zeroPad(ordinalString,BIGINT_TAG_LEN);\\nconst recordKey=prefixc(collectionID,`r${ordinalTag}:${vobjID}`);\\nconst rawValue=syscall.vatstoreGet(recordKey);\\nlet doMoreGC=false;\\nif(rawValue!==undefined){\\nconst value=JSON.parse(rawValue);\\ndoMoreGC=value.slots.map(vrm.removeReachableVref).some((b)=>b);\\nsyscall.vatstoreDelete(recordKey);}\\n\\nreturn doMoreGC;}\\n\\nvrm.setDeleteCollectionEntry(deleteCollectionEntry);\\n\\nfunction summonCollectionInternal(_initial,collectionID,kindName){\\nassert.assert.typeof(kindName,'string');\\nconst kindInfo=storeKindInfo[kindName];\\nkindInfo||assert.Fail`unknown collection kind ${kindName}`;\\nconst{hasWeakKeys,durable}=kindInfo;\\nconst getSchema=()=>{\\nconst result=schemaCache.get(collectionID);\\nassert.assert(result!==undefined);\\nreturn result;};\\n\\nconst dbKeyPrefix=`vc.${collectionID}.`;\\nlet currentGenerationNumber=0;\\n\\nconst makeInvalidKeyTypeMsg=(label)=>\\n`invalid key type for collection ${assert.quote(label)}`;\\nconst makeInvalidValueTypeMsg=(label)=>\\n`invalid value type for collection ${assert.quote(label)}`;\\n\\nconst serializeValue=(value)=>{\\nconst{valueShape,label}=getSchema();\\nif(valueShape!==undefined){\\npatternMatchers.mustMatch(value,valueShape,makeInvalidValueTypeMsg(label));}\\n\\nreturn serialize(value);};\\n\\n\\nconst unserializeValue=(data)=>{\\nconst{valueShape,label}=getSchema();\\nconst value=unserialize(data);\\nif(valueShape!==undefined){\\npatternMatchers.mustMatch(value,valueShape,makeInvalidValueTypeMsg(label));}\\n\\nreturn value;};\\n\\n\\nfunction prefix(dbEntryKey){\\nreturn`${dbKeyPrefix}${dbEntryKey}`;}\\n\\n\\nconst encodeRemotable=(remotable)=>{\\n/* eslint-disable-next-line no-use-before-define*/\\nconst ordinal=getOrdinal(remotable);\\nordinal!==undefined||assert.Fail`no ordinal for ${remotable}`;\\nconst ordinalTag=encodePassable.zeroPad(ordinal,BIGINT_TAG_LEN);\\nreturn`r${ordinalTag}:${convertValToSlot(remotable)}`;};\\n\\n\\n/* `makeEncodePassable` has three named options:*/\\n/* `encodeRemotable`, `encodeError`, and `encodePromise`.*/\\n/* Those which are omitted default to a function that always throws.*/\\n/* So by omitting `encodeError` and `encodePromise`, we know that*/\\n/* the resulting function will encode only `Key` arguments.*/\\nconst encodeKey=encodePassable.makeEncodePassable({encodeRemotable});\\n\\nconst vrefFromDBKey=(dbKey)=>dbKey.substring(BIGINT_TAG_LEN+2);\\n\\nconst decodeRemotable=(encodedKey)=>\\nconvertSlotToVal(vrefFromDBKey(encodedKey));\\n\\n/* `makeDecodePassable` has three named options:*/\\n/* `decodeRemotable`, `decodeError`, and `decodePromise`.*/\\n/* Those which are omitted default to a function that always throws.*/\\n/* So by omitting `decodeError` and `decodePromise`, we know that*/\\n/* the resulting function will decode only to `Key` results.*/\\nconst decodeKey=encodePassable.makeDecodePassable({decodeRemotable});\\n\\nfunction generateOrdinal(remotable){\\nconst nextOrdinal=Number.parseInt(\\nsyscall.vatstoreGet(prefix('|nextOrdinal')),\\n10);\\n\\nsyscall.vatstoreSet(\\nprefix(`|${convertValToSlot(remotable)}`),\\n`${nextOrdinal}`);\\n\\nsyscall.vatstoreSet(prefix('|nextOrdinal'),`${nextOrdinal+1}`);}\\n\\n\\nfunction getOrdinal(remotable){\\nreturn syscall.vatstoreGet(prefix(`|${convertValToSlot(remotable)}`));}\\n\\n\\nfunction deleteOrdinal(remotable){\\nsyscall.vatstoreDelete(prefix(`|${convertValToSlot(remotable)}`));}\\n\\n\\nfunction keyToDBKey(key){\\nconst encodedKey=encodeKey(key);\\nassert.assert(encodedKey.length<MAX_DBKEY_LENGTH,'key too large');\\nreturn prefix(encodedKey);}\\n\\n\\nfunction dbKeyToKey(dbKey){\\nconst dbEntryKey=dbKey.substring(dbKeyPrefix.length);\\nreturn decodeKey(dbEntryKey);}\\n\\n\\nfunction has(key){\\nconst{keyShape}=getSchema();\\nif(!patternMatchers.matches(key,keyShape)){\\nreturn false;}else\\nif(passStyleOf.passStyleOf(key)==='remotable'){\\nreturn getOrdinal(key)!==undefined;}else\\n{\\nreturn syscall.vatstoreGet(keyToDBKey(key))!==undefined;}}\\n\\n\\n\\nfunction mustGet(key,label){\\nif(passStyleOf.passStyleOf(key)==='remotable'&&getOrdinal(key)===undefined){\\nfailNotFound(key,label);}\\n\\nconst dbKey=keyToDBKey(key);\\nconst result=syscall.vatstoreGet(dbKey)||failNotFound(key,label);\\nreturn{dbKey,result};}\\n\\n\\nfunction get(key){\\nconst{keyShape,label}=getSchema();\\npatternMatchers.mustMatch(key,keyShape,makeInvalidKeyTypeMsg(label));\\nconst{result}=mustGet(key,label);\\nreturn unserializeValue(JSON.parse(result));}\\n\\n\\nfunction updateEntryCount(delta){\\nif(!hasWeakKeys){\\nconst entryCount=Number.parseInt(\\nsyscall.vatstoreGet(prefix('|entryCount')),\\n10);\\n\\nsyscall.vatstoreSet(prefix('|entryCount'),`${entryCount+delta}`);}}\\n\\n\\n\\nconst doInit=(key,value,precheckedHas)=>{\\nconst{keyShape,label}=getSchema();\\npatternMatchers.mustMatch(key,keyShape,makeInvalidKeyTypeMsg(label));\\nprecheckedHas||\\n!has(key)||\\nassert.Fail`key ${key} already registered in collection ${assert.quote(label)}`;\\nconst serializedValue=serializeValue(value);\\ncurrentGenerationNumber+=1;\\nassertAcceptableSyscallCapdataSize([serializedValue]);\\nif(durable){\\nfor(const[slotIndex,vref]of serializedValue.slots.entries()){\\nif(!vrm.isDurable(vref)){\\nthrowNotDurable(value,slotIndex,serializedValue);}}}\\n\\n\\n\\nif(passStyleOf.passStyleOf(key)==='remotable'){\\n/** @type {string} */\\n/* @ts-expect-error not undefined b/c of has() check*/\\nconst vref=convertValToSlot(key);\\nif(durable){\\nvrm.isDurable(vref)||assert.Fail`key (${key}) is not durable in ${value}`;}\\n\\ngenerateOrdinal(key);\\nif(hasWeakKeys){\\nvrm.addRecognizableValue(key,`${collectionID}`,true);}else\\n{\\nvrm.addReachableVref(vref);}}\\n\\n\\nfor(const vref of serializedValue.slots){\\nvrm.addReachableVref(vref);}\\n\\nsyscall.vatstoreSet(keyToDBKey(key),JSON.stringify(serializedValue));\\nupdateEntryCount(1);};\\n\\n\\nconst init=(key,value)=>doInit(key,value,false);\\n\\nconst addToSet=(key)=>{\\nif(!has(key)){\\ndoInit(key,null,true);}};\\n\\n\\n\\nfunction set(key,value){\\nconst{keyShape,label}=getSchema();\\npatternMatchers.mustMatch(key,keyShape,makeInvalidKeyTypeMsg(label));\\nconst after=serializeValue(harden(value));\\nassertAcceptableSyscallCapdataSize([after]);\\nif(durable){\\nfor(const[i,vref]of after.slots.entries()){\\nif(!vrm.isDurable(vref)){\\nthrowNotDurable(value,i,after);}}}\\n\\n\\n\\nconst{dbKey,result:rawBefore}=mustGet(key,label);\\nconst before=JSON.parse(rawBefore);\\nvrm.updateReferenceCounts(before.slots,after.slots);\\nsyscall.vatstoreSet(dbKey,JSON.stringify(after));}\\n\\n\\nfunction deleteInternal(key){\\nconst{keyShape,label}=getSchema();\\npatternMatchers.mustMatch(key,keyShape,makeInvalidKeyTypeMsg(label));\\nconst{dbKey,result:rawValue}=mustGet(key,label);\\nconst value=JSON.parse(rawValue);\\nconst doMoreGC1=value.slots.map(vrm.removeReachableVref).some((b)=>b);\\nsyscall.vatstoreDelete(dbKey);\\nlet doMoreGC2=false;\\nif(passStyleOf.passStyleOf(key)==='remotable'){\\ndeleteOrdinal(key);\\nif(hasWeakKeys){\\nvrm.removeRecognizableValue(key,`${collectionID}`,true);}else\\n{\\ndoMoreGC2=vrm.removeReachableVref(convertValToSlot(key));}}\\n\\n\\nreturn doMoreGC1||doMoreGC2;}\\n\\n\\nfunction del(key){\\ndeleteInternal(key);\\nupdateEntryCount(-1);}\\n\\n\\nfunction entriesInternal(\\nyieldKeys,\\nyieldValues,\\nkeyPatt=patternMatchers.M.any(),\\nvaluePatt=patternMatchers.M.any())\\n{\\nassert.assert(yieldKeys||yieldValues,'useless entries()');\\npatternMatchers.assertPattern(keyPatt);\\npatternMatchers.assertPattern(valuePatt);\\n\\nconst[coverStart,coverEnd]=patternMatchers.getRankCover(keyPatt,encodeKey);\\nconst start=prefix(coverStart);/* inclusive*/\\nconst end=prefix(coverEnd);/* exclusive*/\\n\\nconst generationAtStart=currentGenerationNumber;\\nconst checkGen=()=>\\ncurrentGenerationNumber===generationAtStart||\\nassert.Fail`keys in store cannot be added to during iteration`;\\n\\nconst needToMatchKey=!matchAny(keyPatt);\\nconst needToMatchValue=!matchAny(valuePatt);\\n\\n/* we might not need to unserialize the dbKey or get the dbValue*/\\nconst needKeys=yieldKeys||needToMatchKey;\\nconst needValues=yieldValues||needToMatchValue;\\n\\n/**\\n * @yields {[any, any]}\\n * @returns {Generator<[any, any], void, unknown>}\\n */\\nfunction*iter(){\\n/* the inner iterator yields all keys for which (start <= key < end)*/\\nconst iterKeys=vatstoreIterators.enumerateKeysStartEnd(syscall,start,end,checkGen);\\n\\n/* and the outer iterator filters by keyPatt/valuePatt and*/\\n/* yields the right [key,value] tuples*/\\nfor(const dbKey of iterKeys){\\nconst key=needKeys?dbKeyToKey(dbKey):undefined;\\n/* safe because needToMatchKey implies needKeys*/\\nif(needToMatchKey&&!patternMatchers.matches(key,keyPatt)){\\ncontinue;}\\n\\nconst value=needValues?\\nunserializeValue(JSON.parse(syscall.vatstoreGet(dbKey))):\\nundefined;\\nif(needToMatchValue&&!patternMatchers.matches(value,valuePatt)){\\ncontinue;}\\n\\nyield[yieldKeys?key:undefined,yieldValues?value:undefined];}}\\n\\n\\nharden(iter);\\nreturn iter();}\\n\\n\\nfunction keys(keyPatt,valuePatt){\\nfunction*iter(){\\nfor(const entry of entriesInternal(true,false,keyPatt,valuePatt)){\\nyield entry[0];}}\\n\\n\\nharden(iter);\\nreturn iter();}\\n\\n\\n/**\\n * Clear the entire contents of a collection non-selectively. Since we are\\n * being unconditional, we don't need to inspect any of the keys to decide\\n * what to do and therefore can avoid deserializing the keys. In particular,\\n * this avoids swapping in any virtual objects that were used as keys, which\\n * can needlessly thrash the virtual object cache when an entire collection\\n * is being deleted.\\n *\\n * @returns {boolean} true if this operation introduces a potential\\n * opportunity to do further GC.\\n */\\nfunction clearInternalFull(){\\nlet doMoreGC=false;\\nconst[coverStart,coverEnd]=patternMatchers.getRankCover(patternMatchers.M.any(),encodeKey);\\nconst start=prefix(coverStart);\\nconst end=prefix(coverEnd);\\n\\n/* this yields all keys for which (start <= key < end)*/\\nfor(const dbKey of vatstoreIterators.enumerateKeysStartEnd(syscall,start,end)){\\nconst value=JSON.parse(syscall.vatstoreGet(dbKey));\\ndoMoreGC=\\nvalue.slots.map(vrm.removeReachableVref).some((b)=>b)||doMoreGC;\\nsyscall.vatstoreDelete(dbKey);\\nif(encodePassable.isEncodedRemotable(dbKey)){\\nconst keyVref=vrefFromDBKey(dbKey);\\nif(hasWeakKeys){\\nvrm.removeRecognizableVref(keyVref,`${collectionID}`,true);}else\\n{\\ndoMoreGC=vrm.removeReachableVref(keyVref)||doMoreGC;}\\n\\nsyscall.vatstoreDelete(prefix(`|${keyVref}`));}}\\n\\n\\nreturn doMoreGC;}\\n\\n\\nfunction clearInternal(isDeleting,keyPatt,valuePatt){\\nlet doMoreGC=false;\\nif(isDeleting||matchAny(keyPatt)&&matchAny(valuePatt)){\\ndoMoreGC=clearInternalFull();}else\\n{\\nfor(const k of keys(keyPatt,valuePatt)){\\ndoMoreGC=deleteInternal(k)||doMoreGC;}}\\n\\n\\nif(!hasWeakKeys&&!isDeleting){\\nsyscall.vatstoreSet(prefix('|entryCount'),'0');}\\n\\nreturn doMoreGC;}\\n\\n\\nfunction clear(keyPatt,valuePatt){\\nclearInternal(false,keyPatt,valuePatt);}\\n\\n\\nfunction values(keyPatt,valuePatt){\\nfunction*iter(){\\nfor(const entry of entriesInternal(false,true,keyPatt,valuePatt)){\\nyield entry[1];}}\\n\\n\\nharden(iter);\\nreturn iter();}\\n\\n\\nfunction entries(keyPatt,valuePatt){\\nfunction*iter(){\\nfor(const entry of entriesInternal(true,true,keyPatt,valuePatt)){\\nyield entry;}}\\n\\n\\nharden(iter);\\nreturn iter();}\\n\\n\\nfunction countEntries(keyPatt,valuePatt){\\nlet count=0;\\n/* eslint-disable-next-line no-unused-vars*/\\nfor(const k of keys(keyPatt,valuePatt)){\\ncount+=1;}\\n\\nreturn count;}\\n\\n\\nfunction getSize(keyPatt,valuePatt){\\nif(matchAny(keyPatt)&&matchAny(valuePatt)){\\nreturn Number.parseInt(syscall.vatstoreGet(prefix('|entryCount')),10);}\\n\\nreturn countEntries(keyPatt,valuePatt);}\\n\\n\\nfunction sizeInternal(){\\nreturn countEntries();}\\n\\n\\nconst snapshotSet=(keyPatt)=>checkKey.makeCopySet(keys(keyPatt));\\n\\nconst snapshotMap=(keyPatt,valuePatt)=>\\ncheckKey.makeCopyMap(entries(keyPatt,valuePatt));\\n\\nconst addAllToSet=(elems)=>{\\nif(typeof elems[Symbol.iterator]!=='function'){\\nelems=\\nObject.isFrozen(elems)&&checkKey.isCopySet(elems)?\\ncheckKey.getCopySetKeys(elems):\\nfailNotIterable(elems);}\\n\\nfor(const elem of elems){\\naddToSet(elem);}};\\n\\n\\n\\nconst addAllToMap=(mapEntries)=>{\\nif(typeof mapEntries[Symbol.iterator]!=='function'){\\nmapEntries=\\nObject.isFrozen(mapEntries)&&checkKey.isCopyMap(mapEntries)?\\ncheckKey.getCopyMapEntries(mapEntries):\\nfailNotIterable(mapEntries);}\\n\\nfor(const[key,value]of mapEntries){\\nif(has(key)){\\nset(key,value);}else\\n{\\ndoInit(key,value,true);}}};\\n\\n\\n\\n\\nreturn{\\nhas,\\nget,\\ngetSize,\\ninit,\\naddToSet,\\nset,\\ndelete:del,\\nkeys,\\nvalues,\\nentries,\\naddAllToSet,\\naddAllToMap,\\nsnapshotSet,\\nsnapshotMap,\\nsizeInternal,\\nclear,\\nclearInternal};}\\n\\n\\n\\nfunction summonCollection(initial,collectionID,kindName){\\nconst hasWeakKeys=storeKindInfo[kindName].hasWeakKeys;\\nconst raw=summonCollectionInternal(initial,collectionID,kindName);\\n\\nconst{\\nhas,\\nget,\\ninit,\\naddToSet,\\naddAllToMap,\\naddAllToSet,\\nset,\\ndelete:del}=\\nraw;\\nconst weakMethods={\\nhas,\\nget,\\ninit,\\naddToSet,\\naddAllToSet,\\naddAllToMap,\\nset,\\ndelete:del};\\n\\n\\nlet collection;\\nif(hasWeakKeys){\\ncollection=weakMethods;}else\\n{\\nconst{\\nkeys,\\nvalues,\\nentries,\\ngetSize,\\nsnapshotSet,\\nsnapshotMap,\\nclear}=\\nraw;\\ncollection={\\n...weakMethods,\\nkeys,\\nvalues,\\nentries,\\ngetSize,\\nsnapshotSet,\\nsnapshotMap,\\nclear};}\\n\\n\\nreturn collection;}\\n\\n\\nfunction storeSizeInternal(vobjID){\\nconst{id,subid}=parseVatSlots.parseVatSlot(vobjID);\\nconst kindName=storeKindIDToName.get(`${id}`);\\nkindName||assert.Fail`unknown kind ID ${id}`;\\nconst collectionID=`${subid}`;\\nconst collection=summonCollectionInternal(false,collectionID,kindName);\\nreturn collection.sizeInternal();}\\n\\n\\nfunction deleteCollection(vobjID){\\nconst{id,subid}=parseVatSlots.parseVatSlot(vobjID);\\nconst kindName=storeKindIDToName.get(`${id}`);\\nconst collectionID=`${subid}`;\\nconst collection=summonCollectionInternal(false,collectionID,kindName);\\n\\nlet doMoreGC=collection.clearInternal(true);\\nconst record=schemaCache.get(collectionID);\\nassert.assert(record!==undefined);\\nconst{schemataCapData}=record;\\ndoMoreGC=\\nschemataCapData.slots.map(vrm.removeReachableVref).some((b)=>b)||\\ndoMoreGC;\\nfor(const dbKey of vatstoreIterators.enumerateKeysWithPrefix(\\nsyscall,\\nprefixc(collectionID,'|')))\\n{\\n/* this key is owned by schemaCache, and will be deleted when*/\\n/* schemaCache is flushed*/\\nif(dbKey.endsWith('|schemata')){\\ncontinue;}\\n\\n/* but we must still delete the other keys (|nextOrdinal and*/\\n/* |entryCount)*/\\nsyscall.vatstoreDelete(dbKey);}\\n\\nschemaCache.delete(collectionID);\\nreturn doMoreGC;}\\n\\n\\nfunction makeCollection(label,kindName,isDurable,keyShape,valueShape){\\nassert.assert.typeof(label,'string');\\nassert.assert(storeKindInfo[kindName]);\\npatternMatchers.assertPattern(keyShape);\\nif(valueShape){\\npatternMatchers.assertPattern(valueShape);}\\n\\nconst collectionID=`${allocateCollectionID()}`;\\nconst kindID=obtainStoreKindID(kindName);\\nconst vobjID=parseVatSlots.makeBaseRef(kindID,collectionID,isDurable);\\n\\nsyscall.vatstoreSet(prefixc(collectionID,'|nextOrdinal'),'1');\\nconst{hasWeakKeys}=storeKindInfo[kindName];\\nif(!hasWeakKeys){\\nsyscall.vatstoreSet(prefixc(collectionID,'|entryCount'),'0');}\\n\\n\\nconst schemata={label};/* don't populate 'undefined', keep it small*/\\nif(keyShape!==undefined){\\nschemata.keyShape=keyShape;}\\n\\nif(valueShape!==undefined){\\nschemata.valueShape=valueShape;}\\n\\nconst schemataCapData=serialize(harden(schemata));\\nif(isDurable){\\nfor(const[slotIndex,vref]of schemataCapData.slots.entries()){\\nif(!vrm.isDurable(vref)){\\nthrowNotDurable(vref,slotIndex,schemataCapData);}}}\\n\\n\\n\\nfor(const vref of schemataCapData.slots){\\nvrm.addReachableVref(vref);}\\n\\n\\nschemaCache.set(\\ncollectionID,\\nharden({keyShape,valueShape,label,schemataCapData}));\\n\\n\\nreturn[vobjID,summonCollection(true,collectionID,kindName)];}\\n\\n\\nfunction collectionToMapStore(collection){\\nconst{\\nhas,\\nget,\\ninit,\\nset,\\ndelete:del,\\naddAllToMap,\\nkeys,\\nvalues,\\nentries,\\nsnapshotMap,\\ngetSize,\\nclear}=\\ncollection;\\nconst mapStore={\\nhas,\\nget,\\ninit,\\nset,\\ndelete:del,\\naddAll:addAllToMap,\\nkeys,\\nvalues,\\nentries,\\nsnapshot:snapshotMap,\\ngetSize,\\nclear};\\n\\nreturn makeFar.Far('mapStore',mapStore);}\\n\\n\\nfunction collectionToWeakMapStore(collection){\\nconst{has,get,init,set,delete:del,addAllToMap}=collection;\\nconst weakMapStore={\\nhas,\\nget,\\ninit,\\nset,\\ndelete:del,\\naddAll:addAllToMap};\\n\\nreturn makeFar.Far('weakMapStore',weakMapStore);}\\n\\n\\nfunction collectionToSetStore(collection){\\nconst{\\nhas,\\naddToSet,\\ndelete:del,\\naddAllToSet,\\nkeys,\\nsnapshotSet,\\ngetSize,\\nclear}=\\ncollection;\\n\\nconst setStore={\\nhas,\\nadd:addToSet,\\ndelete:del,\\naddAll:addAllToSet,\\nkeys:(patt)=>keys(patt),\\nvalues:(patt)=>keys(patt),\\nsnapshot:snapshotSet,\\ngetSize:(patt)=>getSize(patt),\\nclear};\\n\\nreturn makeFar.Far('setStore',setStore);}\\n\\n\\nfunction collectionToWeakSetStore(collection){\\nconst{has,addToSet,delete:del,addAllToSet}=collection;\\n\\nconst weakSetStore={\\nhas,\\nadd:addToSet,\\ndelete:del,\\naddAll:addAllToSet};\\n\\nreturn makeFar.Far('weakSetStore',weakSetStore);}\\n\\n\\n/**\\n * Produce a big map.\\n *\\n * @template K,V\\n * @param {string} [label] - diagnostic label for the store\\n * @param {StoreOptions} [options]\\n * @returns {MapStore<K,V>}\\n */\\nfunction makeBigMapStore(label='map',options={}){\\nconst{\\nkeyShape=patternMatchers.M.any(),\\nvalueShape=undefined,\\ndurable=false}=\\noptions;\\nconst kindName=durable?'scalarDurableMapStore':'scalarMapStore';\\nconst[vobjID,collection]=makeCollection(\\nlabel,\\nkindName,\\ndurable,\\nkeyShape,\\nvalueShape);\\n\\nconst store=collectionToMapStore(collection);\\nregisterValue(vobjID,store,false);\\nreturn store;}\\n\\n\\nfunction provideBaggage(){\\nlet baggageID=syscall.vatstoreGet('baggageID');\\nif(baggageID){\\nreturn convertSlotToVal(baggageID);}else\\n{\\nconst baggage=makeBigMapStore('baggage',{\\nkeyShape:patternMatchers.M.string(),\\ndurable:true});\\n\\nbaggageID=convertValToSlot(baggage);\\nsyscall.vatstoreSet('baggageID',baggageID);\\n/* artificially increment the baggage's refcount so it never gets GC'd*/\\nvrm.addReachableVref(baggageID);\\nreturn baggage;}}\\n\\n\\n\\n/**\\n * Produce a weak big map.\\n *\\n * @template K,V\\n * @param {string} [label] - diagnostic label for the store\\n * @param {StoreOptions} [options]\\n * @returns {WeakMapStore<K,V>}\\n */\\nfunction makeBigWeakMapStore(label='weakMap',options={}){\\nconst{\\nkeyShape=patternMatchers.M.any(),\\nvalueShape=undefined,\\ndurable=false}=\\noptions;\\nconst kindName=durable?\\n'scalarDurableWeakMapStore':\\n'scalarWeakMapStore';\\nconst[vobjID,collection]=makeCollection(\\nlabel,\\nkindName,\\ndurable,\\nkeyShape,\\nvalueShape);\\n\\nconst store=collectionToWeakMapStore(collection);\\nregisterValue(vobjID,store,false);\\nreturn store;}\\n\\n\\n/**\\n * Produce a big set.\\n *\\n * @template K\\n * @param {string} [label] - diagnostic label for the store\\n * @param {StoreOptions} [options]\\n * @returns {SetStore<K>}\\n */\\nfunction makeBigSetStore(label='set',options={}){\\nconst{\\nkeyShape=patternMatchers.M.scalar(),\\nvalueShape=undefined,\\ndurable=false}=\\noptions;\\nconst kindName=durable?'scalarDurableSetStore':'scalarSetStore';\\nconst[vobjID,collection]=makeCollection(\\nlabel,\\nkindName,\\ndurable,\\nkeyShape,\\nvalueShape);\\n\\nconst store=collectionToSetStore(collection);\\nregisterValue(vobjID,store,false);\\nreturn store;}\\n\\n\\n/**\\n * Produce a weak big set.\\n *\\n * @template K\\n * @param {string} [label] - diagnostic label for the store\\n * @param {StoreOptions} [options]\\n * @returns {WeakSetStore<K>}\\n */\\nfunction makeBigWeakSetStore(label='weakSet',options={}){\\nconst{\\nkeyShape=patternMatchers.M.scalar(),\\nvalueShape=undefined,\\ndurable=false}=\\noptions;\\nconst kindName=durable?\\n'scalarDurableWeakSetStore':\\n'scalarWeakSetStore';\\nconst[vobjID,collection]=makeCollection(\\nlabel,\\nkindName,\\ndurable,\\nkeyShape,\\nvalueShape);\\n\\nconst store=collectionToWeakSetStore(collection);\\nregisterValue(vobjID,store,false);\\nreturn store;}\\n\\n\\nfunction reanimateCollection(vobjID){\\nconst{id,subid}=parseVatSlots.parseVatSlot(vobjID);\\nconst collectionID=`${subid}`;\\nconst kindName=storeKindIDToName.get(`${id}`);\\nreturn summonCollection(false,collectionID,kindName);}\\n\\n\\nfunction reanimateMapStore(vobjID){\\nreturn collectionToMapStore(reanimateCollection(vobjID));}\\n\\n\\nfunction reanimateWeakMapStore(vobjID){\\nreturn collectionToWeakMapStore(reanimateCollection(vobjID));}\\n\\n\\nfunction reanimateSetStore(vobjID){\\nreturn collectionToSetStore(reanimateCollection(vobjID));}\\n\\n\\nfunction reanimateWeakSetStore(vobjID){\\nreturn collectionToWeakSetStore(reanimateCollection(vobjID));}\\n\\n\\nconst testHooks={\\nobtainStoreKindID,\\nstoreSizeInternal,\\nmakeCollection};\\n\\n\\n/**\\n * @param {Pattern} baseKeyShape\\n * @param {StoreOptions} options\\n * @returns {StoreOptions}\\n */\\nconst narrowKeyShapeOption=(baseKeyShape,options)=>{\\nconst{keyShape:keyShapeRestriction}=options;\\n/* To prepare for pattern-based compression*/\\n/* https://github.com/Agoric/agoric-sdk/pull/6432*/\\n/* put the substantive pattern, if any, last in the `M.and` since*/\\n/* an `M.and` pattern compresses only according to its last conjunct.*/\\nconst keyShape=\\nkeyShapeRestriction===undefined?\\nbaseKeyShape:\\npatternMatchers.M.and(baseKeyShape,keyShapeRestriction);\\nreturn harden({...options,keyShape});};\\n\\n\\n/**\\n * Produce a *scalar* big map: keys can only be atomic values, primitives, or\\n * remotables.\\n *\\n * @template K,V\\n * @param {string} [label] - diagnostic label for the store\\n * @param {StoreOptions} [options]\\n * @returns {MapStore<K,V>}\\n */\\nconst makeScalarBigMapStore=(label='map',options={})=>\\nmakeBigMapStore(label,narrowKeyShapeOption(patternMatchers.M.scalar(),options));\\n\\n/**\\n * Produce a *scalar* weak big map: keys can only be atomic values,\\n * primitives, or remotables.\\n *\\n * @template K,V\\n * @param {string} [label] - diagnostic label for the store\\n * @param {StoreOptions} [options]\\n * @returns {WeakMapStore<K,V>}\\n */\\nconst makeScalarBigWeakMapStore=(label='weakMap',options={})=>\\nmakeBigWeakMapStore(label,narrowKeyShapeOption(patternMatchers.M.scalar(),options));\\n\\n/**\\n * Produce a *scalar* big set: keys can only be atomic values, primitives, or\\n * remotables.\\n *\\n * @template K\\n * @param {string} [label] - diagnostic label for the store\\n * @param {StoreOptions} [options]\\n * @returns {SetStore<K>}\\n */\\nconst makeScalarBigSetStore=(label='set',options={})=>\\nmakeBigSetStore(label,narrowKeyShapeOption(patternMatchers.M.scalar(),options));\\n\\n/**\\n * Produce a *scalar* weak big set: keys can only be atomic values,\\n * primitives, or remotables.\\n *\\n * @template K\\n * @param {string} [label] - diagnostic label for the store\\n * @param {StoreOptions} [options]\\n * @returns {WeakSetStore<K>}\\n */\\nconst makeScalarBigWeakSetStore=(label='weakSet',options={})=>\\nmakeBigWeakSetStore(label,narrowKeyShapeOption(patternMatchers.M.scalar(),options));\\n\\nconst flushSchemaCache=()=>schemaCache.flush();\\n\\nfunction getRetentionStats(){\\nreturn{};}\\n\\n\\nreturn harden({\\ninitializeStoreKindInfo,\\nmakeScalarBigMapStore,\\nmakeScalarBigWeakMapStore,\\nmakeScalarBigSetStore,\\nmakeScalarBigWeakSetStore,\\nprovideBaggage,\\nflushSchemaCache,\\ngetRetentionStats,\\ntestHooks});}exports.makeCollectionManager=makeCollectionManager;\",\n \"packages/swingset-liveslots/src/facetiousness.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var\\n\\nassert=require('../../assert/src/assert.js');/**\\n * Assess the facetiousness of a value. If the value is an object containing\\n * only named properties and each such property's value is a function, `obj`\\n * represents a single facet and 'one' is returned. If each property's value\\n * is instead an object of facetiousness 'one', `obj` represents multiple\\n * facets and 'many' is returned. In all other cases `obj` does not represent\\n * any kind of facet abstraction and 'not' is returned.\\n *\\n * @typedef {'one'|'many'|'not'} Facetiousness\\n *\\n * @param {*} obj The (alleged) object to be assessed\\n * @returns {Facetiousness} an assessment of the facetiousness of `obj`\\n */\\nfunction assessFacetiousness(obj){\\nif(typeof obj!=='object'){\\nreturn'not';}\\n\\nlet result;\\nfor(const prop of Reflect.ownKeys(obj)){\\nconst value=obj[prop];\\nlet resultFromProp;\\nif(typeof value==='function'){\\nresultFromProp='one';}else\\nif(\\n/* symbols are not permitted as facet names*/\\ntypeof prop!=='symbol'&&\\nassessFacetiousness(value)==='one')\\n{\\nresultFromProp='many';}else\\n{\\nreturn'not';}\\n\\nif(!result){\\n/* capture the result of inspecting the first property*/\\nresult=resultFromProp;}else\\nif(resultFromProp!==result){\\n/* and bail out upon encountering any deviation*/\\nreturn'not';}}\\n\\n\\n/* empty objects are methodless Far objects*/\\nreturn(/** @type {Facetiousness} */result||'one');}\\n\\n\\n/* note: mutates 'desc' in-place*/\\nconst checkAndUpdateFacetiousness=(tag,desc,proposedFacetNames)=>{\\n/* The first time a durable kind gets a definition, the saved*/\\n/* descriptor will have neither \\\".unfaceted\\\" nor \\\".facets\\\", and we*/\\n/* must update the details in the descriptor. When a later*/\\n/* incarnation redefines the behavior, we must check for*/\\n/* compatibility (all old facets must still be defined). We*/\\n/* re-assign .facets/.unfaceted each time, even if we're not*/\\n/* changing anything.*/\\n\\nif(desc.unfaceted&&proposedFacetNames){\\nassert.Fail`defineDurableKindMulti called for unfaceted KindHandle ${tag}`;}\\n\\nif(desc.facets&&!proposedFacetNames){\\nassert.Fail`defineDurableKind called for faceted KindHandle ${tag}`;}\\n\\nlet newFacetNames;\\nif(proposedFacetNames){\\nconst oldFacetNames=desc.facets?[...desc.facets]:[];\\nconst proposal=[...proposedFacetNames];\\nnewFacetNames=[];\\n/* all old facets must be present in the proposal*/\\nfor(const facet of oldFacetNames){\\nconst proposedIdx=proposal.indexOf(facet);\\nif(proposedIdx===-1){\\nconst orig=oldFacetNames.join(',');\\nconst newer=proposedFacetNames.join(',');\\nassert.Fail`durable kind \\\"${tag}\\\" facets (${newer}) is missing ${facet} from original definition (${orig})`;}\\n\\nproposal.splice(proposedIdx,1);/* remove from proposal*/\\nnewFacetNames.push(facet);}\\n\\n\\n/* new facets are appended in alphabetic order*/\\nproposal.sort();\\ndesc.facets=newFacetNames.concat(proposal);}else\\n{\\ndesc.unfaceted=true;}\\n\\nreturn desc.facets;/* 'undefined' for unfaceted*/\\n/* caller will saveDurableKindDescriptor()*/};exports.assessFacetiousness=assessFacetiousness;exports.checkAndUpdateFacetiousness=checkAndUpdateFacetiousness;\",\n \"packages/swingset-liveslots/src/index.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var liveslots=require('./liveslots.js');var message=require('./message.js');require('./types.js');require('./vatDataTypes.js');/*/ <reference types=\\\"@agoric/store/exported.js\\\" />*/exports.makeLiveSlots=liveslots.makeLiveSlots;exports.makeMarshaller=liveslots.makeMarshaller;exports.insistMessage=message.insistMessage;exports.insistVatDeliveryObject=message.insistVatDeliveryObject;exports.insistVatDeliveryResult=message.insistVatDeliveryResult;exports.insistVatSyscallObject=message.insistVatSyscallObject;exports.insistVatSyscallResult=message.insistVatSyscallResult;\",\n \"packages/swingset-liveslots/src/kdebug.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});let enableKDebug=false;\\n\\nfunction kdebugEnable(flag){\\nenableKDebug=!!flag;}\\n\\n\\nfunction kdebug(...args){\\nif(enableKDebug){\\nconsole.log(...args);}}\\n\\n\\n\\nfunction legibilizeValue(val,slots,smallcaps){\\ntry{\\nif(Array.isArray(val)){\\nlet result='[';\\nfor(const elem of val){\\nif(result.length!==1){\\nresult+=', ';}\\n\\nresult+=legibilizeValue(elem,slots,smallcaps);}\\n\\nresult+=']';\\nreturn result;}else\\nif(val&&typeof val==='object'&&val.constructor===Object){\\nconst qClass=val['@qclass'];\\nif(qClass&&!smallcaps){\\nswitch(qClass){\\ncase'undefined':\\ncase'NaN':\\ncase'Infinity':\\ncase'-Infinity':\\nreturn qClass;\\ncase'bigint':\\nreturn val.digits;\\ncase'slot':\\nreturn`@${slots[val.index]}`;\\ncase'symbol':\\nreturn`[${val.name}]`;\\ncase'@@asyncIterator':\\nreturn`[Symbol.asyncIterator]`;\\ncase'error':\\nreturn`new ${val.name}('${val.message}')`;\\ndefault:\\n/* unknown qClass, treat it like any other object literal*/\\nbreak;}}\\n\\n\\nlet result='{';\\nfor(const prop of Object.getOwnPropertyNames(val)){\\nif(result.length!==1){\\nresult+=', ';}\\n\\n/* prettier-ignore*/\\nresult+=`${String(prop)}: ${legibilizeValue(val[prop],slots,smallcaps)}`;}\\n\\nresult+='}';\\nreturn result;}else\\nif(val&&typeof val==='string'&&smallcaps){\\nconst prefix=val.charAt(0);\\nconst rest=val.substring(1);\\nswitch(prefix){\\ncase'!':\\nreturn`\\\"${rest}\\\"`;\\ncase'%':\\nreturn`[${rest}]`;\\ncase'#':\\ncase'+':\\ncase'-':\\nreturn rest;\\ncase'$':\\ncase'&':{\\nconst idx=Number(rest.slice(0,rest.indexOf('.')));\\nreturn`@${slots[idx]}`;}\\n\\ndefault:\\nreturn JSON.stringify(val)||'<unintelligible value>';}}else\\n\\n{\\nreturn JSON.stringify(val)||'<unintelligible value>';}}\\n\\ncatch{\\nreturn'<unintelligible value>';}}\\n\\n\\n\\nfunction legibilizeMethod(method,smallcaps){\\ntry{\\nif(typeof method==='string'){\\nif(!smallcaps){\\nreturn method;}\\n\\nconst prefix=method.charAt(0);\\nconst rest=method.substring(1);\\nswitch(prefix){\\ncase'%':\\nreturn`[${rest}]`;\\ncase'#':\\nif(rest==='undefined'){\\nreturn'<funcall>';}else\\n{\\nreturn'<unintelligible method>';}\\n\\ncase'!':\\nreturn rest;\\ncase'+':\\ncase'-':\\ncase'$':\\ncase'&':\\nreturn'<unintelligible method>';\\ndefault:\\nreturn method;}}else\\n\\nif(typeof method==='symbol'){\\nreturn`[${method.toString()}]`;}else\\nif(method===undefined){\\nreturn'<funcall>';}else\\nif(typeof method==='object'){\\nif(smallcaps){\\nreturn'<unintelligible method>';}\\n\\nconst qclass=method['@qclass'];\\nif(qclass==='undefined'){\\nreturn'<funcall>';}else\\nif(qclass==='symbol'){\\nreturn`[${method.name}]`;}else\\nif(qclass==='@@asyncIterator'){\\nreturn`[Symbol.asyncIterator]`;}else\\n{\\nreturn'<invalid method type>';}}else\\n\\n{\\nreturn'<unintelligible method>';}}\\n\\ncatch{\\nreturn'<unintelligible method>';}}\\n\\n\\n\\nfunction extractMethod(methargsCapdata){\\ntry{\\nlet smallcaps=false;\\nlet bodyString=methargsCapdata.body;\\nif(bodyString.charAt(0)==='#'){\\nsmallcaps=true;\\nbodyString=bodyString.substring(1);}\\n\\nconst methargs=JSON.parse(bodyString);\\nreturn legibilizeMethod(methargs[0],smallcaps);}\\ncatch{\\nreturn'<unknown>';}}\\n\\n\\n\\nfunction legibilizeMessageArgs(methargsCapdata){\\ntry{\\nlet smallcaps=false;\\nlet bodyString=methargsCapdata.body;\\nif(bodyString.charAt(0)==='#'){\\nsmallcaps=true;\\nbodyString=bodyString.substring(1);}\\n\\nconst methargs=JSON.parse(bodyString);\\nconst[method,args]=methargs;\\nconst methodStr=legibilizeMethod(method,smallcaps);\\nconst argsStrs=args.map((arg)=>\\nlegibilizeValue(arg,methargsCapdata.slots,smallcaps));\\n\\nreturn[methodStr,argsStrs.join(', ')];}\\ncatch{\\nreturn'<unintelligible message args>';}}exports.extractMethod=extractMethod;exports.kdebug=kdebug;exports.kdebugEnable=kdebugEnable;exports.legibilizeMessageArgs=legibilizeMessageArgs;exports.legibilizeMethod=legibilizeMethod;exports.legibilizeValue=legibilizeValue;\",\n \"packages/swingset-liveslots/src/liveslots.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../../node_modules/@endo/marshal/index.js');var assert=require('../../assert/src/assert.js');require('../../../node_modules/@endo/promise-kit/index.js');var noShim=require('../../../node_modules/@endo/eventual-send/src/no-shim.js');var parseVatSlots=require('./parseVatSlots.js');var capdata=require('./capdata.js');var kdebug=require('./kdebug.js');var message=require('./message.js');var virtualReferences=require('./virtualReferences.js');var virtualObjectManager=require('./virtualObjectManager.js');var collectionManager=require('./collectionManager.js');var watchedPromises=require('./watchedPromises.js');var makeFar=require('../../../node_modules/@endo/pass-style/src/make-far.js');var marshal=require('../../../node_modules/@endo/marshal/src/marshal.js');var isPromise=require('../../../node_modules/@endo/promise-kit/src/is-promise.js');var passStyleOf=require('../../../node_modules/@endo/pass-style/src/passStyleOf.js');var remotable=require('../../../node_modules/@endo/pass-style/src/remotable.js');\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nconst SYSCALL_CAPDATA_BODY_SIZE_LIMIT=10_000_000;\\nconst SYSCALL_CAPDATA_SLOTS_LENGTH_LIMIT=10_000;\\n\\nconst{details:X}=assert.assert;\\n\\n/* 'makeLiveSlots' is a dispatcher which uses javascript Maps to keep track*/\\n/* of local objects which have been exported. These cannot be persisted*/\\n/* beyond the runtime of the javascript environment, so this mechanism is not*/\\n/* going to work for our in-chain hosts.*/\\n\\n/**\\n * Instantiate the liveslots layer for a new vat and then populate the vat with\\n * a new root object and its initial associated object graph, if any.\\n *\\n * @param {*} syscall Kernel syscall interface that the vat will have access to\\n * @param {*} forVatID Vat ID label, for use in debug diagnostics\\n * @param {*} vatPowers\\n * @param {IMPORT('./types.js').LiveSlotsOptions} liveSlotsOptions\\n * @param {*} gcTools { WeakRef, FinalizationRegistry, waitUntilQuiescent, gcAndFinalize,\\n * meterControl }\\n * @param {Pick<Console, 'debug' | 'log' | 'info' | 'warn' | 'error'>} console\\n * @param {*} buildVatNamespace\\n *\\n * @returns {*} { dispatch }\\n */\\nfunction build(\\nsyscall,\\nforVatID,\\nvatPowers,\\nliveSlotsOptions={},\\ngcTools,\\nconsole,\\nbuildVatNamespace)\\n{\\nconst{enableDisavow=false,relaxDurabilityRules=false}=\\nliveSlotsOptions;\\nconst{WeakRef,FinalizationRegistry,meterControl}=gcTools;\\nconst enableLSDebug=false;\\nfunction lsdebug(...args){\\nif(enableLSDebug){\\nconsole.log(...args);}}\\n\\n\\n\\nlet didStartVat=false;\\nconst didStopVat=false;\\n\\nconst outstandingProxies=new WeakSet();\\n\\nlet syscallCapdataBodySizeLimit=SYSCALL_CAPDATA_BODY_SIZE_LIMIT;\\nlet syscallCapdataSlotsLengthLimit=SYSCALL_CAPDATA_SLOTS_LENGTH_LIMIT;\\n\\nfunction setSyscallCapdataLimits(\\nbodySizeLimit=SYSCALL_CAPDATA_BODY_SIZE_LIMIT,\\nslotsLengthLimit=SYSCALL_CAPDATA_SLOTS_LENGTH_LIMIT)\\n{\\nsyscallCapdataBodySizeLimit=bodySizeLimit;\\nsyscallCapdataSlotsLengthLimit=slotsLengthLimit;}\\n\\n\\nfunction isAcceptableSyscallCapdataSize(capdatas){\\nlet bodySizeTotal=0;\\nlet slotsLengthTotal=0;\\nfor(const capdata of capdatas){\\nbodySizeTotal+=capdata.body.length;\\nslotsLengthTotal+=capdata.slots.length;}\\n\\nreturn(\\nbodySizeTotal<=syscallCapdataBodySizeLimit&&\\nslotsLengthTotal<=syscallCapdataSlotsLengthLimit);}\\n\\n\\n\\nfunction assertAcceptableSyscallCapdataSize(capdatas){\\nassert.assert(\\nisAcceptableSyscallCapdataSize(capdatas),\\n'syscall capdata too large');}\\n\\n\\n\\n/**\\n * Translation and tracking tables to map in-vat object/promise references\\n * to/from vat-format slot strings.\\n *\\n * Exports: pass-by-presence objects (Remotables) in the vat are exported as\\n * o+NN slots, as are \\\"virtual object\\\" exports. Promises are exported as p+NN\\n * slots. We retain a strong reference to all exports via the\\n * `exportedRemotables` Set until the kernel tells us all external references\\n * have been dropped via dispatch.dropExports, or by some unilateral\\n * revoke-object operation executed by our user-level code.\\n *\\n * Imports: o-NN slots are represented as a Presence. p-NN slots are\\n * represented as an imported Promise, with the resolver held in an\\n * additional table (importedPromisesByPromiseID) to handle a future\\n * incoming resolution message. We retain a weak reference to the Presence,\\n * and use a FinalizationRegistry to learn when the vat has dropped it, so\\n * we can notify the kernel. We retain strong references to unresolved\\n * Promises. When an import is added, the finalizer is added to\\n * `vreffedObjectRegistry`.\\n *\\n * slotToVal is a Map whose keys are slots (strings) and the values are\\n * WeakRefs. If the entry is present but wr.deref()===undefined (the\\n * weakref is dead), treat that as if the entry was not present. The same\\n * slotToVal table is used for both imports and returning exports. The\\n * subset of those which need to be held strongly (exported objects and\\n * promises, imported promises) are kept alive by `exportedRemotables`.\\n *\\n * valToSlot is a WeakMap whose keys are Remotable/Presence/Promise\\n * objects, and the keys are (string) slot identifiers. This is used\\n * for both exports and returned imports.\\n *\\n * We use two weak maps plus the strong `exportedRemotables` set, because\\n * it seems simpler than using four separate maps (import-vs-export times\\n * strong-vs-weak).\\n */\\n\\n/** @type {WeakMap<object, string>} */\\nconst valToSlot=new WeakMap();/* object -> vref*/\\nconst slotToVal=new Map();/* baseRef -> WeakRef(object)*/\\nconst exportedRemotables=new Set();/* objects*/\\nconst kernelRecognizableRemotables=new Set();/* vrefs*/\\nconst importedDevices=new Set();/* device nodes*/\\nconst possiblyDeadSet=new Set();/* baseRefs that need to be checked for being dead*/\\nconst possiblyRetiredSet=new Set();/* vrefs that might need to be rechecked for being retired*/\\n\\n/* importedVPIDs and exportedVPIDs track all promises which the*/\\n/* kernel knows about: the kernel is the decider for importedVPIDs,*/\\n/* and we are the decider for exportedVPIDs*/\\n\\n/* We do not need to include the ancillary promises that*/\\n/* resolutionCollector() creates: those are resolved immediately*/\\n/* after export. However we remove those during resolution just in*/\\n/* case they overlap with non-ancillary ones.*/\\n\\nconst exportedVPIDs=new Map();/* VPID -> Promise, kernel-known, vat-decided*/\\nconst importedVPIDs=new Map();/* VPID -> { promise, resolve, reject }, kernel-known+decided*/\\n\\nfunction retainExportedVref(vref){\\n/* if the vref corresponds to a Remotable, keep a strong reference to it*/\\n/* until the kernel tells us to release it*/\\nconst{type,allocatedByVat,virtual,durable}=parseVatSlots.parseVatSlot(vref);\\nif(type==='object'&&allocatedByVat){\\nif(virtual||durable){\\n/* eslint-disable-next-line no-use-before-define*/\\nvrm.setExportStatus(vref,'reachable');}else\\n{\\n/* eslint-disable-next-line no-use-before-define*/\\nconst remotable=requiredValForSlot(vref);\\nexportedRemotables.add(remotable);\\nkernelRecognizableRemotables.add(vref);}}}\\n\\n\\n\\n\\n/* Imports are in one of 5 states: UNKNOWN, REACHABLE, UNREACHABLE,\\n COLLECTED, FINALIZED. Note that there's no actual state machine with those\\n values, and we can't observe all of the transitions from JavaScript, but\\n we can describe what operations could cause a transition, and what our\\n observations allow us to deduce about the state:\\n * UNKNOWN moves to REACHABLE when a crank introduces a new import\\n * userspace holds a reference only in REACHABLE\\n * REACHABLE moves to UNREACHABLE only during a userspace crank\\n * UNREACHABLE moves to COLLECTED when GC runs, which queues the finalizer\\n * COLLECTED moves to FINALIZED when a new turn runs the finalizer\\n * liveslots moves from FINALIZED to UNKNOWN by syscalling dropImports\\n convertSlotToVal either imports a vref for the first time, or\\n re-introduces a previously-seen vref. It transitions from:\\n * UNKNOWN to REACHABLE by creating a new Presence\\n * UNREACHABLE to REACHABLE by re-using the old Presence that userspace\\n forgot about\\n * COLLECTED/FINALIZED to REACHABLE by creating a new Presence\\n Our tracking tables hold data that depends on the current state:\\n * slotToVal holds a WeakRef in [REACHABLE, UNREACHABLE, COLLECTED]\\n * that WeakRef .deref()s into something in [REACHABLE, UNREACHABLE]\\n * deadSet holds the vref only in FINALIZED\\n * re-introduction must ensure the vref is not in the deadSet\\n Each state thus has a set of perhaps-measurable properties:\\n * UNKNOWN: slotToVal[baseRef] is missing, baseRef not in deadSet\\n * REACHABLE: slotToVal has live weakref, userspace can reach\\n * UNREACHABLE: slotToVal has live weakref, userspace cannot reach\\n * COLLECTED: slotToVal[baseRef] has dead weakref\\n * FINALIZED: slotToVal[baseRef] is missing, baseRef is in deadSet\\n Our finalizer callback is queued by the engine's transition from\\n UNREACHABLE to COLLECTED, but the baseRef might be re-introduced before the\\n callback has a chance to run. There might even be multiple copies of the\\n finalizer callback queued. So the callback must deduce the current state\\n and only perform cleanup (i.e. delete the slotToVal entry and add the\\n baseRef to the deadSet) in the COLLECTED state.\\n */\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nfunction finalizeDroppedObject(baseRef){\\n/* TODO: Ideally this function should assert that it is not metered. This*/\\n/* appears to be fine in practice, but it breaks a number of unit tests in*/\\n/* ways that are not obvious how to fix.*/\\n/* meterControl.assertNotMetered();*/\\nconst wr=slotToVal.get(baseRef);\\n/* The finalizer for a given Presence might run in any state:*/\\n/* * COLLECTED: most common. Action: move to FINALIZED*/\\n/* * REACHABLE/UNREACHABLE: after re-introduction. Action: ignore*/\\n/* * FINALIZED: after re-introduction and subsequent finalizer invocation*/\\n/* (second finalizer executed for the same baseRef). Action: be idempotent*/\\n/* * UNKNOWN: after re-introduction, multiple finalizer invocation,*/\\n/* and post-crank cleanup does dropImports and deletes baseRef from*/\\n/* deadSet. Action: ignore*/\\n\\nif(wr&&!wr.deref()){\\n/* we're in the COLLECTED state, or FINALIZED after a re-introduction*/\\n/* eslint-disable-next-line no-use-before-define*/\\naddToPossiblyDeadSet(baseRef);\\nslotToVal.delete(baseRef);}}\\n\\n\\nconst vreffedObjectRegistry=new FinalizationRegistry(finalizeDroppedObject);\\n\\nasync function scanForDeadObjects(){\\n/* `possiblyDeadSet` accumulates vrefs which have lost a supporting*/\\n/* pillar (in-memory, export, or virtualized data refcount) since the*/\\n/* last call to scanForDeadObjects. The vref might still be supported*/\\n/* by a remaining pillar, or the pillar which was dropped might be back*/\\n/* (e.g., given a new in-memory manifestation).*/\\n\\nconst importsToDrop=new Set();\\nconst importsToRetire=new Set();\\nconst exportsToRetire=new Set();\\nlet doMore;\\nawait null;\\ndo{\\ndoMore=false;\\n\\nawait gcTools.gcAndFinalize();\\n\\n/* possiblyDeadSet contains a baseref for everything (Presences,*/\\n/* Remotables, Representatives) that might have lost a*/\\n/* pillar. The object might still be supported by other pillars,*/\\n/* and the lost pillar might have been reinstantiated by the*/\\n/* time we get here. The first step is to filter this down to a*/\\n/* list of definitely dead baserefs.*/\\n\\nconst deadSet=new Set();\\n\\nfor(const baseRef of possiblyDeadSet){\\nif(slotToVal.has(baseRef)){\\ncontinue;/* RAM pillar remains*/}\\n\\nconst{virtual,durable,type}=parseVatSlots.parseVatSlot(baseRef);\\nassert.assert(type==='object',`unprepared to track ${type}`);\\nif(virtual||durable){\\n/* eslint-disable-next-line no-use-before-define*/\\nif(vrm.isVirtualObjectReachable(baseRef)){\\ncontinue;/* vdata or export pillar remains*/}}\\n\\n\\ndeadSet.add(baseRef);}\\n\\npossiblyDeadSet.clear();\\n\\n/* deadSet now contains objects which are certainly dead*/\\n\\n/* possiblyRetiredSet holds (a subset of??) baserefs which have*/\\n/* lost a recognizer recently. TODO recheck this*/\\n\\nfor(const vref of possiblyRetiredSet){\\n/* eslint-disable-next-line no-use-before-define*/\\nif(!getValForSlot(vref)&&!deadSet.has(vref)){\\n/* Don't retire things that haven't yet made the transition to dead,*/\\n/* i.e., always drop before retiring*/\\n/* eslint-disable-next-line no-use-before-define*/\\nif(!vrm.isVrefRecognizable(vref)){\\nimportsToRetire.add(vref);}}}\\n\\n\\n\\npossiblyRetiredSet.clear();\\n\\nconst deadBaseRefs=Array.from(deadSet);\\ndeadBaseRefs.sort();\\nfor(const baseRef of deadBaseRefs){\\nconst{virtual,durable,allocatedByVat,type}=\\nparseVatSlots.parseVatSlot(baseRef);\\ntype==='object'||assert.Fail`unprepared to track ${type}`;\\nif(virtual||durable){\\n/* Representative: send nothing, but perform refcount checking*/\\n/* eslint-disable-next-line no-use-before-define*/\\nconst[gcAgain,retirees]=vrm.deleteVirtualObject(baseRef);\\nif(retirees){\\nretirees.map((retiree)=>exportsToRetire.add(retiree));}\\n\\ndoMore=doMore||gcAgain;}else\\nif(allocatedByVat){\\n/* Remotable: send retireExport*/\\n/* for remotables, vref === baseRef*/\\nif(kernelRecognizableRemotables.has(baseRef)){\\nkernelRecognizableRemotables.delete(baseRef);\\nexportsToRetire.add(baseRef);}}else\\n\\n{\\n/* Presence: send dropImport unless reachable by VOM*/\\n/* eslint-disable-next-line no-lonely-if, no-use-before-define*/\\nif(!vrm.isPresenceReachable(baseRef)){\\nimportsToDrop.add(baseRef);\\n/* eslint-disable-next-line no-use-before-define*/\\nif(!vrm.isVrefRecognizable(baseRef)){\\n/* for presences, baseRef === vref*/\\nimportsToRetire.add(baseRef);}}}}}while(\\n\\n\\n\\n\\npossiblyDeadSet.size>0||possiblyRetiredSet.size>0||doMore);\\n\\nif(importsToDrop.size){\\nsyscall.dropImports(Array.from(importsToDrop).sort());}\\n\\nif(importsToRetire.size){\\nsyscall.retireImports(Array.from(importsToRetire).sort());}\\n\\nif(exportsToRetire.size){\\nsyscall.retireExports(Array.from(exportsToRetire).sort());}}\\n\\n\\n\\n/**\\n * Remember disavowed Presences which will kill the vat if you try to talk\\n * to them\\n */\\nconst disavowedPresences=new WeakSet();\\nconst disavowalError=harden(Error(`this Presence has been disavowed`));\\n\\nfunction makeImportedPresence(slot,iface=`Alleged: presence ${slot}`){\\n/* Called by convertSlotToVal for type=object (an `o-NN` reference). We*/\\n/* build a Presence for application-level code to receive. This Presence*/\\n/* is associated with 'slot' so that all handled messages get sent to*/\\n/* that slot: pres~.foo() causes a syscall.send(target=slot, msg=foo).*/\\n\\nlsdebug(`makeImportedPresence(${slot})`);\\nconst fulfilledHandler={\\napplyMethod(o,prop,args,returnedP){\\n/* Support: o~.[prop](...args) remote method invocation*/\\nlsdebug(`makeImportedPresence handler.applyMethod (${slot})`);\\nif(disavowedPresences.has(o)){\\n/* eslint-disable-next-line no-use-before-define*/\\nexitVatWithFailure(disavowalError);\\nthrow disavowalError;}\\n\\n/* eslint-disable-next-line no-use-before-define*/\\nreturn queueMessage(slot,prop,args,returnedP);},\\n\\napplyFunction(o,args,returnedP){\\nreturn fulfilledHandler.applyMethod(o,undefined,args,returnedP);},\\n\\nget(o,prop){\\nlsdebug(`makeImportedPresence handler.get (${slot})`);\\nif(disavowedPresences.has(o)){\\n/* eslint-disable-next-line no-use-before-define*/\\nexitVatWithFailure(disavowalError);\\nthrow disavowalError;}\\n\\n/* FIXME: Actually use remote property lookup*/\\nreturn o[prop];}};\\n\\n\\n\\nlet remotePresence;\\nconst p=new noShim.HandledPromise((_res,_rej,resolveWithPresence)=>{\\n/* Use Remotable rather than Far to make a remote from a presence*/\\nremotePresence=makeFar.Remotable(\\niface,\\nundefined,\\nresolveWithPresence(fulfilledHandler));\\n\\n/* remote === presence, actually*/\\n\\n/* todo: mfig says resolveWithPresence*/\\n/* gives us a Presence, Remotable gives us a Remote. I think that*/\\n/* implies we have a lot of renaming to do, 'makeRemote' instead of*/\\n/* 'makeImportedPresence', etc. I'd like to defer that for a later*/\\n/* cleanup/renaming pass.*/});\\n/* no unfulfilledHandler*/\\n\\n/* The call to resolveWithPresence performs the forwarding logic*/\\n/* immediately, so by the time we reach here, E(presence).foo() will use*/\\n/* our fulfilledHandler, and nobody can observe the fact that we failed*/\\n/* to provide an unfulfilledHandler.*/\\n\\n/* We throw 'p' away, but it is retained by the internal tables of*/\\n/* HandledPromise, and will be returned to anyone who calls*/\\n/* `HandledPromise.resolve(presence)`. So we must harden it now, for*/\\n/* safety, to prevent it from being used as a communication channel*/\\n/* between isolated objects that share a reference to the Presence.*/\\nvoid harden(p);\\n\\n/* Up at the application level, presence~.foo(args) starts by doing*/\\n/* HandledPromise.resolve(presence), which retrieves it, and then does*/\\n/* p.eventualSend('foo', [args]), which uses the fulfilledHandler.*/\\n\\n/* We harden the presence for the same safety reasons.*/\\nreturn harden(remotePresence);}\\n\\n\\nfunction makePipelinablePromise(vpid){\\n/* Called by convertSlotToVal(type=promise) for incoming promises (a*/\\n/* `p-NN` reference), and by queueMessage() for the result of an outbound*/\\n/* message (a `p+NN` reference). We build a Promise for application-level*/\\n/* code, to which messages can be pipelined, and we prepare for the*/\\n/* kernel to tell us that it has been resolved in various ways.*/\\nparseVatSlots.insistVatType('promise',vpid);\\nlsdebug(`makePipelinablePromise(${vpid})`);\\n\\n/* The Promise will we associated with a handler that converts p~.foo() into*/\\n/* a syscall.send() that targets the vpid. When the Promise is resolved*/\\n/* (during receipt of a dispatch.notify), this Promise's handler will be*/\\n/* replaced by the handler of the resolution, which might be a Presence or a*/\\n/* local object.*/\\n\\n/* for safety as we shake out bugs in HandledPromise, we guard against*/\\n/* this handler being used after it was supposed to be resolved*/\\nlet handlerActive=true;\\nconst unfulfilledHandler={\\napplyMethod(_p,prop,args,returnedP){\\n/* Support: p~.[prop](...args) remote method invocation*/\\nlsdebug(`makePipelinablePromise handler.applyMethod (${vpid})`);\\nif(!handlerActive){\\nconsole.error(`mIPromise handler called after resolution`);\\nassert.Fail`mIPromise handler called after resolution`;}\\n\\n/* eslint-disable-next-line no-use-before-define*/\\nreturn queueMessage(vpid,prop,args,returnedP);},\\n\\nget(p,prop){\\n/* Support: p~.[prop]*/\\nlsdebug(`makePipelinablePromise handler.get (${vpid})`);\\nif(!handlerActive){\\nconsole.error(`mIPromise handler called after resolution`);\\nassert.Fail`mIPromise handler called after resolution`;}\\n\\n/* FIXME: Actually pipeline.*/\\nreturn noShim.E.when(p,(o)=>o[prop]);}};\\n\\n\\n\\nlet resolve;\\nlet reject;\\nconst p=new noShim.HandledPromise((res,rej,_resPres)=>{\\nresolve=res;\\nreject=rej;},\\nunfulfilledHandler);\\n\\n/* Prepare for the kernel to tell us about resolution. Both ensure the*/\\n/* old handler should never be called again. TODO: once we're confident*/\\n/* about how we interact with HandledPromise, just use harden({ resolve,*/\\n/* reject }).*/\\nconst pRec=harden({\\npromise:p,\\nresolve(resolution){\\nhandlerActive=false;\\nresolve(resolution);},\\n\\n\\nreject(rejection){\\nhandlerActive=false;\\nreject(rejection);}});\\n\\n\\nreturn pRec;}\\n\\n\\nfunction makeDeviceNode(id,iface=`Alleged: device ${id}`){\\nreturn makeFar.Remotable(iface);}\\n\\n\\n/* TODO: fix awkward non-orthogonality: allocateExportID() returns a number,*/\\n/* allocatePromiseID() returns a slot, registerPromise() uses the slot from*/\\n/* allocatePromiseID(), exportPassByPresence() generates a slot itself using*/\\n/* the number from allocateExportID(). Both allocateX fns should return a*/\\n/* number or return a slot; both exportY fns should either create a slot or*/\\n/* use a slot from the corresponding allocateX*/\\n\\nfunction allocateExportID(){\\n/* eslint-disable-next-line no-use-before-define*/\\nreturn vrm.allocateNextID('exportID');}\\n\\n\\nfunction allocateCollectionID(){\\n/* eslint-disable-next-line no-use-before-define*/\\nreturn vrm.allocateNextID('collectionID');}\\n\\n\\nfunction allocatePromiseID(){\\n/* eslint-disable-next-line no-use-before-define*/\\nconst promiseID=vrm.allocateNextID('promiseID');\\nreturn parseVatSlots.makeVatSlot('promise',true,promiseID);}\\n\\n\\nconst knownResolutions=new WeakMap();\\n\\n/**\\n * Determines if a vref from a watched promise or outbound argument\\n * identifies a promise that should be exported, and if so then\\n * adds it to exportedVPIDs and sets up handlers.\\n *\\n * @param {any} vref\\n * @returns {boolean} whether the vref was added to exportedVPIDs\\n */\\nfunction maybeExportPromise(vref){\\n/* we only care about new vpids*/\\nif(\\nparseVatSlots.parseVatSlot(vref).type==='promise'&&\\n!exportedVPIDs.has(vref)&&\\n!importedVPIDs.has(vref))\\n{\\nconst vpid=vref;\\n/* The kernel is about to learn about this promise (syscall.send*/\\n/* arguments or syscall.resolve resolution data), so prepare to*/\\n/* do a syscall.resolve when it fires. The caller must finish*/\\n/* doing their syscall before this turn finishes, to ensure the*/\\n/* kernel isn't surprised by a spurious resolution.*/\\n/* eslint-disable-next-line no-use-before-define*/\\nconst p=requiredValForSlot(vpid);\\n/* if (!knownResolutions.has(p)) { // TODO really?*/\\n/* eslint-disable-next-line no-use-before-define*/\\nfollowForKernel(vpid,p);\\nreturn true;}\\n\\nreturn false;}\\n\\n\\nfunction exportPassByPresence(){\\nconst exportID=allocateExportID();\\nreturn parseVatSlots.makeVatSlot('object',true,exportID);}\\n\\n\\n/* eslint-disable-next-line no-use-before-define*/\\nconst m=marshal.makeMarshal(convertValToSlot,convertSlotToVal,{\\nmarshalName:`liveSlots:${forVatID}`,\\nserializeBodyFormat:'smallcaps',\\n/* TODO Temporary hack.*/\\n/* See https://github.com/Agoric/agoric-sdk/issues/2780*/\\nerrorIdNum:70_000,\\nmarshalSaveError:(err)=>\\n/* By sending this to `console.warn`, under cosmic-swingset this is*/\\n/* controlled by the `console` option given to makeLiveSlots.*/\\nconsole.warn('Logging sent error stack',err)});\\n\\nconst unmeteredUnserialize=meterControl.unmetered(m.unserialize);\\n/* eslint-disable-next-line no-use-before-define*/\\nconst unmeteredConvertSlotToVal=meterControl.unmetered(convertSlotToVal);\\n\\nfunction getSlotForVal(val){\\nreturn valToSlot.get(val);}\\n\\n\\nfunction getValForSlot(baseRef){\\nmeterControl.assertNotMetered();\\nconst wr=slotToVal.get(baseRef);\\nreturn wr&&wr.deref();}\\n\\n\\nfunction requiredValForSlot(baseRef){\\nconst wr=slotToVal.get(baseRef);\\nconst result=wr&&wr.deref();\\nresult||assert.Fail`no value for ${baseRef}`;\\nreturn result;}\\n\\n\\nfunction addToPossiblyDeadSet(baseRef){\\npossiblyDeadSet.add(baseRef);}\\n\\n\\nfunction addToPossiblyRetiredSet(vref){\\npossiblyRetiredSet.add(vref);}\\n\\n\\nconst vrm=virtualReferences.makeVirtualReferenceManager(\\nsyscall,\\ngetSlotForVal,\\nrequiredValForSlot,\\nFinalizationRegistry,\\nWeakRef,\\naddToPossiblyDeadSet,\\naddToPossiblyRetiredSet,\\nrelaxDurabilityRules);\\n\\n\\nconst vom=virtualObjectManager.makeVirtualObjectManager(\\nsyscall,\\nvrm,\\nallocateExportID,\\ngetSlotForVal,\\nrequiredValForSlot,\\n/* eslint-disable-next-line no-use-before-define*/\\nregisterValue,\\nm.serialize,\\nunmeteredUnserialize,\\nassertAcceptableSyscallCapdataSize,\\nliveSlotsOptions);\\n\\n\\nconst collectionManager$1=collectionManager.makeCollectionManager(\\nsyscall,\\nvrm,\\nallocateExportID,\\nallocateCollectionID,\\n/* eslint-disable-next-line no-use-before-define*/\\nconvertValToSlot,\\nunmeteredConvertSlotToVal,\\n/* eslint-disable-next-line no-use-before-define*/\\nregisterValue,\\nm.serialize,\\nunmeteredUnserialize,\\nassertAcceptableSyscallCapdataSize);\\n\\n\\nconst watchedPromiseManager=watchedPromises.makeWatchedPromiseManager({\\nsyscall,\\nvrm,\\nvom,\\ncollectionManager:collectionManager$1,\\n/* eslint-disable-next-line no-use-before-define*/\\nconvertValToSlot,\\nconvertSlotToVal:unmeteredConvertSlotToVal,\\nmaybeExportPromise});\\n\\n\\nfunction convertValToSlot(val){\\n/* lsdebug(`serializeToSlot`, val, Object.isFrozen(val));*/\\n/* This is either a Presence (in presenceToImportID), a*/\\n/* previously-serialized local pass-by-presence object or*/\\n/* previously-serialized local Promise (in valToSlot), a new local*/\\n/* pass-by-presence object, or a new local Promise.*/\\n\\n/* If we've already assigned it an importID or exportID, it might be in*/\\n/* slots/slotMap for this particular act of serialization. If it's new,*/\\n/* it certainly will not be in slotMap. If we've already serialized it in*/\\n/* this particular act, it will definitely be in slotMap.*/\\n\\nif(!valToSlot.has(val)){\\nlet slot;\\n/* must be a new export/store*/\\n/* lsdebug('must be a new export', JSON.stringify(val));*/\\nif(isPromise.isPromise(val)){\\n/* the promise either appeared in outbound arguments, or in a*/\\n/* virtual-object store operation, so immediately after*/\\n/* serialization we'll either add it to exportedVPIDs or*/\\n/* increment a vdata refcount*/\\nslot=allocatePromiseID();}else\\n{\\nif(disavowedPresences.has(val)){\\n/* eslint-disable-next-line no-use-before-define*/\\nexitVatWithFailure(disavowalError);\\nthrow disavowalError;/* cannot reference a disavowed object*/}\\n\\nassert.assert.equal(passStyleOf.passStyleOf(val),'remotable');\\nslot=exportPassByPresence();}\\n\\nconst{type,baseRef}=parseVatSlots.parseVatSlot(slot);/* also used as assertion*/\\nvalToSlot.set(val,slot);\\nslotToVal.set(baseRef,new WeakRef(val));\\nif(type==='object'){\\n/* Set.delete() metering seems unaffected by presence/absence, but it*/\\n/* doesn't matter anyway because deadSet.add only happens when*/\\n/* finializers run, and we wrote xsnap.c to ensure they only run*/\\n/* deterministically (during gcAndFinalize)*/\\nvreffedObjectRegistry.register(val,baseRef,val);}}\\n\\n\\nreturn valToSlot.get(val);}\\n\\n\\nlet importedPromises=null;\\nfunction beginCollectingPromiseImports(){\\nimportedPromises=new Set();}\\n\\nfunction finishCollectingPromiseImports(){\\nconst result=importedPromises;\\nimportedPromises=null;\\nreturn result;}\\n\\n\\nfunction registerValue(baseRef,val,valIsCohort){\\nconst{type,id,facet}=parseVatSlots.parseVatSlot(baseRef);\\n!facet||\\nassert.Fail`registerValue(${baseRef} should not receive individual facets`;\\nslotToVal.set(baseRef,new WeakRef(val));\\nif(valIsCohort){\\nfor(const[index,name]of vrm.getFacetNames(id).entries()){\\nvalToSlot.set(val[name],`${baseRef}:${index}`);}}else\\n\\n{\\nvalToSlot.set(val,baseRef);}\\n\\n/* we don't dropImports on promises, to avoid interaction with retire*/\\nif(type==='object'){\\nvreffedObjectRegistry.register(val,baseRef,val);}}\\n\\n\\n\\n/* The meter usage of convertSlotToVal is strongly affected by GC, because*/\\n/* it only creates a new Presence if one does not already exist. Userspace*/\\n/* moves from REACHABLE to UNREACHABLE, but the JS engine then moves to*/\\n/* COLLECTED (and maybe FINALIZED) on its own, and we must not allow the*/\\n/* latter changes to affect metering. So every call to convertSlotToVal (or*/\\n/* m.unserialize) must be wrapped by unmetered().*/\\nfunction convertSlotToVal(slot,iface=undefined){\\nmeterControl.assertNotMetered();\\nconst{type,allocatedByVat,id,virtual,durable,facet,baseRef}=\\nparseVatSlots.parseVatSlot(slot);\\nlet val=getValForSlot(baseRef);\\nif(val){\\nif(virtual||durable){\\nif(facet!==undefined){\\nreturn vrm.getFacet(id,val,facet);}}\\n\\n\\nreturn val;}\\n\\nlet result;\\nif(virtual||durable){\\nassert.assert.equal(type,'object');\\ntry{\\nval=vrm.reanimate(baseRef);}\\ncatch(err){\\nconst wrappedError=assert.assert.error(X`failed to reanimate ${iface}`);\\nassert.assert.note(wrappedError,X`Original error: ${err}`);\\nthrow wrappedError;}\\n\\nif(facet!==undefined){\\nresult=vrm.getFacet(id,val,facet);}}else\\n\\n{\\n!allocatedByVat||assert.Fail`I don't remember allocating ${slot}`;\\nif(type==='object'){\\n/* this is a new import value*/\\nval=makeImportedPresence(slot,iface);}else\\nif(type==='promise'){\\nconst pRec=makePipelinablePromise(slot);\\nimportedVPIDs.set(slot,pRec);\\nval=pRec.promise;\\n/* ideally we'd wait until .then is called on p before subscribing,*/\\n/* but the current Promise API doesn't give us a way to discover*/\\n/* this, so we must subscribe right away. If we were using Vows or*/\\n/* some other then-able, we could just hook then() to notify us.*/\\nif(importedPromises){\\n/* leave the subscribe() up to dispatch.notify()*/\\nimportedPromises.add(slot);}else\\n{\\n/* probably in dispatch.deliver(), so subscribe now*/\\nsyscall.subscribe(slot);}}else\\n\\nif(type==='device'){\\nval=makeDeviceNode(slot,iface);\\nimportedDevices.add(val);}else\\n{\\nassert.Fail`unrecognized slot type '${type}'`;}}\\n\\n\\nregisterValue(baseRef,val,facet!==undefined);\\nif(!result){\\nresult=val;}\\n\\nreturn result;}\\n\\n\\nfunction revivePromise(slot){\\nmeterControl.assertNotMetered();\\nconst{type}=parseVatSlots.parseVatSlot(slot);\\ntype==='promise'||assert.Fail`revivePromise called on non-promise ${slot}`;\\n!getValForSlot(slot)||assert.Fail`revivePromise called on pre-existing ${slot}`;\\nconst pRec=makePipelinablePromise(slot);\\nimportedVPIDs.set(slot,pRec);\\nconst p=pRec.promise;\\nregisterValue(slot,p);\\nreturn p;}\\n\\nconst unmeteredRevivePromise=meterControl.unmetered(revivePromise);\\n\\nfunction resolutionCollector(){\\nconst resolutions=[];\\nconst doneResolutions=new Set();\\n\\nfunction scanSlots(slots){\\nfor(const slot of slots){\\nconst{type}=parseVatSlots.parseVatSlot(slot);\\nif(type==='promise'){\\n/* this can run metered because it's supposed to always be present*/\\nconst p=requiredValForSlot(slot);\\nconst priorResolution=knownResolutions.get(p);\\nif(priorResolution&&!doneResolutions.has(slot)){\\nconst[priorRejected,priorRes]=priorResolution;\\n/* eslint-disable-next-line no-use-before-define*/\\ncollect(slot,priorRejected,priorRes);}}}}\\n\\n\\n\\n\\n\\nfunction collect(promiseID,rejected,value){\\ndoneResolutions.add(promiseID);\\nmeterControl.assertIsMetered();/* else userspace getters could escape*/\\nlet valueSer;\\ntry{\\nvalueSer=m.serialize(value);}\\ncatch(e){\\n/* Serialization failure.*/\\nvalueSer=m.serialize(e);\\nrejected=true;}\\n\\nvalueSer.slots.map(retainExportedVref);\\n/* do maybeExportPromise() next to the syscall, not here*/\\nresolutions.push([promiseID,rejected,valueSer]);\\nscanSlots(valueSer.slots);}\\n\\n\\nfunction forPromise(promiseID,rejected,value){\\ncollect(promiseID,rejected,value);\\nreturn resolutions;}\\n\\n\\nfunction forSlots(slots){\\nscanSlots(slots);\\nreturn resolutions;}\\n\\n\\nreturn{\\nforPromise,\\nforSlots};}\\n\\n\\n\\nfunction queueMessage(targetSlot,prop,args,returnedP){\\nconst methargs=[prop,args];\\n\\nmeterControl.assertIsMetered();/* else userspace getters could escape*/\\nconst serMethargs=m.serialize(harden(methargs));\\nassertAcceptableSyscallCapdataSize([serMethargs]);\\nserMethargs.slots.map(retainExportedVref);\\n\\nconst resultVPID=allocatePromiseID();\\nlsdebug(`Promise allocation ${forVatID}:${resultVPID} in queueMessage`);\\n/* create a Promise which callers follow for the result, give it a*/\\n/* handler so we can pipeline messages to it, and prepare for the kernel*/\\n/* to notify us of its resolution*/\\nconst pRec=makePipelinablePromise(resultVPID);\\n\\n/* userspace sees `returnedP` (so that's what we need to register*/\\n/* in slotToVal, and what's what we need to retain with a strong*/\\n/* reference via importedVPIDs), but when dispatch.notify arrives,*/\\n/* we need to fire `pRec.promise` because that's what we've got*/\\n/* the firing controls for*/\\nimportedVPIDs.set(resultVPID,harden({...pRec,promise:returnedP}));\\nvalToSlot.set(returnedP,resultVPID);\\nslotToVal.set(resultVPID,new WeakRef(returnedP));\\n\\n/* prettier-ignore*/\\nlsdebug(\\n`ls.qm send(${JSON.stringify(targetSlot)}, ${kdebug.legibilizeMethod(prop)}) -> ${resultVPID}`);\\n\\nsyscall.send(targetSlot,serMethargs,resultVPID);\\n\\n/* The vpids in the syscall.send might be in A:exportedVPIDs,*/\\n/* B:importedVPIDs, or C:neither. Just after the send(), we are*/\\n/* newly on the hook for following the ones in C:neither. One*/\\n/* option would be to feed all the syscall.send slots to*/\\n/* maybeExportPromise(), which will sort them into A/B/C, then*/\\n/* take everything in C:neither and do a .then on it and add it to*/\\n/* exportedVPIDs. Then we call it a day, and allow all the*/\\n/* resolutions to be delivered in a later turn.*/\\n/**/\\n/* But instead, we choose the option that says \\\"but many of those*/\\n/* promises might already be resolved\\\", and if there's more than*/\\n/* one, we could amortize some syscall overhead by emitting all*/\\n/* the known resolutions in a 2-or-larger batch, and in this*/\\n/* moment (in this turn) we have a whole list of them that we can*/\\n/* check synchronously.*/\\n/**/\\n/* To implement this option, the sequence is:*/\\n/* * use W to name the vpids in syscall.send*/\\n/* * feed W into resolutionCollector(), to get 'resolutions'*/\\n/* * that provides the resolution of any promise in W that is*/\\n/* known to be resolved, plus any known-resolved promises*/\\n/* transitively referenced through their resolution data*/\\n/* * all these resolutions will use the original vpid, which the*/\\n/* kernel does not currently know about, because the vpid was*/\\n/* retired earlier, the previous time that promise was*/\\n/* resolved*/\\n/* * name X the set of vpids resolved in 'resolutions'*/\\n/* * assert that X vpids are not in exportedVPIDs or importedVPIDs*/\\n/* * they can only be in X if we remembered the Promise's*/\\n/* resolution, which means we observed the vpid resolve*/\\n/* * at that moment of observation, we would have removed it*/\\n/* from exportedVPIDs, as we did a syscall.resolve on it*/\\n/* * name Y the set of vpids *referenced* by 'resolutions'*/\\n/* * emit syscall.resolve(resolutions)*/\\n/* * Z = (W+Y)-X: the set of vpids we told the kernel but didn't resolve*/\\n/* * feed Z into maybeExportPromise()*/\\n\\nconst maybeNewVPIDs=new Set(serMethargs.slots);\\nconst resolutions=resolutionCollector().forSlots(serMethargs.slots);\\nif(resolutions.length>0){\\ntry{\\nconst resolutionCDs=resolutions.map(\\n([_xvpid,_isReject,resolutionCD])=>resolutionCD);\\n\\nassertAcceptableSyscallCapdataSize(resolutionCDs);}\\ncatch(e){\\nsyscall.exit(true,m.serialize(e));\\nreturn null;}\\n\\nsyscall.resolve(resolutions);\\nfor(const resolution of resolutions){\\nconst[_xvpid,_isReject,resolutionCD]=resolution;\\nfor(const vref of resolutionCD.slots){\\nmaybeNewVPIDs.add(vref);}}\\n\\n\\nfor(const resolution of resolutions){\\nconst[xvpid]=resolution;\\nmaybeNewVPIDs.delete(xvpid);}}\\n\\n\\nfor(const newVPID of Array.from(maybeNewVPIDs).sort()){\\nmaybeExportPromise(newVPID);}\\n\\n\\n/* ideally we'd wait until .then is called on p before subscribing, but*/\\n/* the current Promise API doesn't give us a way to discover this, so we*/\\n/* must subscribe right away. If we were using Vows or some other*/\\n/* then-able, we could just hook then() to notify us.*/\\nsyscall.subscribe(resultVPID);\\n\\n/* We return our new 'pRec.promise' to the handler, and when we*/\\n/* resolve it (during dispatch.notify) its resolution will be used*/\\n/* to resolve the caller's 'returnedP' Promise, but the caller*/\\n/* never sees pRec.promise itself. The caller got back their*/\\n/* 'returnedP' Promise before the handler even got invoked, and*/\\n/* thus before this queueMessage() was called.. If that caller*/\\n/* passes the 'returnedP' Promise they received as argument or*/\\n/* return value, we want it to serialize as resultVPID. And if*/\\n/* someone passes resultVPID to them, we want the user-level code*/\\n/* to get back that Promise, not 'pRec.promise'. As a result, we*/\\n/* do not retain or track 'pRec.promise'. Only 'returnedP' is*/\\n/* registered and retained by importedVPIDs.*/\\n\\nreturn pRec.promise;}\\n\\n\\nfunction forbidPromises(serArgs){\\nfor(const slot of serArgs.slots){\\nparseVatSlots.parseVatSlot(slot).type!=='promise'||\\nassert.Fail`D() arguments cannot include a Promise`;}}\\n\\n\\n\\nfunction DeviceHandler(slot){\\nreturn{\\nget(target,prop){\\nif(typeof prop!=='string'&&typeof prop!=='symbol'){\\nreturn undefined;}\\n\\nreturn(...args)=>{\\nmeterControl.assertIsMetered();/* userspace getters shouldn't escape*/\\nconst serArgs=m.serialize(harden(args));\\nassertAcceptableSyscallCapdataSize([serArgs]);\\nserArgs.slots.map(retainExportedVref);\\n/* if we didn't forbid promises, we'd need to*/\\n/* maybeExportPromise() here*/\\nforbidPromises(serArgs);\\nconst ret=syscall.callNow(slot,prop,serArgs);\\ncapdata.insistCapData(ret);\\nforbidPromises(ret);\\n/* but the unserialize must be unmetered, to prevent divergence*/\\nconst retval=unmeteredUnserialize(ret);\\nreturn retval;};}};}\\n\\n\\n\\n\\n\\nfunction D(x){\\n/* results = D(devicenode).name(args)*/\\nif(outstandingProxies.has(x)){\\nthrow Error('D(D(x)) is invalid');}\\n\\nconst slot=valToSlot.get(x);\\nif(!slot||parseVatSlots.parseVatSlot(slot).type!=='device'){\\nthrow Error('D() must be given a device node');}\\n\\nconst handler=DeviceHandler(slot);\\nconst pr=harden(new Proxy({},handler));\\noutstandingProxies.add(pr);\\nreturn pr;}\\n\\n\\nfunction deliver(target,methargsdata,resultVPID){\\nassert.assert(didStartVat);\\nassert.assert(!didStopVat);\\ncapdata.insistCapData(methargsdata);\\n\\n/* prettier-ignore*/\\nlsdebug(\\n`ls[${forVatID}].dispatch.deliver ${target}.${kdebug.extractMethod(methargsdata)} -> ${resultVPID}`);\\n\\nconst t=convertSlotToVal(target);\\nt||assert.Fail`no target ${target}`;\\n/* TODO: if we acquire new decision-making authority over a promise that*/\\n/* we already knew about ('resultVPID' is already in slotToVal), we should no*/\\n/* longer accept dispatch.notify from the kernel. We currently use*/\\n/* importedPromisesByPromiseID to track a combination of \\\"we care about*/\\n/* when this promise resolves\\\" and \\\"we are listening for the kernel to*/\\n/* resolve it\\\". We should split that into two tables or something. And we*/\\n/* should error-check cases that the kernel shouldn't do, like getting*/\\n/* the same vpid as a result= twice, or getting a result= for an exported*/\\n/* promise (for which we were already the decider).*/\\n\\nmeterControl.assertNotMetered();\\nconst methargs=m.unserialize(methargsdata);\\nconst[method,args]=methargs;\\n\\n/* If the method is missing, or is not a Function, or the method throws a*/\\n/* synchronous exception, we notify the caller (by rejecting the result*/\\n/* promise, if any). If the method returns an eventually-rejected*/\\n/* Promise, we notify them when it resolves.*/\\n\\n/* If the method returns a synchronous value, we notify the caller right*/\\n/* away. If it returns an eventually-fulfilled Promise, we notify the*/\\n/* caller when it resolves.*/\\n\\n/* Both situations are the business of this vat and the calling vat, not*/\\n/* the kernel. deliver() does not report such exceptions to the kernel.*/\\n\\n/* We have a presence, so forward to it.*/\\nlet res;\\nif(args){\\n/* It has arguments, must be a method or function application.*/\\nif(method===undefined){\\nres=noShim.HandledPromise.applyFunction(t,args);}else\\n{\\nres=noShim.HandledPromise.applyMethod(t,method,args);}}else\\n\\n{\\n/* Just a getter.*/\\n/* TODO: untested, but in principle sound.*/\\nres=noShim.HandledPromise.get(t,method);}\\n\\n\\nlet p=res;/* the promise tied to resultVPID*/\\nif(resultVPID){\\nif(importedVPIDs.has(resultVPID)){\\n/* This vpid was imported earlier, and we just now became the*/\\n/* decider, so we already have a local Promise object for*/\\n/* it. We keep using that object.*/\\n/* , but forward it to 'res', and*/\\n/* move it from importedVPIDs to exportedVPIDs.*/\\nconst pRec=importedVPIDs.get(resultVPID);\\n/* remove it from importedVPIDs: the kernel will no longer be*/\\n/* telling us about its resolution*/\\nimportedVPIDs.delete(resultVPID);\\n/* forward it to the userspace-fired result promise (despite*/\\n/* using resolve(), this could either fulfill or reject)*/\\npRec.resolve(res);\\n/* exportedVPIDs will hold a strong reference to the pRec*/\\n/* promise that everyone is already using, and when it fires*/\\n/* we'll notify the kernel*/\\np=pRec.promise;\\n/* note: the kernel does not unsubscribe vats that acquire*/\\n/* decider status (but it probably should), so after we do our*/\\n/* syscall.resolve, the kernel will give us a*/\\n/* dispatch.notify. But we'll ignore the stale vpid by*/\\n/* checking importedVPIDs in notifyOnePromise()*/}else\\n{\\n/* new vpid*/\\nregisterValue(resultVPID,res,false);}\\n\\n/* in both cases, we are now the decider, so treat it like an*/\\n/* exported promise*/\\n/* eslint-disable-next-line no-use-before-define*/\\nfollowForKernel(resultVPID,p);}}\\n\\n\\n\\nfunction unregisterUnreferencedVPID(vpid){\\nlsdebug(`unregisterUnreferencedVPID ${forVatID}:${vpid}`);\\nassert.assert.equal(parseVatSlots.parseVatSlot(vpid).type,'promise');\\n/* we are only called with vpids that are in exportedVPIDs or*/\\n/* importedVPIDs, so the WeakRef should still be populated, making*/\\n/* this safe to call from metered code*/\\nconst p=requiredValForSlot(vpid);\\nif(vrm.getReachablePromiseRefCount(p)===0){\\n/* unregister*/\\nvalToSlot.delete(p);\\nslotToVal.delete(vpid);\\n/* the caller will remove the vpid from*/\\n/* exportedVPIDs/importedVPIDs in a moment*/}}\\n\\n\\n\\n/**\\n *\\n * @param {string} vpid\\n * @param {Promise<unknown>} p\\n */\\nfunction followForKernel(vpid,p){\\nparseVatSlots.insistVatType('promise',vpid);\\nexportedVPIDs.set(vpid,p);\\n\\nfunction handle(isReject,value){\\nknownResolutions.set(p,harden([isReject,value]));\\nlsdebug(`ls.thenHandler fired`,value);\\nassert.assert(exportedVPIDs.has(vpid),vpid);\\nconst rc=resolutionCollector();\\nconst resolutions=rc.forPromise(vpid,isReject,value);\\ntry{\\nconst resolutionCDs=resolutions.map(\\n([_xvpid,_isReject,resolutionCD])=>resolutionCD);\\n\\nassertAcceptableSyscallCapdataSize(resolutionCDs);}\\ncatch(e){\\nsyscall.exit(true,m.serialize(e));\\nreturn;}\\n\\nsyscall.resolve(resolutions);\\n\\nconst maybeNewVPIDs=new Set();\\n/* if we mention a vpid, we might need to track it*/\\nfor(const resolution of resolutions){\\nconst[_xvpid,_isReject,resolutionCD]=resolution;\\nfor(const vref of resolutionCD.slots){\\nmaybeNewVPIDs.add(vref);}}\\n\\n\\n/* but not if we just resolved it (including the primary)*/\\nfor(const resolution of resolutions){\\nconst[xvpid]=resolution;\\nmaybeNewVPIDs.delete(xvpid);}\\n\\n/* track everything that's left*/\\nfor(const newVPID of Array.from(maybeNewVPIDs).sort()){\\nmaybeExportPromise(newVPID);}\\n\\n\\n/* only the primary can possibly be newly resolved*/\\nunregisterUnreferencedVPID(vpid);\\nexportedVPIDs.delete(vpid);}\\n\\n\\nvoid noShim.E.when(\\np,\\n(value)=>handle(false,value),\\n(value)=>handle(true,value));}\\n\\n\\n\\nfunction notifyOnePromise(promiseID,rejected,data){\\ncapdata.insistCapData(data);\\nlsdebug(\\n`ls.dispatch.notify(${promiseID}, ${rejected}, ${data.body}, [${data.slots}])`);\\n\\nparseVatSlots.insistVatType('promise',promiseID);\\nconst pRec=importedVPIDs.get(promiseID);\\n/* we check pRec to ignore stale notifies, either from before an*/\\n/* upgrade, or if we acquire decider authority for a*/\\n/* previously-imported promise*/\\nif(pRec){\\nmeterControl.assertNotMetered();\\nconst val=m.unserialize(data);\\nif(rejected){\\npRec.reject(val);}else\\n{\\npRec.resolve(val);}\\n\\nreturn true;/* caller will remove from importedVPIDs*/}\\n\\n/* else ignore: our predecessor version might have subscribed*/\\nreturn false;}\\n\\n\\nfunction notify(resolutions){\\nassert.assert(didStartVat);\\nassert.assert(!didStopVat);\\n/* notifyOnePromise() will tell us whether each vpid in the batch*/\\n/* was retired or stale*/\\nconst retiredVPIDs=[];\\n/* Deserializing the batch of resolutions may import new promises,*/\\n/* some of which are resolved later in the batch. We'll need to*/\\n/* subscribe to the remaining (new+unresolved) ones.*/\\nbeginCollectingPromiseImports();\\nfor(const resolution of resolutions){\\nconst[vpid,rejected,data]=resolution;\\nconst retired=notifyOnePromise(vpid,rejected,data);\\nif(retired){\\nretiredVPIDs.push(vpid);/* not stale*/}}\\n\\n\\n/* 'imports' is an exclusively-owned Set that holds all new*/\\n/* promise vpids, both resolved and unresolved*/\\nconst imports=finishCollectingPromiseImports();\\nfor(const vpid of retiredVPIDs){\\nunregisterUnreferencedVPID(vpid);/* unregisters if not in vdata*/\\nimportedVPIDs.delete(vpid);\\nimports.delete(vpid);/* resolved, so don't subscribe()*/}\\n\\nfor(const vpid of Array.from(imports).sort()){\\nsyscall.subscribe(vpid);}}\\n\\n\\n\\nfunction dropExports(vrefs){\\nassert.assert(Array.isArray(vrefs));\\nvrefs.map((vref)=>parseVatSlots.insistVatType('object',vref));\\nvrefs.map((vref)=>assert.assert(parseVatSlots.parseVatSlot(vref).allocatedByVat));\\n/* console.log(`-- liveslots acting upon dropExports ${vrefs.join(',')}`);*/\\nmeterControl.assertNotMetered();\\nfor(const vref of vrefs){\\nconst o=getValForSlot(vref);\\nif(o){\\nexportedRemotables.delete(o);}\\n\\nconst{virtual,durable}=parseVatSlots.parseVatSlot(vref);\\nif(virtual||durable){\\nvrm.setExportStatus(vref,'recognizable');}}}\\n\\n\\n\\n\\nfunction retireOneExport(vref){\\nparseVatSlots.insistVatType('object',vref);\\nconst{virtual,durable,allocatedByVat,type}=parseVatSlots.parseVatSlot(vref);\\nassert.assert(allocatedByVat);\\nassert.assert.equal(type,'object');\\n/* console.log(`-- liveslots acting on retireExports ${vref}`);*/\\nif(virtual||durable){\\nvrm.setExportStatus(vref,'none');}else\\n{\\n/* Remotable*/\\nkernelRecognizableRemotables.delete(vref);}}\\n\\n\\n\\nfunction retireExports(vrefs){\\nassert.assert(Array.isArray(vrefs));\\nfor(const vref of vrefs){\\nretireOneExport(vref);}}\\n\\n\\n\\nfunction retireImports(vrefs){\\nassert.assert(Array.isArray(vrefs));\\nvrefs.map((vref)=>parseVatSlots.insistVatType('object',vref));\\nvrefs.map((vref)=>assert.assert(!parseVatSlots.parseVatSlot(vref).allocatedByVat));\\nfor(const vref of vrefs){\\nvrm.ceaseRecognition(vref);}}\\n\\n\\n\\n/* TODO: when we add notifyForward, guard against cycles*/\\n\\nfunction exitVat(completion){\\nmeterControl.assertIsMetered();/* else userspace getters could escape*/\\nconst args=m.serialize(harden(completion));\\nif(isAcceptableSyscallCapdataSize([args])){\\nargs.slots.map(retainExportedVref);\\nsyscall.exit(false,args);}else\\n{\\nsyscall.exit(true,m.serialize(Error('syscall capdata too large')));}}\\n\\n\\n\\nfunction exitVatWithFailure(reason){\\nmeterControl.assertIsMetered();/* else userspace getters could escape*/\\nconst args=m.serialize(harden(reason));\\nif(isAcceptableSyscallCapdataSize([args])){\\nargs.slots.map(retainExportedVref);\\nsyscall.exit(true,args);}else\\n{\\nsyscall.exit(true,m.serialize(Error('syscall capdata too large')));}}\\n\\n\\n\\nfunction disavow(presence){\\nif(!valToSlot.has(presence)){\\nassert.Fail`attempt to disavow unknown ${presence}`;}\\n\\nconst slot=valToSlot.get(presence);\\n/* @ts-expect-error not undefined b/c of has() check*/\\nconst{type,allocatedByVat}=parseVatSlots.parseVatSlot(slot);\\ntype==='object'||assert.Fail`attempt to disavow non-object ${presence}`;\\n/* disavow() is only for imports: we'll use a different API to revoke*/\\n/* exports, one which accepts an Error object*/\\n!allocatedByVat||assert.Fail`attempt to disavow an export`;\\nvalToSlot.delete(presence);\\nslotToVal.delete(slot);\\ndisavowedPresences.add(presence);\\n\\nsyscall.dropImports([slot]);}\\n\\n\\nconst vatGlobals=harden({\\nVatData:{\\ndefineKind:vom.defineKind,\\ndefineKindMulti:vom.defineKindMulti,\\ndefineDurableKind:vom.defineDurableKind,\\ndefineDurableKindMulti:vom.defineDurableKindMulti,\\nmakeKindHandle:vom.makeKindHandle,\\ncanBeDurable:vom.canBeDurable,\\nprovidePromiseWatcher:watchedPromiseManager.providePromiseWatcher,\\nwatchPromise:watchedPromiseManager.watchPromise,\\nmakeScalarBigMapStore:collectionManager$1.makeScalarBigMapStore,\\nmakeScalarBigWeakMapStore:collectionManager$1.makeScalarBigWeakMapStore,\\nmakeScalarBigSetStore:collectionManager$1.makeScalarBigSetStore,\\nmakeScalarBigWeakSetStore:collectionManager$1.makeScalarBigWeakSetStore}});\\n\\n\\n\\nconst inescapableGlobalProperties=harden({\\nWeakMap:vom.VirtualObjectAwareWeakMap,\\nWeakSet:vom.VirtualObjectAwareWeakSet});\\n\\n\\nfunction getRetentionStats(){\\nreturn{\\n...collectionManager$1.getRetentionStats(),\\n...vrm.getRetentionStats(),\\n...vom.getRetentionStats(),\\nexportedRemotables:exportedRemotables.size,\\nimportedDevices:importedDevices.size,\\nkernelRecognizableRemotables:kernelRecognizableRemotables.size,\\nexportedVPIDs:exportedVPIDs.size,\\nimportedVPIDs:importedVPIDs.size,\\npossiblyDeadSet:possiblyDeadSet.size,\\npossiblyRetiredSet:possiblyRetiredSet.size,\\nslotToVal:slotToVal.size};}\\n\\n\\n\\nconst testHooks=harden({\\n...vom.testHooks,\\n...vrm.testHooks,\\n...collectionManager$1.testHooks,\\nsetSyscallCapdataLimits,\\nvatGlobals,\\n\\ngetRetentionStats,\\nexportedRemotables,\\nimportedDevices,\\nkernelRecognizableRemotables,\\nexportedVPIDs,\\nimportedVPIDs,\\npossiblyDeadSet,\\npossiblyRetiredSet,\\nslotToVal,\\nvalToSlot,\\n/* eslint-disable-next-line no-use-before-define*/\\nafterDispatchActions});\\n\\n\\nfunction setVatOption(option,_value){\\n/* note: we removed the only settable option in #7138, but we'll*/\\n/* retain dispatch.changeVatOptions to make it easier to add a new*/\\n/* one in the future*/\\nswitch(option){\\ndefault:\\nconsole.warn(`WARNING setVatOption unknown option ${option}`);}}\\n\\n\\n\\nfunction changeVatOptions(options){\\nfor(const option of Object.getOwnPropertyNames(options)){\\nsetVatOption(option,options[option]);}}\\n\\n\\n\\nlet baggage;\\nasync function startVat(vatParametersCapData){\\ncapdata.insistCapData(vatParametersCapData);\\nassert.assert(!didStartVat);\\ndidStartVat=true;\\nassert.assert(!didStopVat);\\n\\n/* Build the `vatPowers` provided to `buildRootObject`. We include*/\\n/* vatGlobals and inescapableGlobalProperties to make it easier to write*/\\n/* unit tests that share their vatPowers with the test program, for*/\\n/* direct manipulation). 'D' is used by only a few vats: (bootstrap,*/\\n/* bridge, vat-http).*/\\nconst vpow={\\nD,\\nexitVat,\\nexitVatWithFailure,\\n...vatGlobals,\\n...inescapableGlobalProperties,\\n...vatPowers};\\n\\nif(enableDisavow){\\nvpow.disavow=disavow;}\\n\\nharden(vpow);\\n\\nvrm.initializeIDCounters();\\nvom.initializeKindHandleKind();\\ncollectionManager$1.initializeStoreKindInfo();\\n\\nconst vatParameters=m.unserialize(vatParametersCapData);\\nbaggage=collectionManager$1.provideBaggage();\\nwatchedPromiseManager.preparePromiseWatcherTables();\\n\\n/* Below this point, user-provided code might crash or overrun a meter, so*/\\n/* any prior-to-user-code setup that can be done without reference to the*/\\n/* content of the user-provided code should be above this point.*/\\nawait Promise.resolve();\\n\\n/* syscalls/VatData/makeKind must be enabled before invoking buildVatNamespace*/\\nconst vatNS=await buildVatNamespace(\\nvatGlobals,\\ninescapableGlobalProperties);\\n\\nconst buildRootObject=vatNS.buildRootObject;\\ntypeof buildRootObject==='function'||\\nassert.Fail`vat source bundle lacks buildRootObject() function`;\\n\\n/* here we finally invoke the vat code, and get back the root object*/\\nconst rootObject=await buildRootObject(vpow,vatParameters,baggage);\\npassStyleOf.passStyleOf(rootObject)==='remotable'||\\nassert.Fail`buildRootObject() for vat ${forVatID} returned ${rootObject}, which is not Far`;\\nremotable.getInterfaceOf(rootObject)!==undefined||\\nassert.Fail`buildRootObject() for vat ${forVatID} returned ${rootObject} with no interface`;\\nif(valToSlot.has(rootObject)){\\nassert.Fail`buildRootObject() must return ephemeral, not virtual/durable object`;}\\n\\n\\n/* Need to load watched promises *after* buildRootObject() so that handler kindIDs*/\\n/* have a chance to be reassociated with their handlers.*/\\nwatchedPromiseManager.loadWatchedPromiseTable(unmeteredRevivePromise);\\n\\nconst rootSlot=parseVatSlots.makeVatSlot('object',true,BigInt(0));\\nvalToSlot.set(rootObject,rootSlot);\\nslotToVal.set(rootSlot,new WeakRef(rootObject));\\nretainExportedVref(rootSlot);\\n/* we do not use vreffedObjectRegistry for root objects*/\\n\\nvom.insistAllDurableKindsReconnected();}\\n\\n\\n/**\\n * @param {IMPORT('./types.js').VatDeliveryObject} delivery\\n * @returns {void | Promise<void>}\\n */\\nfunction dispatchToUserspace(delivery){\\nlet result;\\nconst[type,...args]=delivery;\\nswitch(type){\\ncase'message':{\\nconst[targetSlot,msg]=args;\\nmessage.insistMessage(msg);\\ndeliver(targetSlot,msg.methargs,msg.result);\\nbreak;}\\n\\ncase'notify':{\\nconst[resolutions]=args;\\nnotify(resolutions);\\nbreak;}\\n\\ncase'dropExports':{\\nconst[vrefs]=args;\\ndropExports(vrefs);\\nbreak;}\\n\\ncase'retireExports':{\\nconst[vrefs]=args;\\nretireExports(vrefs);\\nbreak;}\\n\\ncase'retireImports':{\\nconst[vrefs]=args;\\nretireImports(vrefs);\\nbreak;}\\n\\ncase'changeVatOptions':{\\nconst[options]=args;\\nchangeVatOptions(options);\\nbreak;}\\n\\ncase'startVat':{\\nconst[vpCapData]=args;\\nresult=startVat(vpCapData);\\nbreak;}\\n\\ndefault:\\nassert.Fail`unknown delivery type ${type}`;}\\n\\nreturn result;}\\n\\n\\n/* the first turn of each dispatch is spent in liveslots, and is not*/\\n/* metered*/\\nconst unmeteredDispatch=meterControl.unmetered(dispatchToUserspace);\\n\\nasync function bringOutYourDead(){\\nawait scanForDeadObjects();\\n/* Now flush all the vatstore changes (deletions and refcounts) we*/\\n/* made. dispatch() calls afterDispatchActions() automatically for*/\\n/* most methods, but not bringOutYourDead().*/\\n/* eslint-disable-next-line no-use-before-define*/\\nafterDispatchActions();\\n/* XXX TODO: make this conditional on a config setting*/\\nreturn getRetentionStats();}\\n\\n\\n/**\\n * @param { IMPORT('./types.js').SwingSetCapData } _disconnectObjectCapData\\n * @returns {Promise<void>}\\n */\\nasync function stopVat(_disconnectObjectCapData){\\nconsole.warn('stopVat is a no-op as of #6650');}\\n\\n\\n/**\\n * Do things that should be done (such as flushing caches to disk) after a\\n * dispatch has completed and user code has relinquished agency.\\n */\\nfunction afterDispatchActions(){\\nvrm.flushIDCounters();\\ncollectionManager$1.flushSchemaCache();\\nvom.flushStateCache();}\\n\\n\\n/**\\n * This 'dispatch' function is the entry point for the vat as a whole: the\\n * vat-worker supervisor gives us VatDeliveryObjects (like\\n * dispatch.deliver) to execute. Here in liveslots, we invoke user-provided\\n * code during this time, which might cause us to make some syscalls. This\\n * userspace code might use Promises to add more turns to the ready promise\\n * queue, but we never give it direct access to the timer or IO queues\\n * (setImmediate, setInterval, setTimeout), so once the promise queue is\\n * empty, the vat userspace loses \\\"agency\\\" (the ability to initiate further\\n * execution), and waitUntilQuiescent fires. At that point we return\\n * control to the supervisor by resolving our return promise.\\n *\\n * Liveslots specifically guards against userspace reacquiring agency after\\n * our return promise is fired: vats are idle between cranks. Metering of\\n * the worker guards against userspace performing a synchronous infinite\\n * loop (`for (;;) {}`, the dreaded cthulu operator) or an async one\\n * (`function again() { return Promise.resolve().then(again); }`), by\\n * killing the vat after too much work. Userspace errors during delivery\\n * are expressed by calling syscall.resolve to reject the\\n * dispatch.deliver(result=) promise ID, which is unrelated to the Promise\\n * that `dispatch` returns.\\n *\\n * Liveslots does the authority to stall a crank indefinitely, by virtue of\\n * having access to `waitUntilQuiescent` and `FinalizationRegistry` (to\\n * retain agency), and the ability to disable metering (to disable worker\\n * termination), but only a buggy liveslots would do this. The kernel is\\n * vulnerable to a buggy liveslots never finishing a crank.\\n *\\n * This `dispatch` function always returns a Promise. It resolves (with\\n * nothing) when the crank completes successfully. If it rejects, that\\n * indicates the delivery has failed, and the worker should send an\\n * [\\\"error\\\", ..] `VatDeliveryResult` back to the kernel (which may elect to\\n * terminate the vat). Userspace should not be able to cause the delivery\\n * to fail: only a bug in liveslots should trigger a failure.\\n *\\n * @param {IMPORT('./types.js').VatDeliveryObject} delivery\\n * @returns {Promise<void>}\\n */\\nasync function dispatch(delivery){\\n/* We must short-circuit dispatch to bringOutYourDead here because it has to*/\\n/* be async, same for stopVat*/\\nif(delivery[0]==='bringOutYourDead'){\\nreturn meterControl.runWithoutMeteringAsync(bringOutYourDead);}else\\nif(delivery[0]==='stopVat'){\\nreturn meterControl.runWithoutMeteringAsync(()=>stopVat(delivery[1]));}else\\n{\\nlet complete=false;\\n/* Start user code running, record any internal liveslots errors. We do*/\\n/* *not* directly wait for the userspace function to complete, nor for*/\\n/* any promise it returns to fire.*/\\nconst p=Promise.resolve(delivery).then(unmeteredDispatch);\\nvoid p.finally(()=>complete=true);\\n\\n/* Instead, we wait for userspace to become idle by draining the*/\\n/* promise queue. We clean up and then examine/return 'p' so any*/\\n/* bugs in liveslots that cause an error during*/\\n/* unmeteredDispatch (or a 'buildRootObject' that fails to*/\\n/* complete in time) will be reported to the supervisor (but*/\\n/* only after userspace is idle).*/\\nreturn gcTools.waitUntilQuiescent().then(()=>{\\nafterDispatchActions();\\n/* eslint-disable-next-line prefer-promise-reject-errors*/\\nreturn complete?p:Promise.reject('buildRootObject unresolved');\\n/* the only delivery that pays attention to a user-provided*/\\n/* Promise is startVat, so the error message is specialized to*/\\n/* the only user problem that could cause complete===false*/});}}\\n\\n\\n\\nharden(dispatch);\\n\\n/* we return 'possiblyDeadSet' for unit tests*/\\nreturn harden({\\ndispatch,\\nm,\\ntestHooks});}\\n\\n\\n\\n/**\\n * Instantiate the liveslots layer for a new vat and then populate the vat with\\n * a new root object and its initial associated object graph, if any.\\n *\\n * @param {*} syscall Kernel syscall interface that the vat will have access to\\n * @param {*} forVatID Vat ID label, for use in debug diagostics\\n * @param {*} vatPowers\\n * @param {IMPORT('./types.js').LiveSlotsOptions} liveSlotsOptions\\n * @param {*} gcTools { WeakRef, FinalizationRegistry, waitUntilQuiescent }\\n * @param {Pick<Console, 'debug' | 'log' | 'info' | 'warn' | 'error'>} [liveSlotsConsole]\\n * @param {*} [buildVatNamespace]\\n *\\n * @returns {*} { dispatch }\\n *\\n * setBuildRootObject should be called, once, with a function that will\\n * create a root object for the new vat The caller provided buildRootObject\\n * function produces and returns the new vat's root object:\\n *\\n * buildRootObject(vatPowers, vatParameters)\\n *\\n * Within the vat, `import { E } from '@endo/eventual-send'` will\\n * provide the E wrapper. For any object x, E(x) returns a proxy object\\n * that converts any method invocation into a corresponding eventual send\\n * to x. That is, E(x).foo(arg1, arg2) is equivalent to x~.foo(arg1,\\n * arg2)\\n *\\n * If x is the presence in this vat of a remote object (that is, an object\\n * outside the vat), this will result in a message send out of the vat via\\n * the kernel syscall interface.\\n *\\n * In the same vein, if x is the presence in this vat of a kernel device,\\n * vatPowers.D(x) returns a proxy such that a method invocation on it is\\n * translated into the corresponding immediate invocation of the device\\n * (using, once again, the kernel syscall interface). D(x).foo(args) will\\n * perform an immediate syscall.callNow on the device node.\\n */\\nfunction makeLiveSlots(\\nsyscall,\\nforVatID='unknown',\\nvatPowers=harden({}),\\nliveSlotsOptions,\\ngcTools,\\nliveSlotsConsole=console,\\nbuildVatNamespace)\\n{\\nconst r=build(\\nsyscall,\\nforVatID,\\nvatPowers,\\nliveSlotsOptions,\\ngcTools,\\nliveSlotsConsole,\\nbuildVatNamespace);\\n\\nconst{dispatch,possiblyDeadSet,testHooks}=r;/* omit 'm'*/\\nreturn harden({\\ndispatch,\\npossiblyDeadSet,\\ntestHooks});}\\n\\n\\n\\n/* for tests*/\\nfunction makeMarshaller(syscall,gcTools,vatID='forVatID'){\\n/* @ts-expect-error missing buildVatNamespace param*/\\nconst{m}=build(syscall,vatID,{},{},gcTools,console);\\nreturn{m};}exports.makeLiveSlots=makeLiveSlots;exports.makeMarshaller=makeMarshaller;\",\n \"packages/swingset-liveslots/src/message.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var assert=require('../../assert/src/assert.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\ncapdata=require('./capdata.js');/**\\n * @typedef {{\\n * methargs: IMPORT('./types.js').SwingSetCapData, // of [method, args]\\n * result: string | undefined | null,\\n * }} Message\\n */ /**\\n * Assert function to ensure that something expected to be a message object\\n * actually is. A message object should have a .method property that's a\\n * string, a .args property that's a capdata object, and optionally a .result\\n * property that, if present, must be a string.\\n *\\n * @param {any} message The object to be tested\\n *\\n * @throws {Error} if, upon inspection, the parameter does not satisfy the above\\n * criteria.\\n *\\n * @returns {asserts message is Message}\\n */function insistMessage(message){capdata.insistCapData(message.methargs);if(message.result){typeof message.result==='string'||\\nassert.Fail`message has non-string non-null .result ${message.result}`;}}\\n\\n\\n\\n/**\\n * @param {unknown} vdo\\n * @returns {asserts vdo is IMPORT('./types').VatDeliveryObject}\\n */\\n\\nfunction insistVatDeliveryObject(vdo){\\nassert.assert(Array.isArray(vdo));\\nconst[type,...rest]=vdo;\\nswitch(type){\\ncase'message':{\\nconst[target,msg]=rest;\\nassert.assert.typeof(target,'string');\\ninsistMessage(msg);\\nbreak;}\\n\\ncase'notify':{\\nconst[resolutions]=rest;\\nassert.assert(Array.isArray(resolutions));\\nfor(const[vpid,rejected,data]of resolutions){\\nassert.assert.typeof(vpid,'string');\\nassert.assert.typeof(rejected,'boolean');\\ncapdata.insistCapData(data);}\\n\\nbreak;}\\n\\ncase'dropExports':\\ncase'retireExports':\\ncase'retireImports':{\\nconst[slots]=rest;\\nassert.assert(Array.isArray(slots));\\nfor(const slot of slots){\\nassert.assert.typeof(slot,'string');}\\n\\nbreak;}\\n\\ncase'changeVatOptions':{\\nassert.assert(rest.length===1);\\nbreak;}\\n\\ncase'startVat':{\\nassert.assert(rest.length===1);\\nconst[vatParameters]=rest;\\ncapdata.insistCapData(vatParameters);\\nbreak;}\\n\\ncase'stopVat':{\\nassert.assert(rest.length===1);\\nconst[disconnectObjectCapData]=rest;\\ncapdata.insistCapData(disconnectObjectCapData);\\nbreak;}\\n\\ncase'bringOutYourDead':{\\nassert.assert(rest.length===0);\\nbreak;}\\n\\ndefault:\\nassert.Fail`unknown delivery type ${type}`;}}\\n\\n\\n\\n/**\\n * @param {unknown} vdr\\n * @returns {asserts vdr is VatDeliveryResult}\\n */\\n\\nfunction insistVatDeliveryResult(vdr){\\nassert.assert(Array.isArray(vdr));\\nconst[type,problem,_usage]=vdr;\\nswitch(type){\\ncase'ok':{\\nassert.assert.equal(problem,null);\\nbreak;}\\n\\ncase'error':{\\nassert.assert.typeof(problem,'string');\\nbreak;}\\n\\ndefault:\\nassert.Fail`unknown delivery result type ${type}`;}}\\n\\n\\n\\n/**\\n * @param {unknown} vso\\n * @returns {asserts vso is IMPORT('./types').VatSyscallObject}\\n */\\n\\nfunction insistVatSyscallObject(vso){\\nassert.assert(Array.isArray(vso));\\nconst[type,...rest]=vso;\\nswitch(type){\\ncase'send':{\\nconst[target,msg]=rest;\\nassert.assert.typeof(target,'string');\\ninsistMessage(msg);\\nbreak;}\\n\\ncase'callNow':{\\nconst[target,method,args]=rest;\\nassert.assert.typeof(target,'string');\\nassert.assert.typeof(method,'string');\\ncapdata.insistCapData(args);\\nbreak;}\\n\\ncase'subscribe':{\\nconst[vpid]=rest;\\nassert.assert.typeof(vpid,'string');\\nbreak;}\\n\\ncase'resolve':{\\nconst[resolutions]=rest;\\nassert.assert(Array.isArray(resolutions));\\nfor(const[vpid,rejected,data]of resolutions){\\nassert.assert.typeof(vpid,'string');\\nassert.assert.typeof(rejected,'boolean');\\ncapdata.insistCapData(data);}\\n\\nbreak;}\\n\\ncase'exit':{\\nconst[isFailure,info]=rest;\\nassert.assert.typeof(isFailure,'boolean');\\ncapdata.insistCapData(info);\\nbreak;}\\n\\ncase'vatstoreGet':{\\nconst[key]=rest;\\nassert.assert.typeof(key,'string');\\nbreak;}\\n\\ncase'vatstoreSet':{\\nconst[key,data]=rest;\\nassert.assert.typeof(key,'string');\\nassert.assert.typeof(data,'string');\\nbreak;}\\n\\ncase'vatstoreGetNextKey':{\\nconst[priorKey]=rest;\\nassert.assert.typeof(priorKey,'string');\\nbreak;}\\n\\ncase'vatstoreDelete':{\\nconst[key]=rest;\\nassert.assert.typeof(key,'string');\\nbreak;}\\n\\ncase'dropImports':\\ncase'retireImports':\\ncase'retireExports':\\ncase'abandonExports':{\\nconst[slots]=rest;\\nassert.assert(Array.isArray(slots));\\nfor(const slot of slots){\\nassert.assert.typeof(slot,'string');}\\n\\nbreak;}\\n\\ndefault:\\nassert.Fail`unknown syscall type ${type}`;}}\\n\\n\\n\\n/**\\n * @param {unknown} vsr\\n * @returns {asserts vsr is IMPORT('./types').VatSyscallResult}\\n */\\n\\nfunction insistVatSyscallResult(vsr){\\nassert.assert(Array.isArray(vsr));\\nconst[type,...rest]=vsr;\\nswitch(type){\\ncase'ok':{\\nbreak;}\\n\\ncase'error':{\\nconst[err]=rest;\\nassert.assert.typeof(err,'string');\\nbreak;}\\n\\ndefault:\\nassert.Fail`unknown syscall result type ${type}`;}}exports.insistMessage=insistMessage;exports.insistVatDeliveryObject=insistVatDeliveryObject;exports.insistVatDeliveryResult=insistVatDeliveryResult;exports.insistVatSyscallObject=insistVatSyscallObject;exports.insistVatSyscallResult=insistVatSyscallResult;\",\n \"packages/swingset-liveslots/src/parseVatSlots.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var index=require('../../../node_modules/@endo/nat/src/index.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nassert=require('../../assert/src/assert.js');/* NOTE: confusing terminology: \\\"slot\\\" vs. \\\"reference\\\". All these things*/ /* called \\\"slots\\\" are references, but the word \\\"slot\\\" suggests something into*/ /* which something else is put and a reference isn't one of those. So improved*/ /* terminology would be an improvement, though any such change should be*/ /* thought through very carefully since changing these names will touch many*/ /* files. (You could call it a \\\"reference\\\", except that a phrase like \\\"vat*/ /* reference\\\" is ambiguous as to whether it means a reference belonging to a*/ /* vat or a reference *to* a vat, whereas \\\"vat slot\\\" does not have this problem*/ /* as badly. Also, \\\"slot\\\" is a short, single syllable word, which is nice.*/ /* But still \\\"slot\\\" implies containership which I think is wrong.)*/ /**\\n * Parse a vref string into its component parts:\\n * {\\n * type: STRING, // 'object', 'device', 'promise'\\n * allocatedByVat: BOOL, // true=>allocated by vat, false=>by the kernel\\n * id: Nat,\\n * subid: Nat,\\n * baseRef: STRING,\\n * facet: Nat,\\n * virtual: BOOL, // true=>vref designates a \\\"merely virtual\\\" object (not durable, not ephemeral)\\n * durable: BOOL, // designates a durable (not merely virtual, not ephemeral)\\n * }\\n *\\n * A vref string can take one of the forms:\\n *\\n * T-N\\n * T+N\\n * T+DN/I\\n * T+DN/I:F\\n *\\n * Where:\\n *\\n * T is a single character encoding the type of entity being referenced: 'd'\\n * for 'device', 'o' for 'object', or 'p' for 'promise'. One of the string\\n * values 'device', 'object', or 'promise' is returned as the `type`\\n * property of the result.\\n *\\n * '+' or '-' encodes who allocated the reference: '-' for the kernel\\n * (typically an import) or '+ for the vat (typically an export). This is\\n * returned in the `allocatedByVat` property of the result as a boolean.\\n *\\n * D is the durability status: for object exports (\\\"o+\\\"), this will\\n * be the letter 'd' for durable objects, the letter 'v' for\\n * non-durable (\\\"merely virtual\\\") objects, or empty for\\n * \\\"Remotable\\\" (ephemeral) objects. It is empty for object\\n * imports (\\\"o-\\\"), and both both imports and exports of all other\\n * types (promises, devices)\\n *\\n * N is a decimal integer representing the identity of the referenced entity.\\n * This is returned in the `id` property of the result as a BigInt.\\n *\\n * I if present (only allowed if T is 'o') is a decimal integer representing\\n * the instance id of the referenced object. In this case N denotes a\\n * category of objects that share a common shape, either one of the store\\n * types or a virtual object kind, and I indicates which instance of that\\n * category is being referred to. If present this is returned as the\\n * `subid` property of the result as a BigInt.\\n *\\n * F if present (only allowed if I is also present) is a decimal integer\\n * referencing a facet of the referenced object. In this case N/I denotes\\n * a particular object instance and F indicates which of several possible\\n * facets of that instance is being addressed. If present this is returned\\n * in the `facet` property of the result as a BigInt.\\n *\\n * The `baseRef` property of the result is `vref` stripped of any facet indicator.\\n *\\n * A \\\"vref\\\" identifies an entity visible to vat code to which messages may be\\n * sent and which may be compared for equality to other such entities. Let's\\n * call such an entity an \\\"addressable object\\\".\\n *\\n * A \\\"baseRef\\\" designates an entity that is managed by LiveSlots, both as a unit\\n * of garbage collection specifically and as a unit of memory management more\\n * generally. Such an entity may be a promise or remotable object or imported\\n * presence, all of which will always be JavaScript objects in memory, or it may\\n * be a virtual object or collection, which can be in memory or on disk or both.\\n * Let's call such an entity a \\\"base object\\\". In most cases this is one and the\\n * same with the addressable object that the vref designates, but in the case of\\n * a faceted object it is the cohort record as a whole rather than any particular\\n * individual facet.\\n *\\n * XXX TODO: The previous comment suggests some renaming is warranted:\\n *\\n * In the current implementation, a vref string may only include decimal digits,\\n * the letters 'd'/'o'/'p'/'v', and the punctuation characters '+', '-', '/',\\n * and ':'. Future evolution of the vref syntax might add more characters to\\n * this set, but the characters '|' and ',' are permanently excluded: '|' is\\n * used (notably by the collection manager) as delimiter in vatstore keys that\\n * include vrefs, and ',' is used as a separator in lists of vrefs.\\n *\\n * `slotToVal` maps a baseRef to a base object (actually to a weakRef that\\n * points to a base object)\\n * `getValForSlot` maps a baseRef to a base object, or to undefined if it is not\\n * resident in memory\\n * `convertSlotToVal` maps a vref to to an addressable object, loading it from\\n * disk if necessary\\n *\\n * `valToSlot` maps an addressable object to a vref\\n * `getSlotForVal` maps an addressable object to a vref\\n * `convertValToSlot` maps an addressable object to a vref, generating a new\\n * vref if necessary\\n *\\n * @param {string} vref The string to be parsed, as described above.\\n *\\n * @returns {*} a vref components descriptor corresponding to the vref string\\n * parameter, assuming it is syntactically well formed.\\n *\\n * @throws if the given vref string is syntactically incorrect.\\n */\\nfunction parseVatSlot(vref){\\nassert.assert.typeof(vref,'string');\\nconst parts=vref.split(':');\\nparts.length===1||parts.length===2||assert.Fail`invalid vref ${vref}`;\\nconst[baseRef,facetStr]=parts;\\nlet type;\\nlet allocatedByVat;\\nconst typechar=baseRef[0];\\nconst allocchar=baseRef[1];\\nlet idSuffix=baseRef.slice(2);\\n\\nif(typechar==='o'){\\ntype='object';}else\\nif(typechar==='d'){\\ntype='device';}else\\nif(typechar==='p'){\\ntype='promise';}else\\n{\\nassert.Fail`invalid vref ${vref}`;}\\n\\n\\nif(allocchar==='+'){\\nallocatedByVat=true;}else\\nif(allocchar==='-'){\\nallocatedByVat=false;}else\\n{\\nassert.Fail`invalid vref ${vref}`;}\\n\\n\\nlet virtual=false;\\nlet durable=false;\\nif(idSuffix.startsWith('d')){\\ndurable=true;\\nidSuffix=idSuffix.slice(1);}else\\nif(idSuffix.startsWith('v')){\\nvirtual=true;/* merely virtual*/\\nidSuffix=idSuffix.slice(1);}\\n\\nconst delim=idSuffix.indexOf('/');\\nlet id;\\nlet subid;\\nlet facet;\\nif(delim>0){\\ntype==='object'&&allocatedByVat||assert.Fail`invalid vref ${vref}`;\\nvirtual||durable||assert.Fail`invalid vref ${vref}`;/* subid only exists for virtuals/durables*/\\nid=index.Nat(BigInt(idSuffix.substr(0,delim)));\\nsubid=index.Nat(BigInt(idSuffix.slice(delim+1)));}else\\n{\\nid=index.Nat(BigInt(idSuffix));}\\n\\nif(subid!==undefined&&facetStr!==undefined){\\nfacet=index.Nat(BigInt(facetStr));}\\n\\n\\nreturn{type,allocatedByVat,virtual,durable,id,subid,baseRef,facet};}\\n\\n\\n/**\\n * Generate a vat slot reference string given a type, ownership, and id.\\n *\\n * @param {'object'|'device'|'promise'} type The type\\n * @param {boolean} allocatedByVat Flag: true=>vat allocated, false=>kernel allocated\\n * @param {number | bigint} id The id, a Nat.\\n *\\n * @returns {string} the corresponding vat slot reference string.\\n *\\n * @throws if type is not one of the above known types.\\n */\\nfunction makeVatSlot(type,allocatedByVat,id){\\nlet idSuffix;\\nif(allocatedByVat){\\nidSuffix=`+${index.Nat(id)}`;}else\\n{\\nidSuffix=`-${index.Nat(id)}`;}\\n\\n\\nif(type==='object'){\\nreturn`o${idSuffix}`;}\\n\\nif(type==='device'){\\nreturn`d${idSuffix}`;}\\n\\nif(type==='promise'){\\nreturn`p${idSuffix}`;}\\n\\nthrow assert.Fail`unknown type ${type}`;}\\n\\n\\nfunction makeBaseRef(kindID,id,isDurable){\\nreturn`o+${isDurable?'d':'v'}${kindID}/${id}`;}\\n\\n\\n/**\\n * Assert function to ensure that a vat slot reference string refers to a\\n * slot of a given type.\\n *\\n * @param {string} type The vat slot type desired, a string.\\n * @param {string} vatSlot The vat slot reference string being tested\\n *\\n * @throws if vatSlot is not of the given type or is malformed.\\n *\\n * @returns {void}\\n */\\nfunction insistVatType(type,vatSlot){\\ntype===parseVatSlot(vatSlot).type||\\nassert.Fail`vatSlot ${vatSlot} is not of type ${type}`;}exports.insistVatType=insistVatType;exports.makeBaseRef=makeBaseRef;exports.makeVatSlot=makeVatSlot;exports.parseVatSlot=parseVatSlot;\",\n \"packages/swingset-liveslots/src/types.js\": \"\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n'use strict';/* Ensure this is a module.*/ /**\\n * @callback makeLiveSlots\\n */ /**\\n * The MeterControl object gives liveslots a mechanism to disable metering for certain GC-sensitive\\n * regions of code. Only the XS worker can actually do metering, but we track the enabled/disabled\\n * status on all workers, so that the assertions can be exercised more thoroughly (via non-XS unit\\n * tests). MeterControl.isMeteringDisabled()===false does not mean metering is happening, it just\\n * means that MeterControl isn't disabling it.\\n *\\n * @typedef {object} MeterControl\\n * @property {() => boolean} isMeteringDisabled Ask whether metering is currently disabled.\\n * @property {*} assertIsMetered\\n * @property {*} assertNotMetered\\n * @property {*} runWithoutMetering Run a callback outside metering\\n * @property {*} runWithoutMeteringAsync Run an async callback outside metering\\n * @property {*} unmetered Wrap a callback with runWithoutMetering\\n */ /**\\n * @typedef {{\\n * enableDisavow?: boolean,\\n * relaxDurabilityRules?: boolean,\\n * allowStateShapeChanges?: boolean,\\n * }} LiveSlotsOptions\\n *\\n * @typedef {IMPORT('@endo/marshal').CapData<string>} SwingSetCapData\\n *\\n * @typedef {{\\n * methargs: SwingSetCapData, // of [method, args]\\n * result: string | undefined | null,\\n * }} Message\\n * @typedef { [tag: 'message', target: string, msg: Message]} VatDeliveryMessage\\n * @typedef { [vpid: string, isReject: boolean, data: SwingSetCapData ] } VatOneResolution\\n * @typedef { [tag: 'notify', resolutions: VatOneResolution[] ]} VatDeliveryNotify\\n * @typedef { [tag: 'dropExports', vrefs: string[] ]} VatDeliveryDropExports\\n * @typedef { [tag: 'retireExports', vrefs: string[] ]} VatDeliveryRetireExports\\n * @typedef { [tag: 'retireImports', vrefs: string[] ]} VatDeliveryRetireImports\\n * @typedef { [tag: 'changeVatOptions', options: Record<string, unknown> ]} VatDeliveryChangeVatOptions\\n * @typedef { [tag: 'startVat', vatParameters: SwingSetCapData ]} VatDeliveryStartVat\\n * @typedef { [tag: 'stopVat', disconnectObject: SwingSetCapData ]} VatDeliveryStopVat\\n * @typedef { [tag: 'bringOutYourDead' ]} VatDeliveryBringOutYourDead\\n * @typedef { VatDeliveryMessage | VatDeliveryNotify | VatDeliveryDropExports\\n * | VatDeliveryRetireExports | VatDeliveryRetireImports | VatDeliveryChangeVatOptions\\n * | VatDeliveryStartVat | VatDeliveryStopVat | VatDeliveryBringOutYourDead\\n * } VatDeliveryObject\\n *\\n * @typedef { { compute: number } } MeterConsumption\\n * @typedef { [tag: 'ok', results: any, usage: MeterConsumption | null] |\\n * [tag: 'error', message: string, usage: MeterConsumption | null] } VatDeliveryResult\\n *\\n *\\n * @typedef { [tag: 'send', target: string, msg: Message] } VatSyscallSend\\n * @typedef { [tag: 'callNow', target: string, method: string, args: SwingSetCapData]} VatSyscallCallNow\\n * @typedef { [tag: 'subscribe', vpid: string ]} VatSyscallSubscribe\\n * @typedef { [tag: 'resolve', resolutions: VatOneResolution[] ]} VatSyscallResolve\\n * @typedef { [tag: 'exit', isFailure: boolean, info: SwingSetCapData ]} VatSyscallExit\\n * @typedef { [tag: 'vatstoreGet', key: string ]} VatSyscallVatstoreGet\\n * @typedef { [tag: 'vatstoreGetNextKey', priorKey: string ]} VatSyscallVatstoreGetNextKey\\n * @typedef { [tag: 'vatstoreSet', key: string, data: string ]} VatSyscallVatstoreSet\\n * @typedef { [tag: 'vatstoreDelete', key: string ]} VatSyscallVatstoreDelete\\n * @typedef { [tag: 'dropImports', slots: string[] ]} VatSyscallDropImports\\n * @typedef { [tag: 'retireImports', slots: string[] ]} VatSyscallRetireImports\\n * @typedef { [tag: 'retireExports', slots: string[] ]} VatSyscallRetireExports\\n * @typedef { [tag: 'abandonExports', slots: string[] ]} VatSyscallAbandonExports\\n *\\n * @typedef { VatSyscallSend | VatSyscallCallNow | VatSyscallSubscribe\\n * | VatSyscallResolve | VatSyscallExit | VatSyscallVatstoreGet | VatSyscallVatstoreGetNextKey\\n * | VatSyscallVatstoreSet | VatSyscallVatstoreDelete | VatSyscallDropImports\\n * | VatSyscallRetireImports | VatSyscallRetireExports | VatSyscallAbandonExports\\n * } VatSyscallObject\\n *\\n * @typedef { [tag: 'ok', data: SwingSetCapData | string | string[] | null ]} VatSyscallResultOk\\n * @typedef { [tag: 'error', err: string ] } VatSyscallResultError\\n * @typedef { VatSyscallResultOk | VatSyscallResultError } VatSyscallResult\\n *\\n * @typedef { (vso: VatSyscallObject) => VatSyscallResult } VatSyscallHandler\\n *\\n */ /**\\n * @template V fulfilled value\\n * @template {any[]} [A=unknown[]] arguments\\n * @typedef { {onFulfilled?: (value: V, ...args: A) => void, onRejected?: (reason: unknown, ...args: A) => void} } PromiseWatcher\\n */\",\n \"packages/swingset-liveslots/src/vatDataTypes.js\": \"'use strict';/* Empty JS file to correspond with vatDataTypes.d.ts*/\",\n \"packages/swingset-liveslots/src/vatstore-iterators.js\": \"'use strict';\\n\\nObject.defineProperty(exports,'__esModule',{value:true});/* return an iterator of all existing keys from start (inclusive) to*/ /* end (exclusive), in lexicographic order, calling checkF after*/ /* each 'yield' (which can throw to break the iterator)*/\\n\\nfunction*enumerateKeysStartEnd(syscall,start,end,checkF){\\nlet dbKey;\\nif(syscall.vatstoreGet(start)){\\ndbKey=start;}else\\n{\\ndbKey=syscall.vatstoreGetNextKey(start);/* maybe undefined*/}\\n\\nwhile(dbKey&&dbKey<end){\\nyield dbKey;\\n/* REENTRANCY HAZARD: we resume here after userspace cycles*/\\n/* the iterator, so check if the generation has changed*/\\ncheckF&&checkF();\\n/* fetch next key (which might be past 'end'), and repeat*/\\ndbKey=syscall.vatstoreGetNextKey(dbKey);}}\\n\\n\\nharden(enumerateKeysStartEnd);\\n\\n/* return an iterator of all existing keys that start with 'prefix'*/\\n/* (excluding the prefix itself)*/\\n\\nfunction*enumerateKeysWithPrefix(syscall,prefix){\\nlet key=prefix;\\nwhile(true){\\nkey=syscall.vatstoreGetNextKey(key);\\nif(!key||!key.startsWith(prefix)){\\nbreak;}\\n\\nyield key;}}\\n\\n\\nharden(enumerateKeysWithPrefix);\\n\\nfunction prefixedKeysExist(syscall,prefix){\\nconst nextKey=syscall.vatstoreGetNextKey(prefix);\\nreturn!!(nextKey&&nextKey.startsWith(prefix));}exports.enumerateKeysStartEnd=enumerateKeysStartEnd;exports.enumerateKeysWithPrefix=enumerateKeysWithPrefix;exports.prefixedKeysExist=prefixedKeysExist;\",\n \"packages/swingset-liveslots/src/virtualObjectManager.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../../node_modules/@endo/env-options/index.js');var index=require('../../../node_modules/@endo/errors/index.js');require('../../store/src/index.js');require('../../../node_modules/@endo/exo/tools.js');require('../../../node_modules/@endo/marshal/index.js');var index$1=require('../../../node_modules/@endo/nat/src/index.js');var parseVatSlots=require('./parseVatSlots.js');var vatstoreIterators=require('./vatstore-iterators.js');var cache=require('./cache.js');var facetiousness=require('./facetiousness.js');var envOptions=require('../../../node_modules/@endo/env-options/src/env-options.js');var passStyleOf=require('../../../node_modules/@endo/pass-style/src/passStyleOf.js');var patternMatchers=require('../../../node_modules/@endo/patterns/src/patterns/patternMatchers.js');var exoTools=require('../../../node_modules/@endo/exo/src/exo-tools.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nmakeFar=require('../../../node_modules/@endo/pass-style/src/make-far.js');/* global globalThis */ /**\\n * @import {DurableKindHandle} from '@agoric/swingset-liveslots'\\n * @import {DefineKindOptions} from '@agoric/swingset-liveslots'\\n * @import {ClassContextProvider, KitContextProvider} from '@endo/exo'\\n * @import {ToCapData, FromCapData} from '@endo/marshal';\\n */\\n\\nconst{\\nhasOwn,\\ndefineProperty,\\ngetOwnPropertyNames,\\nvalues,\\nentries,\\nfromEntries}=\\nObject;\\nconst{ownKeys}=Reflect;\\n\\n/* Turn on to give each exo instance its own toStringTag value which exposes*/\\n/* the SwingSet vref.*/\\n/**/\\n/* CONFIDENTIALITY HAZARD NOTE: exposing vrefs to userspace reveals*/\\n/* confidential object-creation activity, so this must not be something*/\\n/* that unprivileged vat code (including unprivileged contracts) can do*/\\n/* for themselves.*/\\nconst LABEL_INSTANCES=envOptions.environmentOptionsListHas('DEBUG','label-instances');\\n\\n/* This file implements the \\\"Virtual Objects\\\" system, currently documented in*/\\n/* {@link https://github.com/Agoric/agoric-sdk/blob/master/packages/SwingSet/docs/virtual-objects.md})*/\\n/**/\\n/* All virtual-object state is keyed by baseRef, like o+v11/5 . For single-facet*/\\n/* Kinds (created with `defineKind`), this is the entire vref. For*/\\n/* multiple-facet Kinds (created with `defineKindMulti`), the cohort of facets*/\\n/* (which all share the same state, but offer different methods, generally*/\\n/* representing different authorities) will each have a vref that extends the*/\\n/* baseRef with a facet identifier, e.g. o+v11/5:0 for the first facet, and*/\\n/* o+v11/5:1 for the second.*/\\n/**/\\n/* To manage context and state and data correctly (not sensitive to GC), we need*/\\n/* two Caches. The first is \\\"dataCache\\\", and maps baseRef to state data. This*/\\n/* data includes the serialized capdata for all properties, and the unserialized*/\\n/* value for properties that have been read or written by an accessor on the*/\\n/* `state` object.*/\\n/**/\\n/* The second cache is \\\"contextCache\\\", and maps baseRef to a context object,*/\\n/* which is either { state, self } or { state, facets } depending on the*/\\n/* facetiousness of the VO. \\\"state\\\" is an object with one accessor pair*/\\n/* (getter+setter) per state property name. The \\\"state\\\" getters/setters know*/\\n/* which baseRef they should use. When invoked, they pull the state data from*/\\n/* `dataCache.get(baseRef).valueMap`. The setter will modify valueMap in place*/\\n/* and mark the entry as dirty, so it can be serialized and written back at*/\\n/* end-of-crank.*/\\n/**/\\n/* Each Representative is built as an Exo with defendPrototype (cohorts of*/\\n/* facets are built with defendPrototypeKit). These are given a*/\\n/* \\\"contextProvider\\\" for later use. For each facet, they build a prototype*/\\n/* object with wrappers for all the methods of that particular facet. When those*/\\n/* wrappers are invoked, the first thing they do is to call*/\\n/* `contextProvider(this)` (where `this` is the representative) to get a*/\\n/* \\\"context\\\" object: { state, self } or { state, facets }, which is passed to*/\\n/* the behavior functions. The contextProvider function uses valToSlot() to*/\\n/* figure out the representative's vref, then derives the baseRef, then consults*/\\n/* contextCache to get (or create) the context.*/\\n/**/\\n/* Our GC sensitivity contraints are:*/\\n/* * userspace must not be able to sense garbage collection*/\\n/* * Representatives are created on-demand when userspace deserializes a vref*/\\n/* * they disappear when UNREACHABLE and GC collects them*/\\n/* {@link https://github.com/Agoric/agoric-sdk/blob/master/packages/SwingSet/docs/garbage-collection.md})*/\\n/* * syscalls must be a deterministic function of userspace behavior*/\\n/* * that includes method invocation and \\\"state\\\" property read/writes*/\\n/* * they should not be influenced by GC until a bringOutYourDead delivery*/\\n/**/\\n/* See the discussion below (near `makeRepresentative`) for more details on how*/\\n/* we meet these constraints.*/\\n\\n/* * Make a cache which maps baseRef to a (mutable) record of {\\n * capdatas, valueMap }.\\n *\\n * 'capdatas' is a mutable Object (record) with state property names\\n * as keys, and their capdata { body, slots } as values, and\\n * 'valueMap' is a Map with state property names as keys, and their\\n * unmarshalled values as values. We need the 'capdatas' record to be\\n * mutable because we will modify its contents in place during\\n * setters, to retain the insertion order later (during flush). We\\n * need capdata at all so we can compare the slots before and after\\n * the update, to adjust the refcounts. Only the values of 'valueMap'\\n * are exposed to userspace.\\n */\\n\\n\\nconst makeDataCache=(syscall)=>{\\n/** @type {(baseRef: string) => { capdatas: any, valueMap: Map<string, any> }} */\\nconst readBacking=(baseRef)=>{\\nconst rawState=syscall.vatstoreGet(`vom.${baseRef}`);\\nindex.assert(rawState);\\nconst capdatas=JSON.parse(rawState);\\nconst valueMap=new Map();/* populated lazily by each state getter*/\\nreturn{capdatas,valueMap};/* both mutable*/};\\n\\n/** @type {(baseRef: string, value: { capdatas: any, valueMap: Map<string, any> }) => void} */\\nconst writeBacking=(baseRef,value)=>{\\nconst rawState=JSON.stringify(value.capdatas);\\nsyscall.vatstoreSet(`vom.${baseRef}`,rawState);};\\n\\n/** @type {(collectionID: string) => void} */\\nconst deleteBacking=(baseRef)=>syscall.vatstoreDelete(`vom.${baseRef}`);\\nreturn cache.makeCache(readBacking,writeBacking,deleteBacking);};\\n\\n\\nconst makeContextCache=(makeState,makeContext)=>{\\n/* non-writeback cache for \\\"context\\\" objects, { state, self/facets }*/\\nconst readBacking=(baseRef)=>{\\nconst state=makeState(baseRef);\\nconst context=makeContext(baseRef,state);\\nreturn context;};\\n\\nconst writeBacking=(_baseRef)=>index.throwRedacted`never called`;\\nconst deleteBacking=(_baseRef)=>index.throwRedacted`never called`;\\nreturn cache.makeCache(readBacking,writeBacking,deleteBacking);};\\n\\n\\n/* The management of single Representatives (i.e. defineKind) is very similar*/\\n/* to that of a cohort of facets (i.e. defineKindMulti). In this description,*/\\n/* we use \\\"self/facets\\\" to refer to either 'self' or 'facets', as appropriate*/\\n/* for the particular Kind. From userspace's perspective, the main difference*/\\n/* is that single-facet Kinds present self/facets as 'context.self', whereas*/\\n/* multi-facet Kinds present it as 'context.facets'.*/\\n\\n/* makeRepresentative/makeFacets returns the self/facets . This serves several*/\\n/* purposes:*/\\n/**/\\n/* * it is returned to userspace when making a new VO instance*/\\n/* * it appears as 'context.self/facets' when VO methods are invoked*/\\n/* * it is stored in the slotToVal table, specifically:*/\\n/* * slotToVal.get(baseref).deref() === self/facets*/\\n/* * (for facets, convertSlotToVal will then extract a single facet)*/\\n/* * it is registered with our FinalizationRegistry*/\\n/* * (for facets, the FR must not fire until all cohort members have been*/\\n/* collected)*/\\n/**/\\n/* Any facet can be passed to valToSlot to learn its vref, from which we learn*/\\n/* the baseRef, which we pass to contextCache.get to retrieve or create a*/\\n/* 'context', which will include self/facets and a 'state' object. So either:*/\\n/* * context = { state, self }*/\\n/* * context = { state, facets }*/\\n/**/\\n/* Userspace might hold on to a Representative, the `facets` record, the context*/\\n/* object, or the state object, for an unbounded length of time: beyond a single*/\\n/* crank/delivery. They might hold on to \\\"context\\\" but drop the Representative,*/\\n/* etc. They may compare these held objects against newer versions they receive*/\\n/* in future interactions. They might attempt to put any of these in a*/\\n/* WeakMap/WeakSet (remembering that they only get the*/\\n/* VirtualObjectAwareWeakMap/Set form that we give them). None of these actions*/\\n/* may allow userspace to sense GC.*/\\n/**/\\n/* Userspace could build a GC sensor out of any object with the following*/\\n/* properties:*/\\n/* * it has a GC-sensitive lifetime (i.e. created by these two functions)*/\\n/* * it is reachable from userspace*/\\n/* * it lacks a vref (else it'd be handled specially by VOAwareWeakMap)*/\\n/**/\\n\\n/* We must mark such objects as \\\"unweakable\\\" to prevent their use in*/\\n/* VOAwareWeakMap -based sensors (unweakable keys are held strongly by those*/\\n/* collections), and we must tie their lifetime to the facets to prevent their*/\\n/* use in a stash-and-compare-later sensor. We achieve the latter by adding a*/\\n/* linkToCohort WeakMap entry from every facet to the cohort record. This also*/\\n/* ensures that the FinalizationRegistry won't see the cohort record go away*/\\n/* until all the individual facets have been collected.*/\\n/**/\\n/* We only need to do this for multi-facet Kinds; single-facet kinds don't*/\\n/* have any extra objects for userspace to work with.*/\\n\\nconst makeRepresentative=(proto,baseRef)=>{\\nconst self={__proto__:proto};\\nif(LABEL_INSTANCES){\\n/* This exposes the vref to userspace, which is a confidentiality hazard*/\\n/* as noted in the CONFIDENTIALITY HAZARD NOTE above.*/\\n/**/\\n/* Aside from that hazard, the frozen string-valued data property is*/\\n/* safe to expose to userspace without enabling a GC sensor.*/\\n/* Strings lack identity and cannot be used as keys in WeakMaps.*/\\n/* If the property were a accessor property, we'd need to*/\\n/* ```js*/\\n/* linkToCohort.set(self, getterFunc);*/\\n/* unweakable.add(getterFunc);*/\\n/* ```*/\\ndefineProperty(self,Symbol.toStringTag,{\\nvalue:`${proto[Symbol.toStringTag]}#${baseRef}`,\\nwritable:false,\\nenumerable:false,\\nconfigurable:false});}\\n\\n\\nreturn harden(self);};\\n\\n\\nconst makeFacets=(\\nfacetNames,\\nprotoKit,\\nlinkToCohort,\\nunweakable,\\nbaseRef)=>\\n{\\nconst facets={};/* aka context.facets*/\\nfor(const name of facetNames){\\nconst facet=makeRepresentative(protoKit[name],baseRef);\\nfacets[name]=facet;\\nlinkToCohort.set(facet,facets);}\\n\\nunweakable.add(facets);\\nreturn harden(facets);};\\n\\n\\nconst insistDurableCapdata=(vrm,what,capdata,valueFor)=>{\\nfor(const[idx,vref]of entries(capdata.slots)){\\nif(!vrm.isDurable(vref)){\\nif(valueFor){\\nindex.throwRedacted`value for ${what} is not durable: slot ${index.bare(idx)} of ${capdata}`;}else\\n{\\nindex.throwRedacted`${what} is not durable: slot ${index.bare(idx)} of ${capdata}`;}}}};\\n\\n\\n\\n\\n\\nconst insistSameCapData=(oldCD,newCD)=>{\\n/* NOTE: this assumes both were marshalled with the same format*/\\n/* (e.g. smallcaps vs pre-smallcaps). To somewhat tolerate new*/\\n/* formats, we'd need to `serialize(unserialize(oldCD))`.*/\\nif(oldCD.body!==newCD.body){\\nindex.throwRedacted`durable Kind stateShape mismatch (body)`;}\\n\\nif(oldCD.slots.length!==newCD.slots.length){\\nindex.throwRedacted`durable Kind stateShape mismatch (slots.length)`;}\\n\\nfor(const[idx,oldVref]of entries(oldCD.slots)){\\nif(newCD.slots[idx]!==oldVref){\\nindex.throwRedacted`durable Kind stateShape mismatch (slot[${idx}])`;}}};\\n\\n\\n\\n\\n/**\\n * Create a new virtual object manager. There is one of these for each vat.\\n *\\n * @param {*} syscall Vat's syscall object, used to access the vatstore operations.\\n * @param {IMPORT('./virtualReferences.js').VirtualReferenceManager} vrm Virtual reference manager, to handle reference counting and GC\\n * of virtual references.\\n * @param {() => number} allocateExportID Function to allocate the next object\\n * export ID for the enclosing vat.\\n * @param {(val: object) => string | undefined} getSlotForVal A function that returns the\\n * object ID (vref) for a given object, if any. their corresponding export\\n * IDs\\n * @param {(slot: string) => object} requiredValForSlot\\n * @param {*} registerValue Function to register a new slot+value in liveSlot's\\n * various tables\\n * @param {ToCapData<string>} serialize Serializer for this vat\\n * @param {FromCapData<string>} unserialize Unserializer for this vat\\n * @param {*} assertAcceptableSyscallCapdataSize Function to check for oversized\\n * syscall params\\n * @param {IMPORT('./types.js').LiveSlotsOptions} [liveSlotsOptions]\\n * @param {{ WeakMap: typeof WeakMap, WeakSet: typeof WeakSet }} [powers]\\n * Specifying the underlying WeakMap/WeakSet objects to wrap with\\n * VirtualObjectAwareWeakMap/Set. By default, capture the ones currently\\n * defined on `globalThis` when the maker is invoked, to avoid infinite\\n * recursion if our returned WeakMap/WeakSet wrappers are subsequently installed\\n * on globalThis.\\n *\\n * @returns a new virtual object manager.\\n *\\n * The virtual object manager allows the creation of persistent objects that do\\n * not need to occupy memory when they are not in use. It provides five\\n * functions:\\n *\\n * - `defineKind`, `defineKindMulti`, `defineDurableKind`, and\\n * `defineDurableKindMulti` enable users to define new types of virtual\\n * object by providing an implementation of the new kind of object's\\n * behavior. The result is a maker function that will produce new\\n * virtualized instances of the defined object type on demand.\\n *\\n * - `VirtualObjectAwareWeakMap` and `VirtualObjectAwareWeakSet` are drop-in\\n * replacements for JavaScript's builtin `WeakMap` and `WeakSet` classes\\n * which understand the magic internal voodoo used to implement virtual\\n * objects and will do the right thing when virtual objects are used as keys.\\n * The intent is that the hosting environment will inject these as\\n * substitutes for their regular JS analogs in way that should be transparent\\n * to ordinary users of those classes.\\n *\\n * - `flushStateCache` will empty the object manager's cache of in-memory object\\n * instances, writing any changed state to the persistent store. This should\\n * be called at the end of each crank, to ensure the syscall trace does not\\n * depend upon GC of Representatives.\\n *\\n * The `defineKind` functions are made available to user vat code in the\\n * `VatData` global (along with various other storage functions defined\\n * elsewhere).\\n */\\nconst makeVirtualObjectManager=(\\nsyscall,\\nvrm,\\nallocateExportID,\\ngetSlotForVal,\\nrequiredValForSlot,\\nregisterValue,\\nserialize,\\nunserialize,\\nassertAcceptableSyscallCapdataSize,\\nliveSlotsOptions={},\\n{WeakMap,WeakSet}=globalThis)=>\\n{\\nconst{allowStateShapeChanges=false}=liveSlotsOptions;\\n\\n/* array of Caches that need to be flushed at end-of-crank, two per Kind*/\\n/* (dataCache, contextCache)*/\\nconst allCaches=[];\\n\\n/* WeakMap tieing VO components together, to prevent anyone who*/\\n/* retains one piece (e.g. the cohort record of facets) from being*/\\n/* able to observe the comings and goings of representatives by*/\\n/* hanging onto that piece while the other pieces are GC'd, then*/\\n/* comparing it to what gets generated when the VO is reconstructed*/\\n/* by a later import.*/\\nconst linkToCohort=new WeakMap();\\n\\nconst canBeDurable=(specimen)=>{\\nconst capData=serialize(specimen);\\nreturn capData.slots.every(vrm.isDurable);};\\n\\n\\n/* Marker associated to flag objects that should be held onto strongly if*/\\n/* somebody attempts to use them as keys in a VirtualObjectAwareWeakSet or*/\\n/* VirtualObjectAwareWeakMap, despite the fact that keys in such collections*/\\n/* are nominally held onto weakly. This to thwart attempts to observe GC by*/\\n/* squirreling away a piece of a VO while the rest of the VO gets GC'd and*/\\n/* then later regenerated.*/\\nconst unweakable=new WeakSet();\\n\\n/* This is a WeakMap from VO aware weak collections to strong Sets that retain*/\\n/* keys used in the associated collection that should not actually be held*/\\n/* weakly.*/\\nconst unweakableKeySets=new WeakMap();\\n\\nconst preserveUnweakableKey=(collection,key)=>{\\nif(unweakable.has(key)){\\nlet uwkeys=unweakableKeySets.get(collection);\\nif(!uwkeys){\\nuwkeys=new Set();\\nunweakableKeySets.set(collection,uwkeys);}\\n\\nuwkeys.add(key);}};\\n\\n\\n\\nconst releaseUnweakableKey=(collection,key)=>{\\nif(unweakable.has(key)){\\nconst uwkeys=unweakableKeySets.get(collection);\\nif(uwkeys){\\nuwkeys.delete(key);}}};\\n\\n\\n\\n\\n/* eslint max-classes-per-file: [\\\"error\\\", 2] */\\n\\nconst actualWeakMaps=new WeakMap();\\nconst virtualObjectMaps=new WeakMap();\\n\\nconst voAwareWeakMapDeleter=(descriptor)=>{\\nfor(const vref of descriptor.vmap.keys()){\\nvrm.removeRecognizableVref(vref,descriptor.vmap);}};\\n\\n\\n\\nclass VirtualObjectAwareWeakMap{\\nconstructor(){\\nactualWeakMaps.set(this,new WeakMap());\\nconst vmap=new Map();\\nvirtualObjectMaps.set(this,vmap);\\nvrm.registerDroppedCollection(this,{\\ncollectionDeleter:voAwareWeakMapDeleter,\\nvmap});}\\n\\n\\n\\nhas(key){\\nconst vkey=vrm.vrefKey(key);\\nif(vkey){\\nreturn virtualObjectMaps.get(this).has(vkey);}else\\n{\\nreturn actualWeakMaps.get(this).has(key);}}\\n\\n\\n\\nget(key){\\nconst vkey=vrm.vrefKey(key);\\nif(vkey){\\nreturn virtualObjectMaps.get(this).get(vkey);}else\\n{\\nreturn actualWeakMaps.get(this).get(key);}}\\n\\n\\n\\nset(key,value){\\nconst vkey=vrm.vrefKey(key);\\nif(vkey){\\nconst vmap=virtualObjectMaps.get(this);\\nif(!vmap.has(vkey)){\\nvrm.addRecognizableValue(key,vmap);}\\n\\nvmap.set(vkey,value);}else\\n{\\npreserveUnweakableKey(this,key);\\nactualWeakMaps.get(this).set(key,value);}\\n\\nreturn this;}\\n\\n\\ndelete(key){\\nconst vkey=vrm.vrefKey(key);\\nif(vkey){\\nconst vmap=virtualObjectMaps.get(this);\\nif(vmap.has(vkey)){\\nvrm.removeRecognizableValue(key,vmap);\\nreturn vmap.delete(vkey);}else\\n{\\nreturn false;}}else\\n\\n{\\nreleaseUnweakableKey(this,key);\\nreturn actualWeakMaps.get(this).delete(key);}}}\\n\\n\\n\\n\\ndefineProperty(VirtualObjectAwareWeakMap,Symbol.toStringTag,{\\nvalue:'WeakMap',\\nwritable:false,\\nenumerable:false,\\nconfigurable:true});\\n\\n\\nconst actualWeakSets=new WeakMap();\\nconst virtualObjectSets=new WeakMap();\\n\\nconst voAwareWeakSetDeleter=(descriptor)=>{\\nfor(const vref of descriptor.vset.values()){\\nvrm.removeRecognizableVref(vref,descriptor.vset);}};\\n\\n\\n\\nclass VirtualObjectAwareWeakSet{\\nconstructor(){\\nactualWeakSets.set(this,new WeakSet());\\nconst vset=new Set();\\nvirtualObjectSets.set(this,vset);\\n\\nvrm.registerDroppedCollection(this,{\\ncollectionDeleter:voAwareWeakSetDeleter,\\nvset});}\\n\\n\\n\\nhas(value){\\nconst vkey=vrm.vrefKey(value);\\nif(vkey){\\nreturn virtualObjectSets.get(this).has(vkey);}else\\n{\\nreturn actualWeakSets.get(this).has(value);}}\\n\\n\\n\\nadd(value){\\nconst vkey=vrm.vrefKey(value);\\nif(vkey){\\nconst vset=virtualObjectSets.get(this);\\nif(!vset.has(value)){\\nvrm.addRecognizableValue(value,vset);\\nvset.add(vkey);}}else\\n\\n{\\npreserveUnweakableKey(this,value);\\nactualWeakSets.get(this).add(value);}\\n\\nreturn this;}\\n\\n\\ndelete(value){\\nconst vkey=vrm.vrefKey(value);\\nif(vkey){\\nconst vset=virtualObjectSets.get(this);\\nif(vset.has(vkey)){\\nvrm.removeRecognizableValue(value,vset);\\nreturn vset.delete(vkey);}else\\n{\\nreturn false;}}else\\n\\n{\\nreleaseUnweakableKey(this,value);\\nreturn actualWeakSets.get(this).delete(value);}}}\\n\\n\\n\\n\\ndefineProperty(VirtualObjectAwareWeakSet,Symbol.toStringTag,{\\nvalue:'WeakSet',\\nwritable:false,\\nenumerable:false,\\nconfigurable:true});\\n\\n\\n/**\\n * @typedef {{\\n * kindID: string,\\n * tag: string,\\n * unfaceted?: boolean,\\n * facets?: string[],\\n * stateShapeCapData?: IMPORT('./types.js').SwingSetCapData\\n * }} DurableKindDescriptor\\n */\\n\\n/**\\n * @param {DurableKindDescriptor} durableKindDescriptor\\n */\\nconst saveDurableKindDescriptor=(durableKindDescriptor)=>{\\nconst{kindID}=durableKindDescriptor;\\nconst key=`vom.dkind.${kindID}.descriptor`;\\nsyscall.vatstoreSet(key,JSON.stringify(durableKindDescriptor));};\\n\\n\\n/**\\n * @param {string} kindID\\n * @returns {DurableKindDescriptor} durableKindDescriptor\\n */\\nconst loadDurableKindDescriptor=(kindID)=>{\\nconst key=`vom.dkind.${kindID}.descriptor`;\\nconst raw=syscall.vatstoreGet(key);\\nraw||index.throwRedacted`unknown kind ID ${kindID}`;\\nreturn JSON.parse(raw);};\\n\\n\\nconst saveNextInstanceID=(kindID)=>{\\nconst key=`vom.dkind.${kindID}.nextID`;\\nsyscall.vatstoreSet(key,`${nextInstanceIDs.get(kindID)}`);};\\n\\n\\nconst loadNextInstanceID=(kindID)=>{\\nconst key=`vom.dkind.${kindID}.nextID`;\\nreturn index$1.Nat(Number(syscall.vatstoreGet(key)));};\\n\\n\\nconst saveVirtualKindDescriptor=(kindID,descriptor)=>{\\n/* we never read these back: they're stored in the DB for the sake*/\\n/* of diagnostics, debugging, and potential external DB*/\\n/* cleanup/upgrade tools*/\\nconst key=`vom.vkind.${kindID}.descriptor`;\\nsyscall.vatstoreSet(key,JSON.stringify(descriptor));};\\n\\n\\n/**\\n * Define a new kind of virtual object.\\n *\\n * @param {string} kindID The kind ID to associate with the new kind.\\n *\\n * @param {string} tag A descriptive tag string as used in calls to `Far`\\n *\\n * @param {*} init An initialization function that will return the initial\\n * state of a new instance of the kind of virtual object being defined.\\n *\\n * @param {boolean} multifaceted True if this should be a multi-faceted\\n * virtual object, false if it should be single-faceted.\\n *\\n * @param {*} behavior A bag of functions (in the case of a single-faceted\\n * object) or a bag of bags of functions (in the case of a multi-faceted\\n * object) that will become the methods of the object or its facets.\\n *\\n * @param {DefineKindOptions<*>} options\\n * Additional options to configure the virtual object kind\\n * being defined. See the documentation of DefineKindOptions\\n * for the meaning of each option.\\n *\\n * @param {boolean} isDurable A flag indicating whether or not the newly defined\\n * kind should be a durable kind.\\n *\\n * @param {DurableKindDescriptor} [durableKindDescriptor] Descriptor for the\\n * durable kind, if it is, in fact, durable\\n *\\n * @returns {*} a maker function that can be called to manufacture new\\n * instances of this kind of object. The parameters of the maker function\\n * are those of the `init` function.\\n *\\n * Notes on theory of operation:\\n *\\n * Virtual objects are structured in three layers: representatives, inner\\n * selves, and state data.\\n *\\n * A representative is the manifestation of a virtual object that vat code has\\n * direct access to. A given virtual object can have at most one\\n * representative, which will be created as needed. This will happen when the\\n * instance is initially made, and can also happen (if it does not already\\n * exist) when the instance's virtual object ID is deserialized, either when\\n * delivered as part of an incoming message or read as part of another virtual\\n * object's state. A representative will be kept alive in memory as long as\\n * there is a variable somewhere that references it directly or indirectly.\\n * However, if a representative becomes unreferenced in memory it is subject\\n * to garbage collection, leaving the representation that is kept in the vat\\n * store as the record of its state from which a mew representative can be\\n * reconstituted at need. Since only one representative exists at a time,\\n * references to them may be compared with the equality operator (===).\\n * Although the identity of a representative can change over time, this is\\n * never visible to code running in the vat. Methods invoked on a\\n * representative always operate on the underlying virtual object state.\\n *\\n * The inner self represents the in-memory information about an object, aside\\n * from its state. There is an inner self for each virtual object that is\\n * currently resident in memory; that is, there is an inner self for each\\n * virtual object for which there is currently a representative present\\n * somewhere in the vat. The inner self maintains two pieces of information:\\n * its corresponding virtual object's virtual object ID, and a pointer to the\\n * virtual object's state in memory if the virtual object's state is, in fact,\\n * currently resident in memory. If the state is not in memory, the inner\\n * self's pointer to the state is null. In addition, the virtual object\\n * manager maintains an LRU cache of inner selves. Inner selves that are in\\n * the cache are not necessarily referenced by any existing representative,\\n * but are available to be used should such a representative be needed. How\\n * this all works will be explained in a moment.\\n *\\n * The state of a virtual object is a collection of mutable properties, each\\n * of whose values is itself immutable and serializable. The methods of a\\n * virtual object have access to this state by closing over a state object.\\n * However, the state object they close over is not the actual state object,\\n * but a wrapper with accessor methods that both ensure that a representation\\n * of the state is in memory when needed and perform deserialization on read\\n * and serialization on write; this wrapper is held by the representative, so\\n * that method invocations always see the wrapper belonging to the invoking\\n * representative. The actual state object holds marshaled serializations of\\n * each of the state properties. When written to persistent storage, this is\\n * represented as a JSON-stringified object each of whose properties is one\\n * of the marshaled property values.\\n *\\n * When a method of a virtual object attempts to access one of the properties\\n * of the object's state, the accessor first checks to see if the state is in\\n * memory. If it is not, it is loaded from persistent storage, the\\n * corresponding inner self is made to point at it, and then the inner self is\\n * placed at the head of the LRU cache (causing the least recently used inner\\n * self to fall off the end of the cache). If it *is* in memory, it is\\n * promoted to the head of the LRU cache but the overall contents of the cache\\n * remain unchanged. When an inner self falls off the end of the LRU, its\\n * reference to the state is nulled out and the object holding the state\\n * becomes garbage collectable.\\n */\\nconst defineKindInternal=(\\nkindID,\\ntag,\\ninit,\\nmultifaceted,\\nbehavior,\\noptions={},\\nisDurable,\\ndurableKindDescriptor=undefined/* only for durables*/)=>\\n{\\nconst{\\nfinish=undefined,\\nstateShape=undefined,\\nreceiveAmplifier=undefined,\\nreceiveInstanceTester=undefined,\\nthisfulMethods=false}=\\noptions;\\nlet{\\n/* These are \\\"let\\\" rather than \\\"const\\\" only to accommodate code*/\\n/* below that tolerates an old version of the vat-data package.*/\\n/* See there for more explanation.*/\\ninterfaceGuard=undefined,\\ninterfaceGuardKit=undefined}=\\noptions;\\n\\nconst statePrototype={};/* Not frozen yet*/\\nconst stateToBaseRefMap=new WeakMap();\\n\\nconst getBaseRef=(state)=>{\\nconst baseRef=stateToBaseRefMap.get(state);\\nbaseRef!==undefined||\\nindex.throwRedacted`state accessors can only be applied to state`;\\nreturn baseRef;};\\n\\n\\nlet proposedFacetNames;/* undefined or a list of strings*/\\n\\n/* 'multifaceted' tells us which API was used: define[Durable]Kind*/\\n/* vs define[Durable]KindMulti. This function checks whether*/\\n/* 'behavior' has one facet, or many, and must match.*/\\nswitch(facetiousness.assessFacetiousness(behavior)){\\ncase'one':{\\nindex.assert(!multifaceted);\\ninterfaceGuardKit===undefined||\\nindex.throwRedacted`Use an interfaceGuard, not interfaceGuardKit, to protect class ${index.quote(\\ntag)\\n}`;\\nproposedFacetNames=undefined;\\nbreak;}\\n\\ncase'many':{\\nindex.assert(multifaceted);\\n\\nif(interfaceGuard&&interfaceGuardKit===undefined){\\n/* This if clause is for the purpose of tolerating versions*/\\n/* of the vata-data package that precede*/\\n/* https://github.com/Agoric/agoric-sdk/pull/8220 .*/\\n/* Before that PR, the options name `interfaceGuard` would*/\\n/* actually carry the InterfaceGuardKit.*/\\n/**/\\n/* Tolerating the old vat-data with the new types.*/\\n/* @ts-expect-error*/\\ninterfaceGuardKit=interfaceGuard;\\ninterfaceGuard=undefined;\\n/* The rest of the code from here makes no further compromise*/\\n/* for that old version of the vat-data package.*/}\\n\\n\\ninterfaceGuard===undefined||\\nindex.throwRedacted`Use an interfaceGuardKit, not an interfaceGuard, to protect class kit ${index.quote(\\ntag)\\n}`;\\nproposedFacetNames=ownKeys(behavior).sort();\\nbreak;}\\n\\ncase'not':{\\nthrow index.throwRedacted`invalid behavior specifier for ${index.quote(tag)}`;}\\n\\ndefault:{\\nthrow index.throwRedacted`invalid facetiousness`;}}\\n\\n\\n/* beyond this point, we use 'multifaceted' to switch modes*/\\n\\n/* The 'stateShape' pattern constrains the `state` of each*/\\n/* instance: which properties it may have, and what their values*/\\n/* are allowed to be. For durable Kinds, the stateShape is*/\\n/* serialized and recorded in the durableKindDescriptor, so future*/\\n/* incarnations (which redefine the kind when they call*/\\n/* defineDurableKind again) can both check for compatibility, and*/\\n/* to decrement refcounts on any slots referenced by the old*/\\n/* shape.*/\\n\\nharden(stateShape);\\nstateShape===undefined||\\npassStyleOf.passStyleOf(stateShape)==='copyRecord'||\\nindex.throwRedacted`A stateShape must be a copyRecord: ${index.quote(stateShape)}`;\\npatternMatchers.assertPattern(stateShape);\\n\\nif(!multifaceted){\\nreceiveAmplifier===undefined||\\nindex.throwRedacted`Only facets of an exo class kit can be amplified, not ${index.quote(tag)}`;}\\n\\n\\nlet facetNames;\\n\\nif(isDurable){\\n/* durableKindDescriptor is created by makeKindHandle, with just*/\\n/* { kindID, tag, nextInstanceID }, then the first*/\\n/* defineDurableKind (maybe us!) will populate*/\\n/* .facets/.unfaceted and a .stateShape . We'll only see those*/\\n/* properties if we're in a non-initial incarnation.*/\\n\\nindex.assert(durableKindDescriptor);\\n\\n/* initial creation will update the descriptor with .facets or*/\\n/* .unfaceted, subsequent re-definitions will assert*/\\n/* compatibility, and reassign facet name->index*/\\nfacetNames=facetiousness.checkAndUpdateFacetiousness(\\ntag,\\ndurableKindDescriptor,\\nproposedFacetNames);\\n\\n\\nconst newShapeCD=serialize(stateShape);\\n\\n/* Durable kinds can only hold durable objects in their state,*/\\n/* so if the stateShape were to require a non-durable object,*/\\n/* nothing could ever match. So we require the shape have only*/\\n/* durable objects*/\\ninsistDurableCapdata(vrm,'stateShape',newShapeCD,false);\\n\\n/* compare against slots of previous definition, incref/decref*/\\nconst oldShapeCD=durableKindDescriptor.stateShapeCapData;\\n\\nconst oldStateShapeSlots=oldShapeCD?oldShapeCD.slots:[];\\nif(oldShapeCD&&!allowStateShapeChanges){\\ninsistSameCapData(oldShapeCD,newShapeCD);}\\n\\nconst newStateShapeSlots=newShapeCD.slots;\\nvrm.updateReferenceCounts(oldStateShapeSlots,newStateShapeSlots);\\ndurableKindDescriptor.stateShapeCapData=newShapeCD;/* replace*/\\n\\nsaveDurableKindDescriptor(durableKindDescriptor);}else\\n{\\nfacetNames=proposedFacetNames;}\\n\\n\\n/** @type {(prop: string) => void} */\\nlet checkStateProperty=(_prop)=>{};\\n/** @type {(value: any, prop: string) => void} */\\nlet checkStatePropertyValue=(_value,_prop)=>{};\\nif(stateShape){\\ncheckStateProperty=(prop)=>{\\nhasOwn(stateShape,prop)||\\nindex.throwRedacted`State must only have fields described by stateShape: ${index.quote(\\nownKeys(stateShape))\\n}`;};\\n\\ncheckStatePropertyValue=(value,prop)=>{\\ncheckStateProperty(prop);\\npatternMatchers.mustMatch(value,stateShape[prop]);};}\\n\\n\\n\\n/* The dataCache holds both unserialized and still-serialized*/\\n/* (capdata) contents of the virtual-object state record.*/\\n/* dataCache[baseRef] -> { capdatas, valueMap }*/\\n/* valueCD=capdatas[prop], value=valueMap.get(prop)*/\\n/** @type { IMPORT('./cache.js').Cache<{ capdatas: any, valueMap: Map<string, any> }>} */\\nconst dataCache=makeDataCache(syscall);\\nallCaches.push(dataCache);\\n\\n/* Behavior functions will receive a 'state' object that provides*/\\n/* access to their virtualized data, with getters and setters*/\\n/* backed by the vatstore DB. When those functions are invoked and*/\\n/* we miss in contextCache, we'll call makeState() and*/\\n/* makeContext(). The makeState() call might read from the*/\\n/* vatstore DB if we miss in dataCache.*/\\n\\n/* We sample dataCache.get() once each time:*/\\n/* * makeState() is called, which happens the first time in each crank that*/\\n/* a method is invoked (and the prototype does getContext)*/\\n/* * when state.prop is read, invoking the getter*/\\n/* * when state.prop is written, invoking the setter*/\\n/* This will cause a syscall.vatstoreGet only once per crank.*/\\n\\nconst makeFieldDescriptor=(prop)=>{\\nreturn harden({\\nget(){\\nconst baseRef=getBaseRef(this);\\nconst record=dataCache.get(baseRef);\\nindex.assert(record!==undefined);\\nconst{valueMap,capdatas}=record;\\nif(!valueMap.has(prop)){\\nconst value=harden(unserialize(capdatas[prop]));\\ncheckStatePropertyValue(value,prop);\\nvalueMap.set(prop,value);}\\n\\nreturn valueMap.get(prop);},\\n\\nset(value){\\nconst baseRef=getBaseRef(this);\\ncheckStatePropertyValue(value,prop);\\nconst capdata=serialize(value);\\nassertAcceptableSyscallCapdataSize([capdata]);\\nif(isDurable){\\ninsistDurableCapdata(vrm,prop,capdata,true);}\\n\\nconst record=dataCache.get(baseRef);/* mutable*/\\nindex.assert(record!==undefined);\\nconst oldSlots=record.capdatas[prop].slots;\\nconst newSlots=capdata.slots;\\nvrm.updateReferenceCounts(oldSlots,newSlots);\\nrecord.capdatas[prop]=capdata;/* modify in place ..*/\\nrecord.valueMap.set(prop,value);\\ndataCache.set(baseRef,record);/* .. but mark as dirty*/},\\n\\nenumerable:true,\\nconfigurable:false});};\\n\\n\\n\\nif(stateShape!==undefined){\\nfor(const prop of ownKeys(stateShape)){\\ndefineProperty(statePrototype,prop,makeFieldDescriptor(prop));}}\\n\\n\\n\\nharden(statePrototype);\\n\\nconst makeState=(baseRef)=>{\\nconst state={__proto__:statePrototype};\\nif(stateShape===undefined){\\nconst record=dataCache.get(baseRef);\\nindex.assert(record!==undefined);\\nfor(const prop of ownKeys(record.capdatas)){\\nindex.assert(typeof prop==='string');\\ncheckStateProperty(prop);\\ndefineProperty(state,prop,makeFieldDescriptor(prop));}}\\n\\n\\nharden(state);\\nstateToBaseRefMap.set(state,baseRef);\\nreturn state;};\\n\\n\\n/* More specifically, behavior functions receive a \\\"context\\\"*/\\n/* object as their first argument, with { state, self } or {*/\\n/* state, facets }. This makeContext() creates one, and is called*/\\n/* if/when those functions are invoked and the \\\"contextCache\\\"*/\\n/* misses, in which case the makeContextCache/readBacking function*/\\n/* will sample dataCache.get, then call both \\\"makeState()\\\" and*/\\n/* \\\"makeContext\\\". The DB might be read by that dataCache.get.*/\\n\\nconst makeContext=(baseRef,state)=>{\\n/* baseRef came from valToSlot, so must be in slotToVal*/\\nconst val=requiredValForSlot(baseRef);\\n/* val is either 'self' or the facet record*/\\nif(multifaceted){\\nreturn harden({state,facets:val});}else\\n{\\nreturn harden({state,self:val});}};\\n\\n\\n\\n/* The contextCache holds the {state,self} or {state,facets} \\\"context\\\"*/\\n/* object, needed by behavior functions. We keep this in a (per-crank)*/\\n/* cache because creating one requires knowledge of the state property*/\\n/* names, which requires a DB read. The property names are fixed at*/\\n/* instance initialization time, so we never write changes to this cache.*/\\n\\nconst contextCache=makeContextCache(makeState,makeContext);\\nallCaches.push(contextCache);\\n\\n/* defendPrototype/defendPrototypeKit accept a contextProvider function,*/\\n/* or a contextProviderKit record which maps facet name strings to*/\\n/* provider functions. It calls the function during invocation of each*/\\n/* method, and expects to get back the \\\"context\\\" record, either { state,*/\\n/* self } for single-facet VOs, or { state, facets } for multi-facet*/\\n/* ones. The provider we use fetches the state data (if not already in the*/\\n/* cache) at the last minute. This moves any syscalls needed by*/\\n/* stateCache.get() out of deserialization time (which is sensitive to GC)*/\\n/* and into method-invocation time (which is not).*/\\n\\nlet proto;\\n/** @type {ClassContextProvider | undefined} */\\nlet contextProviderVar;\\n/** @type { Record<string, KitContextProvider> | undefined } */\\nlet contextProviderKitVar;\\n\\nif(multifaceted){\\ncontextProviderKitVar=fromEntries(\\nfacetNames.map((name,index)=>[\\nname,\\n(rep)=>{\\nconst vref=getSlotForVal(rep);\\nif(vref===undefined){\\nreturn undefined;}\\n\\nconst{baseRef,facet}=parseVatSlots.parseVatSlot(vref);\\n\\n/* Without this check, an attacker (with access to both*/\\n/* cohort1.facetA and cohort2.facetB)*/\\n/* could effectively forge access to*/\\n/* cohort1.facetB and cohort2.facetA.*/\\n/* They could not forge the identity of those two*/\\n/* objects, but they could invoke all their equivalent methods,*/\\n/* by using e.g.*/\\n/* cohort1.facetA.foo.apply(cohort2.facetB, [...args])*/\\nif(Number(facet)!==index){\\nreturn undefined;}\\n\\n\\nreturn harden(contextCache.get(baseRef));}]));\\n\\n\\n\\n\\nproto=exoTools.defendPrototypeKit(\\ntag,\\nharden(contextProviderKitVar),\\nbehavior,\\nthisfulMethods,\\ninterfaceGuardKit);}else\\n\\n{\\ncontextProviderVar=(rep)=>{\\nconst slot=getSlotForVal(rep);\\nif(slot===undefined){\\nreturn undefined;}\\n\\nreturn harden(contextCache.get(slot));};\\n\\nproto=exoTools.defendPrototype(\\ntag,\\nharden(contextProviderVar),\\nbehavior,\\nthisfulMethods,\\ninterfaceGuard);}\\n\\n\\nharden(proto);\\n\\n/* All this to let typescript know that it won't vary during a closure*/\\nconst contextProvider=contextProviderVar;\\nconst contextProviderKit=contextProviderKitVar;\\n\\n/* this builds new Representatives, both when creating a new instance and*/\\n/* for reanimating an existing one when the old rep gets GCed*/\\n\\nconst reanimateVO=(baseRef)=>{\\nif(multifaceted){\\nreturn makeFacets(facetNames,proto,linkToCohort,unweakable,baseRef);}else\\n{\\nreturn makeRepresentative(proto,baseRef);}};\\n\\n\\n\\nconst deleteStoredVO=(baseRef)=>{\\nlet doMoreGC=false;\\nconst record=dataCache.get(baseRef);\\nindex.assert(record!==undefined);\\nfor(const valueCD of Object.values(record.capdatas)){\\nfor(const vref of valueCD.slots){\\ndoMoreGC=vrm.removeReachableVref(vref)||doMoreGC;}}\\n\\n\\ndataCache.delete(baseRef);\\nreturn doMoreGC;};\\n\\n\\n/* Tell the VRM about this Kind.*/\\nvrm.registerKind(kindID,reanimateVO,deleteStoredVO,isDurable);\\nvrm.rememberFacetNames(kindID,facetNames);\\n\\nconst makeNewInstance=(...args)=>{\\nconst id=getNextInstanceID(kindID,isDurable);\\nconst baseRef=parseVatSlots.makeBaseRef(kindID,id,isDurable);\\n/* kdebug(`vo make ${baseRef}`);*/\\n\\nconst initialData=init?init(...args):{};\\n\\n/* catch mistaken use of `() => { foo: 1 }` rather than `() => ({ foo: 1 })`*/\\n/* (the former being a function with a body having a no-op statement labeled*/\\n/* \\\"foo\\\" and returning undefined, the latter being a function with a concise*/\\n/* body that returns an object having a property named \\\"foo\\\").*/\\ntypeof initialData==='object'||\\nindex.throwRedacted`initial data must be object, not ${initialData}`;\\n\\n/* save (i.e. populate the cache) with the initial serialized record*/\\nconst capdatas={};\\nconst valueMap=new Map();\\nfor(const prop of getOwnPropertyNames(initialData)){\\nconst value=initialData[prop];\\ncheckStatePropertyValue(value,prop);\\nconst valueCD=serialize(value);\\n/* TODO: we're only checking the size of one property at a*/\\n/* time, but the real constraint is the vatstoreSet of the*/\\n/* aggregate record. We should apply this check to the full*/\\n/* list of capdatas, plus its likely JSON overhead.*/\\nassertAcceptableSyscallCapdataSize([valueCD]);\\nif(isDurable){\\ninsistDurableCapdata(vrm,prop,valueCD,true);}\\n\\n/* eslint-disable-next-line github/array-foreach*/\\nvalueCD.slots.forEach(vrm.addReachableVref);\\ncapdatas[prop]=valueCD;\\nvalueMap.set(prop,value);}\\n\\n/* dataCache contents remain mutable: state setter modifies in-place*/\\ndataCache.set(baseRef,{capdatas,valueMap});\\n\\n/* make the initial representative or cohort*/\\nlet val;\\nif(multifaceted){\\nval=makeFacets(facetNames,proto,linkToCohort,unweakable,baseRef);}else\\n{\\nval=makeRepresentative(proto,baseRef);}\\n\\nregisterValue(baseRef,val,multifaceted);\\nfinish&&finish(contextCache.get(baseRef));\\nreturn val;};\\n\\n\\nif(receiveAmplifier){\\nindex.assert(contextProviderKit);\\n\\n/* Amplify a facet to a cohort*/\\nconst amplify=(exoFacet)=>{\\nfor(const cp of values(contextProviderKit)){\\nconst context=cp(exoFacet);\\nif(context!==undefined){\\nreturn context.facets;}}\\n\\n\\nthrow index.throwRedacted`Must be a facet of ${index.quote(tag)}: ${exoFacet}`;};\\n\\nharden(amplify);\\nreceiveAmplifier(amplify);}\\n\\n\\nif(receiveInstanceTester){\\nif(multifaceted){\\nindex.assert(contextProviderKit);\\n\\nconst isInstance=(exoFacet,facetName=undefined)=>{\\nif(facetName===undefined){\\n/* Is exoFacet and instance of any facet of this class kit?*/\\nreturn values(contextProviderKit).some(\\n(cp)=>cp(exoFacet)!==undefined);}\\n\\n\\n/* Is this exoFacet an instance of this specific facet column*/\\n/* of this class kit?*/\\nindex.assert.typeof(facetName,'string');\\nconst cp=contextProviderKit[facetName];\\ncp!==undefined||\\nindex.throwRedacted`exo class kit ${index.quote(tag)} has no facet named ${index.quote(facetName)}`;\\nreturn cp(exoFacet)!==undefined;};\\n\\nharden(isInstance);\\nreceiveInstanceTester(isInstance);}else\\n{\\nindex.assert(contextProvider);\\n/* Is this exo an instance of this class?*/\\nconst isInstance=(exo,facetName=undefined)=>{\\nfacetName===undefined||\\nindex.throwRedacted`facetName can only be used with an exo class kit: ${index.quote(\\ntag)\\n} has no facet ${index.quote(facetName)}`;\\nreturn contextProvider(exo)!==undefined;};\\n\\nharden(isInstance);\\nreceiveInstanceTester(isInstance);}}\\n\\n\\n\\nreturn makeNewInstance;};\\n\\n\\nlet kindIDID;\\n/** @type Map<string, DurableKindDescriptor> */\\nconst kindIDToDescriptor=new Map();\\nconst kindHandleToID=new Map();\\nconst definedDurableKinds=new Set();/* kindID*/\\nconst nextInstanceIDs=new Map();/* kindID -> nextInstanceID*/\\n\\nconst reanimateDurableKindID=(vobjID)=>{\\nconst kindID=`${parseVatSlots.parseVatSlot(vobjID).subid}`;\\nconst durableKindDescriptor=loadDurableKindDescriptor(kindID);\\nconst nextInstanceID=loadNextInstanceID(kindID);\\nkindIDToDescriptor.set(kindID,durableKindDescriptor);\\nnextInstanceIDs.set(kindID,nextInstanceID);\\nconst kindHandle=makeFar.Far('kind',{});\\nkindHandleToID.set(kindHandle,kindID);\\n/* KindHandles are held strongly for the remainder of the incarnation, so*/\\n/* their components do not provide GC sensors*/\\nreturn kindHandle;};\\n\\n\\nconst initializeKindHandleKind=()=>{\\nkindIDID=syscall.vatstoreGet('kindIDID');\\nif(!kindIDID){\\nkindIDID=`${allocateExportID()}`;\\nsyscall.vatstoreSet('kindIDID',kindIDID);}\\n\\nvrm.registerKind(kindIDID,reanimateDurableKindID,()=>false,true);};\\n\\n\\nconst getNextInstanceID=(kindID,isDurable)=>{\\nindex.assert.typeof(kindID,'string');\\n/* nextInstanceID is initialized to 1 for brand new kinds, loaded*/\\n/* from DB when redefining existing kinds, held in RAM, and*/\\n/* written to DB after each increment as part of*/\\n/* kindDescriptors[kindID]*/\\nconst id=nextInstanceIDs.get(kindID);\\nindex.assert(id!==undefined);\\nconst next=id+1n;\\nnextInstanceIDs.set(kindID,next);\\nif(isDurable){\\nsaveNextInstanceID(kindID);}\\n\\nreturn id;};\\n\\n\\n/** @type {IMPORT('./vatDataTypes').VatData['defineKind']} */\\nconst defineKind=(tag,init,behavior,options)=>{\\nconst kindID=`${allocateExportID()}`;\\nsaveVirtualKindDescriptor(kindID,{kindID,tag});\\nnextInstanceIDs.set(kindID,1n);\\nreturn defineKindInternal(\\nkindID,\\ntag,\\ninit,\\nfalse,\\nbehavior,\\noptions,\\nfalse);};\\n\\n\\n\\n/** @type {IMPORT('./vatDataTypes').VatData['defineKindMulti']} */\\nconst defineKindMulti=(tag,init,behavior,options)=>{\\nconst kindID=`${allocateExportID()}`;\\nsaveVirtualKindDescriptor(kindID,{kindID,tag});\\nnextInstanceIDs.set(kindID,1n);\\nreturn defineKindInternal(\\nkindID,\\ntag,\\ninit,\\ntrue,\\nbehavior,\\noptions,\\nfalse);};\\n\\n\\n\\n/**\\n *\\n * @param {string} tag\\n * @returns {DurableKindHandle}\\n */\\nconst makeKindHandle=(tag)=>{\\nindex.assert(kindIDID,'initializeKindHandleKind not called yet');\\nconst kindID=`${allocateExportID()}`;\\nconst durableKindDescriptor={kindID,tag};\\nconst nextInstanceID=1n;\\nkindIDToDescriptor.set(kindID,durableKindDescriptor);\\nnextInstanceIDs.set(kindID,nextInstanceID);\\nsaveDurableKindDescriptor(durableKindDescriptor);\\nsaveNextInstanceID(kindID);\\n/** @type {DurableKindHandle} */\\n\\n/* @ts-expect-error cast*/\\nconst kindHandle=makeFar.Far('kind',{});\\nkindHandleToID.set(kindHandle,kindID);\\nconst kindIDvref=parseVatSlots.makeBaseRef(kindIDID,kindID,true);\\nregisterValue(kindIDvref,kindHandle,false);\\nreturn kindHandle;};\\n\\n\\n/** @type {IMPORT('./vatDataTypes').VatData['defineDurableKind']} */\\nconst defineDurableKind=(kindHandle,init,behavior,options)=>{\\nkindHandleToID.has(kindHandle)||index.throwRedacted`unknown handle ${kindHandle}`;\\nconst kindID=kindHandleToID.get(kindHandle);\\nconst durableKindDescriptor=kindIDToDescriptor.get(kindID);\\nindex.assert(durableKindDescriptor);\\nconst{tag}=durableKindDescriptor;\\n!definedDurableKinds.has(kindID)||\\nindex.throwRedacted`redefinition of durable kind ${tag}`;\\nconst maker=defineKindInternal(\\nkindID,\\ntag,\\ninit,\\nfalse,\\nbehavior,\\noptions,\\ntrue,\\ndurableKindDescriptor);\\n\\ndefinedDurableKinds.add(kindID);\\nreturn maker;};\\n\\n\\n/** @type {IMPORT('./vatDataTypes').VatData['defineDurableKindMulti']} */\\nconst defineDurableKindMulti=(kindHandle,init,behavior,options)=>{\\nkindHandleToID.has(kindHandle)||index.throwRedacted`unknown handle ${kindHandle}`;\\nconst kindID=kindHandleToID.get(kindHandle);\\nconst durableKindDescriptor=kindIDToDescriptor.get(kindID);\\nindex.assert(durableKindDescriptor);\\nconst{tag}=durableKindDescriptor;\\n!definedDurableKinds.has(kindID)||\\nindex.throwRedacted`redefinition of durable kind \\\"${tag}\\\"`;\\nconst maker=defineKindInternal(\\nkindID,\\ntag,\\ninit,\\ntrue,\\nbehavior,\\noptions,\\ntrue,\\ndurableKindDescriptor);\\n\\ndefinedDurableKinds.add(kindID);\\nreturn maker;};\\n\\n\\nconst insistAllDurableKindsReconnected=()=>{\\n/* identify all user-defined durable kinds by iterating `vom.dkind.*`*/\\nconst missing=[];\\nconst prefix='vom.dkind.';\\nfor(const key of vatstoreIterators.enumerateKeysWithPrefix(syscall,prefix)){\\nif(key.endsWith('.descriptor')){\\nconst value=syscall.vatstoreGet(key);\\nconst durableKindDescriptor=JSON.parse(value);\\nif(!definedDurableKinds.has(durableKindDescriptor.kindID)){\\nmissing.push(durableKindDescriptor.tag);}}}\\n\\n\\n\\nif(missing.length){\\nconst tags=missing.join(',');\\nthrow Error(`defineDurableKind not called for tags: [${tags}]`);}};\\n\\n\\n\\nconst countWeakKeysForCollection=(collection)=>{\\nconst virtualObjectMap=virtualObjectMaps.get(collection);\\nif(virtualObjectMap){\\nreturn virtualObjectMap.size;}\\n\\nconst virtualObjectSet=virtualObjectSets.get(collection);\\nif(virtualObjectSet){\\nreturn virtualObjectSet.size;}\\n\\nreturn 0;};\\n\\n\\nconst testHooks={\\ncountWeakKeysForCollection,\\n\\ndefinedDurableKinds,\\nnextInstanceIDs};\\n\\n\\nconst flushStateCache=()=>{\\nfor(const cache of allCaches){\\ncache.flush();}};\\n\\n\\n\\nconst getRetentionStats=()=>{\\nreturn{\\ndefinedDurableKinds:definedDurableKinds.size,\\nnextInstanceIDs:nextInstanceIDs.size};};\\n\\n\\n\\nreturn harden({\\ninitializeKindHandleKind,\\ndefineKind,\\ndefineKindMulti,\\ndefineDurableKind,\\ndefineDurableKindMulti,\\nmakeKindHandle,\\ninsistAllDurableKindsReconnected,\\nVirtualObjectAwareWeakMap,\\nVirtualObjectAwareWeakSet,\\nflushStateCache,\\ngetRetentionStats,\\ntestHooks,\\ncanBeDurable});};\\n\\n\\n/**\\n * @typedef { ReturnType<typeof makeVirtualObjectManager> } VirtualObjectManager\\n */exports.makeVirtualObjectManager=makeVirtualObjectManager;\",\n \"packages/swingset-liveslots/src/virtualReferences.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var assert=require('../../assert/src/assert.js');var index=require('../../../node_modules/@endo/nat/src/index.js');var parseVatSlots=require('./parseVatSlots.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nvatstoreIterators=require('./vatstore-iterators.js');/* eslint-disable no-use-before-define, jsdoc/require-returns-type */ /**\\n * @param {*} syscall Vat's syscall object, used to access the vatstore operations.\\n * @param {(val: object) => string | undefined} getSlotForVal A function that returns the\\n * object ID (vref) for a given object, if any. their corresponding export\\n * IDs\\n * @param {(slot: string) => object} requiredValForSlot A function that\\n * converts an object ID (vref) to an object.\\n * @param {*} FinalizationRegistry Powerful JavaScript intrinsic normally denied\\n * by SES\\n * @param {*} WeakRef Powerful JavaScript intrinsic normally denied\\n * by SES\\n * @param {*} addToPossiblyDeadSet Function to record objects whose deaths\\n * should be reinvestigated\\n * @param {*} addToPossiblyRetiredSet Function to record dead objects whose\\n * retirement should be reinvestigated\\n * @param {boolean} relaxDurabilityRules True IFF the associated swingset is\\n * running with relaxed durability rules\\n */\\nfunction makeVirtualReferenceManager(\\nsyscall,\\ngetSlotForVal,\\nrequiredValForSlot,\\nFinalizationRegistry,\\nWeakRef,\\naddToPossiblyDeadSet,\\naddToPossiblyRetiredSet,\\nrelaxDurabilityRules)\\n{\\nconst droppedCollectionRegistry=new FinalizationRegistry(\\nfinalizeDroppedCollection);\\n\\n/* Our JS engine is configured to treat WeakRefs as strong during*/\\n/* organic (non-forced GC), to minimize execution variation. To*/\\n/* prevent FinalizationRegistry callbacks from varying this way, we*/\\n/* must maintain WeakRefs to everything therein. The WeakRef is*/\\n/* retained by the FR \\\"heldValue\\\" context record, next to the*/\\n/* descriptor, and is thus released when the FR fires.*/\\n\\nfunction registerDroppedCollection(target,descriptor){\\nconst wr=new WeakRef(target);\\ndroppedCollectionRegistry.register(target,{descriptor,wr});}\\n\\n\\n/**\\n * Check if a virtual object is unreachable via virtual-data references.\\n *\\n * A virtual object is kept alive if it or any of its facets are reachable by\\n * any of three legs:\\n * - in-memory references (if so, it will have a representative and thus a\\n * non-null slot-to-val entry)\\n * - virtual references (if so, it will have a refcount > 0)\\n * - being exported (if so, its export flag will be set)\\n *\\n * This function is called after a leg has been reported missing,\\n * and reports back on whether the virtual-reference and\\n * export-status legs remain. The caller (liveslots\\n * scanForDeadObjects) will combine this with information about the\\n * RAM leg to decide whether the object is completely unreachable,\\n * and thus should be deleted.\\n *\\n * @param {string} baseRef The virtual object cohort might be dead\\n *\\n * @returns {boolean} True if the object remains referenced, false if unreachable\\n */\\nfunction isVirtualObjectReachable(baseRef){\\nconst refCount=getRefCount(baseRef);\\nconst[reachable,_retirees]=getExportStatus(baseRef);\\nreturn!!(reachable||refCount);}\\n\\n\\n/**\\n * Delete a virtual object\\n *\\n * Once the caller determines that all three legs are gone, they\\n * call us to delete the object.\\n *\\n * Deletion consists of removing the vatstore entries that describe its state\\n * and track its refcount status. In addition, when a virtual object is\\n * deleted, we delete any weak collection entries for which it was a key. If\\n * it had been exported, we also inform the kernel that the vref has been\\n * retired, so other vats can delete their weak collection entries too.\\n *\\n * @param {string} baseRef The virtual object cohort that's certainly dead\\n *\\n * @returns {[boolean, string[]]} A pair of a flag that's true if this\\n * possibly created a new GC opportunity and an array of vrefs that should\\n * now be regarded as unrecognizable\\n */\\nfunction deleteVirtualObject(baseRef){\\nconst refCount=getRefCount(baseRef);\\nconst[reachable,retirees]=getExportStatus(baseRef);\\nassert.assert(!reachable);\\nassert.assert(!refCount);\\nlet doMoreGC=deleteStoredRepresentation(baseRef);\\nsyscall.vatstoreDelete(`vom.rc.${baseRef}`);\\nsyscall.vatstoreDelete(`vom.es.${baseRef}`);\\ndoMoreGC=ceaseRecognition(baseRef)||doMoreGC;\\nreturn[doMoreGC,retirees];}\\n\\n\\n/**\\n * Get information about the export status of a virtual object.\\n *\\n * @param {string} baseRef The baseRef of the virtual object of interest.\\n *\\n * @returns {[boolean, string[]]} A pair of a flag that's true if the\\n * indicated virtual object is reachable and an array of vrefs (to facets\\n * of the object) that should now be regarded as unrecognizable\\n */\\nfunction getExportStatus(baseRef){\\nconst es=syscall.vatstoreGet(`vom.es.${baseRef}`);\\nif(es){\\nconst reachable=es.indexOf('r')>=0;\\nconst retirees=[];\\nif(!reachable){\\nif(es==='s'){\\n/* unfaceted*/\\nretirees.push(baseRef);}else\\n{\\n/* faceted*/\\nfor(let i=0;i<es.length;i+=1){\\nif(es[i]==='s'){\\nretirees.push(`${baseRef}:${i}`);}}}}\\n\\n\\n\\n\\nreturn[reachable,retirees];}else\\n{\\nreturn[false,[]];}}\\n\\n\\n\\nfunction getRefCount(baseRef){\\nconst raw=syscall.vatstoreGet(`vom.rc.${baseRef}`);\\nif(raw){\\nreturn Number(raw);}else\\n{\\nreturn 0;}}\\n\\n\\n\\nfunction setRefCount(baseRef,refCount){\\nconst{facet}=parseVatSlots.parseVatSlot(baseRef);\\n!facet||assert.Fail`setRefCount ${baseRef} should not receive individual facets`;\\nif(refCount===0){\\nsyscall.vatstoreDelete(`vom.rc.${baseRef}`);\\naddToPossiblyDeadSet(baseRef);}else\\n{\\nsyscall.vatstoreSet(`vom.rc.${baseRef}`,`${index.Nat(refCount)}`);}}\\n\\n\\n\\nfunction setExportStatus(vref,exportStatus){\\nconst{baseRef,id,facet}=parseVatSlots.parseVatSlot(vref);\\nconst key=`vom.es.${baseRef}`;\\nconst esRaw=syscall.vatstoreGet(key);\\n/* 'esRaw' may be undefined (nothing is currently exported), and*/\\n/* it might be short (saved by a previous version that had fewer*/\\n/* facets). Pad it out to the current length, which is '1' for*/\\n/* unfaceted Kinds*/\\nconst es=Array.from((esRaw||'').padEnd(getFacetCount(id),'n'));\\nconst facetIdx=facet===undefined?0:facet;\\n/* The export status of each facet is encoded as:*/\\n/* 's' -> 'recognizable' ('s' for \\\"see\\\"), 'r' -> 'reachable', 'n' -> 'none'*/\\nswitch(exportStatus){\\n/* POSSIBLE TODO: An anticipated refactoring may merge*/\\n/* dispatch.dropExports with dispatch.retireExports. If this happens, and*/\\n/* the export status can drop from 'reachable' to 'none' in a single step, we*/\\n/* must perform this \\\"the export pillar has dropped\\\" check in both the*/\\n/* reachable and the none cases (possibly reading the old status first, if*/\\n/* we must ensure addToPossiblyDeadSet only happens once).*/\\ncase'recognizable':{\\nes[facetIdx]='s';\\nsyscall.vatstoreSet(key,es.join(''));\\nconst refCount=getRefCount(baseRef);\\nif(refCount===0&&es.indexOf('r')<0){\\naddToPossiblyDeadSet(baseRef);}\\n\\nbreak;}\\n\\ncase'reachable':\\nes[facetIdx]='r';\\nsyscall.vatstoreSet(key,es.join(''));\\nbreak;\\ncase'none':\\nes[facetIdx]='n';\\nif(es.indexOf('r')<0&&es.indexOf('s')<0){\\nsyscall.vatstoreDelete(key);}else\\n{\\nsyscall.vatstoreSet(key,es.join(''));}\\n\\nbreak;\\ndefault:\\nassert.Fail`invalid set export status ${exportStatus}`;}}\\n\\n\\n\\nfunction incRefCount(baseRef){\\nconst oldRefCount=getRefCount(baseRef);\\nsetRefCount(baseRef,oldRefCount+1);}\\n\\n\\nfunction decRefCount(baseRef){\\nconst oldRefCount=getRefCount(baseRef);\\noldRefCount>0||assert.Fail`attempt to decref ${baseRef} below 0`;\\nsetRefCount(baseRef,oldRefCount-1);}\\n\\n\\n/**\\n * Map from virtual object kind IDs to information about those kinds,\\n * including functions for handling the persistent representations of the\\n * corresponding kinds of objects.\\n */\\nconst kindInfoTable=new Map();\\n\\n/**\\n * Register information describing a persistent object kind.\\n *\\n * @param {string} kindID The kind of persistent object being handle\\n * @param {(string, boolean) => object} [reanimator] Reanimator function for the given kind.\\n * @param {(string) => boolean} [deleter] Deleter function for the given kind.\\n * @param {boolean} [durable] Flag indicating if instances survive vat termination\\n */\\nfunction registerKind(kindID,reanimator,deleter,durable){\\nkindInfoTable.set(`${kindID}`,{reanimator,deleter,durable});}\\n\\n\\n/**\\n * Record the names of the facets of a multi-faceted virtual object.\\n *\\n * @param {string} kindID The kind we're talking about\\n * @param {string[]|null} facetNames A sorted array of facet names to be\\n * recorded, or null if the kind is unfaceted\\n */\\nfunction rememberFacetNames(kindID,facetNames){\\nconst kindInfo=kindInfoTable.get(`${kindID}`);\\nkindInfo||assert.Fail`no kind info for ${kindID}`;\\nassert.assert(kindInfo.facetNames===undefined);\\nkindInfo.facetNames=facetNames;}\\n\\n\\nfunction getFacetNames(kindID){\\nreturn kindInfoTable.get(`${kindID}`).facetNames;}\\n\\n\\nfunction getFacetCount(kindID){\\nconst facetNames=getFacetNames(kindID);\\nreturn facetNames?facetNames.length:1;}\\n\\n\\nfunction getFacet(kindID,facets,facetIndex){\\nconst facetName=getFacetNames(kindID)[facetIndex];\\nfacetName!==undefined||/* allow empty-string -named facets*/\\nassert.Fail`getFacet missing, ${kindID} [${facetIndex}]`;\\nconst facet=facets[facetName];\\nfacet||assert.Fail`getFacet missing, ${kindID} [${facetIndex}] ${facetName}`;\\nreturn facet;}\\n\\n\\n/**\\n * Inquire if a given persistent object kind is a durable kind or not.\\n *\\n * @param {string} kindID The kind of interest\\n *\\n * @returns {boolean} true if the indicated kind is durable.\\n */\\nfunction isDurableKind(kindID){\\nconst{durable}=kindInfoTable.get(`${kindID}`);\\nreturn durable;}\\n\\n\\n/**\\n * Inquire if a given vref is something that can be stored in a durable store\\n * or virtual object.\\n *\\n * @param {string} vref The vref of interest\\n *\\n * @returns {boolean} true if the indicated object reference is durable.\\n */\\nfunction isDurable(vref){\\nconst{type,id,virtual,durable,allocatedByVat}=parseVatSlots.parseVatSlot(vref);\\nif(relaxDurabilityRules){\\n/* we'll pretend an object is durable if running with relaxed rules*/\\nreturn true;}else\\nif(type==='device'){\\n/* devices are durable*/\\nreturn true;}else\\nif(type!=='object'){\\n/* promises are not durable*/\\nreturn false;}else\\nif(!allocatedByVat){\\n/* imports are durable*/\\nreturn true;}else\\nif(virtual||durable){\\n/* stores and virtual objects are durable if their kinds are so configured*/\\nreturn isDurableKind(id);}else\\n{\\n/* otherwise it's not durable*/\\nreturn false;}}\\n\\n\\n\\n/**\\n * Create an in-memory representation of a given object by reanimating it from\\n * persistent storage. Used for deserializing.\\n *\\n * @param {string} baseRef The baseRef of the object being reanimated\\n *\\n * @returns A representative of the object identified by `baseRef`\\n */\\nfunction reanimate(baseRef){\\nconst{id}=parseVatSlots.parseVatSlot(baseRef);\\nconst kindID=`${id}`;\\nconst kindInfo=kindInfoTable.get(kindID);\\nkindInfo||\\nassert.Fail`no kind info for ${kindID} (${baseRef}); check deserialize preceding kind definitions`;\\nconst{reanimator}=kindInfo;\\nif(reanimator){\\nreturn reanimator(baseRef);}else\\n{\\nthrow assert.Fail`unknown kind ${kindID}`;}}\\n\\n\\n\\n/**\\n * Delete the persistent representation of a virtual object given its ID\\n *\\n * @param {string} vobjID The virtual object ID of the object to be expunged\\n */\\nfunction deleteStoredRepresentation(vobjID){\\nconst{id}=parseVatSlots.parseVatSlot(vobjID);\\nconst kindID=`${id}`;\\nconst{deleter}=kindInfoTable.get(kindID);\\nif(deleter){\\nreturn deleter(vobjID);}else\\n{\\nthrow assert.Fail`unknown kind ${kindID}`;}}\\n\\n\\n\\n/**\\n * Map of all Remotables which are reachable by our virtualized data, e.g.\\n * `makeScalarWeakMapStore().set(key, remotable)` or `virtualObject.state.foo =\\n * remotable`. The serialization process stores the Remotable's vref to disk,\\n * but doesn't actually retain the Remotable. To correctly unserialize that\\n * offline data later, we must ensure the Remotable remains alive. This Map\\n * keeps a strong reference to the Remotable along with its (virtual) refcount.\\n */\\n/** @type {Map<object, number>} Remotable->refcount */\\nconst remotableRefCounts=new Map();\\n\\n/* Note that since presence refCounts are keyed by vref, `processDeadSet` must*/\\n/* query the refCount directly in order to determine if a presence that found*/\\n/* its way into the dead set is live or not, whereas it never needs to query*/\\n/* the `remotableRefCounts` map because that map holds actual live references*/\\n/* as keys and so Remotable references will only find their way into the dead*/\\n/* set if they are actually unreferenced (including, notably, their absence*/\\n/* from the `remotableRefCounts` map).*/\\n\\nfunction addReachableVref(vref){\\nconst{type,virtual,durable,allocatedByVat,baseRef}=\\nparseVatSlots.parseVatSlot(vref);\\nif(type==='object'){\\nif(allocatedByVat){\\nif(virtual||durable){\\nincRefCount(baseRef);}else\\n{\\n/* exported non-virtual object: Remotable*/\\nconst remotable=requiredValForSlot(vref);\\nconst oldRefCount=remotableRefCounts.get(remotable)||0;\\nremotableRefCounts.set(remotable,oldRefCount+1);}}else\\n\\n{\\n/* We refcount imports, to preserve their vrefs against*/\\n/* syscall.dropImport when the Presence itself goes away.*/\\nincRefCount(baseRef);}}else\\n\\nif(type==='promise'){\\n/* need to track promises too, maybe in remotableRefCounts*/\\nconst p=requiredValForSlot(vref);\\nconst oldRefCount=remotableRefCounts.get(p)||0;\\nremotableRefCounts.set(p,oldRefCount+1);}}\\n\\n\\n\\nfunction removeReachableVref(vref){\\nlet droppedMemoryReference=false;\\nconst{type,virtual,durable,allocatedByVat,baseRef}=\\nparseVatSlots.parseVatSlot(vref);\\nif(type==='object'){\\nif(allocatedByVat){\\nif(virtual||durable){\\ndecRefCount(baseRef);}else\\n{\\n/* exported non-virtual object: Remotable*/\\nconst remotable=requiredValForSlot(vref);\\nconst oldRefCount=remotableRefCounts.get(remotable)||0;\\noldRefCount>0||assert.Fail`attempt to decref ${vref} below 0`;\\nif(oldRefCount===1){\\nremotableRefCounts.delete(remotable);\\ndroppedMemoryReference=true;}else\\n{\\nremotableRefCounts.set(remotable,oldRefCount-1);}}}else\\n\\n\\n{\\ndecRefCount(baseRef);}}else\\n\\nif(type==='promise'){\\nconst p=requiredValForSlot(vref);\\nconst oldRefCount=remotableRefCounts.get(p)||0;\\noldRefCount>0||assert.Fail`attempt to decref ${vref} below 0`;\\nif(oldRefCount===1){\\nremotableRefCounts.delete(p);\\ndroppedMemoryReference=true;/* true for promises too*/}else\\n{\\nremotableRefCounts.set(p,oldRefCount-1);}}\\n\\n\\nreturn droppedMemoryReference;}\\n\\n\\nfunction getReachablePromiseRefCount(p){\\nreturn remotableRefCounts.get(p)||0;}\\n\\n\\n/* for testing only*/\\nfunction getReachableRefCount(vref){\\nconst{type,virtual,durable,allocatedByVat,baseRef}=\\nparseVatSlots.parseVatSlot(vref);\\nassert.assert(type==='object');\\nif(allocatedByVat){\\nif(virtual||durable){\\nreturn getRefCount(baseRef);}else\\n{\\nconst remotable=requiredValForSlot(baseRef);\\nreturn remotableRefCounts.get(remotable);}}else\\n\\n{\\nreturn getRefCount(baseRef);}}\\n\\n\\n\\nfunction updateReferenceCounts(beforeSlots,afterSlots){\\n/* Note that the slots of a capdata object are not required to be*/\\n/* deduplicated nor are they expected to be presented in any particular*/\\n/* order, so the comparison of which references appear in the before state*/\\n/* to which appear in the after state must look only at the presence or*/\\n/* absence of individual elements from the slots arrays and pay no attention*/\\n/* to the organization of the slots arrays themselves.*/\\nconst vrefStatus=new Map();\\nfor(const vref of beforeSlots){\\nvrefStatus.set(vref,'drop');}\\n\\nfor(const vref of afterSlots){\\nif(vrefStatus.get(vref)==='drop'){\\nvrefStatus.set(vref,'keep');}else\\nif(!vrefStatus.has(vref)){\\nvrefStatus.set(vref,'add');}}\\n\\n\\nconst keys=[...vrefStatus.keys()].sort();\\nfor(const vref of keys){\\nswitch(vrefStatus.get(vref)){\\ncase'add':\\naddReachableVref(vref);\\nbreak;\\ncase'drop':\\nremoveReachableVref(vref);\\nbreak;\\ndefault:\\nbreak;}}}\\n\\n\\n\\n\\n/**\\n * Check if a given vref points to a reachable presence.\\n *\\n * @param {string} vref The vref of the presence being enquired about\\n *\\n * @returns {boolean} true if the indicated presence remains reachable.\\n */\\nfunction isPresenceReachable(vref){\\nreturn!!getRefCount(vref);}\\n\\n\\n/**\\n * A vref is \\\"recognizable\\\" when it is used as the key of a weak Map\\n * or Set: that Map/Set can be used to query whether a future\\n * specimen matches the original or not, without holding onto the\\n * original.\\n *\\n * This 'vrefRecognizers' is a Map from those vrefs to the set of\\n * recognizing weak collections, for virtual keys and non-virtual\\n * collections. Specifically, the vrefs correspond to imported\\n * Presences or virtual-object Representatives (Remotables do not\\n * participate: they are keyed by the actual Remotable object, not\\n * its vref). The collections are either a VirtualObjectAwareWeakMap\\n * or a VirtualObjectAwareWeakSet. We remove the entry when the key\\n * is removed from the collection, and when the entire collection is\\n * deleted.\\n *\\n * It is critical that each collection have exactly one recognizer that is\\n * unique to that collection, because the recognizers themselves will be\\n * tracked by their object identities, but the recognizer cannot be the\\n * collection itself else it would prevent the collection from being garbage\\n * collected.\\n *\\n * TODO: all the \\\"recognizers\\\" in principle could be, and probably should be,\\n * reduced to deleter functions. However, since the VirtualObjectAware\\n * collections are actual JavaScript classes I need to take some care to\\n * ensure that I've got the exactly-one-per-collection invariant handled\\n * correctly.\\n *\\n * TODO: concoct a better type def than Set<any>\\n */\\n/**\\n * @typedef { Map<string, *> | Set<string> } Recognizer\\n */\\n/** @type {Map<string, Set<Recognizer>>} */\\nconst vrefRecognizers=new Map();\\n\\nfunction addRecognizableValue(value,recognizer,recognizerIsVirtual){\\nconst vref=getSlotForVal(value);\\nif(vref){\\nconst{type,allocatedByVat,virtual,durable}=parseVatSlots.parseVatSlot(vref);\\nif(type==='object'&&(!allocatedByVat||virtual||durable)){\\nif(recognizerIsVirtual){\\nsyscall.vatstoreSet(`vom.ir.${vref}|${recognizer}`,'1');}else\\n{\\nlet recognizerSet=vrefRecognizers.get(vref);\\nif(!recognizerSet){\\nrecognizerSet=new Set();\\nvrefRecognizers.set(vref,recognizerSet);}\\n\\nrecognizerSet.add(recognizer);}}}}\\n\\n\\n\\n\\n\\nfunction removeRecognizableVref(vref,recognizer,recognizerIsVirtual){\\nconst{type,allocatedByVat,virtual,durable}=parseVatSlots.parseVatSlot(vref);\\nif(type==='object'&&(!allocatedByVat||virtual||durable)){\\nif(recognizerIsVirtual){\\nsyscall.vatstoreDelete(`vom.ir.${vref}|${recognizer}`);}else\\n{\\nconst recognizerSet=vrefRecognizers.get(vref);\\nassert.assert(recognizerSet&&recognizerSet.has(recognizer));\\nrecognizerSet.delete(recognizer);\\nif(recognizerSet.size===0){\\nvrefRecognizers.delete(vref);\\nif(!allocatedByVat){\\naddToPossiblyRetiredSet(vref);}}}}}\\n\\n\\n\\n\\n\\n\\nfunction removeRecognizableValue(value,recognizer,recognizerIsVirtual){\\nconst vref=getSlotForVal(value);\\nif(vref){\\nremoveRecognizableVref(vref,recognizer,recognizerIsVirtual);}}\\n\\n\\n\\nlet deleteCollectionEntry;\\nfunction setDeleteCollectionEntry(fn){\\ndeleteCollectionEntry=fn;}\\n\\n\\n/**\\n * Remove a given vref from all weak collections in which it was used as a\\n * key.\\n *\\n * @param {string} vref The vref that shall henceforth no longer be recognized\\n *\\n * @returns {boolean} true if this possibly creates a GC opportunity\\n */\\nfunction ceaseRecognition(vref){\\nlet doMoreGC=false;\\nconst p=parseVatSlots.parseVatSlot(vref);\\nif(p.allocatedByVat&&(p.virtual||p.durable)&&p.facet===undefined){\\n/* If `vref` identifies a multi-faceted object that should no longer be*/\\n/* \\\"recognized\\\", what that really means that all references to its*/\\n/* individual facets should no longer be recognized -- nobody actually*/\\n/* references the object itself except internal data structures. So in*/\\n/* this case we need individually to stop recognizing the facets*/\\n/* themselves.*/\\nconst kindInfo=kindInfoTable.get(`${p.id}`);\\n/* This function can be called either from `dispatch.retireImports` or*/\\n/* from `deleteVirtualObject`. In the latter case the vref is*/\\n/* actually a baseRef and so needs to be expanded to cease recognition of*/\\n/* all the facets.*/\\nif(kindInfo){\\nconst{facetNames}=kindInfo;\\nif(facetNames){\\nfor(let i=0;i<facetNames.length;i+=1){\\ndoMoreGC=ceaseRecognition(`${vref}:${i}`)||doMoreGC;}\\n\\nreturn doMoreGC;}}}\\n\\n\\n\\n\\n/* remove from all voAwareWeakMap/Sets that knew about it*/\\nconst recognizerSet=vrefRecognizers.get(vref);\\nif(recognizerSet){\\nvrefRecognizers.delete(vref);\\nfor(const recognizer of recognizerSet){\\nif(recognizer instanceof Map){\\nrecognizer.delete(vref);\\ndoMoreGC=true;}else\\nif(recognizer instanceof Set){\\nrecognizer.delete(vref);}else\\n{\\nassert.Fail`unknown recognizer type ${typeof recognizer}`;}}}\\n\\n\\n\\n\\n/* and from (weak) virtual collections that knew about it*/\\nconst prefix=`vom.ir.${vref}|`;\\nfor(const key of vatstoreIterators.enumerateKeysWithPrefix(syscall,prefix)){\\nsyscall.vatstoreDelete(key);\\nconst parts=key.split('|');\\ndoMoreGC=deleteCollectionEntry(parts[1],vref)||doMoreGC;}\\n\\nreturn doMoreGC;}\\n\\n\\nfunction isVrefRecognizable(vref){\\nif(vrefRecognizers.has(vref)){\\nreturn true;}else\\n{\\nreturn vatstoreIterators.prefixedKeysExist(syscall,`vom.ir.${vref}|`);}}\\n\\n\\n\\nfunction finalizeDroppedCollection({descriptor}){\\n/* the 'wr' WeakRef will be dropped about now*/\\n/**/\\n/* note: technically, the engine is allowed to inspect this*/\\n/* callback, observe that 'wr' is not extracted, and then not*/\\n/* retain it in the first place (back in*/\\n/* registerDroppedCollection), but no engine goes that far*/\\ndescriptor.collectionDeleter(descriptor);}\\n\\n\\nfunction vrefKey(value){\\nconst vobjID=getSlotForVal(value);\\nif(vobjID){\\nconst{type,virtual,durable,allocatedByVat}=parseVatSlots.parseVatSlot(vobjID);\\nif(type==='object'&&(virtual||durable||!allocatedByVat)){\\nreturn vobjID;}}\\n\\n\\nreturn undefined;}\\n\\n\\nfunction countCollectionsForWeakKey(vref){\\nconst recognizerSet=vrefRecognizers.get(vref);\\nlet size=recognizerSet?recognizerSet.size:0;\\nconst prefix=`vom.ir.${vref}|`;\\n/* eslint-disable-next-line no-underscore-dangle*/\\nfor(const _key of vatstoreIterators.enumerateKeysWithPrefix(syscall,prefix)){\\nsize+=1;}\\n\\nreturn size;}\\n\\n\\n/**\\n * Counters to track the next number for various categories of allocation.\\n * `exportID` starts at 1 because 'o+0' is always automatically\\n * pre-assigned to the root object.\\n * `promiseID` starts at 5 as a very minor aid to debugging: when puzzling\\n * over trace logs and the like, it helps for the numbers in various species\\n * of IDs that are jumbled together to be a little out of sync and thus a\\n * little less similar to each other.\\n */\\nconst initialIDCounters={exportID:1,collectionID:1,promiseID:5};\\n/** @type {Record<string, number>} */\\nlet idCounters;\\nlet idCountersAreDirty=false;\\n\\nfunction initializeIDCounters(){\\nif(!idCounters){\\n/* the saved value might be missing, or from an older liveslots*/\\n/* (with fewer counters), so merge it with our initial values*/\\nconst saved=JSON.parse(syscall.vatstoreGet('idCounters')||'{}');\\nidCounters={...initialIDCounters,...saved};\\nidCountersAreDirty=true;}}\\n\\n\\n\\nfunction allocateNextID(name){\\nif(!idCounters){\\n/* Normally `initializeIDCounters` would be called from startVat, but some*/\\n/* tests bypass that so this is a backstop. Note that the invocation from*/\\n/* startVat is there to make vatStore access patterns a bit more*/\\n/* consistent from one vat to another, principally as a confusion*/\\n/* reduction measure in service of debugging; it is not a correctness*/\\n/* issue.*/\\ninitializeIDCounters();}\\n\\nconst result=idCounters[name];\\nresult!==undefined||assert.Fail`unknown idCounters[${name}]`;\\nidCounters[name]+=1;\\nidCountersAreDirty=true;\\nreturn result;}\\n\\n\\nfunction flushIDCounters(){\\nif(idCountersAreDirty){\\nsyscall.vatstoreSet('idCounters',JSON.stringify(idCounters));\\nidCountersAreDirty=false;}}\\n\\n\\n\\nconst testHooks={\\ngetReachableRefCount,\\ncountCollectionsForWeakKey,\\n\\n/* don't harden() the mock FR, that will break it*/\\ngetDroppedCollectionRegistry:()=>droppedCollectionRegistry,\\nremotableRefCounts,\\nvrefRecognizers,\\nkindInfoTable};\\n\\n\\nfunction getRetentionStats(){\\nreturn{\\nremotableRefCounts:remotableRefCounts.size,\\nvrefRecognizers:vrefRecognizers.size,\\nkindInfoTable:kindInfoTable.size};}\\n\\n\\n\\nreturn harden({\\nregisterDroppedCollection,\\nisDurable,\\nisDurableKind,\\nregisterKind,\\nrememberFacetNames,\\ngetFacet,\\ngetFacetNames,\\nreanimate,\\naddReachableVref,\\nremoveReachableVref,\\nupdateReferenceCounts,\\ngetReachablePromiseRefCount,\\naddRecognizableValue,\\nremoveRecognizableVref,\\nremoveRecognizableValue,\\nvrefKey,\\nisPresenceReachable,\\nisVrefRecognizable,\\nsetExportStatus,\\nisVirtualObjectReachable,\\ndeleteVirtualObject,\\nceaseRecognition,\\nsetDeleteCollectionEntry,\\ngetRetentionStats,\\ninitializeIDCounters,\\nallocateNextID,\\nflushIDCounters,\\ntestHooks});}\\n\\n\\n/** @typedef {ReturnType<typeof makeVirtualReferenceManager>} VirtualReferenceManager */exports.makeVirtualReferenceManager=makeVirtualReferenceManager;\",\n \"packages/swingset-liveslots/src/watchedPromises.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var index=require('../../../node_modules/@endo/errors/index.js');var noShim=require('../../../node_modules/@endo/eventual-send/src/no-shim.js');var assert=require('../../assert/src/assert.js');require('../../store/src/index.js');var parseVatSlots=require('./parseVatSlots.js');var patternMatchers=require('../../../node_modules/@endo/patterns/src/patterns/patternMatchers.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nexoMakers=require('../../../node_modules/@endo/exo/src/exo-makers.js');/* @ts-check*/ /**\\n * @template V\\n * @template {any[]} [A=unknown[]]\\n * @typedef {[watcher: IMPORT('./types.js').PromiseWatcher<V, A>, ...args: A]} PromiseWatcherTuple\\n */ /**\\n * @param {object} options\\n * @param {*} options.syscall\\n * @param {IMPORT('./virtualReferences.js').VirtualReferenceManager} options.vrm\\n * @param {IMPORT('./virtualObjectManager.js').VirtualObjectManager} options.vom\\n * @param {*} options.collectionManager\\n * @param {IMPORT('@endo/marshal').ConvertValToSlot<any>} options.convertValToSlot\\n * @param {IMPORT('@endo/marshal').ConvertSlotToVal<any>} options.convertSlotToVal\\n * @param {(vref: any) => boolean} options.maybeExportPromise\\n */function makeWatchedPromiseManager({syscall,vrm,vom,\\ncollectionManager,\\nconvertValToSlot,\\nconvertSlotToVal,\\nmaybeExportPromise})\\n{\\nconst{makeScalarBigMapStore}=collectionManager;\\nconst{defineDurableKind}=vom;\\n\\n/**\\n * virtual Store (not durable) mapping vpid to Promise objects, to\\n * maintain the slotToVal registration until resolution. Without\\n * this, slotToVal would forget local Promises that aren't exported.\\n *\\n * @type {MapStore<string, Promise<unknown>>}\\n */\\nlet promiseRegistrations;\\n\\n/**\\n * watched promises by vpid: each entry is an array of watches on the\\n * corresponding vpid; each of these is in turn an array of a watcher object\\n * and the arguments associated with it by `watchPromise`.\\n * @type {MapStore<string, PromiseWatcherTuple<unknown>[]>}\\n */\\nlet watchedPromiseTable;\\n\\n/**\\n * defined promise watcher objects indexed by kindHandle\\n *\\n * @type {MapStore<IMPORT('./vatDataTypes.js').DurableKindHandle, IMPORT('./types.js').PromiseWatcher<unknown>>}\\n */\\nlet promiseWatcherByKindTable;\\n\\nfunction preparePromiseWatcherTables(){\\npromiseRegistrations=makeScalarBigMapStore('promiseRegistrations');\\nlet watcherTableID=syscall.vatstoreGet('watcherTableID');\\nif(watcherTableID){\\npromiseWatcherByKindTable=convertSlotToVal(watcherTableID);}else\\n{\\npromiseWatcherByKindTable=makeScalarBigMapStore(\\n'promiseWatcherByKind',\\n{durable:true});\\n\\nwatcherTableID=convertValToSlot(promiseWatcherByKindTable);\\nsyscall.vatstoreSet('watcherTableID',watcherTableID);\\n/* artificially increment the table's refcount so it never gets GC'd*/\\nvrm.addReachableVref(watcherTableID);}\\n\\n\\nlet watchedPromiseTableID=syscall.vatstoreGet('watchedPromiseTableID');\\nif(watchedPromiseTableID){\\nwatchedPromiseTable=convertSlotToVal(watchedPromiseTableID);}else\\n{\\nwatchedPromiseTable=makeScalarBigMapStore('watchedPromises',{\\nkeyShape:patternMatchers.M.string(),/* key is always a vpid*/\\ndurable:true});\\n\\nwatchedPromiseTableID=convertValToSlot(watchedPromiseTable);\\nsyscall.vatstoreSet('watchedPromiseTableID',watchedPromiseTableID);\\n/* artificially increment the table's refcount so it never gets GC'd*/\\nvrm.addReachableVref(watchedPromiseTableID);}}\\n\\n\\n\\n/**\\n * @template T\\n * @param {Promise<T>} p\\n * @param {string} vpid\\n * @returns {void}\\n */\\nfunction pseudoThen(p,vpid){\\n/**\\n *\\n * @param {T} value\\n * @param {boolean} wasFulfilled\\n */\\nfunction settle(value,wasFulfilled){\\nconst watches=watchedPromiseTable.get(vpid);\\nwatchedPromiseTable.delete(vpid);\\npromiseRegistrations.delete(vpid);\\nfor(const watch of watches){\\nconst[watcher,...args]=watch;\\nvoid Promise.resolve().then(()=>{\\nif(wasFulfilled){\\nif(watcher.onFulfilled){\\nwatcher.onFulfilled(value,...args);}}else\\n\\n{\\nif(watcher.onRejected){\\nwatcher.onRejected(value,...args);}else\\n{\\nthrow value;/* for host's unhandled rejection handler to catch*/}}});}}\\n\\n\\n\\n\\n\\n\\nvoid noShim.E.when(\\np,\\n(res)=>settle(res,true),\\n(rej)=>settle(rej,false));}\\n\\n\\n\\n/**\\n * Revives watched promises.\\n *\\n * @param {(vref: any) => Promise<any>} revivePromise\\n * @returns {void}\\n */\\nfunction loadWatchedPromiseTable(revivePromise){\\nfor(const vpid of watchedPromiseTable.keys()){\\nconst p=revivePromise(vpid);\\npromiseRegistrations.init(vpid,p);\\npseudoThen(p,vpid);}}\\n\\n\\n\\n/**\\n * @template V\\n * @template {any[]} A]\\n * @param {IMPORT('./vatDataTypes.js').DurableKindHandle} kindHandle\\n * @param {(value: V, ...args: A) => void} fulfillHandler\\n * @param {(reason: any, ...args: A) => void} rejectHandler\\n * @returns {IMPORT('./types.js').PromiseWatcher<V, A>}\\n */\\nfunction providePromiseWatcher(\\nkindHandle,\\n/* @ts-expect-error xxx rest params in typedef*/\\nfulfillHandler=(_value)=>{\\n/* It's fine to not pass the value through since promise watchers are not chainable*/},\\n\\n/* @ts-expect-error xxx rest params in typedef*/\\nrejectHandler=(reason)=>{\\n/* Replicate the unhandled rejection that would have happened if the*/\\n/* watcher had not implemented an `onRejected` method. See `settle` above*/\\nthrow reason;})\\n\\n{\\nassert.assert.typeof(fulfillHandler,'function');\\nassert.assert.typeof(rejectHandler,'function');\\n\\nconst makeWatcher=defineDurableKind(kindHandle,exoMakers.initEmpty,{\\n/** @type {(context: unknown, res: V, ...args: A) => void} */\\nonFulfilled:(_context,res,...args)=>fulfillHandler(res,...args),\\n/** @type {(context: unknown, rej: unknown, ...args: A) => void} */\\nonRejected:(_context,rej,...args)=>rejectHandler(rej,...args)});\\n\\n\\nif(promiseWatcherByKindTable.has(kindHandle)){\\nreturn promiseWatcherByKindTable.get(kindHandle);}else\\n{\\nconst watcher=makeWatcher();\\npromiseWatcherByKindTable.init(kindHandle,watcher);\\nreturn watcher;}}\\n\\n\\n\\n/**\\n * @type {<P extends Promise<any>, A extends any[]>(p: P, watcher: IMPORT('./types.js').PromiseWatcher<Awaited<P>, A>, ...args: A) => void}\\n */\\nfunction watchPromise(p,watcher,...args){\\n/* The following wrapping defers setting up the promise watcher itself to a*/\\n/* later turn so that if the promise to be watched was the return value from*/\\n/* a preceding eventual message send, then the assignment of a vpid to that*/\\n/* promise, which happens in a turn after the initiation of the send, will*/\\n/* have happened by the time the code below executes, and thus when we call*/\\n/* `convertValToSlot` on the promise here we'll get back the vpid that was*/\\n/* assigned rather than generating a new one that nobody knows about.*/\\n\\n/* TODO: add vpid->p virtual table mapping, to keep registration alive*/\\n/* TODO: remove mapping upon resolution*/\\n/* maybe check importedVPIDs here and add to table if !has*/\\nvoid Promise.resolve().then(()=>{\\nconst watcherVref=convertValToSlot(watcher);\\nassert.assert(watcherVref,'invalid watcher');\\nconst{virtual,durable}=parseVatSlots.parseVatSlot(watcherVref);\\nvirtual||\\ndurable||\\n/* separate line so easy to breakpoint on*/\\nindex.throwRedacted`promise watcher must be a virtual object`;\\nif(watcher.onFulfilled){\\nassert.assert.typeof(watcher.onFulfilled,'function');}\\n\\nif(watcher.onRejected){\\nassert.assert.typeof(watcher.onRejected,'function');}\\n\\nassert.assert(\\nwatcher.onFulfilled||watcher.onRejected,\\n'promise watcher must implement at least one handler method');\\n\\n\\nconst vpid=convertValToSlot(p);\\nassert.assert(vpid,'invalid promise');\\nconst{type}=parseVatSlots.parseVatSlot(vpid);\\nassert.assert(type==='promise','watchPromise only watches promises');\\nif(watchedPromiseTable.has(vpid)){\\nconst watches=watchedPromiseTable.get(vpid);\\nwatchedPromiseTable.set(vpid,harden([...watches,[watcher,...args]]));}else\\n{\\nwatchedPromiseTable.init(vpid,harden([[watcher,...args]]));\\n\\n/* Ensure that this vat's promises are rejected at termination.*/\\nif(maybeExportPromise(vpid)){\\nsyscall.subscribe(vpid);}\\n\\n\\npromiseRegistrations.init(vpid,p);\\npseudoThen(p,vpid);}});}\\n\\n\\n\\n\\nreturn harden({\\npreparePromiseWatcherTables,\\nloadWatchedPromiseTable,\\nprovidePromiseWatcher,\\nwatchPromise});}exports.makeWatchedPromiseManager=makeWatchedPromiseManager;\",\n \"packages/swingset-xsnap-supervisor/lib/entry.js\": \"'use strict';require('./supervisor-subprocess-xsnap.js');\",\n \"packages/swingset-xsnap-supervisor/lib/gc-and-finalize.js\": \"'use strict';\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nObject.defineProperty(exports,'__esModule',{value:true});/* global setImmediate */ /* A note on our GC terminology:\\n *\\n * We define four states for any JS object to be in:\\n *\\n * REACHABLE: There exists a path from some root (live export or top-level\\n * global) to this object, making it ineligible for collection. Userspace vat\\n * code has a strong reference to it (and userspace is not given access to\\n * WeakRef, so it has no weak reference that might be used to get access).\\n *\\n * UNREACHABLE: There is no strong reference from a root to the object.\\n * Userspace vat code has no means to access the object, although liveslots\\n * might (via a WeakRef). The object is eligible for collection, but that\\n * collection has not yet happened. The liveslots WeakRef is still alive: if\\n * it were to call `.deref()`, it would get the object.\\n *\\n * COLLECTED: The JS engine has performed enough GC to notice the\\n * unreachability of the object, and has collected it. The liveslots WeakRef\\n * is dead: `wr.deref() === undefined`. Neither liveslots nor userspace has\\n * any way to reach the object, and never will again. A finalizer callback\\n * has been queued, but not yet executed.\\n *\\n * FINALIZED: The JS engine has run the finalizer callback. Once the\\n * callback completes, the object is thoroughly dead and unremembered,\\n * and no longer exists in one of these four states.\\n *\\n * The transition from REACHABLE to UNREACHABLE always happens as a result of\\n * a message delivery or resolution notification (e.g when userspace\\n * overwrites a variable, deletes a Map entry, or a callback on the promise\\n * queue which closed over some objects is retired and deleted).\\n *\\n * The transition from UNREACHABLE to COLLECTED can happen spontaneously, as\\n * the JS engine decides it wants to perform GC. It will also happen\\n * deliberately if we provoke a GC call with a magic function like `gc()`\\n * (when Node.js imports `engine-gc`, which is morally-equivalent to\\n * running with `--expose-gc`, or when XS is configured to provide it as a\\n * C-level callback). We can force GC, but we cannot prevent it from happening\\n * at other times.\\n *\\n * FinalizationRegistry callbacks are defined to run on their own turn, so\\n * the transition from COLLECTED to FINALIZED occurs at a turn boundary.\\n * Node.js appears to schedule these finalizers on the timer/IO queue, not\\n * the promise/microtask queue. So under Node.js, you need a `setImmediate()`\\n * or two to ensure that finalizers have had a chance to run. XS is different\\n * but responds well to similar techniques.\\n */ /* * `gcAndFinalize` must be defined in the start compartment. It uses\\n * platform-specific features to provide a function which provokes a full GC\\n * operation: all \\\"UNREACHABLE\\\" objects should transition to \\\"COLLECTED\\\"\\n * before it returns. In addition, `gcAndFinalize()` returns a Promise. This\\n * Promise will resolve (with `undefined`) after all FinalizationRegistry\\n * callbacks have executed, causing all COLLECTED objects to transition to\\n * FINALIZED. If the caller can manage call gcAndFinalize with an empty\\n * promise queue, then their .then callback will also start with an empty\\n * promise queue, and there will be minimal uncollected unreachable objects\\n * in the heap when it begins.\\n *\\n * `gcAndFinalize` depends upon platform-specific tools to provoke a GC sweep\\n * and wait for finalizers to run: a `gc()` function, and `setImmediate`. If\\n * these tools do not exist, this function will do nothing, and return a\\n * dummy pre-resolved Promise.\\n */function makeGcAndFinalize(gcPower){if(typeof gcPower!=='function'){if(gcPower!==false){/* We weren't explicitly disabled, so warn.*/console.warn(Error(`no gcPower() function; skipping finalizer provocation`));}}return async function gcAndFinalize(){if(typeof gcPower!=='function'){return;}/* on Node.js, GC seems to work better if the promise queue is empty first*/await new Promise(setImmediate);/* on xsnap, we must do it twice for some reason*/await new Promise(setImmediate);gcPower();/* this gives finalizers a chance to run*/await new Promise(setImmediate);/* Node.js seems to need another for promises to get cleared out*/await new Promise(setImmediate);};}exports.makeGcAndFinalize=makeGcAndFinalize;\",\n \"packages/swingset-xsnap-supervisor/lib/supervisor-helper.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../swingset-liveslots/src/index.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nmessage=require('../../swingset-liveslots/src/message.js');/**\\n * @import {VatDeliveryObject} from '@agoric/swingset-liveslots'\\n * @import {VatDeliveryResult} from '@agoric/swingset-liveslots'\\n * @import {VatSyscallObject} from '@agoric/swingset-liveslots'\\n * @import {VatSyscallHandler} from '@agoric/swingset-liveslots'\\n * @typedef {IMPORT('@endo/marshal').CapData<string>} SwingSetCapData\\n * @typedef { (delivery: VatDeliveryObject) => (VatDeliveryResult | Promise<VatDeliveryResult>) } VatDispatcherSyncAsync\\n * @typedef { (delivery: VatDeliveryObject) => Promise<VatDeliveryResult> } VatDispatcher\\n */ /**\\n * Given the liveslots 'dispatch' function, return a version that never\\n * rejects. It will always return a VatDeliveryResult, even if liveslots\\n * throws or rejects. All supervisors should wrap the liveslots `dispatch`\\n * function with this one, and call it in response to messages from the\\n * manager process.\\n *\\n * @param {VatDispatcherSyncAsync} dispatch\\n * @returns {VatDispatcher}\\n */function makeSupervisorDispatch(dispatch){/**\\n * @param {VatDeliveryObject} delivery\\n * @returns {Promise<VatDeliveryResult>}\\n */async function dispatchToVat(delivery){/* the (low-level) vat is responsible for giving up agency, but we still*/ /* protect against exceptions*/return Promise.resolve(delivery).then(dispatch).then(\\n(res)=>harden(['ok',res,null]),\\n(err)=>{\\n/* TODO react more thoughtfully, maybe terminate the vat*/\\nconsole.warn(`error during vat dispatch() of ${delivery}`,err);\\nreturn harden(['error',`${err}`,null]);});}\\n\\n\\n\\n\\nreturn harden(dispatchToVat);}\\n\\nharden(makeSupervisorDispatch);\\n\\n\\n/**\\n * This returns a function that is provided to liveslots as the 'syscall'\\n * argument: an object with one method per syscall type. These methods return\\n * data, or nothing. If the kernel experiences a problem executing the syscall,\\n * the method will throw, or the kernel will kill the vat, or both.\\n *\\n * I should be given a `syscallToManager` function that accepts a\\n * VatSyscallObject and (synchronously) returns a VatSyscallResult.\\n *\\n * @param {VatSyscallHandler} syscallToManager\\n * @typedef { unknown } TheSyscallObjectWithMethodsThatLiveslotsWants\\n * @returns {TheSyscallObjectWithMethodsThatLiveslotsWants}\\n */\\nfunction makeSupervisorSyscall(syscallToManager){\\nfunction doSyscall(fields){\\nmessage.insistVatSyscallObject(fields);\\n/** @type { VatSyscallObject } */\\nconst vso=harden(fields);\\nlet r;\\ntry{\\nr=syscallToManager(vso);}\\ncatch(err){\\nconsole.warn(`worker got error during syscall:`,err);\\nthrow err;}\\n\\nconst vsr=r;\\nmessage.insistVatSyscallResult(vsr);\\nconst[type,...rest]=vsr;\\nswitch(type){\\ncase'ok':{\\nconst[data]=rest;\\nreturn data;}\\n\\ncase'error':{\\nconst[err]=rest;\\nthrow Error(`syscall.${fields[0]} failed: ${err}`);}\\n\\ndefault:\\nthrow Error(`unknown result type ${type}`);}}\\n\\n\\n\\n/* this will be given to liveslots, it should have distinct methods that*/\\n/* return immediate results or throw errors*/\\nconst syscallForVat={\\n/** @type {(target: string, method: string, args: SwingSetCapData, result?: string) => unknown } */\\nsend:(target,methargs,result)=>\\ndoSyscall(['send',target,{methargs,result}]),\\nsubscribe:(vpid)=>doSyscall(['subscribe',vpid]),\\nresolve:(resolutions)=>doSyscall(['resolve',resolutions]),\\nexit:(isFailure,data)=>doSyscall(['exit',isFailure,data]),\\ndropImports:(vrefs)=>doSyscall(['dropImports',vrefs]),\\nretireImports:(vrefs)=>doSyscall(['retireImports',vrefs]),\\nretireExports:(vrefs)=>doSyscall(['retireExports',vrefs]),\\nabandonExports:(vrefs)=>doSyscall(['abandonExports',vrefs]),\\n\\n/* These syscalls should be omitted if the worker cannot get a*/\\n/* synchronous return value back from the kernel, such as when the worker*/\\n/* is in a child process or thread, and cannot be blocked until the*/\\n/* result gets back. vatstoreSet and vatstoreDelete are included because*/\\n/* vatstoreSet requires a result, and we offer them as a group.*/\\ncallNow:(target,method,args)=>\\ndoSyscall(['callNow',target,method,args]),\\nvatstoreGet:(key)=>{\\nconst result=doSyscall(['vatstoreGet',key]);\\nreturn result===null?undefined:result;},\\n\\nvatstoreGetNextKey:(priorKey)=>doSyscall(['vatstoreGetNextKey',priorKey]),\\nvatstoreSet:(key,value)=>doSyscall(['vatstoreSet',key,value]),\\nvatstoreDelete:(key)=>doSyscall(['vatstoreDelete',key])};\\n\\n\\nreturn harden(syscallForVat);}\\n\\n\\nharden(makeSupervisorSyscall);\\n\\n\\n/**\\n * Create a vat console from a log stream maker.\\n *\\n * TODO: consider other methods per SES VirtualConsole.\\n * See https://github.com/Agoric/agoric-sdk/issues/2146\\n *\\n * @param {(level: string) => (...args: any[]) => void} makeLog\\n */\\nfunction makeVatConsole(makeLog){\\nreturn harden({\\ndebug:makeLog('debug'),\\nlog:makeLog('log'),\\ninfo:makeLog('info'),\\nwarn:makeLog('warn'),\\nerror:makeLog('error')});}\\n\\n\\n\\nharden(makeVatConsole);exports.makeSupervisorDispatch=makeSupervisorDispatch;exports.makeSupervisorSyscall=makeSupervisorSyscall;exports.makeVatConsole=makeVatConsole;\",\n \"packages/swingset-xsnap-supervisor/lib/supervisor-subprocess-xsnap.js\": \"'use strict';var assert=require('../../assert/src/assert.js');var index=require('../../../node_modules/@endo/import-bundle/src/index.js');require('../../swingset-liveslots/src/index.js');var waitUntilQuiescent=require('./waitUntilQuiescent.js');var gcAndFinalize=require('./gc-and-finalize.js');var supervisorHelper=require('./supervisor-helper.js');var message=require('../../swingset-liveslots/src/message.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nliveslots=require('../../swingset-liveslots/src/liveslots.js');/* global globalThis WeakRef FinalizationRegistry */ /**\\n * @import {VatDeliveryObject} from '@agoric/swingset-liveslots'\\n * @import {VatDeliveryResult} from '@agoric/swingset-liveslots'\\n * @import {VatSyscallObject} from '@agoric/swingset-liveslots'\\n * @import {VatSyscallResult} from '@agoric/swingset-liveslots'\\n * @import {VatSyscallHandler} from '@agoric/swingset-liveslots'\\n * @import {LiveSlotsOptions} from '@agoric/swingset-liveslots'\\n * @import {MeterControl} from '@agoric/swingset-liveslots'\\n */\\n\\nconst encoder=new TextEncoder();\\nconst decoder=new TextDecoder();\\n\\n/* eslint-disable-next-line no-unused-vars*/\\nfunction workerLog(first,...args){\\n/* console.log(`---worker: ${first}`, ...args);*/}\\n\\n\\nworkerLog(`supervisor started`);\\n\\nfunction makeMeterControl(){\\nlet meteringDisabled=0;\\n\\nfunction isMeteringDisabled(){\\nreturn!!meteringDisabled;}\\n\\n\\nfunction assertIsMetered(msg){\\nassert.assert(!meteringDisabled,msg);}\\n\\nfunction assertNotMetered(msg){\\nassert.assert(!!meteringDisabled,msg);}\\n\\n\\nfunction runWithoutMetering(thunk){\\nconst limit=globalThis.currentMeterLimit();\\nconst before=globalThis.resetMeter(0,0);\\nmeteringDisabled+=1;\\ntry{\\nreturn thunk();}finally\\n{\\nglobalThis.resetMeter(limit,before);\\nmeteringDisabled-=1;}}\\n\\n\\n\\nasync function runWithoutMeteringAsync(thunk){\\nconst limit=globalThis.currentMeterLimit();\\nconst before=globalThis.resetMeter(0,0);\\nmeteringDisabled+=1;\\nreturn Promise.resolve().\\nthen(()=>thunk()).\\nfinally(()=>{\\nglobalThis.resetMeter(limit,before);\\nmeteringDisabled-=1;});}\\n\\n\\n\\n/* return a version of f that runs outside metering*/\\nfunction unmetered(f){\\nfunction wrapped(...args){\\nreturn runWithoutMetering(()=>f(...args));}\\n\\nreturn harden(wrapped);}\\n\\n\\n/** @type { MeterControl } */\\nconst meterControl={\\nisMeteringDisabled,\\nassertIsMetered,\\nassertNotMetered,\\nrunWithoutMetering,\\nrunWithoutMeteringAsync,\\nunmetered};\\n\\nreturn harden(meterControl);}\\n\\n\\nconst meterControl=makeMeterControl();\\n\\n/**\\n * Wrap byte-level protocols with tagged array codec.\\n *\\n * @param {(cmd: ArrayBuffer) => ArrayBuffer} issueCommand as from xsnap\\n * @typedef { [unknown, ...unknown[]] } Tagged tagged array\\n */\\nfunction managerPort(issueCommand){\\n/** @type { (item: Tagged) => ArrayBuffer } */\\nconst encode=(item)=>{\\nlet txt;\\ntry{\\ntxt=JSON.stringify(item);}\\ncatch(nope){\\nworkerLog(nope.message,item);\\nthrow nope;}\\n\\nreturn encoder.encode(txt).buffer;};\\n\\n\\n/** @type { (msg: ArrayBuffer) => any } */\\nconst decodeData=(msg)=>JSON.parse(decoder.decode(msg)||'null');\\n\\n/** @type { (msg: ArrayBuffer) => Tagged } */\\nfunction decode(msg){\\n/** @type { Tagged } */\\nconst item=decodeData(msg);\\nArray.isArray(item)||assert.Fail`expected array`;\\nitem.length>0||assert.Fail`empty array lacks tag`;\\nreturn item;}\\n\\n\\nreturn harden({\\n/** @type { (item: Tagged) => void } */\\nsend:(item)=>{\\nissueCommand(encode(item));},\\n\\n/** @type { (item: Tagged) => unknown } */\\ncall:(item)=>decodeData(issueCommand(encode(item))),\\n\\n/**\\n * Wrap an async Tagged handler in the xsnap async reporting idiom.\\n *\\n * @param {(item: Tagged) => Promise<Tagged>} f async Tagged handler\\n * @returns {(msg: ArrayBuffer) => Report<ArrayBuffer>} xsnap style handleCommand\\n *\\n * @typedef { { result?: T } } Report<T> report T when idle\\n * @template T\\n */\\nhandlerFrom(f){\\nconst lastResort=encoder.encode(`exception from ${f.name}`).buffer;\\nreturn(msg)=>{\\nconst report={};\\nf(decode(msg)).\\nthen((item)=>{\\nworkerLog('result',item);\\nreport.result=encode(item);}).\\n\\ncatch((err)=>{\\nreport.result=encode(['err',err.name,err.message]);}).\\n\\ncatch((_err)=>{\\nreport.result=lastResort;});\\n\\nreturn report;};}});}\\n\\n\\n\\n\\n\\n/* please excuse copy-and-paste from kernel.js*/\\nfunction abbreviateReplacer(_,arg){\\nif(typeof arg==='bigint'){\\n/* since testLog is only for testing, 2^53 is enough.*/\\n/* precedent: 32a1dd3*/\\nreturn Number(arg);}\\n\\nif(typeof arg==='string'&&arg.length>=40){\\n/* truncate long strings*/\\nreturn`${arg.slice(0,15)}...${arg.slice(arg.length-15)}`;}\\n\\nreturn arg;}\\n\\n\\n/**\\n * @param {ReturnType<typeof managerPort>} port\\n */\\nfunction makeWorker(port){\\n/** @type { ((delivery: VatDeliveryObject) => Promise<VatDeliveryResult>) | null } */\\nlet dispatch=null;\\n\\n/**\\n * @param {unknown} vatID\\n * @param {unknown} bundle\\n * @param {LiveSlotsOptions} liveSlotsOptions\\n * @returns {Promise<Tagged>}\\n */\\nasync function setBundle(vatID,bundle,liveSlotsOptions){\\n/** @type { VatSyscallHandler } */\\nfunction syscallToManager(vatSyscallObject){\\nworkerLog('doSyscall',vatSyscallObject);\\nconst result=port.call(['syscall',vatSyscallObject]);\\nworkerLog(' ... syscall result:',result);\\nmessage.insistVatSyscallResult(result);\\nreturn result;}\\n\\n\\nconst syscall=supervisorHelper.makeSupervisorSyscall(syscallToManager);\\n\\nconst vatPowers={\\ntestLog:(...args)=>\\nport.send([\\n'testLog',\\n...args.map((arg)=>\\ntypeof arg==='string'?\\narg:\\nJSON.stringify(arg,abbreviateReplacer))])};\\n\\n\\n\\n\\nconst gcTools=harden({\\nWeakRef,\\nFinalizationRegistry,\\nwaitUntilQuiescent:waitUntilQuiescent.waitUntilQuiescent,\\ngcAndFinalize:gcAndFinalize.makeGcAndFinalize(globalThis.gc),\\nmeterControl});\\n\\n\\n/** @param {string} source */\\nconst makeLogMaker=(source)=>{\\n/** @param {string} level */\\nconst makeLog=(level)=>{\\n/* Capture the `console.log`, etc.'s `printAll` function.*/\\nconst printAll=console[level];\\nassert.assert.typeof(printAll,'function');\\nconst portSendingPrinter=(...args)=>{\\nport.send(['sourcedConsole',source,level,...args]);};\\n\\nreturn(...args)=>{\\n/* Use the causal console, but output to the port.*/\\n/**/\\n/* FIXME: This is a hack until the start compartment can create*/\\n/* Console objects that log to a different destination than*/\\n/* `globalThis.console`.*/\\nconst{print:savePrinter}=globalThis;\\ntry{\\nglobalThis.print=portSendingPrinter;\\nprintAll(...args);}finally\\n{\\nglobalThis.print=savePrinter;}};};\\n\\n\\n\\nreturn makeLog;};\\n\\n\\nconst workerEndowments={\\nconsole:supervisorHelper.makeVatConsole(makeLogMaker('vat')),\\n/* See https://github.com/Agoric/agoric-sdk/issues/9515*/\\nassert:globalThis.assert,\\n/* bootstrap provides HandledPromise*/\\nHandledPromise:globalThis.HandledPromise,\\nTextEncoder,\\nTextDecoder,\\nBase64:globalThis.Base64/* Present only in XSnap*/};\\n\\n\\nasync function buildVatNamespace(\\nlsEndowments,\\ninescapableGlobalProperties)\\n{\\nassert.assert(bundle,'bundle undefined (duplicate buildVatNamespace call?)');\\nconst vatNS=await index.importBundle(bundle,{\\nendowments:{...workerEndowments,...lsEndowments},\\ninescapableGlobalProperties});\\n\\nbundle=undefined;/* overwrite to allow GC to discard big string*/\\nworkerLog(`got vatNS:`,Object.keys(vatNS).join(','));\\nreturn vatNS;}\\n\\n\\nconst ls=liveslots.makeLiveSlots(\\nsyscall,\\nvatID,\\nvatPowers,\\nliveSlotsOptions,\\ngcTools,\\nsupervisorHelper.makeVatConsole(makeLogMaker('ls')),\\nbuildVatNamespace);\\n\\n\\nassert.assert(ls.dispatch);\\ndispatch=supervisorHelper.makeSupervisorDispatch(ls.dispatch);\\nworkerLog(`got dispatch`);\\nreturn['dispatchReady'];}\\n\\n\\n/** @type { (item: Tagged) => Promise<Tagged> } */\\nasync function handleItem([tag,...args]){\\nworkerLog('handleItem',tag,args.length);\\nswitch(tag){\\ncase'setBundle':{\\nassert.assert(!dispatch,'cannot setBundle again');\\nconst liveSlotsOptions=/** @type LiveSlotsOptions */args[2];\\nreturn setBundle(args[0],args[1],liveSlotsOptions);}\\n\\ncase'deliver':{\\nassert.assert(dispatch,'cannot deliver before setBundle');\\nconst[vatDeliveryObject]=args;\\nharden(vatDeliveryObject);\\nmessage.insistVatDeliveryObject(vatDeliveryObject);\\nreturn dispatch(vatDeliveryObject);}\\n\\ndefault:\\nworkerLog('handleItem: bad tag',tag,args.length);\\nreturn['bad tag',tag];}}\\n\\n\\n\\nreturn harden({\\nhandleItem});}\\n\\n\\n\\n/* xsnap provides issueCommand global*/\\nconst port=managerPort(globalThis.issueCommand);\\nconst worker=makeWorker(port);\\n\\n/* Send unexpected console messages to the manager port.*/\\nglobalThis.print=(...args)=>{\\nport.send(['sourcedConsole','xsnap','error',...args]);};\\n\\n\\nglobalThis.handleCommand=port.handlerFrom(worker.handleItem);\",\n \"packages/swingset-xsnap-supervisor/lib/waitUntilQuiescent.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var\\n\\n\\n\\nindex=require('../../../node_modules/@endo/promise-kit/index.js');/* global setImmediate */ /* This can only be imported from the Start Compartment, where 'setImmediate'*/ /* is available.*/\\n\\nfunction waitUntilQuiescent(){\\n/* the delivery might cause some number of (native) Promises to be*/\\n/* created and resolved, so we use the IO queue to detect when the*/\\n/* Promise queue is empty. The IO queue (setImmediate and setTimeout) is*/\\n/* lower-priority than the Promise queue on browsers and Node 11, but on*/\\n/* Node 10 it is higher. So this trick requires Node 11.*/\\n/* https://jsblog.insiderattack.net/new-changes-to-timers-and-microtasks-from-node-v11-0-0-and-above-68d112743eb3*/\\n/** @type {IMPORT('@endo/promise-kit').PromiseKit<void>} */\\nconst{promise:queueEmptyP,resolve}=index.makePromiseKit();\\nsetImmediate(()=>resolve());\\nreturn queueEmptyP;}exports.waitUntilQuiescent=waitUntilQuiescent;\"\n};\n const nsBundle = {};\n\n function createEvalString(filename) {\n const code = sourceBundle[filename];\n if (!code) {\n return undefined;\n }\n return `\\\n(function getExport(require, exports) { \\\n 'use strict'; \\\n const module = { exports }; \\\n \\\n ${code}\n return module.exports;\n})\n//# sourceURL=${filePrefix}/${filename}\n`;\n }\n\n function computeExports(filename, exportPowers, exports) {\n const { require: systemRequire, systemEval, _log } = exportPowers;\n // This captures the endowed require.\n const match = filename.match(/^(.*)\\/[^/]+$/);\n const thisdir = match ? match[1] : '.';\n const contextRequire = mod => {\n // Do path algebra to find the actual source.\n const els = mod.split('/');\n let prefix;\n if (els[0][0] === '@') {\n // Scoped name.\n prefix = els.splice(0, 2).join('/');\n } else if (els[0][0] === '.') {\n // Relative.\n els.unshift(...thisdir.split('/'));\n } else {\n // Bare or absolute.\n prefix = els.splice(0, 1);\n }\n\n const suffix = [];\n for (const el of els) {\n if (el === '.' || el === '') {\n // Do nothing.\n } else if (el === '..') {\n // Traverse upwards.\n suffix.pop();\n } else {\n suffix.push(el);\n }\n }\n\n // log(mod, prefix, suffix);\n if (prefix !== undefined) {\n suffix.unshift(prefix);\n }\n let modPath = suffix.join('/');\n if (modPath.startsWith('./')) {\n modPath = modPath.slice(2);\n }\n // log('requiring', modPath);\n if (!(modPath in nsBundle)) {\n // log('evaluating', modPath);\n // Break cycles, but be tolerant of modules\n // that completely override their exports object.\n nsBundle[modPath] = {};\n nsBundle[modPath] = computeExports(\n modPath,\n exportPowers,\n nsBundle[modPath],\n );\n }\n\n // log('returning', nsBundle[modPath]);\n return nsBundle[modPath];\n };\n\n const code = createEvalString(filename);\n if (!code) {\n // log('missing code for', filename, sourceBundle);\n if (systemRequire) {\n return systemRequire(filename);\n }\n throw Error(\n `require(${JSON.stringify(\n filename,\n )}) failed; no toplevel require endowment`,\n );\n }\n\n // log('evaluating', code);\n // eslint-disable-next-line no-eval\n return (systemEval || eval)(code)(contextRequire, exports);\n }\n\n // Evaluate the entrypoint recursively, seeding the exports.\n const systemRequire = typeof require === 'undefined' ? undefined : require;\n const systemEval = typeof nestedEvaluate === 'undefined' ? undefined : nestedEvaluate;\n return computeExports(entrypoint, { require: systemRequire, systemEval }, {});\n}\n//# sourceURL=/bundled-source/...-preamble.js\n","sourceMap":"//# sourceURL=/bundled-source/...-preamble.js\n"}
|
|
1
|
+
{"moduleFormat":"nestedEvaluate","source":"function getExportWithNestedEvaluate(filePrefix) {\n 'use strict';\n // Serialised sources.\n if (filePrefix === undefined) {\n filePrefix = \"/bundled-source/...\";\n }\n const moduleFormat = \"nestedEvaluate\";\n const entrypoint = \"packages/swingset-xsnap-supervisor/lib/entry.js\";\n const sourceBundle = {\n \"node_modules/@endo/base64/atob.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('./decode.js');var\\n\\ndecode=require('./src/decode.js');/**\\n * @param {string} encodedData a binary string containing base64-encoded data\\n * @returns {string} an ASCII string containing decoded data from `encodedData`\\n */\\nconst atob=(encodedData)=>{\\nconst buf=decode.decodeBase64(encodedData);\\nreturn String.fromCharCode(...buf);};exports.atob=atob;\",\n \"node_modules/@endo/base64/btoa.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('./encode.js');var\\n\\nencode=require('./src/encode.js');/**\\n * @param {string} stringToEncode the binary string to encode\\n * @returns {string} an ASCII string containing the base64 representation of `stringToEncode`\\n */\\nconst btoa=(stringToEncode)=>{\\nconst bytes=stringToEncode.split('').map((char)=>{\\nconst b=char.charCodeAt(0);\\nif(b>0xff){\\nthrow Error(`btoa: character out of range: ${char}`);}\\n\\nreturn b;});\\n\\nconst buf=new Uint8Array(bytes);\\nreturn encode.encodeBase64(buf);};exports.btoa=btoa;\",\n \"node_modules/@endo/base64/decode.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var decode=require('./src/decode.js');exports.decodeBase64=decode.decodeBase64;\",\n \"node_modules/@endo/base64/encode.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var encode=require('./src/encode.js');exports.encodeBase64=encode.encodeBase64;\",\n \"node_modules/@endo/base64/index.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var encode=require('./src/encode.js');var decode=require('./src/decode.js');var btoa=require('./btoa.js');var atob=require('./atob.js');exports.encodeBase64=encode.encodeBase64;exports.decodeBase64=decode.decodeBase64;exports.btoa=btoa.btoa;exports.atob=atob.atob;\",\n \"node_modules/@endo/base64/src/common.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});/* @ts-check*/\\n\\nconst padding='=';\\n\\nconst alphabet64=\\n'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\\n\\n/**\\n * The numeric value corresponding to each letter of the alphabet.\\n * If an alphabet is named for the Greek letters alpha and beta, then clearly a\\n * monodu is named for the corresponding Greek numbers mono and duo.\\n *\\n * @type {Record<string, number>}\\n */\\nconst monodu64={};\\nfor(let i=0;i<alphabet64.length;i+=1){\\nconst c=alphabet64[i];\\nmonodu64[c]=i;}exports.alphabet64=alphabet64;exports.monodu64=monodu64;exports.padding=padding;\",\n \"node_modules/@endo/base64/src/decode.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var\\n\\n\\n\\n\\n\\ncommon=require('./common.js');/* @ts-check*/ /**\\n * Decodes a Base64 string into bytes, as specified in\\n * https://tools.ietf.org/html/rfc4648#section-4\\n *\\n * XSnap is a JavaScript engine based on Moddable/XS.\\n * The algorithm below is orders of magnitude too slow on this VM, but it\\n * arranges a native binding on the global object.\\n * We use that if it is available instead.\\n *\\n * This function is exported from this *file* for use in benchmarking,\\n * but is not part of the *module*'s public API.\\n *\\n * @param {string} string Base64-encoded string\\n * @param {string} [name] The name of the string as it will appear in error\\n * messages.\\n * @returns {Uint8Array} decoded bytes\\n */\\nconst jsDecodeBase64=(string,name='<unknown>')=>{\\nconst data=new Uint8Array(Math.ceil(string.length*4/3));\\nlet register=0;\\nlet quantum=0;\\nlet i=0;/* index in string*/\\nlet j=0;/* index in data*/\\n\\nwhile(i<string.length&&string[i]!==common.padding){\\nconst number=common.monodu64[string[i]];\\nif(number===undefined){\\nthrow Error(`Invalid base64 character ${string[i]} in string ${name}`);}\\n\\nregister=register<<6|number;\\nquantum+=6;\\nif(quantum>=8){\\nquantum-=8;\\ndata[j]=register>>>quantum;\\nj+=1;\\nregister&=(1<<quantum)-1;}\\n\\ni+=1;}\\n\\n\\nwhile(quantum>0){\\nif(i===string.length||string[i]!==common.padding){\\nthrow Error(`Missing padding at offset ${i} of string ${name}`);}\\n\\n/* We MAY reject non-zero padding bits, but choose not to.*/\\n/* https://datatracker.ietf.org/doc/html/rfc4648#section-3.5*/\\ni+=1;\\nquantum-=2;}\\n\\n\\nif(i<string.length){\\nthrow Error(\\n`Base64 string has trailing garbage ${string.substr(\\ni)\\n} in string ${name}`);}\\n\\n\\n\\nreturn data.subarray(0,j);};\\n\\n\\n/* The XS Base64.decode function is faster, but might return ArrayBuffer (not*/\\n/* Uint8Array). Adapt it to our needs.*/\\nconst adaptDecoder=\\n(nativeDecodeBase64)=>\\n(...args)=>{\\nconst decoded=nativeDecodeBase64(...args);\\nif(decoded instanceof Uint8Array){\\nreturn decoded;}\\n\\nreturn new Uint8Array(decoded);};\\n\\n\\n/** @type {typeof jsDecodeBase64} */\\nconst decodeBase64=\\nglobalThis.Base64!==undefined?\\nadaptDecoder(globalThis.Base64.decode):\\njsDecodeBase64;exports.decodeBase64=decodeBase64;exports.jsDecodeBase64=jsDecodeBase64;\",\n \"node_modules/@endo/base64/src/encode.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var\\n\\n\\n\\n\\n\\ncommon=require('./common.js');/* @ts-check*/ /**\\n * XSnap is a JavaScript engine based on Moddable/XS.\\n * The algorithm below is orders of magnitude too slow on this VM, but it\\n * arranges a native binding on the global object.\\n * We use that if it is available instead.\\n *\\n * This function is exported from this *file* for use in benchmarking,\\n * but is not part of the *module*'s public API.\\n *\\n * @param {Uint8Array} data\\n * @returns {string} base64 encoding\\n */\\nconst jsEncodeBase64=(data)=>{\\n/* A cursory benchmark shows that string concatenation is about 25% faster*/\\n/* than building an array and joining it in v8, in 2020, for strings of about*/\\n/* 100 long.*/\\nlet string='';\\nlet register=0;\\nlet quantum=0;\\n\\nfor(let i=0;i<data.length;i+=1){\\nconst b=data[i];\\nregister=register<<8|b;\\nquantum+=8;\\nif(quantum===24){\\nstring+=\\ncommon.alphabet64[register>>>18&0x3f]+\\ncommon.alphabet64[register>>>12&0x3f]+\\ncommon.alphabet64[register>>>6&0x3f]+\\ncommon.alphabet64[register>>>0&0x3f];\\nregister=0;\\nquantum=0;}}\\n\\n\\n\\nswitch(quantum){\\ncase 0:\\nbreak;\\ncase 8:\\nstring+=\\ncommon.alphabet64[register>>>2&0x3f]+\\ncommon.alphabet64[register<<4&0x3f]+\\ncommon.padding+\\ncommon.padding;\\nbreak;\\ncase 16:\\nstring+=\\ncommon.alphabet64[register>>>10&0x3f]+\\ncommon.alphabet64[register>>>4&0x3f]+\\ncommon.alphabet64[register<<2&0x3f]+\\ncommon.padding;\\nbreak;\\ndefault:\\nthrow Error(`internal: bad quantum ${quantum}`);}\\n\\nreturn string;};\\n\\n\\n/**\\n * Encodes bytes into a Base64 string, as specified in\\n * https://tools.ietf.org/html/rfc4648#section-4\\n *\\n * @type {typeof jsEncodeBase64}\\n */\\nconst encodeBase64=\\nglobalThis.Base64!==undefined?globalThis.Base64.encode:jsEncodeBase64;exports.encodeBase64=encodeBase64;exports.jsEncodeBase64=jsEncodeBase64;\",\n \"node_modules/@endo/common/apply-labeling-error.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var noShim=require('../eventual-send/src/no-shim.js');require('../promise-kit/index.js');var throwLabeled=require('./throw-labeled.js');var\\n\\n\\n\\nisPromise=require('../promise-kit/src/is-promise.js');/**\\n * Calls `func(...args)`, but annotating any failure error with `label`.\\n *\\n * If `label` is omitted or `undefined`, then this is equivalent to\\n * `func(...args).\\n *\\n * Otherwise, if it successfully returns a non-promise, that non-promise is\\n * returned.\\n *\\n * If it throws, rethrow a similar error whose message is\\n * ```js\\n * `${label}: ${originalMessage}`\\n * ```\\n * That way, in an error happens deep within a stack of calls to\\n * `applyLabelingError`, the resulting error will show the stack of labels.\\n *\\n * If it returns a promise, then `applyLabelingError` cannot tell until that\\n * promise settles whether it represents a success or failure. So it immediately\\n * returns a new promise. If the original promise fulfills, then the\\n * fulfillment is propagated to the returned promise.\\n *\\n * If the promise rejects with an error, then the returned promise is\\n * rejected with a similar promise, prefixed with the label in that same way.\\n *\\n * @template A,R\\n * @param {(...args: A[]) => R} func\\n * @param {A[]} args\\n * @param {string|number} [label]\\n * @returns {R}\\n */\\nconst applyLabelingError=(func,args,label=undefined)=>{\\nif(label===undefined){\\nreturn func(...args);}\\n\\nlet result;\\ntry{\\nresult=func(...args);}\\ncatch(err){\\nthrowLabeled.throwLabeled(err,label);}\\n\\nif(isPromise.isPromise(result)){\\n/* Cannot be at-ts-expect-error because there is no type error locally.*/\\n/* Rather, a type error only as imported into exo.*/\\n/* @ts-ignore If result is a rejected promise, this will*/\\n/* return a promise with a different rejection reason. But this*/\\n/* confuses TypeScript because it types that case as `Promise<never>`*/\\n/* which is cool for a promise that will never fulfll.*/\\n/* But TypeScript doesn't understand that this will only happen*/\\n/* when `result` was a rejected promise. In only this case `R`*/\\n/* should already allow `Promise<never>` as a subtype.*/\\nreturn noShim.E.when(result,undefined,(reason)=>throwLabeled.throwLabeled(reason,label));}else\\n{\\nreturn result;}};\\n\\n\\nharden(applyLabelingError);exports.applyLabelingError=applyLabelingError;\",\n \"node_modules/@endo/common/from-unique-entries.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var index=require('../errors/index.js');\\n\\nconst{fromEntries}=Object;\\nconst{ownKeys}=Reflect;\\n\\n/**\\n * Throws if multiple entries use the same property name. Otherwise acts\\n * like `Object.fromEntries` but hardens the result.\\n * Use it to protect from property names computed from user-provided data.\\n *\\n * @template [T=any]\\n * @param {Iterable<readonly [PropertyKey, T]>} allEntries\\n * @returns {{ [k: string]: T; }}\\n */\\nconst fromUniqueEntries=(allEntries)=>{\\nconst entriesArray=[...allEntries];\\nconst result=harden(fromEntries(entriesArray));\\nif(ownKeys(result).length===entriesArray.length){\\nreturn result;}\\n\\nconst names=new Set();\\nfor(const[name,_]of entriesArray){\\nif(names.has(name)){\\nindex.throwRedacted`collision on property name ${index.quote(name)}: ${entriesArray}`;}\\n\\nnames.add(name);}\\n\\nthrow index.throwRedacted`internal: failed to create object from unique entries`;};\\n\\nharden(fromUniqueEntries);exports.fromUniqueEntries=fromUniqueEntries;\",\n \"node_modules/@endo/common/ident-checker.js\": \"'use strict';\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nObject.defineProperty(exports,'__esModule',{value:true});/* TODO Complete migration of Checker type from @endo/pass-style to @endo/common*/ /* by having @endo/pass-style, and everyone else who needs it, import it from*/ /* `@endo/common/ident-checker.js`.*/ /**\\n * @callback Checker\\n * Internal to a useful pattern for writing checking logic\\n * (a \\\"checkFoo\\\" function) that can be used to implement a predicate\\n * (an \\\"isFoo\\\" function) or a validator (an \\\"assertFoo\\\" function).\\n *\\n * * A predicate ideally only returns `true` or `false` and rarely throws.\\n * * A validator throws an informative diagnostic when the predicate\\n * would have returned `false`, and simply returns `undefined` normally\\n * when the predicate would have returned `true`.\\n * * The internal checking function that they share is parameterized by a\\n * `Checker` that determines how to proceed with a failure condition.\\n * Predicates pass in an identity function as checker. Validators\\n * pass in `assertChecker` which is a trivial wrapper around `assert`.\\n *\\n * See the various uses for good examples.\\n * @param {boolean} cond\\n * @param {IMPORT('ses').Details} [details]\\n * @returns {boolean}\\n */ /**\\n * In the `assertFoo`/`isFoo`/`checkFoo` pattern, `checkFoo` has a `check`\\n * parameter of type `Checker`. `assertFoo` calls `checkFoo` passes\\n * `assertChecker` as the `check` argument. `isFoo` passes `identChecker`\\n * as the `check` argument. `identChecker` acts precisely like an\\n * identity function, but is typed as a `Checker` to indicate its\\n * intended use.\\n *\\n * @type {Checker}\\n */const identChecker=(cond,_details)=>cond;harden(identChecker);exports.identChecker=identChecker;\",\n \"node_modules/@endo/common/list-difference.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});/**\\n * Return a list of all the elements present in the `leftList` and not\\n * in the `rightList`. Return in the order of their appearance in `leftList`.\\n * Uses the comparison built into `Set` membership (SameValueZero)\\n * which is like JavaScript's `===` except that it judges any `NaN` to\\n * be the same as any `NaN` and it judges `0` to be the same a `-0`.\\n *\\n * This is often used on lists of names that should match, in order to generate\\n * useful diagnostics about the unmatched names.\\n *\\n * @template {any} V\\n * @param {V[]} leftList\\n * @param {V[]} rightList\\n */\\nconst listDifference=(leftList,rightList)=>{\\nconst rightSet=new Set(rightList);\\nreturn leftList.filter((element)=>!rightSet.has(element));};\\n\\nharden(listDifference);exports.listDifference=listDifference;\",\n \"node_modules/@endo/common/make-array-iterator.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var\\n\\nmakeIterator=require('./make-iterator.js');/**\\n * A `harden`ing analog of Array.prototype[Symbol.iterator].\\n *\\n * @template [T=unknown]\\n * @param {Array<T>} arr\\n * @returns {IterableIterator<T>}\\n */\\nconst makeArrayIterator=(arr)=>{\\nconst{length}=arr;\\nlet i=0;\\nreturn makeIterator.makeIterator(()=>{\\n/** @type {T} */\\nlet value;\\nif(i<length){\\nvalue=arr[i];\\ni+=1;\\nreturn harden({done:false,value});}\\n\\n/* @ts-expect-error The terminal value doesn't matter*/\\nreturn harden({done:true,value});});};\\n\\n\\nharden(makeArrayIterator);exports.makeArrayIterator=makeArrayIterator;\",\n \"node_modules/@endo/common/make-iterator.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});/**\\n * Makes a one-shot iterable iterator from a provided `next` function.\\n *\\n * @template [T=unknown]\\n * @param {() => IteratorResult<T>} next\\n * @returns {IterableIterator<T>}\\n */\\nconst makeIterator=(next)=>{\\nconst iter=harden({\\n[Symbol.iterator]:()=>iter,\\nnext});\\n\\nreturn iter;};\\n\\nharden(makeIterator);exports.makeIterator=makeIterator;\",\n \"node_modules/@endo/common/object-map.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});const{entries,fromEntries}=Object;\\n\\n/**\\n * By analogy with how `Array.prototype.map` will map the elements of\\n * an array to transformed elements of an array of the same shape,\\n * `objectMap` will do likewise for the string-named own enumerable\\n * properties of an object.\\n *\\n * Typical usage applies `objectMap` to a CopyRecord, i.e.,\\n * an object for which `passStyleOf(original) === 'copyRecord'`. For these,\\n * none of the following edge cases arise. The result will be a CopyRecord\\n * with exactly the same property names, whose values are the mapped form of\\n * the original's values.\\n *\\n * When the original is not a CopyRecord, some edge cases to be aware of\\n * * No matter how mutable the original object, the returned object is\\n * hardened.\\n * * Only the string-named enumerable own properties of the original\\n * are mapped. All other properties are ignored.\\n * * If any of the original properties were accessors, `Object.entries`\\n * will cause its `getter` to be called and will use the resulting\\n * value.\\n * * No matter whether the original property was an accessor, writable,\\n * or configurable, all the properties of the returned object will be\\n * non-writable, non-configurable, data properties.\\n * * No matter what the original object may have inherited from, and\\n * no matter whether it was a special kind of object such as an array,\\n * the returned object will always be a plain object inheriting directly\\n * from `Object.prototype` and whose state is only these new mapped\\n * own properties.\\n *\\n * With these differences, even if the original object was not a CopyRecord,\\n * if all the mapped values are Passable, then the returned object will be\\n * a CopyRecord.\\n *\\n * @template {Record<string, any>} O\\n * @template R map result\\n * @param {O} original\\n * @param {(value: O[keyof O], key: keyof O) => R} mapFn\\n * @returns {Record<keyof O, R>}\\n */\\nconst objectMap=(original,mapFn)=>{\\nconst ents=entries(original);\\nconst mapEnts=ents.map(\\n([k,v])=>/** @type {[keyof O, R]} */[k,mapFn(v,k)]);\\n\\nreturn(/** @type {Record<keyof O, R>} */harden(fromEntries(mapEnts)));};\\n\\nharden(objectMap);exports.objectMap=objectMap;\",\n \"node_modules/@endo/common/throw-labeled.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var\\n\\nindex=require('../errors/index.js');/**\\n * Given an error `innerErr` and a `label`, throws a similar\\n * error whose message string is `${label}: ${innerErr.message}`.\\n * See `applyLabelingError` for the motivating use.\\n *\\n * @param {Error} innerErr\\n * @param {string|number} label\\n * @param {IMPORT('ses').GenericErrorConstructor} [errConstructor]\\n * @param {IMPORT('ses').AssertMakeErrorOptions} [options]\\n * @returns {never}\\n */\\nconst throwLabeled=(\\ninnerErr,\\nlabel,\\nerrConstructor=undefined,\\noptions=undefined)=>\\n{\\nif(typeof label==='number'){\\nlabel=`[${label}]`;}\\n\\nconst outerErr=index.makeError(\\n`${label}: ${innerErr.message}`,\\nerrConstructor,\\noptions);\\n\\nindex.note(outerErr,index.redacted`Caused by ${innerErr}`);\\nthrow outerErr;};\\n\\nharden(throwLabeled);exports.throwLabeled=throwLabeled;\",\n \"node_modules/@endo/compartment-mapper/import-archive.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var importArchive=require('./src/import-archive.js');exports.importArchive=importArchive.importArchive;exports.loadArchive=importArchive.loadArchive;exports.parseArchive=importArchive.parseArchive;\",\n \"node_modules/@endo/compartment-mapper/src/compartment-map.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\npolicyFormat=require('./policy-format.js');/* Validates a compartment map against its schema. */ /* TODO convert to the new `||` assert style.*/ /* Deferred because this file pervasively uses simple template strings rather than*/ /* template strings tagged with `assert.details` (aka `X`), and uses*/ /* this definition of `q` rather than `assert.quote`*/\\nconst q=JSON.stringify;\\n\\n/** @type {(a: string, b: string) => number} */\\n/* eslint-disable-next-line no-nested-ternary*/\\nconst stringCompare=(a,b)=>a===b?0:a<b?-1:1;\\n\\n/**\\n * @param {number} length\\n * @param {string} term\\n */\\nconst cumulativeLength=(length,term)=>{\\nreturn length+term.length;};\\n\\n\\n/**\\n * @param {Array<string> | undefined} a\\n * @param {Array<string> | undefined} b\\n */\\nconst pathCompare=(a,b)=>{\\n/* Undefined is not preferred*/\\nif(a===undefined&&b===undefined){\\nreturn 0;}\\n\\nif(a===undefined){\\nreturn 1;}\\n\\nif(b===undefined){\\nreturn-1;}\\n\\n/* Prefer the shortest dependency path.*/\\nif(a.length!==b.length){\\nreturn a.length-b.length;}\\n\\n/* Otherwise, favor the shortest cumulative length.*/\\nconst aSum=a.reduce(cumulativeLength,0);\\nconst bSum=b.reduce(cumulativeLength,0);\\nif(aSum!==bSum){\\nreturn aSum-bSum;}\\n\\n/* Otherwise, compare terms lexically.*/\\nassert(a.length===b.length);/* Reminder*/\\n/* This loop guarantees that if any pair of terms is different, including the*/\\n/* case where one is a prefix of the other, we will return a non-zero value.*/\\nfor(let i=0;i<a.length;i+=1){\\nconst comparison=stringCompare(a[i],b[i]);\\nif(comparison!==0){\\nreturn comparison;}}\\n\\n\\n/* If all pairs of terms are the same respective lengths, we are guaranteed*/\\n/* that they are exactly the same or one of them is lexically distinct and would*/\\n/* have already been caught.*/\\nreturn 0;};\\n\\n\\n/**\\n * @template T\\n * @param {Iterable<T>} iterable\\n */\\nfunction*enumerate(iterable){\\nlet index=0;\\nfor(const value of iterable){\\nyield[index,value];\\nindex+=1;}}\\n\\n\\n\\n/**\\n * @param {Record<string, unknown>} object\\n * @param {string} message\\n */\\nconst assertEmptyObject=(object,message)=>{\\nassert(Object.keys(object).length===0,message);};\\n\\n\\n/**\\n * @param {unknown} conditions\\n * @param {string} url\\n */\\nconst assertConditions=(conditions,url)=>{\\nif(conditions===undefined)return;\\nassert(\\nArray.isArray(conditions),\\n`conditions must be an array, got ${conditions} in ${q(url)}`);\\n\\nfor(const[index,value]of enumerate(conditions)){\\nassert.typeof(\\nvalue,\\n'string',\\n`conditions[${index}] must be a string, got ${value} in ${q(url)}`);}};\\n\\n\\n\\n\\n/**\\n * @param {Record<string, unknown>} allegedModule\\n * @param {string} path\\n * @param {string} url\\n */\\nconst assertCompartmentModule=(allegedModule,path,url)=>{\\nconst{compartment,module,...extra}=allegedModule;\\nassertEmptyObject(\\nextra,\\n`${path} must not have extra properties, got ${q({\\nextra,\\ncompartment})\\n} in ${q(url)}`);\\n\\nassert.typeof(\\ncompartment,\\n'string',\\n`${path}.compartment must be a string, got ${q(compartment)} in ${q(url)}`);\\n\\nassert.typeof(\\nmodule,\\n'string',\\n`${path}.module must be a string, got ${q(module)} in ${q(url)}`);};\\n\\n\\n\\n/**\\n * @param {Record<string, unknown>} allegedModule\\n * @param {string} path\\n * @param {string} url\\n */\\nconst assertFileModule=(allegedModule,path,url)=>{\\nconst{location,parser,sha512,...extra}=allegedModule;\\nassertEmptyObject(\\nextra,\\n`${path} must not have extra properties, got ${q(\\nObject.keys(extra))\\n} in ${q(url)}`);\\n\\nassert.typeof(\\nlocation,\\n'string',\\n`${path}.location must be a string, got ${q(location)} in ${q(url)}`);\\n\\nassert.typeof(\\nparser,\\n'string',\\n`${path}.parser must be a string, got ${q(parser)} in ${q(url)}`);\\n\\n\\nif(sha512!==undefined){\\nassert.typeof(\\nsha512,\\n'string',\\n`${path}.sha512 must be a string, got ${q(sha512)} in ${q(url)}`);}};\\n\\n\\n\\n\\n/**\\n * @param {Record<string, unknown>} allegedModule\\n * @param {string} path\\n * @param {string} url\\n */\\nconst assertExitModule=(allegedModule,path,url)=>{\\nconst{exit,...extra}=allegedModule;\\nassertEmptyObject(\\nextra,\\n`${path} must not have extra properties, got ${q(\\nObject.keys(extra))\\n} in ${q(url)}`);\\n\\nassert.typeof(\\nexit,\\n'string',\\n`${path}.exit must be a string, got ${q(exit)} in ${q(url)}`);};\\n\\n\\n\\n/**\\n * @param {unknown} allegedModule\\n * @param {string} path\\n * @param {string} url\\n */\\nconst assertModule=(allegedModule,path,url)=>{\\nconst moduleDescriptor=Object(allegedModule);\\nassert(\\nallegedModule===moduleDescriptor&&!Array.isArray(moduleDescriptor),\\n`${path} must be an object, got ${allegedModule} in ${q(url)}`);\\n\\n\\nconst{compartment,module,location,parser,exit,deferredError}=\\nmoduleDescriptor;\\nif(compartment!==undefined||module!==undefined){\\nassertCompartmentModule(moduleDescriptor,path,url);}else\\nif(location!==undefined||parser!==undefined){\\nassertFileModule(moduleDescriptor,path,url);}else\\nif(exit!==undefined){\\nassertExitModule(moduleDescriptor,path,url);}else\\nif(deferredError!==undefined){\\nassert.typeof(\\ndeferredError,\\n'string',\\n`${path}.deferredError must be a string contaiing an error message`);}else\\n\\n{\\nassert.fail(\\n`${path} is not a valid module descriptor, got ${q(allegedModule)} in ${q(\\nurl)\\n}`);}};\\n\\n\\n\\n\\n/**\\n * @param {unknown} allegedModules\\n * @param {string} path\\n * @param {string} url\\n */\\nconst assertModules=(allegedModules,path,url)=>{\\nconst modules=Object(allegedModules);\\nassert(\\nallegedModules===modules||!Array.isArray(modules),\\n`modules must be an object, got ${q(allegedModules)} in ${q(url)}`);\\n\\nfor(const[key,value]of Object.entries(modules)){\\nassertModule(value,`${path}.modules[${q(key)}]`,url);}};\\n\\n\\n\\n/**\\n * @param {unknown} allegedParsers\\n * @param {string} path\\n * @param {string} url\\n */\\nconst assertParsers=(allegedParsers,path,url)=>{\\nif(allegedParsers===undefined){\\nreturn;}\\n\\nconst parsers=Object(allegedParsers);\\nassert(\\nallegedParsers===parsers&&!Array.isArray(parsers),\\n`${path}.parsers must be an object, got ${allegedParsers} in ${q(url)}`);\\n\\n\\nfor(const[key,value]of Object.entries(parsers)){\\nassert.typeof(\\nkey,\\n'string',\\n`all keys of ${path}.parsers must be strings, got ${key} in ${q(url)}`);\\n\\nassert.typeof(\\nvalue,\\n'string',\\n`${path}.parsers[${q(key)}] must be a string, got ${value} in ${q(url)}`);}};\\n\\n\\n\\n\\n/**\\n * @param {unknown} allegedScope\\n * @param {string} path\\n * @param {string} url\\n */\\nconst assertScope=(allegedScope,path,url)=>{\\nconst scope=Object(allegedScope);\\nassert(\\nallegedScope===scope&&!Array.isArray(scope),\\n`${path} must be an object, got ${allegedScope} in ${q(url)}`);\\n\\n\\nconst{compartment,...extra}=scope;\\nassertEmptyObject(\\nextra,\\n`${path} must not have extra properties, got ${q(\\nObject.keys(extra))\\n} in ${q(url)}`);\\n\\n\\nassert.typeof(\\ncompartment,\\n'string',\\n`${path}.compartment must be a string, got ${q(compartment)} in ${q(url)}`);};\\n\\n\\n\\n/**\\n * @param {unknown} allegedScopes\\n * @param {string} path\\n * @param {string} url\\n */\\nconst assertScopes=(allegedScopes,path,url)=>{\\nif(allegedScopes===undefined){\\nreturn;}\\n\\nconst scopes=Object(allegedScopes);\\nassert(\\nallegedScopes===scopes&&!Array.isArray(scopes),\\n`${path}.scopes must be an object, got ${q(allegedScopes)} in ${q(url)}`);\\n\\n\\nfor(const[key,value]of Object.entries(scopes)){\\nassert.typeof(\\nkey,\\n'string',\\n`all keys of ${path}.scopes must be strings, got ${key} in ${q(url)}`);\\n\\nassertScope(value,`${path}.scopes[${q(key)}]`,url);}};\\n\\n\\n\\n/**\\n * @param {unknown} allegedTypes\\n * @param {string} path\\n * @param {string} url\\n */\\nconst assertTypes=(allegedTypes,path,url)=>{\\nif(allegedTypes===undefined){\\nreturn;}\\n\\nconst types=Object(allegedTypes);\\nassert(\\nallegedTypes===types&&!Array.isArray(types),\\n`${path}.types must be an object, got ${allegedTypes} in ${q(url)}`);\\n\\n\\nfor(const[key,value]of Object.entries(types)){\\nassert.typeof(\\nkey,\\n'string',\\n`all keys of ${path}.types must be strings, got ${key} in ${q(url)}`);\\n\\nassert.typeof(\\nvalue,\\n'string',\\n`${path}.types[${q(key)}] must be a string, got ${value} in ${q(url)}`);}};\\n\\n\\n\\n\\n/**\\n * @param {unknown} allegedPolicy\\n * @param {string} path\\n * @param {string} [url]\\n */\\n\\nconst assertPolicy=(\\nallegedPolicy,\\npath,\\nurl='<unknown-compartment-map.json>')=>\\n{\\npolicyFormat.assertPackagePolicy(allegedPolicy,`${path}.policy`,url);};\\n\\n\\n/**\\n * @param {unknown} allegedCompartment\\n * @param {string} path\\n * @param {string} url\\n */\\nconst assertCompartment=(allegedCompartment,path,url)=>{\\nconst compartment=Object(allegedCompartment);\\nassert(\\nallegedCompartment===compartment&&!Array.isArray(compartment),\\n`${path} must be an object, got ${allegedCompartment} in ${q(url)}`);\\n\\n\\nconst{\\nlocation,\\nname,\\nlabel,\\nparsers,\\ntypes,\\nscopes,\\nmodules,\\npolicy,\\n...extra}=\\ncompartment;\\n\\nassertEmptyObject(\\nextra,\\n`${path} must not have extra properties, got ${q(\\nObject.keys(extra))\\n} in ${q(url)}`);\\n\\n\\nassert.typeof(\\nlocation,\\n'string',\\n`${path}.location in ${q(url)} must be string, got ${q(location)}`);\\n\\nassert.typeof(\\nname,\\n'string',\\n`${path}.name in ${q(url)} must be string, got ${q(name)}`);\\n\\nassert.typeof(\\nlabel,\\n'string',\\n`${path}.label in ${q(url)} must be string, got ${q(label)}`);\\n\\n\\nassertModules(modules,path,url);\\nassertParsers(parsers,path,url);\\nassertScopes(scopes,path,url);\\nassertTypes(types,path,url);\\nassertPolicy(policy,path,url);};\\n\\n\\n/**\\n * @param {unknown} allegedCompartments\\n * @param {string} url\\n */\\nconst assertCompartments=(allegedCompartments,url)=>{\\nconst compartments=Object(allegedCompartments);\\nassert(\\nallegedCompartments===compartments||!Array.isArray(compartments),\\n`compartments must be an object, got ${q(allegedCompartments)} in ${q(\\nurl)\\n}`);\\n\\nfor(const[key,value]of Object.entries(compartments)){\\nassertCompartment(value,`compartments[${q(key)}]`,url);}};\\n\\n\\n\\n/**\\n * @param {unknown} allegedEntry\\n * @param {string} url\\n */\\nconst assertEntry=(allegedEntry,url)=>{\\nconst entry=Object(allegedEntry);\\nassert(\\nallegedEntry===entry&&!Array.isArray(entry),\\n`\\\"entry\\\" must be an object in compartment map, got ${allegedEntry} in ${q(\\nurl)\\n}`);\\n\\nconst{compartment,module,...extra}=entry;\\nassertEmptyObject(\\nextra,\\n`\\\"entry\\\" must not have extra properties in compartment map, got ${q(\\nObject.keys(extra))\\n} in ${q(url)}`);\\n\\nassert.typeof(\\ncompartment,\\n'string',\\n`entry.compartment must be a string in compartment map, got ${compartment} in ${q(\\nurl)\\n}`);\\n\\nassert.typeof(\\nmodule,\\n'string',\\n`entry.module must be a string in compartment map, got ${module} in ${q(\\nurl)\\n}`);};\\n\\n\\n\\n/**\\n * @param {unknown} allegedCompartmentMap\\n * @param {string} [url]\\n * @returns {asserts compartmentMap is IMPORT('./types.js').CompartmentMapDescriptor}\\n */\\n\\nconst assertCompartmentMap=(\\nallegedCompartmentMap,\\nurl='<unknown-compartment-map.json>')=>\\n{\\nconst compartmentMap=Object(allegedCompartmentMap);\\nassert(\\nallegedCompartmentMap===compartmentMap&&!Array.isArray(compartmentMap),\\n`Compartment map must be an object, got ${allegedCompartmentMap} in ${q(\\nurl)\\n}`);\\n\\nconst{\\n/* TODO migrate tags to conditions*/\\n/* https://github.com/endojs/endo/issues/2388*/\\ntags:conditions,\\nentry,\\ncompartments,\\n...extra}=\\nObject(compartmentMap);\\nassertEmptyObject(\\nextra,\\n`Compartment map must not have extra properties, got ${q(\\nObject.keys(extra))\\n} in ${q(url)}`);\\n\\nassertConditions(conditions,url);\\nassertEntry(entry,url);\\nassertCompartments(compartments,url);};exports.assertCompartmentMap=assertCompartmentMap;exports.pathCompare=pathCompare;exports.stringCompare=stringCompare;\",\n \"node_modules/@endo/compartment-mapper/src/extension.js\": \"'use strict';\\n\\n\\n\\nObject.defineProperty(exports,'__esModule',{value:true});/* Extracts the extension from a URL pathname. */ /* @ts-check*/ /**\\n * `parseExtension` returns the file extension for the given URL, or an empty\\n * string if the path has no extension.\\n * Exported for tests.\\n *\\n * @param {string} location\\n * @returns {string}\\n */\\nconst parseExtension=(location)=>{\\nconst lastSlash=location.lastIndexOf('/');\\nif(lastSlash<0){\\nreturn'';}\\n\\nconst base=location.slice(lastSlash+1);\\nconst lastDot=base.lastIndexOf('.');\\nif(lastDot<0){\\nreturn'';}\\n\\nreturn base.slice(lastDot+1);};exports.parseExtension=parseExtension;\",\n \"node_modules/@endo/compartment-mapper/src/import-archive-lite.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../zip/index.js');var link=require('./link.js');var json=require('./json.js');var powers=require('./powers.js');var nodeModuleSpecifier=require('./node-module-specifier.js');var compartmentMap=require('./compartment-map.js');var importHook=require('./import-hook.js');var policy=require('./policy.js');var reader=require('../../zip/src/reader.js');/* Provides functions for evaluating the modules in an archive (a zip\\n * file with a `compartment-map.json` and a file for each module it contains.)\\n *\\n * These functions do not have a bias for any particular mapping, so you will\\n * need to use `mapNodeModules` from `@endo/compartment-map/node-modules.js` or\\n * a similar device to construct one.\\n *\\n * The default `parserForLanguage` mapping is empty.\\n * You will need to provide the `defaultParserForLanguage` from\\n * `@endo/compartment-mapper/import-parsers.js` or\\n * `@endo/compartment-mapper/archive-parsers.js`.\\n */\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nconst DefaultCompartment=Compartment;\\n\\nconst{Fail,quote:q}=assert;\\n\\nconst textDecoder=new TextDecoder();\\n\\nconst{assign,create,freeze}=Object;\\n\\n/**\\n * @param {string} errorMessage - error to throw on execute\\n * @returns {StaticModuleType}\\n */\\nconst postponeErrorToExecute=(errorMessage)=>{\\n/* Return a place-holder that'd throw an error if executed*/\\n/* This allows cjs parser to more eagerly find calls to require*/\\n/* - if parser identified a require call that's a local function, execute will never be called*/\\n/* - if actual required module is missing, the error will happen anyway - at execution time*/\\n\\nconst record=freeze({\\nimports:[],\\nexports:[],\\nexecute:()=>{\\nthrow Error(errorMessage);}});\\n\\n\\n\\nreturn record;};\\n\\n\\n/**\\n * @param {(path: string) => Uint8Array} get\\n * @param {Record<string, CompartmentDescriptor>} compartments\\n * @param {string} archiveLocation\\n * @param {ParserForLanguage} parserForLanguage\\n * @param {HashFn} [computeSha512]\\n * @param {ComputeSourceLocationHook} [computeSourceLocation]\\n * @param {ExitModuleImportHook} [exitModuleImportHook]\\n * @param {ComputeSourceMapLocationHook} [computeSourceMapLocation]\\n * @returns {ImportHookMaker}\\n */\\nconst makeArchiveImportHookMaker=(\\nget,\\ncompartments,\\narchiveLocation,\\nparserForLanguage,\\ncomputeSha512=undefined,\\ncomputeSourceLocation=undefined,\\nexitModuleImportHook=undefined,\\ncomputeSourceMapLocation=undefined)=>\\n{\\n/* per-assembly:*/\\n/** @type {ImportHookMaker} */\\nconst makeImportHook=({\\npackageLocation,\\npackageName,\\nattenuators\\n/* note `compartments` are not passed to makeImportHook because*/\\n/* the reference was passed to makeArchiveImportHookMaker.*/})=>\\n{\\n/* per-compartment:*/\\nconst compartmentDescriptor=compartments[packageLocation];\\nconst{modules}=compartmentDescriptor;\\n/** @type {ImportHook} */\\nconst importHook=async(moduleSpecifier)=>{\\nawait null;\\n/* per-module:*/\\nconst module=modules[moduleSpecifier];\\nif(module===undefined){\\nif(exitModuleImportHook){\\n/* At this point in archive importing, if a module is not found and*/\\n/* exitModuleImportHook exists, the only possibility is that the*/\\n/* module is a \\\"builtin\\\" module and the policy needs to be enforced.*/\\npolicy.enforceModulePolicy(moduleSpecifier,compartmentDescriptor,{\\nexit:true,\\nerrorHint:`Blocked in loading. ${q(\\nmoduleSpecifier)\\n} was not in the archive and an attempt was made to load it as a builtin`});\\n\\nconst record=await exitModuleImportHook(moduleSpecifier);\\nif(record){\\n/* note it's not being marked as exit in sources*/\\n/* it could get marked and the second pass, when the archive is being executed, would have the data*/\\n/* to enforce which exits can be dynamically imported*/\\nreturn{\\nrecord:await policy.attenuateModuleHook(\\nmoduleSpecifier,\\nrecord,\\ncompartmentDescriptor.policy,\\nattenuators),\\n\\nspecifier:moduleSpecifier};}else\\n\\n{\\n/* if exitModuleImportHook is allowed, the mechanism to defer*/\\n/* errors in archive creation is never used. We don't want to*/\\n/* throw until the module execution is attempted. This is because*/\\n/* the cjs parser eagerly looks for require calls, and if it finds*/\\n/* one, it will try to import the module even if the require is*/\\n/* never reached.*/\\nreturn postponeErrorToExecute(\\n`Cannot find external module ${q(moduleSpecifier)} in package ${q(\\npackageLocation)\\n} in archive ${q(archiveLocation)}`);}}\\n\\n\\n\\nthrow Error(\\n`Cannot find module ${q(moduleSpecifier)} in package ${q(\\npackageLocation)\\n} in archive ${q(archiveLocation)}`);}\\n\\n\\nif(module.deferredError!==undefined){\\nreturn postponeErrorToExecute(module.deferredError);}\\n\\nif(module.parser===undefined){\\nthrow Error(\\n`Cannot parse module ${q(moduleSpecifier)} in package ${q(\\npackageLocation)\\n} in archive ${q(archiveLocation)}`);}\\n\\n\\nconst parser=parserForLanguage[module.parser];\\nif(parser===undefined){\\nthrow Error(\\n`Cannot parse ${q(module.parser)} module ${q(\\nmoduleSpecifier)\\n} in package ${q(packageLocation)} in archive ${q(archiveLocation)}`);}\\n\\n\\nconst{parse}=parser;\\nconst moduleLocation=`${packageLocation}/${module.location}`;\\nconst moduleBytes=get(moduleLocation);\\n\\nif(computeSha512!==undefined&&module.sha512!==undefined){\\nconst sha512=computeSha512(moduleBytes);\\nif(sha512!==module.sha512){\\nthrow Error(\\n`Module ${q(module.location)} of package ${q(\\npackageLocation)\\n} in archive ${q(\\narchiveLocation)\\n} failed a SHA-512 integrity check`);}}\\n\\n\\n\\n\\nlet sourceLocation=`file:///${moduleLocation}`;\\nif(packageName!==undefined){\\nconst base=packageName.split('/').slice(-1).join('/');\\nsourceLocation=`.../${nodeModuleSpecifier.join(base,moduleSpecifier)}`;}\\n\\nif(computeSourceLocation!==undefined){\\nsourceLocation=\\ncomputeSourceLocation(packageLocation,moduleSpecifier)||\\nsourceLocation;}\\n\\n\\nlet sourceMapUrl;\\nif(\\ncomputeSourceMapLocation!==undefined&&\\nmodule.sha512!==undefined)\\n{\\nsourceMapUrl=computeSourceMapLocation({\\ncompartment:packageLocation,\\nmodule:moduleSpecifier,\\nlocation:sourceLocation,\\nsha512:module.sha512});}\\n\\n\\n\\n/* eslint-disable-next-line no-await-in-loop*/\\nconst{record}=await parse(\\nmoduleBytes,\\nmoduleSpecifier,\\nsourceLocation,\\npackageLocation,\\n{\\nsourceMapUrl,\\ncompartmentDescriptor});\\n\\n\\nreturn{record,specifier:moduleSpecifier};};\\n\\nreturn importHook;};\\n\\nreturn makeImportHook;};\\n\\n\\n/* Have to give it a name to capture the external meaning of Compartment*/\\n/* Otherwise @param {typeof Compartment} takes the Compartment to mean*/\\n/* the const variable defined within the function.*/\\n/** @typedef {typeof Compartment} CompartmentConstructor */\\n\\n/**\\n * @param {Uint8Array} archiveBytes\\n * @param {string} [archiveLocation]\\n * @param {object} [options]\\n * @param {string} [options.expectedSha512]\\n * @param {HashFn} [options.computeSha512]\\n * @param {Record<string, unknown>} [options.modules]\\n * @param {ExitModuleImportHook} [options.importHook]\\n * @param {CompartmentConstructor} [options.Compartment]\\n * @param {ComputeSourceLocationHook} [options.computeSourceLocation]\\n * @param {ComputeSourceMapLocationHook} [options.computeSourceMapLocation]\\n * @param {ParserForLanguage} [options.parserForLanguage]\\n * @param {LanguageForExtension} [options.languageForExtension]\\n * @returns {Promise<Application>}\\n */\\nconst parseArchive=async(\\narchiveBytes,\\narchiveLocation='<unknown>',\\noptions={})=>\\n{\\nawait null;\\nconst{\\ncomputeSha512=undefined,\\nexpectedSha512=undefined,\\ncomputeSourceLocation=undefined,\\ncomputeSourceMapLocation=undefined,\\nCompartment=DefaultCompartment,\\nmodules=undefined,\\nimportHook:exitModuleImportHook=undefined,\\nparserForLanguage:parserForLanguageOption={},\\nlanguageForExtension:languageForExtensionOption={}}=\\noptions;\\n\\nconst parserForLanguage=freeze(\\nassign(create(null),parserForLanguageOption));\\n\\nconst languageForExtension=freeze(\\nassign(create(null),languageForExtensionOption));\\n\\n\\nconst compartmentExitModuleImportHook=importHook.exitModuleImportHookMaker({\\nmodules,\\nexitModuleImportHook});\\n\\n\\nconst archive=new reader.ZipReader(archiveBytes,{name:archiveLocation});\\n\\n/* Track all modules that get loaded, all files that are used.*/\\nconst unseen=new Set(archive.files.keys());\\nunseen.size>=2||\\nFail`Archive failed sanity check: should contain at least a compartment map file and one module file in ${q(\\narchiveLocation)\\n}`;\\n\\n/**\\n * @param {string} path\\n */\\nconst get=(path)=>{\\nunseen.delete(path);\\nreturn archive.read(path);};\\n\\n\\nconst compartmentMapBytes=get('compartment-map.json');\\n\\nlet sha512;\\nif(computeSha512!==undefined){\\nsha512=computeSha512(compartmentMapBytes);}\\n\\nif(expectedSha512!==undefined){\\nif(sha512===undefined){\\nthrow Error(\\n`Cannot verify expectedSha512 without also providing computeSha512, for archive ${archiveLocation}`);}\\n\\n\\nif(sha512!==expectedSha512){\\nthrow Error(\\n`Archive compartment map failed a SHA-512 integrity check, expected ${expectedSha512}, got ${sha512}, for archive ${archiveLocation}`);}}\\n\\n\\n\\nconst compartmentMapText=textDecoder.decode(compartmentMapBytes);\\nconst compartmentMap$1=json.parseLocatedJson(\\ncompartmentMapText,\\n'compartment-map.json');\\n\\ncompartmentMap.assertCompartmentMap(compartmentMap$1,archiveLocation);\\n\\nconst{\\ncompartments,\\nentry:{module:moduleSpecifier}}=\\ncompartmentMap$1;\\n\\n/* Archive integrity checks: ensure every module is pre-loaded so its hash*/\\n/* gets checked, and ensure that every file in the archive is used, and*/\\n/* therefore checked.*/\\nif(computeSha512!==undefined){\\nconst makeImportHook=makeArchiveImportHookMaker(\\nget,\\ncompartments,\\narchiveLocation,\\nparserForLanguage,\\ncomputeSha512,\\ncomputeSourceLocation,\\ncompartmentExitModuleImportHook,\\ncomputeSourceMapLocation);\\n\\n/* A weakness of the current Compartment design is that the `modules` map*/\\n/* must be given a module namespace object that passes a brand check.*/\\n/* We don't have module instances for the preload phase, so we supply fake*/\\n/* namespaces.*/\\nconst{compartment,pendingJobsPromise}=link.link(compartmentMap$1,{\\nmakeImportHook,\\nparserForLanguage,\\nlanguageForExtension,\\nmodules:Object.fromEntries(\\nObject.keys(modules||{}).map((specifier)=>{\\nreturn[specifier,{namespace:{}}];})),\\n\\n\\nCompartment});\\n\\n\\nawait pendingJobsPromise;\\n\\nawait compartment.load(moduleSpecifier);\\nunseen.size===0||\\nFail`Archive contains extraneous files: ${q([...unseen])} in ${q(\\narchiveLocation)\\n}`;}\\n\\n\\n/** @type {ExecuteFn} */\\nconst execute=async(options)=>{\\nconst{\\nglobals,\\nmodules,\\ntransforms,\\n__shimTransforms__,\\nCompartment,\\nimportHook:exitModuleImportHook}=\\noptions||{};\\n\\nconst compartmentExitModuleImportHook=importHook.exitModuleImportHookMaker({\\nmodules,\\nexitModuleImportHook});\\n\\nconst makeImportHook=makeArchiveImportHookMaker(\\nget,\\ncompartments,\\narchiveLocation,\\nparserForLanguage,\\ncomputeSha512,\\ncomputeSourceLocation,\\ncompartmentExitModuleImportHook,\\ncomputeSourceMapLocation);\\n\\nconst{compartment,pendingJobsPromise}=link.link(compartmentMap$1,{\\nmakeImportHook,\\nparserForLanguage,\\nlanguageForExtension,\\nglobals,\\nmodules,\\ntransforms,\\n__shimTransforms__,\\nCompartment});\\n\\n\\nawait pendingJobsPromise;\\n\\n/* eslint-disable-next-line dot-notation*/\\nreturn compartment['import'](moduleSpecifier);};\\n\\n\\nreturn{import:execute,sha512};};\\n\\n\\n/**\\n * @param {ReadFn | ReadPowers} readPowers\\n * @param {string} archiveLocation\\n * @param {LoadArchiveOptions} [options]\\n * @returns {Promise<Application>}\\n */\\nconst loadArchive=async(\\nreadPowers,\\narchiveLocation,\\noptions={})=>\\n{\\nconst{read,computeSha512}=powers.unpackReadPowers(readPowers);\\nconst{\\nexpectedSha512,\\ncomputeSourceLocation,\\nmodules,\\ncomputeSourceMapLocation,\\nparserForLanguage,\\nlanguageForExtension}=\\noptions;\\nconst archiveBytes=await read(archiveLocation);\\nreturn parseArchive(archiveBytes,archiveLocation,{\\ncomputeSha512,\\nexpectedSha512,\\ncomputeSourceLocation,\\nmodules,\\ncomputeSourceMapLocation,\\nparserForLanguage,\\nlanguageForExtension});};\\n\\n\\n\\n/**\\n * @param {ReadFn | ReadPowers} readPowers\\n * @param {string} archiveLocation\\n * @param {LoadArchiveOptions} options\\n * @returns {Promise<SomeObject>}\\n */\\nconst importArchive=async(readPowers,archiveLocation,options)=>{\\nconst archive=await loadArchive(readPowers,archiveLocation,options);\\nreturn archive.import(options);};exports.importArchive=importArchive;exports.loadArchive=loadArchive;exports.parseArchive=parseArchive;\",\n \"node_modules/@endo/compartment-mapper/src/import-archive-parsers.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var parsePreCjs=require('./parse-pre-cjs.js');var parseJson=require('./parse-json.js');var parseText=require('./parse-text.js');var parseBytes=require('./parse-bytes.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nparsePreMjs=require('./parse-pre-mjs.js');/* Provides a set of default language behaviors (parsers) suitable for\\n * evaluating archives (zip files with a `compartment-map.json` and a file for\\n * each module) with pre-compiled ESM and CommonJS.\\n *\\n * This module does not entrain a dependency on Babel.\\n */ /** @satisfies {Readonly<ParserForLanguage>} */const defaultParserForLanguage=Object.freeze(/** @type {const} */{'pre-cjs-json':parsePreCjs[\\\"default\\\"],'pre-mjs-json':parsePreMjs[\\\"default\\\"],json:parseJson[\\\"default\\\"],\\ntext:parseText[\\\"default\\\"],\\nbytes:parseBytes[\\\"default\\\"]});exports.defaultParserForLanguage=defaultParserForLanguage;\",\n \"node_modules/@endo/compartment-mapper/src/import-archive.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var importArchiveParsers=require('./import-archive-parsers.js');var importArchiveLite=require('./import-archive-lite.js');/* Provides functions for evaluating modules in an archive (a zip file\\n * with a `compartment-map.json` and a file for a module and each of its\\n * transitive dependencies.)\\n *\\n * These functions accept the URL of an entry module and find its transitive\\n * dependencies through the Node.js `node_modules` conventions.\\n *\\n * These functions use the default parsers in `import-archive-parsers.js`,\\n * which support only pre-compiled ESM and CommonJS.\\n *\\n * See `import-archive-lite.js` for functions that are not coupled to these\\n * parsers or the `node_modules` conventions without necessarily entraining a\\n * dependency on Babel.\\n */\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nconst{assign,create,freeze}=Object;\\n\\n/** @import {Application} from './types.js' */\\n/** @import {ComputeSourceLocationHook} from './types.js' */\\n/** @import {ComputeSourceMapLocationHook} from './types.js' */\\n/** @import {ExecuteOptions} from './types.js' */\\n/** @import {ExitModuleImportHook} from './types.js' */\\n/** @import {HashFn} from './types.js' */\\n/** @import {LoadArchiveOptions} from './types.js' */\\n/** @import {ReadPowers} from './types.js' */\\n/** @import {ParserForLanguage} from './types.js' */\\n\\n/* Must give the type of Compartment a name to capture the external meaning of*/\\n/* Compartment Otherwise @param {typeof Compartment} takes the Compartment to*/\\n/* mean the const variable defined within the function.*/\\n/**/\\n/** @typedef {typeof Compartment} CompartmentConstructor */\\n\\n/**\\n * @typedef {object} Options\\n * @property {string} [expectedSha512]\\n * @property {HashFn} [computeSha512]\\n * @property {Record<string, unknown>} [modules]\\n * @property {ExitModuleImportHook} [importHook]\\n * @property {CompartmentConstructor} [Compartment]\\n * @property {ComputeSourceLocationHook} [computeSourceLocation]\\n * @property {ComputeSourceMapLocationHook} [computeSourceMapLocation]\\n * @property {ParserForLanguage} [parserForLanguage]\\n */\\n\\n/**\\n * Add the default parserForLanguage option.\\n * @param {Options} [options]\\n * @returns {Options}\\n */\\nconst assignParserForLanguage=(options={})=>{\\nconst{parserForLanguage:parserForLanguageOption,...rest}=options;\\n/** @type {ParserForLanguage} */\\nconst parserForLanguage=freeze(\\nassign(create(null),importArchiveParsers.defaultParserForLanguage,parserForLanguageOption));\\n\\nreturn{...rest,parserForLanguage};};\\n\\n\\n/**\\n * @param {Uint8Array} archiveBytes\\n * @param {string} [archiveLocation]\\n * @param {Options} [options]\\n * @returns {Promise<Application>}\\n */\\nconst parseArchive=async(\\narchiveBytes,\\narchiveLocation='<unknown>',\\noptions={})=>\\n\\nimportArchiveLite.parseArchive(\\narchiveBytes,\\narchiveLocation,\\nassignParserForLanguage(options));\\n\\n\\n/**\\n * @param {IMPORT('@endo/zip').ReadFn | ReadPowers} readPowers\\n * @param {string} archiveLocation\\n * @param {LoadArchiveOptions} [options]\\n * @returns {Promise<Application>}\\n */\\nconst loadArchive=async(readPowers,archiveLocation,options)=>\\nimportArchiveLite.loadArchive(\\nreadPowers,\\narchiveLocation,\\nassignParserForLanguage(options));\\n\\n\\n/**\\n * @param {IMPORT('@endo/zip').ReadFn | ReadPowers} readPowers\\n * @param {string} archiveLocation\\n * @param {ExecuteOptions & LoadArchiveOptions} options\\n * @returns {Promise<object>}\\n */\\nconst importArchive=async(readPowers,archiveLocation,options)=>\\nimportArchiveLite.importArchive(\\nreadPowers,\\narchiveLocation,\\nassignParserForLanguage(options));exports.importArchive=importArchive;exports.loadArchive=loadArchive;exports.parseArchive=parseArchive;\",\n \"node_modules/@endo/compartment-mapper/src/import-hook.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var policy=require('./policy.js');var nodeModuleSpecifier=require('./node-module-specifier.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\npowers=require('./powers.js');/* Provides the implementation of each compartment's `importHook` when using\\n * `import.js`, `import-lite.js`, `archive.js`, or `archive-lite.js`.\\n * However, `import-archive.js` and `import-archive-lite.js` use their own variant.\\n *\\n * For building archives, these import hooks create a table of all the modules\\n * in a \\\"working set\\\" of transitive dependencies.\\n */ /* q, as in quote, for quoting strings in error messages.*/const q=JSON.stringify;const{apply}=Reflect;/**\\n * TypeScript cannot be relied upon to deal with the nuances of Readonly, so we\\n * borrow the pass-through type definition of harden here.\\n *\\n * @type {IMPORT('ses').Harden}\\n */const freeze=Object.freeze;\\n\\nconst{hasOwnProperty}=Object.prototype;\\n/**\\n * @param {Record<string, any>} haystack\\n * @param {string} needle\\n */\\nconst has=(haystack,needle)=>apply(hasOwnProperty,haystack,[needle]);\\n\\n/**\\n * @param {string} rel - a relative URL\\n * @param {string} abs - a fully qualified URL\\n * @returns {string}\\n */\\nconst resolveLocation=(rel,abs)=>new URL(rel,abs).toString();\\n\\n/* this is annoying*/\\nfunction getImportsFromRecord(record){\\nreturn(has(record,'record')?record.record.imports:record.imports)||[];}\\n\\n\\n/* Node.js default resolution allows for an incomplement specifier that does not include a suffix.*/\\n/* https://nodejs.org/api/modules.html#all-together*/\\nconst nodejsConventionSearchSuffixes=[\\n/* LOAD_AS_FILE(X)*/\\n'.js',\\n'.json',\\n'.node',\\n/* LOAD_INDEX(X)*/\\n'/index.js',\\n'/index.json',\\n'/index.node'];\\n\\n\\n/**\\n * @param {object} params\\n * @param {Record<string, any>=} params.modules\\n * @param {ExitModuleImportHook=} params.exitModuleImportHook\\n * @returns {ExitModuleImportHook|undefined}\\n */\\nconst exitModuleImportHookMaker=({\\nmodules=undefined,\\nexitModuleImportHook=undefined})=>\\n{\\nif(!modules&&!exitModuleImportHook){\\nreturn undefined;}\\n\\nreturn async(specifier)=>{\\nif(modules&&has(modules,specifier)){\\nconst ns=modules[specifier];\\nreturn Object.freeze({\\nimports:[],\\nexports:ns?Object.keys(ns):[],\\nexecute:(moduleExports)=>{\\nmoduleExports.default=ns;\\nObject.assign(moduleExports,ns);}});}\\n\\n\\n\\nif(exitModuleImportHook){\\nreturn exitModuleImportHook(specifier);}\\n\\nreturn undefined;};};\\n\\n\\n\\n/**\\n * @param {ReadFn|ReadPowers} readPowers\\n * @param {string} baseLocation\\n * @param {object} options\\n * @param {Sources} [options.sources]\\n * @param {Record<string, CompartmentDescriptor>} [options.compartmentDescriptors]\\n * @param {boolean} [options.archiveOnly]\\n * @param {HashFn} [options.computeSha512]\\n * @param {Array<string>} [options.searchSuffixes] - Suffixes to search if the\\n * unmodified specifier is not found.\\n * Pass [] to emulate Node.js’s strict behavior.\\n * The default handles Node.js’s CommonJS behavior.\\n * Unlike Node.js, the Compartment Mapper lifts CommonJS up, more like a\\n * bundler, and does not attempt to vary the behavior of resolution depending\\n * on the language of the importing module.\\n * @param {string} options.entryCompartmentName\\n * @param {string} options.entryModuleSpecifier\\n * @param {ExitModuleImportHook} [options.exitModuleImportHook]\\n * @param {IMPORT('./types.js').SourceMapHook} [options.sourceMapHook]\\n * @returns {ImportHookMaker}\\n */\\nconst makeImportHookMaker=(\\nreadPowers,\\nbaseLocation,\\n{\\nsources=Object.create(null),\\ncompartmentDescriptors=Object.create(null),\\narchiveOnly=false,\\ncomputeSha512=undefined,\\nsearchSuffixes=nodejsConventionSearchSuffixes,\\nsourceMapHook=undefined,\\nentryCompartmentName,\\nentryModuleSpecifier,\\nexitModuleImportHook=undefined})=>\\n\\n{\\n/* Set of specifiers for modules (scoped to compartment) whose parser is not*/\\n/* using heuristics to determine imports.*/\\n/** @type {Map<string, Set<string>>} compartment name ->* module specifier */\\nconst strictlyRequired=new Map([\\n[entryCompartmentName,new Set([entryModuleSpecifier])]]);\\n\\n\\n/**\\n * @param {string} compartmentName\\n */\\nconst strictlyRequiredForCompartment=(compartmentName)=>{\\nlet compartmentStrictlyRequired=strictlyRequired.get(compartmentName);\\nif(compartmentStrictlyRequired!==undefined){\\nreturn compartmentStrictlyRequired;}\\n\\ncompartmentStrictlyRequired=new Set();\\nstrictlyRequired.set(compartmentName,compartmentStrictlyRequired);\\nreturn compartmentStrictlyRequired;};\\n\\n\\n/* per-compartment:*/\\n/** @type {ImportHookMaker} */\\nconst makeImportHook=({\\npackageLocation,\\npackageName:_packageName,\\nattenuators,\\nparse,\\nshouldDeferError,\\ncompartments})=>\\n{\\n/* per-compartment:*/\\npackageLocation=resolveLocation(packageLocation,baseLocation);\\nconst packageSources=sources[packageLocation]||Object.create(null);\\nsources[packageLocation]=packageSources;\\nconst compartmentDescriptor=compartmentDescriptors[packageLocation]||{};\\nconst{modules:moduleDescriptors=Object.create(null)}=\\ncompartmentDescriptor;\\ncompartmentDescriptor.modules=moduleDescriptors;\\n\\n/**\\n * @param {string} specifier\\n * @param {Error} error - error to throw on execute\\n * @returns {StaticModuleType}\\n */\\nconst deferError=(specifier,error)=>{\\n/* strictlyRequired is populated with imports declared by modules whose parser is not using heuristics to figure*/\\n/* out imports. We're guaranteed they're reachable. If the same module is imported and required, it will not*/\\n/* defer, because importing from esm makes it strictly required.*/\\n/* Note that ultimately a situation may arise, with exit modules, where the module never reaches importHook but*/\\n/* its imports do. In that case the notion of strictly required is no longer boolean, it's true,false,noidea.*/\\nif(strictlyRequiredForCompartment(packageLocation).has(specifier)){\\nthrow error;}\\n\\n/* Return a place-holder that'd throw an error if executed*/\\n/* This allows cjs parser to more eagerly find calls to require*/\\n/* - if parser identified a require call that's a local function, execute will never be called*/\\n/* - if actual required module is missing, the error will happen anyway - at execution time*/\\nconst record=freeze({\\nimports:[],\\nexports:[],\\nexecute:()=>{\\nthrow error;}});\\n\\n\\npackageSources[specifier]={\\ndeferredError:error.message};\\n\\n\\nreturn record;};\\n\\n\\n/** @type {ImportHook} */\\nconst importHook=async(moduleSpecifier)=>{\\nawait null;\\ncompartmentDescriptor.retained=true;\\n\\n/* per-module:*/\\n\\n/* In Node.js, an absolute specifier always indicates a built-in or*/\\n/* third-party dependency.*/\\n/* The `moduleMapHook` captures all third-party dependencies, unless*/\\n/* we allow importing any exit.*/\\nif(moduleSpecifier!=='.'&&!moduleSpecifier.startsWith('./')){\\nif(exitModuleImportHook){\\nconst record=await exitModuleImportHook(moduleSpecifier);\\nif(record){\\n/* It'd be nice to check the policy before importing it, but we can only throw a policy error if the*/\\n/* hook returns something. Otherwise, we need to fall back to the 'cannot find' error below.*/\\npolicy.enforceModulePolicy(moduleSpecifier,compartmentDescriptor,{\\nexit:true,\\nerrorHint:`Blocked in loading. ${q(\\nmoduleSpecifier)\\n} was not in the compartment map and an attempt was made to load it as a builtin`});\\n\\nif(archiveOnly){\\n/* Return a place-holder.*/\\n/* Archived compartments are not executed.*/\\nreturn freeze({imports:[],exports:[],execute(){}});}\\n\\n/* note it's not being marked as exit in sources*/\\n/* it could get marked and the second pass, when the archive is being executed, would have the data*/\\n/* to enforce which exits can be dynamically imported*/\\nconst attenuatedRecord=await policy.attenuateModuleHook(\\nmoduleSpecifier,\\nrecord,\\ncompartmentDescriptor.policy,\\nattenuators);\\n\\nreturn attenuatedRecord;}}\\n\\n\\nreturn deferError(\\nmoduleSpecifier,\\nError(\\n`Cannot find external module ${q(\\nmoduleSpecifier)\\n} in package ${packageLocation}`));}\\n\\n\\n\\n\\n/* Collate candidate locations for the moduleSpecifier,*/\\n/* to support Node.js conventions and similar.*/\\nconst candidates=[moduleSpecifier];\\nfor(const candidateSuffix of searchSuffixes){\\ncandidates.push(`${moduleSpecifier}${candidateSuffix}`);}\\n\\n\\nconst{maybeRead}=powers.unpackReadPowers(readPowers);\\n\\nfor(const candidateSpecifier of candidates){\\nconst candidateModuleDescriptor=moduleDescriptors[candidateSpecifier];\\nif(candidateModuleDescriptor!==undefined){\\nconst{compartment:candidateCompartmentName=packageLocation}=\\ncandidateModuleDescriptor;\\nconst candidateCompartment=compartments[candidateCompartmentName];\\nif(candidateCompartment===undefined){\\nthrow Error(\\n`compartment missing for candidate ${candidateSpecifier} in ${candidateCompartmentName}`);}\\n\\n\\n/* modify compartmentMap to include this redirect*/\\nconst candidateCompartmentDescriptor=\\ncompartmentDescriptors[candidateCompartmentName];\\nif(candidateCompartmentDescriptor===undefined){\\nthrow Error(\\n`compartmentDescriptor missing for candidate ${candidateSpecifier} in ${candidateCompartmentName}`);}\\n\\n\\ncandidateCompartmentDescriptor.modules[moduleSpecifier]=\\ncandidateModuleDescriptor;\\n/* return a redirect*/\\n/** @type {RedirectStaticModuleInterface} */\\nconst record={\\nspecifier:candidateSpecifier,\\ncompartment:candidateCompartment};\\n\\nreturn record;}\\n\\n\\n/* Using a specifier as a location.*/\\n/* This is not always valid.*/\\n/* But, for Node.js, when the specifier is relative and not a directory*/\\n/* name, they are usable as URL's.*/\\nconst moduleLocation=resolveLocation(\\ncandidateSpecifier,\\npackageLocation);\\n\\n/* eslint-disable-next-line no-await-in-loop*/\\nconst moduleBytes=await maybeRead(moduleLocation);\\nif(moduleBytes!==undefined){\\n/** @type {string | undefined} */\\nlet sourceMap;\\n/* eslint-disable-next-line no-await-in-loop*/\\nconst envelope=await parse(\\nmoduleBytes,\\ncandidateSpecifier,\\nmoduleLocation,\\npackageLocation,\\n{\\nreadPowers,\\nsourceMapHook:\\nsourceMapHook&&(\\n(nextSourceMapObject)=>{\\nsourceMap=JSON.stringify(nextSourceMapObject);}),\\n\\ncompartmentDescriptor});\\n\\n\\nconst{\\nparser,\\nbytes:transformedBytes,\\nrecord:concreteRecord}=\\nenvelope;\\n\\n/* Facilitate a redirect if the returned record has a different*/\\n/* module specifier than the requested one.*/\\nif(candidateSpecifier!==moduleSpecifier){\\nmoduleDescriptors[moduleSpecifier]={\\nmodule:candidateSpecifier,\\ncompartment:packageLocation};}\\n\\n\\n/** @type {StaticModuleType} */\\nconst record={\\nrecord:concreteRecord,\\nspecifier:candidateSpecifier,\\nimportMeta:{url:moduleLocation}};\\n\\n\\nlet sha512;\\nif(computeSha512!==undefined){\\nsha512=computeSha512(transformedBytes);\\n\\nif(sourceMapHook!==undefined&&sourceMap!==undefined){\\nsourceMapHook(sourceMap,{\\ncompartment:packageLocation,\\nmodule:candidateSpecifier,\\nlocation:moduleLocation,\\nsha512});}}\\n\\n\\n\\n\\nconst packageRelativeLocation=moduleLocation.slice(\\npackageLocation.length);\\n\\npackageSources[candidateSpecifier]={\\nlocation:packageRelativeLocation,\\nsourceLocation:moduleLocation,\\nparser,\\nbytes:transformedBytes,\\nrecord:concreteRecord,\\nsha512};\\n\\nif(!shouldDeferError(parser)){\\nfor(const importSpecifier of getImportsFromRecord(record)){\\nstrictlyRequiredForCompartment(packageLocation).add(\\nnodeModuleSpecifier.resolve(importSpecifier,moduleSpecifier));}}\\n\\n\\n\\n\\nreturn record;}}\\n\\n\\n\\nreturn deferError(\\nmoduleSpecifier,\\n/* TODO offer breadcrumbs in the error message, or how to construct breadcrumbs with another tool.*/\\nError(\\n`Cannot find file for internal module ${q(\\nmoduleSpecifier)\\n} (with candidates ${candidates.\\nmap((x)=>q(x)).\\njoin(', ')}) in package ${packageLocation}`));};\\n\\n\\n\\nreturn importHook;};\\n\\nreturn makeImportHook;};exports.exitModuleImportHookMaker=exitModuleImportHookMaker;exports.makeImportHookMaker=makeImportHookMaker;\",\n \"node_modules/@endo/compartment-mapper/src/json.js\": \"'use strict';\\n\\n\\nObject.defineProperty(exports,'__esModule',{value:true});/* Annotates JSON parse exceptions with the location of the source. */ /* @ts-check*/ /**\\n * Parses JSON and, if necessary, throws exceptions that include the location\\n * of the offending file.\\n *\\n * @param {string} source\\n * @param {string} location\\n */\\nconst parseLocatedJson=(source,location)=>{\\ntry{\\nreturn JSON.parse(source);}\\ncatch(error){\\nif(error instanceof SyntaxError){\\nthrow SyntaxError(`Cannot parse JSON from ${location}, ${error}`);}\\n\\nthrow error;}};exports.parseLocatedJson=parseLocatedJson;\",\n \"node_modules/@endo/compartment-mapper/src/link.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var nodeModuleSpecifier=require('./node-module-specifier.js');var extension=require('./extension.js');var policy=require('./policy.js');/* Provides the linking behavior shared by all Compartment Mapper workflows.\\n * This involves creating and configuring compartments according to the\\n * specifications in a compartment map, and is suitable for compartment maps\\n * that just outline the locations of compartments and their inter-linkage and\\n * also compartment maps that include every module descriptor in the transitive\\n * dependencies of their entry module.\\n */\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nconst{assign,create,entries,freeze,fromEntries}=Object;\\nconst{hasOwnProperty}=Object.prototype;\\nconst{apply}=Reflect;\\nconst{allSettled}=Promise;\\n\\n/**\\n * @template T\\n * @type {(iterable: Iterable<ERef<T>>) => Promise<Array<PromiseSettledResult<T>>>}\\n */\\nconst promiseAllSettled=allSettled.bind(Promise);\\n\\nconst defaultCompartment=Compartment;\\n\\n/* q, as in quote, for strings in error messages.*/\\nconst q=JSON.stringify;\\n\\n/**\\n * @param {Record<string, unknown>} object\\n * @param {string} key\\n * @returns {boolean}\\n */\\nconst has=(object,key)=>apply(hasOwnProperty,object,[key]);\\n\\n/**\\n * Decide if extension is clearly indicating a parser/language for a file\\n *\\n * @param {string} extension\\n * @returns {boolean}\\n */\\nconst extensionImpliesLanguage=(extension)=>extension!=='js';\\n\\n/**\\n * `makeExtensionParser` produces a `parser` that parses the content of a\\n * module according to the corresponding module language, given the extension\\n * of the module specifier and the configuration of the containing compartment.\\n * We do not yet support import assertions and we do not have a mechanism\\n * for validating the MIME type of the module content against the\\n * language implied by the extension or file name.\\n *\\n * @param {Record<string, string>} languageForExtension - maps a file extension\\n * to the corresponding language.\\n * @param {Record<string, string>} languageForModuleSpecifier - In a rare case,\\n * the type of a module is implied by package.json and should not be inferred\\n * from its extension.\\n * @param {ParserForLanguage} parserForLanguage\\n * @param {ModuleTransforms} moduleTransforms\\n * @returns {ParseFn}\\n */\\nconst makeExtensionParser=(\\nlanguageForExtension,\\nlanguageForModuleSpecifier,\\nparserForLanguage,\\nmoduleTransforms)=>\\n{\\nreturn async(bytes,specifier,location,packageLocation,options)=>{\\nawait null;\\nlet language;\\nconst extension$1=extension.parseExtension(location);\\n\\nif(\\n!extensionImpliesLanguage(extension$1)&&\\nhas(languageForModuleSpecifier,specifier))\\n{\\nlanguage=languageForModuleSpecifier[specifier];}else\\n{\\nlanguage=languageForExtension[extension$1]||extension$1;}\\n\\n\\nlet sourceMap;\\n\\nif(has(moduleTransforms,language)){\\ntry{\\n({\\nbytes,\\nparser:language,\\nsourceMap}=\\nawait moduleTransforms[language](\\nbytes,\\nspecifier,\\nlocation,\\npackageLocation,\\n{\\n/* At time of writing, sourceMap is always undefined, but keeping*/\\n/* it here is more resilient if the surrounding if block becomes a*/\\n/* loop for multi-step transforms.*/\\nsourceMap}));}\\n\\n\\ncatch(err){\\nthrow Error(\\n`Error transforming ${q(language)} source in ${q(location)}: ${\\nerr.message\\n}`,\\n{cause:err});}}\\n\\n\\n\\n\\nif(!has(parserForLanguage,language)){\\nthrow Error(\\n`Cannot parse module ${specifier} at ${location}, no parser configured for the language ${language}`);}\\n\\n\\nconst{parse}=/** @type {ParserImplementation} */\\nparserForLanguage[language];\\n\\nreturn parse(bytes,specifier,location,packageLocation,{\\nsourceMap,\\n...options});};};\\n\\n\\n\\n\\n/**\\n * @param {LanguageForExtension} languageForExtension\\n * @param {Record<string, string>} languageForModuleSpecifier - In a rare case, the type of a module\\n * is implied by package.json and should not be inferred from its extension.\\n * @param {ParserForLanguage} parserForLanguage\\n * @param {ModuleTransforms} moduleTransforms\\n * @returns {ParseFn}\\n */\\nconst mapParsers=(\\nlanguageForExtension,\\nlanguageForModuleSpecifier,\\nparserForLanguage,\\nmoduleTransforms={})=>\\n{\\nconst languageForExtensionEntries=[];\\nconst problems=[];\\nfor(const[extension,language]of entries(languageForExtension)){\\nif(has(parserForLanguage,language)){\\nlanguageForExtensionEntries.push([extension,language]);}else\\n{\\nproblems.push(`${q(language)} for extension ${q(extension)}`);}}\\n\\n\\nif(problems.length>0){\\nthrow Error(`No parser available for language: ${problems.join(', ')}`);}\\n\\nreturn makeExtensionParser(\\nfromEntries(languageForExtensionEntries),\\nlanguageForModuleSpecifier,\\nparserForLanguage,\\nmoduleTransforms);};\\n\\n\\n\\n/**\\n * For a full, absolute module specifier like \\\"dependency\\\",\\n * produce the module specifier in the dependency, like \\\".\\\".\\n * For a deeper path like \\\"@org/dep/aux\\\" and a prefix like \\\"@org/dep\\\", produce\\n * \\\"./aux\\\".\\n *\\n * @param {string} moduleSpecifier\\n * @param {string} prefix\\n * @returns {string=}\\n */\\nconst trimModuleSpecifierPrefix=(moduleSpecifier,prefix)=>{\\nif(moduleSpecifier===prefix){\\nreturn'.';}\\n\\nif(moduleSpecifier.startsWith(`${prefix}/`)){\\nreturn`./${moduleSpecifier.slice(prefix.length+1)}`;}\\n\\nreturn undefined;};\\n\\n\\n/**\\n * `makeModuleMapHook` generates a `moduleMapHook` for the `Compartment`\\n * constructor, suitable for Node.js style packages where any module in the\\n * package might be imported.\\n * Since searching for all of these modules up front is either needlessly\\n * costly (on a file system) or impossible (from a web service), we\\n * let the import graph guide our search.\\n * Any module specifier with an absolute prefix should be captured by\\n * the `moduleMap` or `moduleMapHook`.\\n *\\n * @param {CompartmentDescriptor} compartmentDescriptor\\n * @param {Record<string, Compartment>} compartments\\n * @param {string} compartmentName\\n * @param {Record<string, ModuleDescriptor>} moduleDescriptors\\n * @param {Record<string, ModuleDescriptor>} scopeDescriptors\\n * @returns {ModuleMapHook | undefined}\\n */\\nconst makeModuleMapHook=(\\ncompartmentDescriptor,\\ncompartments,\\ncompartmentName,\\nmoduleDescriptors,\\nscopeDescriptors)=>\\n{\\n/**\\n * @param {string} moduleSpecifier\\n * @returns {string | object | undefined}\\n */\\nconst moduleMapHook=(moduleSpecifier)=>{\\ncompartmentDescriptor.retained=true;\\n\\nconst moduleDescriptor=moduleDescriptors[moduleSpecifier];\\nif(moduleDescriptor!==undefined){\\n/* \\\"foreignCompartmentName\\\" refers to the compartment which*/\\n/* may differ from the current compartment*/\\nconst{\\ncompartment:foreignCompartmentName=compartmentName,\\nmodule:foreignModuleSpecifier,\\nexit}=\\nmoduleDescriptor;\\nif(exit!==undefined){\\nreturn undefined;/* fall through to import hook*/}\\n\\nif(foreignModuleSpecifier!==undefined){\\n/* archive goes through foreignModuleSpecifier for local modules too*/\\nif(!moduleSpecifier.startsWith('./')){\\n/* This code path seems to only be reached on subsequent imports of the same specifier in the same compartment.*/\\n/* The check should be redundant and is only left here out of abundance of caution.*/\\npolicy.enforceModulePolicy(moduleSpecifier,compartmentDescriptor,{\\nexit:false,\\nerrorHint:\\n'This check should not be reachable. If you see this error, please file an issue.'});}\\n\\n\\n\\nconst foreignCompartment=compartments[foreignCompartmentName];\\nif(foreignCompartment===undefined){\\nthrow Error(\\n`Cannot import from missing compartment ${q(\\nforeignCompartmentName)\\n}}`);}\\n\\n\\nreturn{\\ncompartment:foreignCompartment,\\nnamespace:foreignModuleSpecifier};}}\\n\\n\\n\\n\\n/* Search for a scope that shares a prefix with the requested module*/\\n/* specifier.*/\\n/* This might be better with a trie, but only a benchmark on real-world*/\\n/* data would tell us whether the additional complexity would translate to*/\\n/* better performance, so this is left readable and presumed slow for now.*/\\nfor(const[scopePrefix,scopeDescriptor]of entries(scopeDescriptors)){\\nconst foreignModuleSpecifier=trimModuleSpecifierPrefix(\\nmoduleSpecifier,\\nscopePrefix);\\n\\n\\nif(foreignModuleSpecifier!==undefined){\\nconst{compartment:foreignCompartmentName}=scopeDescriptor;\\nif(foreignCompartmentName===undefined){\\nthrow Error(\\n`Cannot import from scope ${scopePrefix} due to missing \\\"compartment\\\" property`);}\\n\\n\\nconst foreignCompartment=compartments[foreignCompartmentName];\\nif(foreignCompartment===undefined){\\nthrow Error(\\n`Cannot import from missing compartment ${q(\\nforeignCompartmentName)\\n}`);}\\n\\n\\n\\npolicy.enforceModulePolicy(scopePrefix,compartmentDescriptor,{\\nexit:false,\\nerrorHint:`Blocked in linking. ${q(\\nmoduleSpecifier)\\n} is part of the compartment map and resolves to ${q(\\nforeignCompartmentName)\\n}.`});\\n\\n/* The following line is weird.*/\\n/* Information is flowing backward.*/\\n/* This moduleMapHook writes back to the `modules` descriptor, from the*/\\n/* original compartment map.*/\\n/* So the compartment map that was used to create the compartment*/\\n/* assembly, can then be captured in an archive, obviating the need for*/\\n/* a moduleMapHook when we assemble compartments from the resulting*/\\n/* archive.*/\\nmoduleDescriptors[moduleSpecifier]={\\ncompartment:foreignCompartmentName,\\nmodule:foreignModuleSpecifier};\\n\\nreturn{\\ncompartment:foreignCompartment,\\nnamespace:foreignModuleSpecifier};}}\\n\\n\\n\\n\\n/* No entry in the module map.*/\\n/* Compartments will fall through to their `importHook`.*/\\nreturn undefined;};\\n\\n\\nreturn moduleMapHook;};\\n\\n\\n/**\\n * Assemble a DAG of compartments as declared in a compartment map starting at\\n * the named compartment and building all compartments that it depends upon,\\n * recursively threading the modules exported by one compartment into the\\n * compartment that imports them.\\n * Returns the root of the compartment DAG.\\n * Does not load or execute any modules.\\n * Uses makeImportHook with the given \\\"location\\\" string of each compartment in\\n * the DAG.\\n * Passes the given globals and external modules into the root compartment\\n * only.\\n *\\n * @param {CompartmentMapDescriptor} compartmentMap\\n * @param {LinkOptions} options\\n */\\nconst link=(\\n{entry,compartments:compartmentDescriptors},\\n{\\nresolve=nodeModuleSpecifier.resolve,\\nmakeImportHook,\\nparserForLanguage:parserForLanguageOption={},\\nlanguageForExtension:languageForExtensionOption={},\\nglobals={},\\ntransforms=[],\\nmoduleTransforms={},\\n__shimTransforms__=[],\\narchiveOnly=false,\\nCompartment=defaultCompartment})=>\\n\\n{\\nconst{compartment:entryCompartmentName}=entry;\\n\\n/** @type {Record<string, Compartment>} */\\nconst compartments=create(null);\\n\\n/**\\n * @param {string} attenuatorSpecifier\\n */\\nconst attenuators=policy.makeDeferredAttenuatorsProvider(\\ncompartments,\\ncompartmentDescriptors);\\n\\n\\nconst pendingJobs=[];\\n\\n/** @type {LanguageForExtension} */\\nconst defaultLanguageForExtension=freeze(\\nassign(create(null),languageForExtensionOption));\\n\\n/** @type {ParserForLanguage} */\\nconst parserForLanguage=freeze(\\nassign(create(null),parserForLanguageOption));\\n\\n\\nfor(const[compartmentName,compartmentDescriptor]of entries(\\ncompartmentDescriptors))\\n{\\n/* TODO: The default assignments seem to break type inference*/\\nconst{\\nlocation,\\nname,\\nmodules=create(null),\\nparsers:languageForExtensionOverrides={},\\ntypes:languageForModuleSpecifierOverrides={},\\nscopes=create(null)}=\\ncompartmentDescriptor;\\n\\n/* Capture the default.*/\\n/* The `moduleMapHook` writes back to the compartment map.*/\\ncompartmentDescriptor.modules=modules;\\n\\n/** @type {Record<string, string>} */\\nconst languageForModuleSpecifier=freeze(\\nassign(create(null),languageForModuleSpecifierOverrides));\\n\\n/** @type {LanguageForExtension} */\\nconst languageForExtension=freeze(\\nassign(\\ncreate(null),\\ndefaultLanguageForExtension,\\nlanguageForExtensionOverrides));\\n\\n\\n\\nconst parse=mapParsers(\\nlanguageForExtension,\\nlanguageForModuleSpecifier,\\nparserForLanguage,\\nmoduleTransforms);\\n\\n/** @type {ShouldDeferError} */\\nconst shouldDeferError=(language)=>{\\nif(language&&has(parserForLanguage,language)){\\nreturn(/** @type {ParserImplementation} */parserForLanguage[language].\\nheuristicImports);}else\\n{\\n/* If language is undefined or there's no parser, the error we could consider deferring is surely related to*/\\n/* that. Nothing to throw here.*/\\nreturn false;}};\\n\\n\\n\\n/* If we ever need an alternate resolution algorithm, it should be*/\\n/* indicated in the compartment descriptor and a behavior selected here.*/\\nconst resolveHook=resolve;\\nconst importHook=makeImportHook({\\npackageLocation:location,\\npackageName:name,\\nattenuators,\\nparse,\\nshouldDeferError,\\ncompartments});\\n\\nconst moduleMapHook=makeModuleMapHook(\\ncompartmentDescriptor,\\ncompartments,\\ncompartmentName,\\nmodules,\\nscopes);\\n\\n\\nconst compartment=new Compartment({\\nname:location,\\nresolveHook,\\nimportHook,\\nmoduleMapHook,\\ntransforms,\\n__shimTransforms__,\\n__options__:true});\\n\\n\\nif(!archiveOnly){\\npolicy.attenuateGlobals(\\ncompartment.globalThis,\\nglobals,\\ncompartmentDescriptor.policy,\\nattenuators,\\npendingJobs,\\ncompartmentDescriptor.name);}\\n\\n\\n\\ncompartments[compartmentName]=compartment;}\\n\\n\\nconst compartment=compartments[entryCompartmentName];\\nif(compartment===undefined){\\nthrow Error(\\n`Cannot assemble compartment graph because the root compartment named ${q(\\nentryCompartmentName)\\n} is missing from the compartment map`);}\\n\\n\\nconst attenuatorsCompartment=compartments[policy.ATTENUATORS_COMPARTMENT];\\n\\nreturn{\\ncompartment,\\ncompartments,\\nattenuatorsCompartment,\\npendingJobsPromise:promiseAllSettled(pendingJobs).then(\\n/** @param {PromiseSettledResult<unknown>[]} results */(results)=>{\\nconst errors=results.\\nfilter((result)=>result.status==='rejected').\\nmap(\\n/** @param {PromiseRejectedResult} result */(result)=>\\nresult.reason);\\n\\nif(errors.length>0){\\nthrow Error(\\n`Globals attenuation errors: ${errors.\\nmap((error)=>error.message).\\njoin(', ')}`);}})};};\\n\\n\\n\\n\\n\\n\\n\\n/**\\n * @param {CompartmentMapDescriptor} compartmentMap\\n * @param {LinkOptions} options\\n * @deprecated Use {@link link}.\\n */\\nconst assemble=(compartmentMap,options)=>\\nlink(compartmentMap,options).compartment;exports.assemble=assemble;exports.link=link;exports.mapParsers=mapParsers;\",\n \"node_modules/@endo/compartment-mapper/src/node-module-specifier.js\": \"'use strict';\\n\\n\\n\\n\\n\\n\\nObject.defineProperty(exports,'__esModule',{value:true});/* Provides functions for interacting with Node.js module specifiers in\\n * their canonical form.\\n * This is a kind of path math that is platform-agnostic.\\n */ /* @ts-check*/ /* q, as in quote, for error messages.*/const q=JSON.stringify;/**\\n * Advances a partial module specifier solution by following the path\\n * components in the given problem.\\n * The problem may not produce a path that escapes the solution, that is, the\\n * problem may not traverse up from an empty solution.\\n * `Solve` returns false if the problem attempts to escape.\\n * Advanding a partial solution is the core of `resolve`, `join`, and\\n * `relativize`, which have different invariants.\\n *\\n * @param {Array<string>} solution - fully resolved path components, including\\n * any from a prior path resolution initially.\\n * @param {Array<string>} problem - partially resolved path components, that\\n * is, including '.' and '..' components.\\n * @returns {boolean} whether the solver terminated early because of a\\n * nonsensical attempt to traverse above the root directory.\\n */\\nconst solve=(solution,problem)=>{\\nfor(const part of problem){\\nif(part==='.'||part===''){\\n/* no-op*/}else\\nif(part==='..'){\\nif(solution.length===0){\\nreturn false;}\\n\\nsolution.pop();}else\\n{\\nsolution.push(part);}}\\n\\n\\nreturn true;};\\n\\n\\n/**\\n * `Resolve` computes the full module specifier for a given imported module specifier\\n * relative to the referrer module specifier.\\n * In Node.js compartments, the referrer must be an internal module specifier\\n * in the context of a compartment, and all internal module specifiers begin\\n * with a \\\".\\\" path component.\\n * The referent may be either internal or external.\\n * In Node.js, fully resolved paths are valid module specifiers, but these\\n * paths that begin with / are disallowed as they could be used to defeat\\n * compartment containment.\\n *\\n * @param {string} spec - a path to resolve.\\n * @param {string} referrer - the fully resolved path of referrer module.\\n * @returns {string} the fully resolved path.\\n */\\nconst resolve=(spec,referrer)=>{\\nspec=String(spec||'');\\nreferrer=String(referrer||'');\\n\\nif(spec.startsWith('/')){\\nthrow Error(`Module specifier ${q(spec)} must not begin with \\\"/\\\"`);}\\n\\nif(!referrer.startsWith('./')){\\nthrow Error(`Module referrer ${q(referrer)} must begin with \\\"./\\\"`);}\\n\\n\\nconst specParts=spec.split('/');\\nconst solution=[];\\nconst problem=[];\\nif(specParts[0]==='.'||specParts[0]==='..'){\\nconst referrerParts=referrer.split('/');\\nproblem.push(...referrerParts);\\nproblem.pop();\\nsolution.push('.');}\\n\\nproblem.push(...specParts);\\n\\nif(!solve(solution,problem)){\\nthrow Error(\\n`Module specifier ${q(spec)} via referrer ${q(\\nreferrer)\\n} must not traverse behind an empty path`);}\\n\\n\\n\\nreturn solution.join('/');};\\n\\n\\n/**\\n * To construct a module map from a node_modules package, inter-package linkage\\n * requires connecting a full base module specifier like \\\"dependency-package\\\"\\n * to the other package's full internal module specifier like \\\".\\\" or\\n * \\\"./utility\\\", to form a local full module specifier like \\\"dependency-package\\\"\\n * or \\\"dependency-package/utility\\\".\\n * This type of join may assert that the base is absolute and the referrent is\\n * relative.\\n *\\n * @param {string} base - the fully resolved path of a module.\\n * @param {string} spec - the partially resolved path of another module.\\n * @returns {string} the fully resolved path of the specified module.\\n */\\nconst join=(base,spec)=>{\\nspec=String(spec||'');\\nbase=String(base||'');\\n\\nconst specParts=spec.split('/');\\nconst baseParts=base.split('/');\\n\\nif(specParts.length>1&&specParts[0]===''){\\nthrow Error(`Module specifier ${q(spec)} must not start with \\\"/\\\"`);}\\n\\nif(baseParts[0]==='.'||baseParts[0]==='..'){\\nthrow Error(`External module specifier ${q(base)} must be absolute`);}\\n\\nif(specParts[0]!=='.'){\\nthrow Error(`Internal module specifier ${q(spec)} must be relative`);}\\n\\n\\nconst solution=[];\\nif(!solve(solution,specParts)){\\nthrow Error(\\n`Module specifier ${q(spec)} via base ${q(\\nbase)\\n} must not refer to a module outside of the base`);}\\n\\n\\n\\nreturn[base,...solution].join('/');};\\n\\n\\n/**\\n * Relativize turns absolute identifiers into relative identifiers.\\n * In package.json, internal module identifiers can be either relative or\\n * absolute, but compartments backed by node_modules always use relative module\\n * specifiers for internal linkage.\\n *\\n * @param {string} spec - a module specifier that of a local module, that might\\n * be erroneously framed without an initial '.' path component.\\n * @returns {string} the idempotent module specifier, ensured to begin with\\n * '.'.\\n */\\nconst relativize=(spec)=>{\\nspec=String(spec||'');\\n\\nconst solution=[];\\nif(!solve(solution,spec.split('/'))){\\nthrow Error(\\n`Module specifier ${q(spec)} must not traverse behind an empty path`);}\\n\\n\\n\\nreturn['.',...solution].join('/');};exports.join=join;exports.relativize=relativize;exports.resolve=resolve;\",\n \"node_modules/@endo/compartment-mapper/src/parse-bytes.js\": \"'use strict';\\n\\n\\n\\n\\n\\nObject.defineProperty(exports,'__esModule',{value:true});/* Provides rudimentary support for treating an arbitrary file as a module that\\n * exports the bytes of that file.\\n */ /* @ts-check*/ /**\\n * TypeScript cannot be relied upon to deal with the nuances of Readonly, so we\\n * borrow the pass-through type definition of harden here.\\n *\\n * @type {IMPORT('ses').Harden}\\n */const freeze=Object.freeze;\\n/** @type {IMPORT('./types.js').ParseFn} */\\nconst parseBytes=async(\\nbytes,\\n_specifier,\\n_location,\\n_packageLocation)=>\\n{\\n/* Snapshot ArrayBuffer*/\\nconst buffer=new ArrayBuffer(bytes.length);\\nconst bytesView=new Uint8Array(buffer);\\nbytesView.set(bytes);\\n\\n/** @type {Array<string>} */\\nconst imports=freeze([]);\\n\\n/**\\n * @param {object} exports\\n */\\nconst execute=(exports)=>{\\nexports.default=buffer;};\\n\\n\\nreturn{\\nparser:'bytes',\\nbytes,\\nrecord:freeze({\\nimports,\\nexports:freeze(['default']),\\nexecute:freeze(execute)})};};\\n\\n\\n\\n\\n/** @type {IMPORT('./types.js').ParserImplementation} */\\nvar parserBytes={\\nparse:parseBytes,\\nheuristicImports:false};exports[\\\"default\\\"]=parserBytes;exports.parseBytes=parseBytes;\",\n \"node_modules/@endo/compartment-mapper/src/parse-cjs-shared-export-wrapper.js\": \"'use strict';\\n\\n\\n\\n\\n\\n\\n\\nObject.defineProperty(exports,'__esModule',{value:true});/* Provides shared functionality for {@link parse-cjs.js} and {@link\\n * parse-archive-cjs.js} toward importing or archiving CommonJS as a virtual\\n * module source.\\n */ /* @ts-check*/ /** @import {ReadFn} from './types.js' */ /** @import {ReadPowers} from './types.js' */const{apply}=Reflect;const{freeze,keys,create,hasOwnProperty,defineProperty}=Object;\\n\\n/**\\n * @param {object} object\\n * @param {string} key\\n * @returns {boolean}\\n */\\nconst has=(object,key)=>apply(hasOwnProperty,object,[key]);\\n\\nconst noTrailingSlash=(path)=>{\\nconst l=path.length-1;\\nreturn path[l]==='\\\\\\\\'||path[l]==='/'?path.slice(0,-1):path;};\\n\\n\\n/**\\n * Generates values for __filename and __dirname from location\\n *\\n * @param {ReadPowers | ReadFn | undefined} readPowers\\n * @param {string} location\\n * @returns {{\\n * filename:string|null,\\n * dirname: string|null\\n * }}\\n */\\nconst getModulePaths=(readPowers,location)=>{\\nif(\\nreadPowers&&\\ntypeof readPowers!=='function'&&\\nreadPowers.fileURLToPath)\\n{\\nlet filename=location;\\nlet dirname;\\ntry{\\ndirname=new URL('./',filename).href;}\\ncatch(_){\\nreturn{\\nfilename:null,\\ndirname:null};}\\n\\n\\n\\nfilename=readPowers.fileURLToPath(filename).toString();\\ndirname=noTrailingSlash(readPowers.fileURLToPath(dirname).toString());\\n\\nreturn{\\nfilename,\\ndirname};}else\\n\\n{\\nreturn{\\nfilename:null,\\ndirname:null};}};\\n\\n\\n\\n\\n/**\\n * ModuleEnvironmentRecord wrapper\\n * Creates shared export processing primitives to be used both Location and Archive usecases of cjs\\n *\\n * @param {object} in\\n * @param {object} in.moduleEnvironmentRecord\\n * @param {Compartment} in.compartment\\n * @param {Record<string, string>} in.resolvedImports\\n * @param {string} in.location\\n * @param {ReadFn | ReadPowers | undefined} in.readPowers\\n * @returns {{\\n * module: { exports: any },\\n * moduleExports: any,\\n * afterExecute: Function,\\n * require: Function,\\n * }}\\n */\\nconst wrap=({\\nmoduleEnvironmentRecord,\\ncompartment,\\nresolvedImports,\\nlocation,\\nreadPowers})=>\\n{\\n/* This initial default value makes things like exports.hasOwnProperty() work in cjs.*/\\nmoduleEnvironmentRecord.default=create(\\ncompartment.globalThis.Object.prototype);\\n\\n\\n/* Set all exported properties on the defult and call namedExportProp to add them on the namespace for import *.*/\\n/* Root namespace is only accessible for imports. Requiring from cjs gets the default field of the namespace.*/\\nconst promoteToNamedExport=(prop,value)=>{\\n/* __esModule needs to be present for typescript-compiled modules to work, can't be skipped*/\\nif(prop!=='default'){\\nmoduleEnvironmentRecord[prop]=value;}};\\n\\n\\n\\nconst redefined=new Set();\\n\\nconst originalExports=new Proxy(moduleEnvironmentRecord.default,{\\nset(_target,prop,value){\\npromoteToNamedExport(prop,value);\\nmoduleEnvironmentRecord.default[prop]=value;\\nreturn true;},\\n\\ndefineProperty(target,prop,descriptor){\\nif(has(descriptor,'value')){\\n/* This will result in non-enumerable properties being enumerable for named import purposes. We could check*/\\n/* enumerable here, but I don't see possible benefits of such restriction.*/\\npromoteToNamedExport(prop,descriptor.value);}\\n\\n/* All the defineProperty trickery with getters used for lazy initialization will work. The trap is here only to*/\\n/* elevate the values with namedExportProp whenever possible. Replacing getters with wrapped ones to facilitate*/\\n/* propagating the lazy value to the namespace is not possible because defining a property with modified*/\\n/* descriptor.get in the trap will cause an error.*/\\n/* Object.defineProperty is used instead of Reflect.defineProperty for better error messages.*/\\ndefineProperty(target,prop,descriptor);\\n/* Make a note to propagate the value from the getter to the module*/\\n/* environment record when the module finishes executing.*/\\nredefined.add(prop);\\nreturn true;}});\\n\\n\\n\\nlet finalExports=originalExports;\\n\\nconst module=freeze({\\nget exports(){\\nreturn finalExports;},\\n\\nset exports(value){\\nfinalExports=value;}});\\n\\n\\n\\nconst require=(/** @type {string} */importSpecifier)=>{\\nif(!has(resolvedImports,importSpecifier)){\\nthrow new Error(\\n`Cannot find module \\\"${importSpecifier}\\\" in \\\"${location}\\\"`);}\\n\\n\\nconst namespace=compartment.importNow(resolvedImports[importSpecifier]);\\n/* If you read this file carefully, you'll see it's not possible for a cjs module to not have the default anymore.*/\\n/* It's currently possible to require modules that were not created by this file though.*/\\nif(has(namespace,'default')){\\nreturn namespace.default;}else\\n{\\nreturn namespace;}};\\n\\n\\nif(typeof readPowers==='object'&&readPowers.requireResolve){\\nconst{requireResolve}=readPowers;\\nrequire.resolve=freeze((specifier,options)=>\\nrequireResolve(location,specifier,options));}else\\n\\n{\\nrequire.resolve=freeze((specifier)=>{\\nconst error=Error(\\n`Cannot find module '${specifier}'\\\\nAdd requireResolve to Endo Compartment Mapper readPowers.`);\\n\\ndefineProperty(error,'code',{value:'MODULE_NOT_FOUND'});\\nthrow error;});}\\n\\n\\n\\nfreeze(require);\\n\\nconst afterExecute=()=>{\\nconst exportsHaveBeenOverwritten=finalExports!==originalExports;\\n/* Promotes keys from redefined module.export to top level namespace for import **/\\n/* Note: We could do it less consistently but closer to how node does it if we iterated over exports detected by*/\\n/* the lexer.*/\\nif(exportsHaveBeenOverwritten){\\nmoduleEnvironmentRecord.default=finalExports;\\nfor(const prop of keys(moduleEnvironmentRecord.default||{})){\\nif(prop!=='default'){\\nmoduleEnvironmentRecord[prop]=moduleEnvironmentRecord.default[prop];}}}else\\n\\n\\n{\\nfor(const prop of redefined){\\nmoduleEnvironmentRecord[prop]=moduleEnvironmentRecord.default[prop];}}};\\n\\n\\n\\n\\nreturn{\\nmodule,\\nmoduleExports:originalExports,\\nafterExecute,\\nrequire};};exports.getModulePaths=getModulePaths;exports.wrap=wrap;\",\n \"node_modules/@endo/compartment-mapper/src/parse-json.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var\\n\\n\\n\\n\\n\\njson=require('./json.js');/* Provides language support for importing JSON modules. */ /**\\n * TypeScript cannot be relied upon to deal with the nuances of Readonly, so we\\n * borrow the pass-through type definition of harden here.\\n *\\n * @type {IMPORT('ses').Harden}\\n */\\nconst freeze=Object.freeze;\\n\\nconst textDecoder=new TextDecoder();\\n\\n/** @type {IMPORT('./types.js').ParseFn} */\\nconst parseJson=async(\\nbytes,\\n_specifier,\\nlocation,\\n_packageLocation)=>\\n{\\nconst source=textDecoder.decode(bytes);\\nconst imports=freeze([]);\\n\\n/**\\n * @param {object} exports\\n */\\nconst execute=(exports)=>{\\nexports.default=json.parseLocatedJson(source,location);};\\n\\nreturn{\\nparser:'json',\\nbytes,\\nrecord:freeze({\\nimports,\\nexports:freeze(['default']),\\nexecute:freeze(execute)})};};\\n\\n\\n\\n\\n/** @type {IMPORT('./types.js').ParserImplementation} */\\nvar parserJson={\\nparse:parseJson,\\nheuristicImports:false};exports[\\\"default\\\"]=parserJson;exports.parseJson=parseJson;\",\n \"node_modules/@endo/compartment-mapper/src/parse-pre-cjs.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var json=require('./json.js');var parseCjsSharedExportWrapper=require('./parse-cjs-shared-export-wrapper.js');/* Provides language-specific behavior for importing pre-compiled CommonJS.\\n * Pre-compiled CommonJS is a module in JSON format that describes its imports,\\n * exports, and source to execute in the presence of `require`, `module`, and\\n * `exports`.\\n */\\n\\n\\n\\n\\n\\n\\nconst textDecoder=new TextDecoder();\\n\\n/** @type {IMPORT('./types.js').ParseFn} */\\nconst parsePreCjs=async(\\nbytes,\\n_specifier,\\nlocation,\\n_packageLocation,\\n{readPowers}={})=>\\n{\\nconst text=textDecoder.decode(bytes);\\nconst{source,imports,exports,reexports}=json.parseLocatedJson(\\ntext,\\nlocation);\\n\\n\\nconst{filename,dirname}=await parseCjsSharedExportWrapper.getModulePaths(readPowers,location);\\n\\n/**\\n * @param {object} moduleEnvironmentRecord\\n * @param {Compartment} compartment\\n * @param {Record<string, string>} resolvedImports\\n */\\nconst execute=(moduleEnvironmentRecord,compartment,resolvedImports)=>{\\nconst functor=compartment.evaluate(source);\\n\\nconst{require,moduleExports,module,afterExecute}=parseCjsSharedExportWrapper.wrap({\\nmoduleEnvironmentRecord,\\ncompartment,\\nresolvedImports,\\nlocation,\\nreadPowers});\\n\\n\\nfunctor(require,moduleExports,module,filename,dirname);\\n\\nafterExecute();};\\n\\n\\nreturn{\\nparser:'pre-cjs-json',\\nbytes,\\nrecord:{\\nimports,\\nreexports,\\nexports,\\nexecute}};};\\n\\n\\n\\n\\n/** @type {IMPORT('./types.js').ParserImplementation} */\\nvar parserPreCjs={\\nparse:parsePreCjs,\\nheuristicImports:true};exports[\\\"default\\\"]=parserPreCjs;exports.parsePreCjs=parsePreCjs;\",\n \"node_modules/@endo/compartment-mapper/src/parse-pre-mjs.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var json=require('./json.js');/* Provides language-specific behaviors for importing pre-compiled ESM.\\n * Pre-compiling or translating ESM from a module to a script with a\\n * calling-convention is necessary to prepare an archive so that it can be\\n * imported by the SES shim without entraining a dependency on Babel.\\n */\\n\\n\\n\\n\\n\\nconst textDecoder=new TextDecoder();\\n\\n/** @type {IMPORT('./types.js').ParseFn} */\\nconst parsePreMjs=async(\\nbytes,\\n_specifier,\\nlocation,\\n_packageLocation,\\n{sourceMapUrl}={})=>\\n{\\nconst text=textDecoder.decode(bytes);\\nconst record=json.parseLocatedJson(text,location);\\nif(sourceMapUrl){\\n/* eslint-disable-next-line no-underscore-dangle*/\\nrecord.__syncModuleProgram__+=`//# sourceMappingURL=${sourceMapUrl}\\\\n`;}else\\n{\\n/* eslint-disable-next-line no-underscore-dangle*/\\nrecord.__syncModuleProgram__+=`//# sourceURL=${location}\\\\n`;}\\n\\nreturn{\\nparser:'pre-mjs-json',\\nbytes,\\nrecord};};\\n\\n\\n\\n/** @type {IMPORT('./types.js').ParserImplementation} */\\nvar parserPreMjs={\\nparse:parsePreMjs,\\nheuristicImports:false};exports[\\\"default\\\"]=parserPreMjs;exports.parsePreMjs=parsePreMjs;\",\n \"node_modules/@endo/compartment-mapper/src/parse-text.js\": \"'use strict';\\n\\n\\n\\n\\n\\n\\nObject.defineProperty(exports,'__esModule',{value:true});/* Provides language-behaviors for importing a module as a document that\\n * exports itself as a string based on a UTF-8 interpretation of the module's\\n * text.\\n */ /* @ts-check*/ /**\\n * TypeScript cannot be relied upon to deal with the nuances of Readonly, so we\\n * borrow the pass-through type definition of harden here.\\n *\\n * @type {IMPORT('ses').Harden}\\n */const freeze=Object.freeze;const textDecoder=new TextDecoder();\\n\\n/** @type {IMPORT('./types.js').ParseFn} */\\nconst parseText=async(\\nbytes,\\n_specifier,\\n_location,\\n_packageLocation)=>\\n{\\nconst text=textDecoder.decode(bytes);\\n\\n/** @type {Array<string>} */\\nconst imports=freeze([]);\\n\\n/**\\n * @param {object} exports\\n */\\nconst execute=(exports)=>{\\nexports.default=text;};\\n\\n\\nreturn{\\nparser:'text',\\nbytes,\\nrecord:freeze({\\nimports,\\nexports:freeze(['default']),\\nexecute:freeze(execute)})};};\\n\\n\\n\\n\\n/** @type {IMPORT('./types.js').ParserImplementation} */\\nvar parserText={\\nparse:parseText,\\nheuristicImports:false};exports[\\\"default\\\"]=parserText;exports.parseText=parseText;\",\n \"node_modules/@endo/compartment-mapper/src/policy-format.js\": \"'use strict';\\n\\n\\n\\n\\n\\n\\nObject.defineProperty(exports,'__esModule',{value:true});/* Provides functions for enforcing compartment-map linkage and global variable\\n * policies for each compartment.\\n */ /* @ts-check*/ /** @import {SomePackagePolicy} from './types.js' */ /** @import {SomePolicy} from './types.js' */const{entries,keys}=Object;\\nconst{isArray}=Array;\\nconst q=JSON.stringify;\\n\\nconst ATTENUATOR_KEY='attenuate';\\nconst ATTENUATOR_PARAMS_KEY='params';\\nconst WILDCARD_POLICY_VALUE='any';\\nconst POLICY_FIELDS_LOOKUP=/** @type {const} */[\\n'builtins',\\n'globals',\\n'packages'];\\n\\n\\n/**\\n *\\n * @param {IMPORT('./types.js').PackagePolicy} packagePolicy\\n * @param {'builtins'|'globals'|'packages'} field\\n * @param {string} itemName\\n * @returns {boolean | IMPORT('./types.js').AttenuationDefinition}\\n */\\nconst policyLookupHelper=(packagePolicy,field,itemName)=>{\\nif(!POLICY_FIELDS_LOOKUP.includes(field)){\\nthrow Error(`Invalid field ${q(field)}`);}\\n\\nif(\\ntypeof packagePolicy!=='object'||\\npackagePolicy===null||\\n!packagePolicy[field])\\n{\\nreturn false;}\\n\\n\\nif(packagePolicy[field]===WILDCARD_POLICY_VALUE){\\nreturn true;}\\n\\n\\nconst value=/** @type {IMPORT('./types.js').AttenuationDefinition} */\\npackagePolicy[field];\\n\\nif(itemName in value){\\nreturn value[itemName];}\\n\\nreturn false;};\\n\\n\\n/**\\n * Type guard; checks if the policy value is set to the wildcard value to allow everything\\n *\\n * @param {unknown} policyValue\\n * @returns {policyValue is IMPORT('./types.js').WildcardPolicy}\\n */\\nconst isAllowingEverything=(policyValue)=>\\npolicyValue===WILDCARD_POLICY_VALUE;\\n\\n/**\\n * Type guard for `AttenuationDefinition`\\n * @param {unknown} allegedDefinition\\n * @returns {allegedDefinition is IMPORT('./types.js').AttenuationDefinition}\\n */\\nconst isAttenuationDefinition=(allegedDefinition)=>{\\nreturn Boolean(\\nallegedDefinition&&\\ntypeof allegedDefinition==='object'&&\\ntypeof allegedDefinition[ATTENUATOR_KEY]==='string'||/* object with attenuator name*/\\nisArray(allegedDefinition)/* params for default attenuator*/);};\\n\\n\\n\\n/**\\n *\\n * @param {IMPORT('./types.js').AttenuationDefinition} attenuationDefinition\\n * @returns {IMPORT('./types.js').UnifiedAttenuationDefinition}\\n */\\nconst getAttenuatorFromDefinition=(attenuationDefinition)=>{\\nif(!isAttenuationDefinition(attenuationDefinition)){\\nthrow Error(\\n`Invalid attenuation ${q(\\nattenuationDefinition)\\n}, must be an array of params for default attenuator or an object with an attenuator key`);}\\n\\n\\nif(isArray(attenuationDefinition)){\\nreturn{\\ndisplayName:'<default attenuator>',\\nspecifier:null,\\nparams:attenuationDefinition};}else\\n\\n{\\nreturn{\\ndisplayName:attenuationDefinition[ATTENUATOR_KEY],\\nspecifier:attenuationDefinition[ATTENUATOR_KEY],\\nparams:attenuationDefinition[ATTENUATOR_PARAMS_KEY]};}};\\n\\n\\n\\n\\n/* TODO: should be a type guard*/\\nconst isRecordOf=(item,predicate)=>{\\nif(typeof item!=='object'||item===null||isArray(item)){\\nreturn false;}\\n\\nreturn entries(item).every(([key,value])=>predicate(value,key));};\\n\\n\\n/**\\n * Type guard for `boolean`\\n * @param {unknown} item\\n * @returns {item is boolean}\\n */\\nconst isBoolean=(item)=>typeof item==='boolean';\\n\\n/* TODO: should be a type guard*/\\nconst predicateOr=\\n(...predicates)=>\\n(item)=>\\npredicates.some((p)=>p(item));\\n\\n/**\\n * @param {unknown} item\\n * @returns {item is IMPORT('./types.js').PolicyItem}\\n */\\nconst isPolicyItem=(item)=>\\nitem===undefined||\\nitem===WILDCARD_POLICY_VALUE||\\nisRecordOf(item,isBoolean);\\n\\n/**\\n * This asserts (i.e., throws) that `allegedPackagePolicy` is a valid `PackagePolicy`.\\n *\\n * Mild-mannered during the day, but fights crime at night as a type guard.\\n *\\n * @param {unknown} allegedPackagePolicy - Alleged `PackagePolicy` to test\\n * @param {string} path - Path in the `Policy` object; used for error messages only\\n * @param {string} [url] - URL of the policy file; used for error messages only\\n * @returns {asserts allegedPackagePolicy is SomePackagePolicy|undefined}\\n */\\nconst assertPackagePolicy=(allegedPackagePolicy,path,url)=>{\\nif(allegedPackagePolicy===undefined){\\nreturn;}\\n\\nconst inUrl=url?` in ${q(url)}`:'';\\n\\nconst packagePolicy=Object(allegedPackagePolicy);\\nassert(\\nallegedPackagePolicy===packagePolicy&&!isArray(allegedPackagePolicy),\\n`${path} must be an object, got ${q(allegedPackagePolicy)}${inUrl}`);\\n\\nconst{\\npackages,\\nbuiltins,\\nglobals,\\nnoGlobalFreeze,\\ndefaultAttenuator:_ignore,/* a carve out for the default attenuator in compartment map*/\\n/* eslint-disable-next-line no-unused-vars*/\\noptions,/* any extra options*/\\n...extra}=\\n/** @type {SomePackagePolicy} */packagePolicy;\\n\\nassert(\\nkeys(extra).length===0,\\n`${path} must not have extra properties, got ${q(keys(extra))}${inUrl}`);\\n\\n\\nassert(\\nnoGlobalFreeze===undefined||typeof noGlobalFreeze==='boolean',\\n`${path}.noGlobalFreeze must be a boolean, got ${q({\\nnoGlobalFreeze})\\n}${inUrl}`);\\n\\n\\nisPolicyItem(packages)||\\nassert.fail(\\n`${path}.packages must be a record of booleans, got ${q({\\npackages})\\n}${inUrl}`);\\n\\n\\nisPolicyItem(globals)||\\nisAttenuationDefinition(globals)||\\nassert.fail(\\n`${path}.globals must be a record of booleans or a single attenuation, got ${q(\\n{\\nglobals})\\n\\n}${inUrl}`);\\n\\n\\nisPolicyItem(builtins)||\\nisRecordOf(builtins,predicateOr(isBoolean,isAttenuationDefinition))||\\nassert.fail(\\n`${path}.builtins must be a record of booleans or attenuations, got ${q({\\nbuiltins})\\n}${inUrl}`);};\\n\\n\\n\\n/**\\n * This asserts (i.e., throws) that `allegedPolicy` is a valid `Policy`\\n *\\n * It also moonlights as a type guard.\\n *\\n * @param {unknown} allegedPolicy - Alleged `Policy` to test\\n * @returns {asserts allegedPolicy is SomePolicy|undefined}\\n */\\nconst assertPolicy=(allegedPolicy)=>{\\nif(allegedPolicy===undefined){\\nreturn;}\\n\\nconst policy=Object(allegedPolicy);\\nassert(\\nallegedPolicy===policy&&!Array.isArray(policy),\\n`policy must be an object, got ${allegedPolicy}`);\\n\\n\\nconst{resources,entry,defaultAttenuator,...extra}=policy;\\nassert(\\nkeys(extra).length===0,\\n`policy must not have extra properties, got ${q(keys(extra))}`);\\n\\n\\nassert(\\ntypeof resources==='object'&&resources!==null&&!isArray(resources),\\n`policy.resources must be an object, got ${q(resources)}`);\\n\\nassert(\\n!defaultAttenuator||typeof defaultAttenuator==='string',\\n`policy.defaultAttenuator must be a string, got ${q(defaultAttenuator)}`);\\n\\n\\nassertPackagePolicy(entry,`policy.entry`);\\n\\nfor(const[key,value]of entries(resources)){\\nassertPackagePolicy(value,`policy.resources[\\\"${key}\\\"]`);}};exports.assertPackagePolicy=assertPackagePolicy;exports.assertPolicy=assertPolicy;exports.getAttenuatorFromDefinition=getAttenuatorFromDefinition;exports.isAllowingEverything=isAllowingEverything;exports.isAttenuationDefinition=isAttenuationDefinition;exports.policyLookupHelper=policyLookupHelper;\",\n \"node_modules/@endo/compartment-mapper/src/policy.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var policyFormat=require('./policy-format.js');/* Provides mechanisms for interacting with Compartment Map runtime policies.\\n */\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nconst{create,entries,values,assign,freeze,getOwnPropertyDescriptors}=\\nObject;\\nconst{ownKeys}=Reflect;\\nconst q=JSON.stringify;\\n\\n/**\\n * Const string to identify the internal attenuators compartment\\n */\\nconst ATTENUATORS_COMPARTMENT='<ATTENUATORS>';\\n\\n/**\\n * Copies properties (optionally limited to a specific list) from one object\\n * to another. By default, copies all enumerable, own, string- and\\n * symbol-named properties.\\n *\\n * @param {object} from\\n * @param {object} to\\n * @param {Array<string | symbol>} [list]\\n * @returns {object}\\n */\\nconst selectiveCopy=(from,to,list)=>{\\nif(!list){\\nconst descs=getOwnPropertyDescriptors(from);\\nlist=ownKeys(from).filter(\\n(key)=>\\n/* @ts-expect-error TypeScript still confused about a symbol as index*/\\ndescs[key].enumerable);}\\n\\n\\nfor(let index=0;index<list.length;index+=1){\\nconst key=list[index];\\n/* If an endowment is missing, global value is undefined.*/\\n/* This is an expected behavior if globals are used for platform feature detection*/\\nto[key]=from[key];}\\n\\nreturn to;};\\n\\n\\n/**\\n * Parses an attenuation definition for attenuator names\\n *\\n * Note: this function is recursive\\n * @param {string[]} attenuators - List of attenuator names; may be mutated\\n * @param {IMPORT('./types.js').AttenuationDefinition|IMPORT('./types.js').Policy} policyFragment\\n */\\nconst collectAttenuators=(attenuators,policyFragment)=>{\\nif('attenuate'in policyFragment){\\nattenuators.push(policyFragment.attenuate);}\\n\\nfor(const value of values(policyFragment)){\\nif(typeof value==='object'&&value!==null){\\ncollectAttenuators(attenuators,value);}}};\\n\\n\\n\\n\\nconst attenuatorsCache=new WeakMap();\\n\\n/**\\n * Goes through policy and lists all attenuator specifiers used.\\n * Memoization keyed on policy object reference\\n *\\n * @param {IMPORT('./types.js').Policy} [policy]\\n * @returns {Array<string>} attenuators\\n */\\nconst detectAttenuators=(policy)=>{\\nif(!policy){\\nreturn[];}\\n\\nif(!attenuatorsCache.has(policy)){\\nconst attenuators=[];\\nif(policy.defaultAttenuator){\\nattenuators.push(policy.defaultAttenuator);}\\n\\ncollectAttenuators(attenuators,policy);\\nattenuatorsCache.set(policy,attenuators);}\\n\\nreturn attenuatorsCache.get(policy);};\\n\\n\\n/**\\n * Generates a string identifying a package for policy lookup purposes.\\n *\\n * @param {IMPORT('./types.js').PackageNamingKit} namingKit\\n * @returns {string}\\n */\\nconst generateCanonicalName=({isEntry=false,name,path})=>{\\nif(isEntry){\\nthrow Error('Entry module cannot be identified with a canonicalName');}\\n\\nif(name===ATTENUATORS_COMPARTMENT){\\nreturn ATTENUATORS_COMPARTMENT;}\\n\\nreturn path.join('>');};\\n\\n\\n/**\\n * Verifies if a module identified by `namingKit` can be a dependency of a package per `packagePolicy`.\\n * `packagePolicy` is required, when policy is not set, skipping needs to be handled by the caller.\\n *\\n * @param {IMPORT('./types.js').PackageNamingKit} namingKit\\n * @param {IMPORT('./types.js').PackagePolicy} packagePolicy\\n * @returns {boolean}\\n */\\nconst dependencyAllowedByPolicy=(namingKit,packagePolicy)=>{\\nif(namingKit.isEntry){\\n/* dependency on entry compartment should never be allowed*/\\nreturn false;}\\n\\nconst canonicalName=generateCanonicalName(namingKit);\\nreturn!!policyFormat.policyLookupHelper(packagePolicy,'packages',canonicalName);};\\n\\n\\n/**\\n * Returns the policy applicable to the canonicalName of the package\\n *\\n * @overload\\n * @param {IMPORT('./types.js').PackageNamingKit} namingKit - a key in the policy resources spec is derived from these\\n * @param {IMPORT('./types.js').Policy} policy - user supplied policy\\n * @returns {IMPORT('./types.js').PackagePolicy} packagePolicy if policy was specified\\n */\\n\\n/**\\n * Returns `undefined`\\n *\\n * @overload\\n * @param {IMPORT('./types.js').PackageNamingKit} namingKit - a key in the policy resources spec is derived from these\\n * @param {IMPORT('./types.js').Policy} [policy] - user supplied policy\\n * @returns {IMPORT('./types.js').PackagePolicy|undefined} packagePolicy if policy was specified\\n */\\n\\n/**\\n * Returns the policy applicable to the canonicalName of the package\\n *\\n * @param {IMPORT('./types.js').PackageNamingKit} namingKit - a key in the policy resources spec is derived from these\\n * @param {IMPORT('./types.js').Policy} [policy] - user supplied policy\\n */\\nconst getPolicyForPackage=(namingKit,policy)=>{\\nif(!policy){\\nreturn undefined;}\\n\\nif(namingKit.isEntry){\\nreturn policy.entry;}\\n\\nconst canonicalName=generateCanonicalName(namingKit);\\nif(canonicalName===ATTENUATORS_COMPARTMENT){\\nreturn{\\ndefaultAttenuator:policy.defaultAttenuator,\\npackages:'any'};}\\n\\n\\nif(policy.resources&&policy.resources[canonicalName]!==undefined){\\nreturn policy.resources[canonicalName];}else\\n{\\n/* Allow skipping policy entries for packages with no powers.*/\\nreturn create(null);}};\\n\\n\\n\\n/**\\n * Get list of globals from package policy\\n * @param {IMPORT('./types.js').PackagePolicy} [packagePolicy]\\n * @returns {Array<string>}\\n */\\nconst getGlobalsList=(packagePolicy)=>{\\nif(!packagePolicy||!packagePolicy.globals){\\nreturn[];}\\n\\nreturn entries(packagePolicy.globals).\\nfilter(([_key,value])=>value).\\nmap(([key,_vvalue])=>key);};\\n\\n\\nconst GLOBAL_ATTENUATOR='attenuateGlobals';\\nconst MODULE_ATTENUATOR='attenuateModule';\\n\\n/**\\n * Imports attenuator per its definition and provider\\n * @param {IMPORT('./types.js').AttenuationDefinition} attenuationDefinition\\n * @param {IMPORT('./types.js').DeferredAttenuatorsProvider} attenuatorsProvider\\n * @param {string} attenuatorExportName\\n * @returns {Promise<Function>}\\n */\\nconst importAttenuatorForDefinition=async(\\nattenuationDefinition,\\nattenuatorsProvider,\\nattenuatorExportName)=>\\n{\\nif(!attenuatorsProvider){\\nthrow Error(`attenuatorsProvider is required to import attenuators`);}\\n\\nconst{specifier,params,displayName}=policyFormat.getAttenuatorFromDefinition(\\nattenuationDefinition);\\n\\nconst attenuator=await attenuatorsProvider.import(specifier);\\nif(!attenuator[attenuatorExportName]){\\nthrow Error(\\n`Attenuator ${q(displayName)} does not export ${q(attenuatorExportName)}`);}\\n\\n\\n/* TODO: uncurry bind for security?*/\\nconst attenuate=attenuator[attenuatorExportName].bind(attenuator,params);\\nreturn attenuate;};\\n\\n\\n/**\\n * Makes an async provider for attenuators\\n * @param {Record<string, Compartment>} compartments\\n * @param {Record<string, IMPORT('./types.js').CompartmentDescriptor>} compartmentDescriptors\\n * @returns {IMPORT('./types.js').DeferredAttenuatorsProvider}\\n */\\nconst makeDeferredAttenuatorsProvider=(\\ncompartments,\\ncompartmentDescriptors)=>\\n{\\nlet importAttenuator;\\nlet defaultAttenuator;\\n/* Attenuators compartment is not created when there's no policy.*/\\n/* Errors should be thrown when the provider is used.*/\\nif(!compartmentDescriptors[ATTENUATORS_COMPARTMENT]){\\nimportAttenuator=async()=>{\\nthrow Error(`No attenuators specified in policy`);};}else\\n\\n{\\ndefaultAttenuator=\\ncompartmentDescriptors[ATTENUATORS_COMPARTMENT].policy.defaultAttenuator;\\n\\n/* At the time of this function being called, attenuators compartment won't*/\\n/* exist yet, we need to defer looking them up in the compartment to the*/\\n/* time of the import function being called.*/\\n/**\\n *\\n * @param {string} attenuatorSpecifier\\n * @returns {Promise<IMPORT('./types.js').Attenuator>}\\n */\\nimportAttenuator=async(attenuatorSpecifier)=>{\\nif(!attenuatorSpecifier){\\nif(!defaultAttenuator){\\nthrow Error(`No default attenuator specified in policy`);}\\n\\nattenuatorSpecifier=defaultAttenuator;}\\n\\nconst{namespace}=\\nawait compartments[ATTENUATORS_COMPARTMENT].import(attenuatorSpecifier);\\nreturn namespace;};}\\n\\n\\n\\nreturn{\\nimport:importAttenuator};};\\n\\n\\n\\n/**\\n * Attenuates the `globalThis` object\\n *\\n * @param {object} options\\n * @param {IMPORT('./types.js').DeferredAttenuatorsProvider} options.attenuators\\n * @param {IMPORT('./types.js').AttenuationDefinition} options.attenuationDefinition\\n * @param {object} options.globalThis\\n * @param {object} options.globals\\n */\\nasync function attenuateGlobalThis({\\nattenuators,\\nattenuationDefinition,\\nglobalThis,\\nglobals})\\n{\\nconst attenuate=await importAttenuatorForDefinition(\\nattenuationDefinition,\\nattenuators,\\nGLOBAL_ATTENUATOR);\\n\\n\\n/* attenuate can either define properties on globalThis on its own,*/\\n/* or return an object with properties to transfer onto globalThis.*/\\n/* The latter is consistent with how module attenuators work so that*/\\n/* one attenuator implementation can be used for both if use of*/\\n/* defineProperty is not needed for attenuating globals.*/\\n\\n/* Globals attenuator could be made async by adding a single `await`*/\\n/* here, but module attenuation must be synchronous, so we make it*/\\n/* synchronous too for consistency.*/\\n\\n/* For async attenuators see PR https://github.com/endojs/endo/pull/1535*/\\n\\nconst result=/* await */attenuate(globals,globalThis);\\nif(typeof result==='object'&&result!==null){\\nassign(globalThis,result);}}\\n\\n\\n\\n/**\\n * Filters available globals and returns a copy according to the policy\\n *\\n * @param {object} globalThis\\n * @param {object} globals\\n * @param {IMPORT('./types.js').PackagePolicy} packagePolicy\\n * @param {IMPORT('./types.js').DeferredAttenuatorsProvider} attenuators\\n * @param {Array<Promise>} pendingJobs\\n * @param {string} name\\n * @returns {void}\\n */\\nconst attenuateGlobals=(\\nglobalThis,\\nglobals,\\npackagePolicy,\\nattenuators,\\npendingJobs,\\nname='<unknown>')=>\\n{\\nlet freezeGlobalThisUnlessOptedOut=()=>{\\nfreeze(globalThis);};\\n\\nif(packagePolicy&&packagePolicy.noGlobalFreeze){\\nfreezeGlobalThisUnlessOptedOut=()=>{};}\\n\\nif(!packagePolicy||policyFormat.isAllowingEverything(packagePolicy.globals)){\\nselectiveCopy(globals,globalThis);\\nfreezeGlobalThisUnlessOptedOut();\\nreturn;}\\n\\nif(policyFormat.isAttenuationDefinition(packagePolicy.globals)){\\nconst attenuationDefinition=packagePolicy.globals;\\nconst{displayName}=policyFormat.getAttenuatorFromDefinition(attenuationDefinition);\\nconst attenuationPromise=Promise.resolve()/* delay to next tick while linking is synchronously finalized*/.\\nthen(()=>\\nattenuateGlobalThis({\\nattenuators,\\nattenuationDefinition,\\nglobalThis,\\nglobals})).\\n\\n\\nthen(freezeGlobalThisUnlessOptedOut,(error)=>{\\nfreezeGlobalThisUnlessOptedOut();\\nthrow Error(\\n`Error while attenuating globals for ${q(name)} with ${q(\\ndisplayName)\\n}: ${q(error.message)}`/* TODO: consider an option to expose stacktrace for ease of debugging*/);});\\n\\n\\npendingJobs.push(attenuationPromise);\\n\\nreturn;}\\n\\nconst list=getGlobalsList(packagePolicy);\\nselectiveCopy(globals,globalThis,list);\\nfreezeGlobalThisUnlessOptedOut();};\\n\\n\\n/**\\n * @param {string} [errorHint]\\n * @returns {string}\\n */\\nconst diagnoseModulePolicy=(errorHint)=>{\\nif(!errorHint){\\nreturn'';}\\n\\nreturn` (info: ${errorHint})`;};\\n\\n\\n/**\\n * Options for {@link enforceModulePolicy}\\n * @typedef EnforceModulePolicyOptions\\n * @property {boolean} [exit] - Whether it is an exit module\\n * @property {string} [errorHint] - Error hint message\\n */\\n\\n/**\\n * Throws if importing of the specifier is not allowed by the policy\\n *\\n * @param {string} specifier\\n * @param {IMPORT('./types.js').CompartmentDescriptor} compartmentDescriptor\\n * @param {EnforceModulePolicyOptions} [options]\\n */\\nconst enforceModulePolicy=(\\nspecifier,\\ncompartmentDescriptor,\\n{exit,errorHint}={})=>\\n{\\nconst{policy,modules,label}=compartmentDescriptor;\\nif(!policy){\\nreturn;}\\n\\n\\nif(!exit){\\nif(!modules[specifier]){\\nthrow Error(\\n`Importing ${q(specifier)} in ${q(\\nlabel)\\n} was not allowed by packages policy ${q(\\npolicy.packages)\\n}${diagnoseModulePolicy(errorHint)}`);}\\n\\n\\nreturn;}\\n\\n\\nif(!policyFormat.policyLookupHelper(policy,'builtins',specifier)){\\nthrow Error(\\n`Importing ${q(specifier)} was not allowed by policy builtins:${q(\\npolicy.builtins)\\n}${diagnoseModulePolicy(errorHint)}`);}};\\n\\n\\n\\n\\n/**\\n * Attenuates a module\\n * @param {object} options\\n * @param {IMPORT('./types.js').DeferredAttenuatorsProvider} options.attenuators\\n * @param {IMPORT('./types.js').AttenuationDefinition} options.attenuationDefinition\\n * @param {IMPORT('ses').ThirdPartyStaticModuleInterface} options.originalModuleRecord\\n * @returns {Promise<IMPORT('ses').ThirdPartyStaticModuleInterface>}\\n */\\nasync function attenuateModule({\\nattenuators,\\nattenuationDefinition,\\noriginalModuleRecord})\\n{\\nconst attenuate=await importAttenuatorForDefinition(\\nattenuationDefinition,\\nattenuators,\\nMODULE_ATTENUATOR);\\n\\n\\n/* An async attenuator maker could be introduced here to return a synchronous attenuator.*/\\n/* For async attenuators see PR https://github.com/endojs/endo/pull/1535*/\\n\\nreturn freeze({\\nimports:originalModuleRecord.imports,\\n/* It seems ok to declare the exports but then let the attenuator trim the values.*/\\n/* Seems ok for attenuation to leave them undefined - accessing them is malicious behavior.*/\\nexports:originalModuleRecord.exports,\\nexecute:(moduleExports,compartment,resolvedImports)=>{\\nconst ns={};\\noriginalModuleRecord.execute(ns,compartment,resolvedImports);\\nconst attenuated=attenuate(ns);\\nmoduleExports.default=attenuated;\\nassign(moduleExports,attenuated);}});}\\n\\n\\n\\n\\n/**\\n * Throws if importing of the specifier is not allowed by the policy\\n *\\n * @param {string} specifier - exit module name\\n * @param {IMPORT('ses').ThirdPartyStaticModuleInterface} originalModuleRecord - reference to the exit module\\n * @param {IMPORT('./types.js').PackagePolicy} policy - local compartment policy\\n * @param {IMPORT('./types.js').DeferredAttenuatorsProvider} attenuators - a key-value where attenuations can be found\\n * @returns {Promise<IMPORT('ses').ThirdPartyStaticModuleInterface>} - the attenuated module\\n */\\nconst attenuateModuleHook=async(\\nspecifier,\\noriginalModuleRecord,\\npolicy,\\nattenuators)=>\\n{\\nconst policyValue=policyFormat.policyLookupHelper(policy,'builtins',specifier);\\nif(!policy||policyValue===true){\\nreturn originalModuleRecord;}\\n\\n\\nif(!policyValue){\\nthrow Error(\\n`Attenuation failed '${specifier}' was not in policy builtins:${q(\\npolicy.builtins)\\n}`);}\\n\\n\\nreturn attenuateModule({\\nattenuators,\\nattenuationDefinition:policyValue,\\noriginalModuleRecord});};exports.ATTENUATORS_COMPARTMENT=ATTENUATORS_COMPARTMENT;exports.attenuateGlobals=attenuateGlobals;exports.attenuateModuleHook=attenuateModuleHook;exports.dependencyAllowedByPolicy=dependencyAllowedByPolicy;exports.detectAttenuators=detectAttenuators;exports.enforceModulePolicy=enforceModulePolicy;exports.getPolicyForPackage=getPolicyForPackage;exports.makeDeferredAttenuatorsProvider=makeDeferredAttenuatorsProvider;\",\n \"node_modules/@endo/compartment-mapper/src/powers.js\": \"'use strict';\\n\\n\\n\\n\\n\\n\\n\\n\\nObject.defineProperty(exports,'__esModule',{value:true});/* As the interface of the Compartment Mapper evolved, it became necessary to\\n * expand some function signatures that accepted a single power to one that\\n * accepted a powers object.\\n * This module provides functions for safely unpacking I/O capabilities and\\n * maintaining backward-compatibility with older accepted usage patterns.\\n */ /* @ts-check*/ /** @type {IMPORT('./types.js').CanonicalFn} */const canonicalShim=async(path)=>path;/**\\n * @param {IMPORT('./types.js').ReadFn | IMPORT('./types.js').ReadPowers | IMPORT('./types.js').MaybeReadPowers} powers\\n * @returns {IMPORT('./types.js').MaybeReadPowers}\\n */const unpackReadPowers=(powers)=>{/** @type {IMPORT('./types.js').ReadFn | undefined} */\\nlet read;\\n/** @type {IMPORT('./types.js').MaybeReadFn | undefined} */\\nlet maybeRead;\\n/** @type {IMPORT('./types.js').CanonicalFn | undefined} */\\nlet canonical;\\n\\nif(typeof powers==='function'){\\nread=powers;}else\\n{\\n({read,maybeRead,canonical}=powers);}\\n\\n\\nif(canonical===undefined){\\ncanonical=canonicalShim;}\\n\\n\\nif(maybeRead===undefined){\\n/** @param {string} path */\\nmaybeRead=(path)=>\\n/** @type {IMPORT('./types.js').ReadFn} */read(path).catch(\\n(_error)=>undefined);}\\n\\n\\n\\nreturn{\\n...powers,\\nread,\\nmaybeRead,\\ncanonical};};exports.unpackReadPowers=unpackReadPowers;\",\n \"node_modules/@endo/env-options/index.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var envOptions=require('./src/env-options.js');exports.environmentOptionsListHas=envOptions.environmentOptionsListHas;exports.getEnvironmentOption=envOptions.getEnvironmentOption;exports.getEnvironmentOptionsList=envOptions.getEnvironmentOptionsList;exports.makeEnvironmentCaptor=envOptions.makeEnvironmentCaptor;\",\n \"node_modules/@endo/env-options/src/env-options.js\": \"'use strict';\\n\\n\\n\\n\\n\\n\\n\\nObject.defineProperty(exports,'__esModule',{value:true});/* global globalThis */ /* @ts-check*/ /* `@endo/env-options` needs to be imported quite early, and so should*/ /* avoid importing from ses or anything that depends on ses.*/ /* /////////////////////////////////////////////////////////////////////////////*/ /* Prelude of cheap good - enough imitations of things we'd use or*/ /* do differently if we could depend on ses*/\\n\\nconst{freeze}=Object;\\nconst{apply}=Reflect;\\n\\n/* Should be equivalent to the one in ses' commons.js even though it*/\\n/* uses the other technique.*/\\nconst uncurryThis=\\n(fn)=>\\n(receiver,...args)=>\\napply(fn,receiver,args);\\nconst arrayPush=uncurryThis(Array.prototype.push);\\nconst arrayIncludes=uncurryThis(Array.prototype.includes);\\nconst stringSplit=uncurryThis(String.prototype.split);\\n\\nconst q=JSON.stringify;\\n\\nconst Fail=(literals,...args)=>{\\nlet msg=literals[0];\\nfor(let i=0;i<args.length;i+=1){\\nmsg=`${msg}${args[i]}${literals[i+1]}`;}\\n\\nthrow Error(msg);};\\n\\n\\n/* end prelude*/\\n/* /////////////////////////////////////////////////////////////////////////////*/\\n\\n/**\\n * `makeEnvironmentCaptor` provides a mechanism for getting environment\\n * variables, if they are needed, and a way to catalog the names of all\\n * the environment variables that were captured.\\n *\\n * @param {object} aGlobal\\n * @param {boolean} [dropNames] Defaults to false. If true, don't track\\n * names used.\\n */\\nconst makeEnvironmentCaptor=(aGlobal,dropNames=false)=>{\\nconst capturedEnvironmentOptionNames=[];\\n\\n/**\\n * Gets an environment option by name and returns the option value or the\\n * given default.\\n *\\n * @param {string} optionName\\n * @param {string} defaultSetting\\n * @param {string[]} [optOtherValues]\\n * If provided, the option value must be included or match `defaultSetting`.\\n * @returns {string}\\n */\\nconst getEnvironmentOption=(\\noptionName,\\ndefaultSetting,\\noptOtherValues=undefined)=>\\n{\\ntypeof optionName==='string'||\\nFail`Environment option name ${q(optionName)} must be a string.`;\\ntypeof defaultSetting==='string'||\\nFail`Environment option default setting ${q(\\ndefaultSetting)\\n} must be a string.`;\\n\\n/** @type {string} */\\nlet setting=defaultSetting;\\nconst globalProcess=aGlobal.process||undefined;\\nconst globalEnv=\\ntypeof globalProcess==='object'&&globalProcess.env||undefined;\\nif(typeof globalEnv==='object'){\\nif(optionName in globalEnv){\\nif(!dropNames){\\narrayPush(capturedEnvironmentOptionNames,optionName);}\\n\\nconst optionValue=globalEnv[optionName];\\n/* eslint-disable-next-line @endo/no-polymorphic-call*/\\ntypeof optionValue==='string'||\\nFail`Environment option named ${q(\\noptionName)\\n}, if present, must have a corresponding string value, got ${q(\\noptionValue)\\n}`;\\nsetting=optionValue;}}\\n\\n\\noptOtherValues===undefined||\\nsetting===defaultSetting||\\narrayIncludes(optOtherValues,setting)||\\nFail`Unrecognized ${q(optionName)} value ${q(\\nsetting)\\n}. Expected one of ${q([defaultSetting,...optOtherValues])}`;\\nreturn setting;};\\n\\nfreeze(getEnvironmentOption);\\n\\n/**\\n * @param {string} optionName\\n * @returns {string[]}\\n */\\nconst getEnvironmentOptionsList=(optionName)=>{\\nconst option=getEnvironmentOption(optionName,'');\\nreturn freeze(option===''?[]:stringSplit(option,','));};\\n\\nfreeze(getEnvironmentOptionsList);\\n\\nconst environmentOptionsListHas=(optionName,element)=>\\narrayIncludes(getEnvironmentOptionsList(optionName),element);\\n\\nconst getCapturedEnvironmentOptionNames=()=>{\\nreturn freeze([...capturedEnvironmentOptionNames]);};\\n\\nfreeze(getCapturedEnvironmentOptionNames);\\n\\nreturn freeze({\\ngetEnvironmentOption,\\ngetEnvironmentOptionsList,\\nenvironmentOptionsListHas,\\ngetCapturedEnvironmentOptionNames});};\\n\\n\\nfreeze(makeEnvironmentCaptor);\\n\\n/**\\n * For the simple case, where the global in question is `globalThis` and no\\n * reporting of option names is desired.\\n */\\nconst{\\ngetEnvironmentOption,\\ngetEnvironmentOptionsList,\\nenvironmentOptionsListHas}=\\nmakeEnvironmentCaptor(globalThis,true);exports.environmentOptionsListHas=environmentOptionsListHas;exports.getEnvironmentOption=getEnvironmentOption;exports.getEnvironmentOptionsList=getEnvironmentOptionsList;exports.makeEnvironmentCaptor=makeEnvironmentCaptor;\",\n \"node_modules/@endo/errors/index.js\": \"'use strict';\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nObject.defineProperty(exports,'__esModule',{value:true});/* global globalThis */ /*/ <reference types=\\\"ses\\\"/>*/ /* This module assumes the existence of a non-standard `assert` host object.*/ /* SES version 0.11.0 introduces this global object and entangles it*/ /* with the `console` host object in scope when it initializes,*/ /* allowing errors, particularly assertion errors, to hide their \\\"details\\\"*/ /* from callers that might catch those errors, then reveal them to the*/ /* underlying console.*/ /* To the extent that this `console` is considered a resource,*/ /* this module must be considered a resource module.*/ /* The assertions re-exported here are defined in*/ /* https://github.com/endojs/endo/blob/HEAD/packages/ses/src/error/assert.js*/\\n\\nconst globalAssert=globalThis.assert;\\n\\nif(globalAssert===undefined){\\nthrow Error(\\n`Cannot initialize @endo/errors, missing globalThis.assert, import 'ses' before '@endo/errors'`);}\\n\\n\\n\\nconst missing=/** @type {const} */[\\n'typeof',\\n'error',\\n'fail',\\n'equal',\\n'string',\\n'note',\\n'details',\\n'Fail',\\n'quote',\\n/* As of 2024-02, the Agoric chain's bootstrap vat runs with a version of SES that*/\\n/* predates addition of the 'bare' method, so we must tolerate its absence and fall*/\\n/* back to quote behavior in that environment (see below).*/\\n/* 'bare',*/\\n'makeAssert'].\\nfilter((name)=>globalAssert[name]===undefined);\\nif(missing.length>0){\\nthrow Error(\\n`Cannot initialize @endo/errors, missing globalThis.assert methods ${missing.join(\\n', ')\\n}`);}\\n\\n\\n\\n/* The global assert mixed assertions and utility functions.*/\\n/* This module splits them apart*/\\n/* and also updates the names of the utility functions.*/\\nconst{\\nbare,\\ndetails:redacted,\\nerror:makeError,\\nFail:throwRedacted,\\nmakeAssert:_omittedMakeAssert,\\nnote,\\nquote,\\n...assertions}=\\nglobalAssert;\\n/** @type {IMPORT(\\\"ses\\\").AssertionFunctions } */\\n/* @ts-expect-error missing properties assigned next*/\\nconst assert=(value,optDetails,errContructor,options)=>\\nglobalAssert(value,optDetails,errContructor,options);\\nObject.assign(assert,assertions);\\n\\n/* As of 2024-02, the Agoric chain's bootstrap vat runs with a version of SES*/\\n/* that predates the addition of the 'bare' method, so we must fall back to*/\\n/* quote behavior for that environment.*/\\nconst bareOrQuote=bare||quote;exports.Fail=throwRedacted;exports.X=redacted;exports.annotateError=note;exports.assert=assert;exports.b=bareOrQuote;exports.bare=bareOrQuote;exports.makeError=makeError;exports.note=note;exports.q=quote;exports.quote=quote;exports.redacted=redacted;exports.throwRedacted=throwRedacted;\",\n \"node_modules/@endo/eventual-send/src/E.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var trackTurns=require('./track-turns.js');var messageBreakpoints=require('./message-breakpoints.js');\\n\\n\\nconst{details:X,quote:q,Fail,error:makeError}=assert;\\nconst{assign,create}=Object;\\n\\nconst onSend=messageBreakpoints.makeMessageBreakpointTester('ENDO_SEND_BREAKPOINTS');\\n\\n/** @type {ProxyHandler<any>} */\\nconst baseFreezableProxyHandler={\\nset(_target,_prop,_value){\\nreturn false;},\\n\\nisExtensible(_target){\\nreturn false;},\\n\\nsetPrototypeOf(_target,_value){\\nreturn false;},\\n\\ndeleteProperty(_target,_prop){\\nreturn false;}};\\n\\n\\n\\n/* E Proxy handlers pretend that any property exists on the target and returns*/\\n/* a function for their value. While this function is \\\"bound\\\" by context, it is*/\\n/* meant to be called as a method. For that reason, the returned function*/\\n/* includes a check that the `this` argument corresponds to the initial*/\\n/* receiver when the function was retrieved.*/\\n/* E Proxy handlers also forward direct calls to the target in case the remote*/\\n/* is a function instead of an object. No such receiver checks are necessary in*/\\n/* that case.*/\\n\\n/**\\n * A Proxy handler for E(x).\\n *\\n * @param {any} recipient Any value passed to E(x)\\n * @param {IMPORT('./types').HandledPromiseConstructor} HandledPromise\\n * @returns {ProxyHandler<unknown>} the Proxy handler\\n */\\nconst makeEProxyHandler=(recipient,HandledPromise)=>\\nharden({\\n...baseFreezableProxyHandler,\\nget:(_target,propertyKey,receiver)=>{\\nreturn harden(\\n{\\n/* This function purposely checks the `this` value (see above)*/\\n/* In order to be `this` sensitive it is defined using concise method*/\\n/* syntax rather than as an arrow function. To ensure the function*/\\n/* is not constructable, it also avoids the `function` syntax.*/\\n/** @type {(...args: any[]) => Promise<unknown>} */\\n[propertyKey](...args){\\nif(this!==receiver){\\n/* Reject the async function call*/\\nreturn HandledPromise.reject(\\nmakeError(\\nX`Unexpected receiver for \\\"${q(propertyKey)}\\\" method of E(${q(\\nrecipient)\\n})`));}\\n\\n\\n\\n\\nif(onSend&&onSend.shouldBreakpoint(recipient,propertyKey)){\\n/* eslint-disable-next-line no-debugger*/\\ndebugger;/* LOOK UP THE STACK*/\\n/* Stopped at a breakpoint on eventual-send of a method-call*/\\n/* message,*/\\n/* so that you can walk back on the stack to see how we came to*/\\n/* make this eventual-send*/}\\n\\nreturn HandledPromise.applyMethod(recipient,propertyKey,args);}\\n\\n/* @ts-expect-error https://github.com/microsoft/TypeScript/issues/50319*/}[\\npropertyKey]);},\\n\\n\\napply:(_target,_thisArg,argArray=[])=>{\\nif(onSend&&onSend.shouldBreakpoint(recipient,undefined)){\\n/* eslint-disable-next-line no-debugger*/\\ndebugger;/* LOOK UP THE STACK*/\\n/* Stopped at a breakpoint on eventual-send of a function-call message,*/\\n/* so that you can walk back on the stack to see how we came to*/\\n/* make this eventual-send*/}\\n\\nreturn HandledPromise.applyFunction(recipient,argArray);},\\n\\nhas:(_target,_p)=>{\\n/* We just pretend everything exists.*/\\nreturn true;}});\\n\\n\\n\\n/**\\n * A Proxy handler for E.sendOnly(x)\\n * It is a variant on the E(x) Proxy handler.\\n *\\n * @param {any} recipient Any value passed to E.sendOnly(x)\\n * @param {IMPORT('./types').HandledPromiseConstructor} HandledPromise\\n * @returns {ProxyHandler<unknown>} the Proxy handler\\n */\\nconst makeESendOnlyProxyHandler=(recipient,HandledPromise)=>\\nharden({\\n...baseFreezableProxyHandler,\\nget:(_target,propertyKey,receiver)=>{\\nreturn harden(\\n{\\n/* This function purposely checks the `this` value (see above)*/\\n/* In order to be `this` sensitive it is defined using concise method*/\\n/* syntax rather than as an arrow function. To ensure the function*/\\n/* is not constructable, it also avoids the `function` syntax.*/\\n/** @type {(...args: any[]) => undefined} */\\n[propertyKey](...args){\\n/* Throw since the function returns nothing*/\\nthis===receiver||\\nFail`Unexpected receiver for \\\"${q(\\npropertyKey)\\n}\\\" method of E.sendOnly(${q(recipient)})`;\\nif(onSend&&onSend.shouldBreakpoint(recipient,propertyKey)){\\n/* eslint-disable-next-line no-debugger*/\\ndebugger;/* LOOK UP THE STACK*/\\n/* Stopped at a breakpoint on eventual-send of a method-call*/\\n/* message,*/\\n/* so that you can walk back on the stack to see how we came to*/\\n/* make this eventual-send*/}\\n\\nHandledPromise.applyMethodSendOnly(recipient,propertyKey,args);\\nreturn undefined;}\\n\\n/* @ts-expect-error https://github.com/microsoft/TypeScript/issues/50319*/}[\\npropertyKey]);},\\n\\n\\napply:(_target,_thisArg,argsArray=[])=>{\\nif(onSend&&onSend.shouldBreakpoint(recipient,undefined)){\\n/* eslint-disable-next-line no-debugger*/\\ndebugger;/* LOOK UP THE STACK*/\\n/* Stopped at a breakpoint on eventual-send of a function-call message,*/\\n/* so that you can walk back on the stack to see how we came to*/\\n/* make this eventual-send*/}\\n\\nHandledPromise.applyFunctionSendOnly(recipient,argsArray);\\nreturn undefined;},\\n\\nhas:(_target,_p)=>{\\n/* We just pretend that everything exists.*/\\nreturn true;}});\\n\\n\\n\\n/**\\n * A Proxy handler for E.get(x)\\n * It is a variant on the E(x) Proxy handler.\\n *\\n * @param {any} x Any value passed to E.get(x)\\n * @param {IMPORT('./types').HandledPromiseConstructor} HandledPromise\\n * @returns {ProxyHandler<unknown>} the Proxy handler\\n */\\nconst makeEGetProxyHandler=(x,HandledPromise)=>\\nharden({\\n...baseFreezableProxyHandler,\\nhas:(_target,_prop)=>true,\\nget:(_target,prop)=>HandledPromise.get(x,prop)});\\n\\n\\n/**\\n * @param {IMPORT('./types').HandledPromiseConstructor} HandledPromise\\n */\\nconst makeE=(HandledPromise)=>{\\nreturn harden(\\nassign(\\n/**\\n * E(x) returns a proxy on which you can call arbitrary methods. Each of these\\n * method calls returns a promise. The method will be invoked on whatever\\n * 'x' designates (or resolves to) in a future turn, not this one.\\n *\\n * @template T\\n * @param {T} x target for method/function call\\n * @returns {ECallableOrMethods<RemoteFunctions<T>>} method/function call proxy\\n */\\n/* @ts-expect-error XXX typedef*/\\n(x)=>harden(new Proxy(()=>{},makeEProxyHandler(x,HandledPromise))),\\n{\\n/**\\n * E.get(x) returns a proxy on which you can get arbitrary properties.\\n * Each of these properties returns a promise for the property. The promise\\n * value will be the property fetched from whatever 'x' designates (or\\n * resolves to) in a future turn, not this one.\\n *\\n * @template T\\n * @param {T} x target for property get\\n * @returns {EGetters<LocalRecord<T>>} property get proxy\\n * @readonly\\n */\\nget:(x)=>\\n/* @ts-expect-error XXX typedef*/\\nharden(\\nnew Proxy(create(null),makeEGetProxyHandler(x,HandledPromise))),\\n\\n\\n/**\\n * E.resolve(x) converts x to a handled promise. It is\\n * shorthand for HandledPromise.resolve(x)\\n *\\n * @template T\\n * @param {T} x value to convert to a handled promise\\n * @returns {Promise<Awaited<T>>} handled promise for x\\n * @readonly\\n */\\nresolve:HandledPromise.resolve,\\n\\n/**\\n * E.sendOnly returns a proxy similar to E, but for which the results\\n * are ignored (undefined is returned).\\n *\\n * @template T\\n * @param {T} x target for method/function call\\n * @returns {ESendOnlyCallableOrMethods<RemoteFunctions<T>>} method/function call proxy\\n * @readonly\\n */\\nsendOnly:(x)=>\\n/* @ts-expect-error XXX typedef*/\\nharden(\\nnew Proxy(()=>{},makeESendOnlyProxyHandler(x,HandledPromise))),\\n\\n\\n/**\\n * E.when(x, res, rej) is equivalent to\\n * HandledPromise.resolve(x).then(res, rej)\\n *\\n * @template T\\n * @template [U = T]\\n * @param {T|PromiseLike<T>} x value to convert to a handled promise\\n * @param {(value: T) => ERef<U>} [onfulfilled]\\n * @param {(reason: any) => ERef<U>} [onrejected]\\n * @returns {Promise<U>}\\n * @readonly\\n */\\nwhen:(x,onfulfilled,onrejected)=>\\nHandledPromise.resolve(x).then(\\n...trackTurns.trackTurns([onfulfilled,onrejected]))}));};\\n\\n\\n\\n\\n\\n\\n\\n\\n/** @typedef {ReturnType<makeE>} EProxy */\\n\\n/**\\n * Creates a type that accepts both near and marshalled references that were\\n * returned from `Remotable` or `Far`, and also promises for such references.\\n *\\n * @template Primary The type of the primary reference.\\n * @template [Local=DataOnly<Primary>] The local properties of the object.\\n * @typedef {ERef<Local & IMPORT('./types').RemotableBrand<Local, Primary>>} FarRef\\n */\\n\\n/**\\n * `DataOnly<T>` means to return a record type `T2` consisting only of\\n * properties that are *not* functions.\\n *\\n * @template T The type to be filtered.\\n * @typedef {Omit<T, FilteredKeys<T, IMPORT('./types').Callable>>} DataOnly\\n */\\n\\n/**\\n * @see {@link https://github.com/microsoft/TypeScript/issues/31394}\\n * @template T\\n * @typedef {PromiseLike<T> | T} ERef\\n */\\n\\n/**\\n * @template {IMPORT('./types').Callable} T\\n * @typedef {(\\n * ReturnType<T> extends PromiseLike<infer U> // if function returns a promise\\n * ? T // return the function\\n * : (...args: Parameters<T>) => Promise<Awaited<ReturnType<T>>> // make it return a promise\\n * )} ECallable\\n */\\n\\n/**\\n * @template T\\n * @typedef {{\\n * readonly [P in keyof T]: T[P] extends IMPORT('./types').Callable\\n * ? ECallable<T[P]>\\n * : never;\\n * }} EMethods\\n */\\n\\n/**\\n * @template T\\n * @typedef {{\\n * readonly [P in keyof T]: T[P] extends PromiseLike<infer U>\\n * ? T[P]\\n * : Promise<Awaited<T[P]>>;\\n * }} EGetters\\n */\\n\\n/**\\n * @template {IMPORT('./types').Callable} T\\n * @typedef {(...args: Parameters<T>) => Promise<void>} ESendOnlyCallable\\n */\\n\\n/**\\n * @template T\\n * @typedef {{\\n * readonly [P in keyof T]: T[P] extends IMPORT('./types').Callable\\n * ? ESendOnlyCallable<T[P]>\\n * : never;\\n * }} ESendOnlyMethods\\n */\\n\\n/**\\n * @template T\\n * @typedef {(\\n * T extends IMPORT('./types').Callable\\n * ? ESendOnlyCallable<T> & ESendOnlyMethods<Required<T>>\\n * : ESendOnlyMethods<Required<T>>\\n * )} ESendOnlyCallableOrMethods\\n */\\n\\n/**\\n * @template T\\n * @typedef {(\\n * T extends IMPORT('./types').Callable\\n * ? ECallable<T> & EMethods<Required<T>>\\n * : EMethods<Required<T>>\\n * )} ECallableOrMethods\\n */\\n\\n/**\\n * Return a union of property names/symbols/numbers P for which the record element T[P]'s type extends U.\\n *\\n * Given const x = { a: 123, b: 'hello', c: 42, 49: () => {}, 53: 67 },\\n *\\n * FilteredKeys<typeof x, number> is the type 'a' | 'c' | 53.\\n * FilteredKeys<typeof x, string> is the type 'b'.\\n * FilteredKeys<typeof x, 42 | 67> is the type 'c' | 53.\\n * FilteredKeys<typeof x, boolean> is the type never.\\n *\\n * @template T\\n * @template U\\n * @typedef {{ [P in keyof T]: T[P] extends U ? P : never; }[keyof T]} FilteredKeys\\n */\\n\\n/**\\n * `PickCallable<T>` means to return a single root callable or a record type\\n * consisting only of properties that are functions.\\n *\\n * @template T\\n * @typedef {(\\n * T extends IMPORT('./types').Callable\\n * ? (...args: Parameters<T>) => ReturnType<T> // a root callable, no methods\\n * : Pick<T, FilteredKeys<T, IMPORT('./types').Callable>> // any callable methods\\n * )} PickCallable\\n */\\n\\n/**\\n * `RemoteFunctions<T>` means to return the functions and properties that are remotely callable.\\n *\\n * @template T\\n * @typedef {(\\n * T extends IMPORT('./types').RemotableBrand<infer L, infer R> // if a given T is some remote interface R\\n * ? PickCallable<R> // then return the callable properties of R\\n * : Awaited<T> extends IMPORT('./types').RemotableBrand<infer L, infer R> // otherwise, if the final resolution of T is some remote interface R\\n * ? PickCallable<R> // then return the callable properties of R\\n * : T extends PromiseLike<infer U> // otherwise, if T is a promise\\n * ? Awaited<T> // then return resolved value T\\n * : T // otherwise, return T\\n * )} RemoteFunctions\\n */\\n\\n/**\\n * @template T\\n * @typedef {(\\n * T extends IMPORT('./types').RemotableBrand<infer L, infer R>\\n * ? L\\n * : Awaited<T> extends IMPORT('./types').RemotableBrand<infer L, infer R>\\n * ? L\\n * : T extends PromiseLike<infer U>\\n * ? Awaited<T>\\n * : T\\n * )} LocalRecord\\n */\\n\\n/**\\n * @template [R = unknown]\\n * @typedef {{\\n * promise: Promise<R>;\\n * settler: IMPORT('./types').Settler<R>;\\n * }} EPromiseKit\\n */\\n\\n/**\\n * Type for an object that must only be invoked with E. It supports a given\\n * interface but declares all the functions as asyncable.\\n *\\n * @template T\\n * @typedef {(\\n * T extends IMPORT('./types').Callable\\n * ? (...args: Parameters<T>) => ERef<Awaited<EOnly<ReturnType<T>>>>\\n * : T extends Record<PropertyKey, IMPORT('./types').Callable>\\n * ? {\\n * [K in keyof T]: T[K] extends IMPORT('./types').Callable\\n * ? (...args: Parameters<T[K]>) => ERef<Awaited<EOnly<ReturnType<T[K]>>>>\\n * : T[K];\\n * }\\n * : T\\n * )} EOnly\\n */exports[\\\"default\\\"]=makeE;\",\n \"node_modules/@endo/eventual-send/src/exports.js\": \"'use strict';/* Just a dummy to use exports.d.ts and satisfy runtime imports.*/\",\n \"node_modules/@endo/eventual-send/src/local.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var messageBreakpoints=require('./message-breakpoints.js');\\n\\nconst{details:X,quote:q,Fail}=assert;\\n\\nconst{getOwnPropertyDescriptors,getPrototypeOf,freeze}=Object;\\nconst{apply,ownKeys}=Reflect;\\n\\nconst ntypeof=(specimen)=>specimen===null?'null':typeof specimen;\\n\\nconst onDelivery=messageBreakpoints.makeMessageBreakpointTester('ENDO_DELIVERY_BREAKPOINTS');\\n\\n/**\\n * TODO Consolidate with `isObject` that's currently in `@endo/marshal`\\n *\\n * @param {any} val\\n * @returns {boolean}\\n */\\nconst isObject=(val)=>Object(val)===val;\\n\\n/**\\n * Prioritize symbols as earlier than strings.\\n *\\n * @param {string|symbol} a\\n * @param {string|symbol} b\\n * @returns {-1 | 0 | 1}\\n */\\nconst compareStringified=(a,b)=>{\\nif(typeof a===typeof b){\\nconst left=String(a);\\nconst right=String(b);\\n/* eslint-disable-next-line no-nested-ternary*/\\nreturn left<right?-1:left>right?1:0;}\\n\\nif(typeof a==='symbol'){\\nassert(typeof b==='string');\\nreturn-1;}\\n\\nassert(typeof a==='string');\\nassert(typeof b==='symbol');\\nreturn 1;};\\n\\n\\n/**\\n * @param {any} val\\n * @returns {(string|symbol)[]}\\n */\\nconst getMethodNames=(val)=>{\\nlet layer=val;\\nconst names=new Set();/* Set to deduplicate*/\\nwhile(layer!==null&&layer!==Object.prototype){\\n/* be tolerant of non-objects*/\\nconst descs=getOwnPropertyDescriptors(layer);\\nfor(const name of ownKeys(descs)){\\n/* In case a method is overridden by a non-method,*/\\n/* test `val[name]` rather than `layer[name]`*/\\nif(typeof val[name]==='function'){\\nnames.add(name);}}\\n\\n\\nif(!isObject(val)){\\nbreak;}\\n\\nlayer=getPrototypeOf(layer);}\\n\\nreturn harden([...names].sort(compareStringified));};\\n\\n/* The top level of the eventual send modules can be evaluated before*/\\n/* ses creates `harden`, and so cannot rely on `harden` at top level.*/\\nfreeze(getMethodNames);\\n\\nconst localApplyFunction=(recipient,args)=>{\\ntypeof recipient==='function'||\\nassert.fail(\\nX`Cannot invoke target as a function; typeof target is ${q(\\nntypeof(recipient))\\n}`,\\nTypeError);\\n\\nif(onDelivery&&onDelivery.shouldBreakpoint(recipient,undefined)){\\n/* eslint-disable-next-line no-debugger*/\\ndebugger;/* STEP INTO APPLY*/\\n/* Stopped at a breakpoint on this delivery of an eventual function call*/\\n/* so that you can step *into* the following `apply` in order to see the*/\\n/* function call as it happens. Or step *over* to see what happens*/\\n/* after the function call returns.*/}\\n\\nconst result=apply(recipient,undefined,args);\\nreturn result;};\\n\\n\\nconst localApplyMethod=(recipient,methodName,args)=>{\\nif(methodName===undefined||methodName===null){\\n/* Base case; bottom out to apply functions.*/\\nreturn localApplyFunction(recipient,args);}\\n\\nif(recipient===undefined||recipient===null){\\nassert.fail(\\nX`Cannot deliver ${q(methodName)} to target; typeof target is ${q(\\nntypeof(recipient))\\n}`,\\nTypeError);}\\n\\n\\nconst fn=recipient[methodName];\\nif(fn===undefined){\\nassert.fail(\\nX`target has no method ${q(methodName)}, has ${q(\\ngetMethodNames(recipient))\\n}`,\\nTypeError);}\\n\\n\\nconst ftype=ntypeof(fn);\\ntypeof fn==='function'||\\nFail`invoked method ${q(methodName)} is not a function; it is a ${q(\\nftype)\\n}`;\\nif(onDelivery&&onDelivery.shouldBreakpoint(recipient,methodName)){\\n/* eslint-disable-next-line no-debugger*/\\ndebugger;/* STEP INTO APPLY*/\\n/* Stopped at a breakpoint on this delivery of an eventual method call*/\\n/* so that you can step *into* the following `apply` in order to see the*/\\n/* method call as it happens. Or step *over* to see what happens*/\\n/* after the method call returns.*/}\\n\\nconst result=apply(fn,recipient,args);\\nreturn result;};\\n\\n\\nconst localGet=(t,key)=>t[key];exports.getMethodNames=getMethodNames;exports.localApplyFunction=localApplyFunction;exports.localApplyMethod=localApplyMethod;exports.localGet=localGet;\",\n \"node_modules/@endo/eventual-send/src/message-breakpoints.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../env-options/index.js');var envOptions=require('../../env-options/src/env-options.js');\\n\\nconst{quote:q,Fail}=assert;\\n\\nconst{hasOwn,freeze,entries}=Object;\\n\\n/**\\n * @typedef {string | '*'} MatchStringTag\\n * A star `'*'` matches any recipient. Otherwise, the string is\\n * matched against the value of a recipient's `@@toStringTag`\\n * after stripping out any leading `'Alleged: '` or `'DebugName: '`\\n * prefix. For objects defined with `Far` this is the first argument,\\n * known as the `farName`. For exos, this is the tag.\\n */\\n/**\\n * @typedef {string | '*'} MatchMethodName\\n * A star `'*'` matches any method name. Otherwise, the string is\\n * matched against the method name. Currently, this is only an exact match.\\n * However, beware that we may introduce a string syntax for\\n * symbol method names.\\n */\\n/**\\n * @typedef {number | '*'} MatchCountdown\\n * A star `'*'` will always breakpoint. Otherwise, the string\\n * must be a non-negative integer. Once that is zero, always breakpoint.\\n * Otherwise decrement by one each time it matches until it reaches zero.\\n * In other words, the countdown represents the number of\\n * breakpoint occurrences to skip before actually breakpointing.\\n */\\n\\n/**\\n * This is the external JSON representation, in which\\n * - the outer property name is the class-like tag or '*',\\n * - the inner property name is the method name or '*',\\n * - the value is a non-negative integer countdown or '*'.\\n *\\n * @typedef {Record<MatchStringTag, Record<MatchMethodName, MatchCountdown>>} MessageBreakpoints\\n */\\n\\n/**\\n * This is the internal JSON representation, in which\\n * - the outer property name is the method name or '*',\\n * - the inner property name is the class-like tag or '*',\\n * - the value is a non-negative integer countdown or '*'.\\n *\\n * @typedef {Record<MatchMethodName, Record<MatchStringTag, MatchCountdown>>} BreakpointTable\\n */\\n\\n/**\\n * @typedef {object} MessageBreakpointTester\\n * @property {() => MessageBreakpoints} getBreakpoints\\n * @property {(newBreakpoints?: MessageBreakpoints) => void} setBreakpoints\\n * @property {(\\n * recipient: object,\\n * methodName: string | symbol | undefined\\n * ) => boolean} shouldBreakpoint\\n */\\n\\n/**\\n * @param {any} val\\n * @returns {val is Record<string, any>}\\n */\\nconst isJSONRecord=(val)=>\\ntypeof val==='object'&&val!==null&&!Array.isArray(val);\\n\\n/**\\n * Return `tag` after stripping off any `'Alleged: '` or `'DebugName: '`\\n * prefix if present.\\n * ```js\\n * simplifyTag('Alleged: moola issuer') === 'moola issuer'\\n * ```\\n * If there are multiple such prefixes, only the outer one is removed.\\n *\\n * @param {string} tag\\n * @returns {string}\\n */\\nconst simplifyTag=(tag)=>{\\nfor(const prefix of['Alleged: ','DebugName: ']){\\nif(tag.startsWith(prefix)){\\nreturn tag.slice(prefix.length);}}\\n\\n\\nreturn tag;};\\n\\n\\n/**\\n * @param {string} optionName\\n * @returns {MessageBreakpointTester | undefined}\\n */\\nconst makeMessageBreakpointTester=(optionName)=>{\\nlet breakpoints=JSON.parse(envOptions.getEnvironmentOption(optionName,'null'));\\n\\nif(breakpoints===null){\\nreturn undefined;}\\n\\n\\n/** @type {BreakpointTable} */\\nlet breakpointsTable;\\n\\nconst getBreakpoints=()=>breakpoints;\\nfreeze(getBreakpoints);\\n\\nconst setBreakpoints=(newBreakpoints=breakpoints)=>{\\nisJSONRecord(newBreakpoints)||\\nFail`Expected ${q(optionName)} option to be a JSON breakpoints record`;\\n\\n/** @type {BreakpointTable} */\\n/* @ts-expect-error confused by __proto__*/\\nconst newBreakpointsTable={__proto__:null};\\n\\nfor(const[tag,methodBPs]of entries(newBreakpoints)){\\ntag===simplifyTag(tag)||\\nFail`Just use simple tag ${q(simplifyTag(tag))} rather than ${q(tag)}`;\\nisJSONRecord(methodBPs)||\\nFail`Expected ${q(optionName)} option's ${q(\\ntag)\\n} to be a JSON methods breakpoints record`;\\nfor(const[methodName,count]of entries(methodBPs)){\\ncount==='*'||\\ntypeof count==='number'&&\\nNumber.isSafeInteger(count)&&\\ncount>=0||\\nFail`Expected ${q(optionName)} option's ${q(tag)}.${q(\\nmethodName)\\n} to be \\\"*\\\" or a non-negative integer`;\\n\\nconst classBPs=hasOwn(newBreakpointsTable,methodName)?\\nnewBreakpointsTable[methodName]:\\nnewBreakpointsTable[methodName]={\\n/* @ts-expect-error confused by __proto__*/\\n__proto__:null};\\n\\nclassBPs[tag]=count;}}\\n\\n\\nbreakpoints=newBreakpoints;\\nbreakpointsTable=newBreakpointsTable;};\\n\\nfreeze(setBreakpoints);\\n\\nconst shouldBreakpoint=(recipient,methodName)=>{\\nif(methodName===undefined||methodName===null){\\n/* TODO enable function breakpointing*/\\nreturn false;}\\n\\nconst classBPs=breakpointsTable[methodName]||breakpointsTable['*'];\\nif(classBPs===undefined){\\nreturn false;}\\n\\nlet tag=simplifyTag(recipient[Symbol.toStringTag]);\\nlet count=classBPs[tag];\\nif(count===undefined){\\ntag='*';\\ncount=classBPs[tag];\\nif(count===undefined){\\nreturn false;}}\\n\\n\\nif(count==='*'){\\nreturn true;}\\n\\nif(count===0){\\nreturn true;}\\n\\nassert(typeof count==='number'&&count>=1);\\nclassBPs[tag]=count-1;\\nreturn false;};\\n\\nfreeze(shouldBreakpoint);\\n\\nconst breakpointTester=freeze({\\ngetBreakpoints,\\nsetBreakpoints,\\nshouldBreakpoint});\\n\\nbreakpointTester.setBreakpoints();\\nreturn breakpointTester;};\\n\\nfreeze(makeMessageBreakpointTester);exports.makeMessageBreakpointTester=makeMessageBreakpointTester;\",\n \"node_modules/@endo/eventual-send/src/no-shim.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var E$1=require('./E.js');\\n\\n\\n\\nrequire('./exports.js');/* XXX module exports for HandledPromise fail if these aren't in scope*/ /** @import {Handler, HandledExecutor} from './handled-promise.js' */ /** @import {ECallableOrMethods, EGetters, ERef, ERemoteFunctions, ESendOnlyCallableOrMethods, LocalRecord, RemoteFunctions} from './E.js' */\\n\\nconst hp=HandledPromise;\\nconst E=E$1[\\\"default\\\"](hp);exports.E=E;exports.HandledPromise=hp;\",\n \"node_modules/@endo/eventual-send/src/track-turns.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../env-options/index.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nenvOptions=require('../../env-options/src/env-options.js');/* global globalThis */ /* NOTE: We can't import these because they're not in scope before lockdown.*/ /* We also cannot currently import them because it would create a cyclic*/ /* dependency, though this is more easily fixed.*/ /* import { assert, X, Fail } from '@endo/errors';*/ /* See also https://github.com/Agoric/agoric-sdk/issues/9515*/ /* WARNING: Global Mutable State!*/ /* This state is communicated to `assert` that makes it available to the*/ /* causal console, which affects the console log output. Normally we*/ /* regard the ability to see console log output as a meta-level privilege*/ /* analogous to the ability to debug. Aside from that, this module should*/ /* not have any observably mutable state.*/\\n\\nlet hiddenPriorError;\\nlet hiddenCurrentTurn=0;\\nlet hiddenCurrentEvent=0;\\n\\n/* Turn on if you seem to be losing error logging at the top of the event loop*/\\nconst VERBOSE=envOptions.environmentOptionsListHas('DEBUG','track-turns');\\n\\n/* Track-turns is disabled by default and can be enabled by an environment*/\\n/* option.*/\\nconst ENABLED=\\nenvOptions.getEnvironmentOption('TRACK_TURNS','disabled',['enabled'])==='enabled';\\n\\n/* We hoist the following functions out of trackTurns() to discourage the*/\\n/* closures from holding onto 'args' or 'func' longer than necessary,*/\\n/* which we've seen cause HandledPromise arguments to be retained for*/\\n/* a surprisingly long time.*/\\n\\nconst addRejectionNote=(detailsNote)=>(reason)=>{\\nif(reason instanceof Error){\\nglobalThis.assert.note(reason,detailsNote);}\\n\\nif(VERBOSE){\\nconsole.log('REJECTED at top of event loop',reason);}};\\n\\n\\n\\nconst wrapFunction=\\n(func,sendingError,X)=>\\n(...args)=>{\\nhiddenPriorError=sendingError;\\nhiddenCurrentTurn+=1;\\nhiddenCurrentEvent=0;\\ntry{\\nlet result;\\ntry{\\nresult=func(...args);}\\ncatch(err){\\nif(err instanceof Error){\\nglobalThis.assert.note(\\nerr,\\nX`Thrown from: ${hiddenPriorError}:${hiddenCurrentTurn}.${hiddenCurrentEvent}`);}\\n\\n\\nif(VERBOSE){\\nconsole.log('THROWN to top of event loop',err);}\\n\\nthrow err;}\\n\\n/* Must capture this now, not when the catch triggers.*/\\nconst detailsNote=X`Rejection from: ${hiddenPriorError}:${hiddenCurrentTurn}.${hiddenCurrentEvent}`;\\nPromise.resolve(result).catch(addRejectionNote(detailsNote));\\nreturn result;}finally\\n{\\nhiddenPriorError=undefined;}};\\n\\n\\n\\n/**\\n * Given a list of `TurnStarterFn`s, returns a list of `TurnStarterFn`s whose\\n * `this`-free call behaviors are not observably different to those that\\n * cannot see console output. The only purpose is to cause additional\\n * information to appear on the console.\\n *\\n * The call to `trackTurns` is itself a sending event, that occurs in some call\\n * stack in some turn number at some event number within that turn. Each call\\n * to any of the returned `TurnStartFn`s is a receiving event that begins a new\\n * turn. This sending event caused each of those receiving events.\\n *\\n * @template {TurnStarterFn[]} T\\n * @param {T} funcs\\n * @returns {T}\\n */\\nconst trackTurns=(funcs)=>{\\nif(!ENABLED||typeof globalThis==='undefined'||!globalThis.assert){\\nreturn funcs;}\\n\\nconst{details:X,note:annotateError}=globalThis.assert;\\n\\nhiddenCurrentEvent+=1;\\nconst sendingError=Error(\\n`Event: ${hiddenCurrentTurn}.${hiddenCurrentEvent}`);\\n\\nif(hiddenPriorError!==undefined){\\nannotateError(sendingError,X`Caused by: ${hiddenPriorError}`);}\\n\\n\\nreturn(/** @type {T} */\\nfuncs.map((func)=>func&&wrapFunction(func,sendingError,X)));};\\n\\n\\n\\n/**\\n * An optional function that is not this-sensitive, expected to be called at\\n * bottom of stack to start a new turn.\\n *\\n * @typedef {((...args: any[]) => any) | undefined} TurnStarterFn\\n */exports.trackTurns=trackTurns;\",\n \"node_modules/@endo/eventual-send/utils.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var local=require('./src/local.js');var messageBreakpoints=require('./src/message-breakpoints.js');exports.getMethodNames=local.getMethodNames;exports.makeMessageBreakpointTester=messageBreakpoints.makeMessageBreakpointTester;\",\n \"node_modules/@endo/exo/index.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var exoMakers=require('./src/exo-makers.js');require('./src/types.js');var getInterface=require('./src/get-interface.js');exports.defineExoClass=exoMakers.defineExoClass;exports.defineExoClassKit=exoMakers.defineExoClassKit;exports.initEmpty=exoMakers.initEmpty;exports.makeExo=exoMakers.makeExo;exports.GET_INTERFACE_GUARD=getInterface.GET_INTERFACE_GUARD;\",\n \"node_modules/@endo/exo/src/exo-makers.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var objectMap=require('../../common/object-map.js');require('../../env-options/index.js');var index=require('../../errors/index.js');var exoTools=require('./exo-tools.js');var\\n\\n\\n\\n\\n\\n\\nenvOptions=require('../../env-options/src/env-options.js');/*/ <reference types=\\\"ses\\\"/>*/ /**\\n * @import {Amplify, ExoClassKitMethods, ExoClassMethods, FarClassOptions, Guarded, GuardedKit, ExoClassInterfaceGuardKit, IsInstance, KitContext, ExoClassInterfaceGuard, Methods, FacetName} from './types.js';\\n */\\n\\nconst{create,seal,freeze,defineProperty,values}=Object;\\n\\n/* Turn on to give each exo instance its own toStringTag value.*/\\nconst LABEL_INSTANCES=envOptions.environmentOptionsListHas('DEBUG','label-instances');\\n\\n/**\\n * @template {{}} T\\n * @param {T} proto\\n * @param {number} instanceCount\\n * @returns {T}\\n */\\nconst makeSelf=(proto,instanceCount)=>{\\nconst self=create(proto);\\nif(LABEL_INSTANCES){\\ndefineProperty(self,Symbol.toStringTag,{\\nvalue:`${proto[Symbol.toStringTag]}#${instanceCount}`,\\nwritable:false,\\nenumerable:false,\\nconfigurable:false});}\\n\\n\\nreturn harden(self);};\\n\\n\\nconst emptyRecord=harden({});\\n\\n/**\\n * When calling `defineDurableKind` and\\n * its siblings, used as the `init` function argument to indicate that the\\n * state record of the (virtual/durable) instances of the kind/exoClass\\n * should be empty, and that the returned maker function should have zero\\n * parameters.\\n *\\n * @returns {{}}\\n */\\nconst initEmpty=()=>emptyRecord;\\n\\n/**\\n * @template {(...args: any[]) => any} I init function\\n * @template {Methods} M methods\\n * @param {string} tag\\n * @param {ExoClassInterfaceGuard<M> | undefined} interfaceGuard\\n * @param {I} init\\n * @param {ExoClassMethods<M, I>} methods\\n * @param {FarClassOptions<IMPORT('./types.js').ClassContext<ReturnType<I>, M>>} [options]\\n * @returns {(...args: Parameters<I>) => Guarded<M>}\\n */\\nconst defineExoClass=(\\ntag,\\ninterfaceGuard,\\ninit,\\nmethods,\\noptions={})=>\\n{\\nharden(methods);\\nconst{\\nfinish=undefined,\\nreceiveAmplifier=undefined,\\nreceiveInstanceTester=undefined}=\\noptions;\\nreceiveAmplifier===undefined||\\nindex.throwRedacted`Only facets of an exo class kit can be amplified ${index.quote(tag)}`;\\n\\n/** @type {WeakMap<M, IMPORT('./types.js').ClassContext<ReturnType<I>, M>>} */\\nconst contextMap=new WeakMap();\\nconst proto=exoTools.defendPrototype(\\ntag,\\n(self)=>/** @type {any} */contextMap.get(self),\\nmethods,\\ntrue,\\ninterfaceGuard);\\n\\nlet instanceCount=0;\\n/**\\n * @param {Parameters<I>} args\\n */\\nconst makeInstance=(...args)=>{\\n/* Be careful not to freeze the state record*/\\nconst state=seal(init(...args));\\ninstanceCount+=1;\\nconst self=makeSelf(proto,instanceCount);\\n\\n/* Be careful not to freeze the state record*/\\n/** @type {IMPORT('./types.js').ClassContext<ReturnType<I>,M>} */\\nconst context=freeze({state,self});\\ncontextMap.set(self,context);\\nif(finish){\\nfinish(context);}\\n\\nreturn self;};\\n\\n\\nif(receiveInstanceTester){\\n/** @type {IsInstance} */\\nconst isInstance=(exo,facetName=undefined)=>{\\nfacetName===undefined||\\nindex.throwRedacted`facetName can only be used with an exo class kit: ${index.quote(\\ntag)\\n} has no facet ${index.quote(facetName)}`;\\nreturn contextMap.has(exo);};\\n\\nharden(isInstance);\\nreceiveInstanceTester(isInstance);}\\n\\n\\nreturn harden(makeInstance);};\\n\\nharden(defineExoClass);\\n\\n/**\\n * @template {(...args: any[]) => any} I init function\\n * @template {Record<FacetName, Methods>} F facet methods\\n * @param {string} tag\\n * @param {ExoClassInterfaceGuardKit<F> | undefined } interfaceGuardKit\\n * @param {I} init\\n * @param {ExoClassKitMethods<F, I>} methodsKit\\n * @param {FarClassOptions<\\n * KitContext<ReturnType<I>, GuardedKit<F>>,\\n * GuardedKit<F>\\n * >} [options]\\n * @returns {(...args: Parameters<I>) => GuardedKit<F>}\\n */\\nconst defineExoClassKit=(\\ntag,\\ninterfaceGuardKit,\\ninit,\\nmethodsKit,\\noptions={})=>\\n{\\nharden(methodsKit);\\nconst{\\nfinish=undefined,\\nreceiveAmplifier=undefined,\\nreceiveInstanceTester=undefined}=\\noptions;\\nconst contextMapKit=objectMap.objectMap(methodsKit,()=>new WeakMap());\\nconst getContextKit=objectMap.objectMap(\\ncontextMapKit,\\n(contextMap)=>(facet)=>contextMap.get(facet));\\n\\nconst prototypeKit=exoTools.defendPrototypeKit(\\ntag,\\ngetContextKit,\\nmethodsKit,\\ntrue,\\ninterfaceGuardKit);\\n\\nlet instanceCount=0;\\n/**\\n * @param {Parameters<I>} args\\n */\\nconst makeInstanceKit=(...args)=>{\\n/* Be careful not to freeze the state record*/\\nconst state=seal(init(...args));\\n/* Don't freeze context until we add facets*/\\n/** @type {{ state: ReturnType<I>, facets: any }} */\\nconst context={state,facets:null};\\ninstanceCount+=1;\\nconst facets=objectMap.objectMap(prototypeKit,(proto,facetName)=>{\\nconst self=makeSelf(proto,instanceCount);\\ncontextMapKit[facetName].set(self,context);\\nreturn self;});\\n\\ncontext.facets=facets;\\n/* Be careful not to freeze the state record*/\\nfreeze(context);\\nif(finish){\\nfinish(context);}\\n\\nreturn(/** @type {GuardedKit<F>} */context.facets);};\\n\\n\\nif(receiveAmplifier){\\n/** @type {Amplify} */\\nconst amplify=(exoFacet)=>{\\nfor(const contextMap of values(contextMapKit)){\\nif(contextMap.has(exoFacet)){\\nconst{facets}=contextMap.get(exoFacet);\\nreturn facets;}}\\n\\n\\nthrow index.throwRedacted`Must be a facet of ${index.quote(tag)}: ${exoFacet}`;};\\n\\nharden(amplify);\\nreceiveAmplifier(amplify);}\\n\\n\\nif(receiveInstanceTester){\\n/** @type {IsInstance} */\\nconst isInstance=(exoFacet,facetName=undefined)=>{\\nif(facetName===undefined){\\nreturn values(contextMapKit).some((contextMap)=>\\ncontextMap.has(exoFacet));}\\n\\n\\nassert.typeof(facetName,'string');\\nconst contextMap=contextMapKit[facetName];\\ncontextMap!==undefined||\\nindex.throwRedacted`exo class kit ${index.quote(tag)} has no facet named ${index.quote(facetName)}`;\\nreturn contextMap.has(exoFacet);};\\n\\nharden(isInstance);\\nreceiveInstanceTester(isInstance);}\\n\\n\\nreturn harden(makeInstanceKit);};\\n\\nharden(defineExoClassKit);\\n\\n/**\\n * @template {Methods} T\\n * @param {string} tag\\n * @param {IMPORT('@endo/patterns').InterfaceGuard<{\\n * [M in keyof T]: IMPORT('@endo/patterns').MethodGuard\\n * }> | undefined} interfaceGuard CAVEAT: static typing does not yet support `callWhen` transformation\\n * @param {T} methods\\n * @param {FarClassOptions<IMPORT('./types.js').ClassContext<{},T>>} [options]\\n * @returns {Guarded<T>}\\n */\\nconst makeExo=(tag,interfaceGuard,methods,options=undefined)=>{\\nconst makeInstance=defineExoClass(\\ntag,\\ninterfaceGuard,\\ninitEmpty,\\nmethods,\\noptions);\\n\\nreturn makeInstance();};\\n\\nharden(makeExo);exports.defineExoClass=defineExoClass;exports.defineExoClassKit=defineExoClassKit;exports.initEmpty=initEmpty;exports.makeExo=makeExo;\",\n \"node_modules/@endo/exo/src/exo-tools.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../eventual-send/utils.js');require('../../pass-style/index.js');require('../../far/src/index.js');require('../../patterns/index.js');var listDifference=require('../../common/list-difference.js');var objectMap=require('../../common/object-map.js');var index=require('../../errors/index.js');var getInterface=require('./get-interface.js');var patternMatchers=require('../../patterns/src/patterns/patternMatchers.js');var passStyleOf=require('../../pass-style/src/passStyleOf.js');var getGuardPayloads=require('../../patterns/src/patterns/getGuardPayloads.js');var noShim=require('../../eventual-send/src/no-shim.js');var local=require('../../eventual-send/src/local.js');var checkKey=require('../../patterns/src/keys/checkKey.js');var passStyleHelpers=require('../../pass-style/src/passStyle-helpers.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nmakeFar=require('../../pass-style/src/make-far.js');/**\\n * @import {InterfaceGuard, Method, MethodGuard, MethodGuardPayload} from '@endo/patterns'\\n * @import {ClassContext, ContextProvider, FacetName, KitContext, KitContextProvider, MatchConfig, Methods} from './types.js'\\n */\\n\\nconst{apply,ownKeys}=Reflect;\\nconst{defineProperties,fromEntries}=Object;\\n\\n/**\\n * A method guard, for inclusion in an interface guard, that does not\\n * enforce any constraints of incoming arguments or return results.\\n */\\nconst RawMethodGuard=patternMatchers.M.call().rest(patternMatchers.M.raw()).returns(patternMatchers.M.raw());\\n\\nconst REDACTED_RAW_ARG='<redacted raw arg>';\\n\\n/**\\n * A method guard, for inclusion in an interface guard, that enforces only that\\n * all arguments are passable and that the result is passable. (In far classes,\\n * \\\"any\\\" means any *passable*.) This is the least possible non-raw\\n * enforcement for a method guard, and is implied by all other\\n * non-raw method guards.\\n */\\nconst PassableMethodGuard=patternMatchers.M.call().rest(patternMatchers.M.any()).returns(patternMatchers.M.any());\\n\\n/**\\n * @param {IMPORT('@endo/pass-style').Passable[]} syncArgs\\n * @param {MatchConfig} matchConfig\\n * @param {string} [label]\\n * @returns {IMPORT('@endo/pass-style').Passable[]} Returns the args that should be passed to the raw method.\\n */\\nconst defendSyncArgs=(syncArgs,matchConfig,label=undefined)=>{\\nconst{\\ndeclaredLen,\\nhasRestArgGuard,\\nrestArgGuardIsRaw,\\nparamsPattern,\\nredactedIndices}=\\nmatchConfig;\\n\\n/* Use syncArgs if possible, but copy it when necessary to implement*/\\n/* redactions.*/\\nlet matchableArgs=syncArgs;\\nif(restArgGuardIsRaw&&syncArgs.length>declaredLen){\\nconst restLen=syncArgs.length-declaredLen;\\nconst redactedRest=Array(restLen).fill(REDACTED_RAW_ARG);\\nmatchableArgs=[...syncArgs.slice(0,declaredLen),...redactedRest];}else\\nif(\\nredactedIndices.length>0&&\\nredactedIndices[0]<syncArgs.length)\\n{\\n/* Copy the arguments array, avoiding hardening the redacted ones (which are*/\\n/* trivially matched using REDACTED_RAW_ARG as a sentinel value).*/\\nmatchableArgs=[...syncArgs];}\\n\\n\\nfor(const i of redactedIndices){\\nif(i>=matchableArgs.length){\\nbreak;}\\n\\nmatchableArgs[i]=REDACTED_RAW_ARG;}\\n\\n\\npatternMatchers.mustMatch(harden(matchableArgs),paramsPattern,label);\\n\\nif(hasRestArgGuard){\\nreturn syncArgs;}\\n\\nsyncArgs.length<=declaredLen||\\nindex.throwRedacted`${index.quote(label)} accepts at most ${index.quote(declaredLen)} arguments, not ${index.quote(\\nsyncArgs.length)\\n}: ${syncArgs}`;\\nreturn syncArgs;};\\n\\n\\n/**\\n * Convert a method guard to a match config for more efficient per-call\\n * execution. This is a one-time conversion, so it's OK to be slow.\\n *\\n * Most of the work is done to detect `M.raw()` so that we build a match pattern\\n * and metadata instead of doing this in the hot path.\\n * @param {MethodGuardPayload} methodGuardPayload\\n * @returns {MatchConfig}\\n */\\nconst buildMatchConfig=(methodGuardPayload)=>{\\nconst{\\nargGuards,\\noptionalArgGuards=[],\\nrestArgGuard}=\\nmethodGuardPayload;\\n\\nconst matchableArgGuards=[...argGuards,...optionalArgGuards];\\n\\nconst redactedIndices=[];\\nfor(let i=0;i<matchableArgGuards.length;i+=1){\\nif(patternMatchers.isRawGuard(matchableArgGuards[i])){\\nmatchableArgGuards[i]=REDACTED_RAW_ARG;\\nredactedIndices.push(i);}}\\n\\n\\n\\n/* Pass through raw rest arguments without matching.*/\\nlet matchableRestArgGuard=restArgGuard;\\nif(patternMatchers.isRawGuard(matchableRestArgGuard)){\\nmatchableRestArgGuard=patternMatchers.M.arrayOf(REDACTED_RAW_ARG);}\\n\\nconst matchableMethodGuardPayload=harden({\\n...methodGuardPayload,\\nargGuards:matchableArgGuards.slice(0,argGuards.length),\\noptionalArgGuards:matchableArgGuards.slice(argGuards.length),\\nrestArgGuard:matchableRestArgGuard});\\n\\n\\nconst paramsPattern=patternMatchers.M.splitArray(\\nmatchableMethodGuardPayload.argGuards,\\nmatchableMethodGuardPayload.optionalArgGuards,\\nmatchableMethodGuardPayload.restArgGuard);\\n\\n\\nreturn harden({\\ndeclaredLen:matchableArgGuards.length,\\nhasRestArgGuard:restArgGuard!==undefined,\\nrestArgGuardIsRaw:restArgGuard!==matchableRestArgGuard,\\nparamsPattern,\\nredactedIndices,\\nmatchableMethodGuardPayload});};\\n\\n\\n\\n/**\\n * @param {(representative: any) => ClassContext | KitContext} getContext\\n * @param {CallableFunction} behaviorMethod\\n * @param {MethodGuardPayload} methodGuardPayload\\n * @param {string} label\\n * @returns {Method}\\n */\\nconst defendSyncMethod=(\\ngetContext,\\nbehaviorMethod,\\nmethodGuardPayload,\\nlabel)=>\\n{\\nconst{returnGuard}=methodGuardPayload;\\nconst isRawReturn=patternMatchers.isRawGuard(returnGuard);\\nconst matchConfig=buildMatchConfig(methodGuardPayload);\\nconst{syncMethod}={\\n/* Note purposeful use of `this` and concise method syntax*/\\nsyncMethod(...syncArgs){\\ntry{\\nconst context=getContext(this);\\n/* Only harden args and return value if not dealing with a raw value guard.*/\\nconst realArgs=defendSyncArgs(syncArgs,matchConfig,label);\\nconst result=apply(behaviorMethod,context,realArgs);\\nif(!isRawReturn){\\npatternMatchers.mustMatch(harden(result),returnGuard,`${label}: result`);}\\n\\nreturn result;}\\ncatch(thrownThing){\\nthrow passStyleOf.toThrowable(thrownThing);}}};\\n\\n\\n\\nreturn syncMethod;};\\n\\n\\n/**\\n * @param {MethodGuardPayload} methodGuardPayload\\n */\\nconst desync=(methodGuardPayload)=>{\\nconst{\\nargGuards,\\noptionalArgGuards=[],\\nrestArgGuard}=\\nmethodGuardPayload;\\n!patternMatchers.isAwaitArgGuard(restArgGuard)||\\nindex.throwRedacted`Rest args may not be awaited: ${restArgGuard}`;\\nconst rawArgGuards=[...argGuards,...optionalArgGuards];\\n\\nconst awaitIndexes=[];\\nfor(let i=0;i<rawArgGuards.length;i+=1){\\nconst argGuard=rawArgGuards[i];\\nif(patternMatchers.isAwaitArgGuard(argGuard)){\\nrawArgGuards[i]=getGuardPayloads.getAwaitArgGuardPayload(argGuard).argGuard;\\nawaitIndexes.push(i);}}\\n\\n\\nreturn{\\nawaitIndexes,\\nrawMethodGuardPayload:{\\n...methodGuardPayload,\\nargGuards:rawArgGuards.slice(0,argGuards.length),\\noptionalArgGuards:rawArgGuards.slice(argGuards.length)}};};\\n\\n\\n\\n\\n/**\\n * @param {(representative: any) => ClassContext | KitContext} getContext\\n * @param {CallableFunction} behaviorMethod\\n * @param {MethodGuardPayload} methodGuardPayload\\n * @param {string} label\\n */\\nconst defendAsyncMethod=(\\ngetContext,\\nbehaviorMethod,\\nmethodGuardPayload,\\nlabel)=>\\n{\\nconst{returnGuard}=methodGuardPayload;\\nconst isRawReturn=patternMatchers.isRawGuard(returnGuard);\\n\\nconst{awaitIndexes,rawMethodGuardPayload}=desync(methodGuardPayload);\\nconst matchConfig=buildMatchConfig(rawMethodGuardPayload);\\n\\nconst{asyncMethod}={\\n/* Note purposeful use of `this` and concise method syntax*/\\nasyncMethod(...args){\\nconst awaitList=[];\\nfor(const i of awaitIndexes){\\nif(i>=args.length){\\nbreak;}\\n\\nawaitList.push(args[i]);}\\n\\nconst p=Promise.all(awaitList);\\nconst syncArgs=[...args];\\nconst resultP=noShim.E.when(\\np,\\n/** @param {any[]} awaitedArgs */(awaitedArgs)=>{\\nfor(let j=0;j<awaitedArgs.length;j+=1){\\nsyncArgs[awaitIndexes[j]]=awaitedArgs[j];}\\n\\n/* Get the context after all waiting in case we ever do revocation*/\\n/* by removing the context entry. Avoid TOCTTOU!*/\\nconst context=getContext(this);\\nconst realArgs=defendSyncArgs(syncArgs,matchConfig,label);\\nreturn apply(behaviorMethod,context,realArgs);});\\n\\n\\nreturn noShim.E.when(resultP,(fulfillment)=>{\\nif(!isRawReturn){\\npatternMatchers.mustMatch(harden(fulfillment),returnGuard,`${label}: result`);}\\n\\nreturn fulfillment;}).\\ncatch((reason)=>\\n/* Done is a chained `.catch` rather than an onRejected clause of the*/\\n/* `E.when` above in case the `mustMatch` throws.*/\\nPromise.reject(passStyleOf.toThrowable(reason)));}};\\n\\n\\n\\nreturn asyncMethod;};\\n\\n\\n/**\\n *\\n * @param {(representative: any) => ClassContext | KitContext} getContext\\n * @param {CallableFunction} behaviorMethod\\n * @param {MethodGuard} methodGuard\\n * @param {string} label\\n */\\nconst defendMethod=(getContext,behaviorMethod,methodGuard,label)=>{\\nconst methodGuardPayload=getGuardPayloads.getMethodGuardPayload(methodGuard);\\nconst{callKind}=methodGuardPayload;\\nif(callKind==='sync'){\\nreturn defendSyncMethod(\\ngetContext,\\nbehaviorMethod,\\nmethodGuardPayload,\\nlabel);}else\\n\\n{\\nassert(callKind==='async');\\nreturn defendAsyncMethod(\\ngetContext,\\nbehaviorMethod,\\nmethodGuardPayload,\\nlabel);}};\\n\\n\\n\\n\\n/**\\n * @param {string} methodTag\\n * @param {ContextProvider} contextProvider\\n * @param {CallableFunction} behaviorMethod\\n * @param {MethodGuard} methodGuard\\n */\\nconst bindMethod=(\\nmethodTag,\\ncontextProvider,\\nbehaviorMethod,\\nmethodGuard)=>\\n{\\nassert.typeof(behaviorMethod,'function');\\n\\n/**\\n * @param {any} representative\\n * @returns {ClassContext | KitContext}\\n */\\nconst getContext=(representative)=>{\\nrepresentative||\\n/* separate line to ease breakpointing*/\\nindex.throwRedacted`Method ${methodTag} called without 'this' object`;\\nconst context=contextProvider(representative);\\nif(context===undefined){\\nthrow index.throwRedacted`${index.quote(\\nmethodTag)\\n} may only be applied to a valid instance: ${representative}`;}\\n\\nreturn context;};\\n\\n\\nconst method=defendMethod(\\ngetContext,\\nbehaviorMethod,\\nmethodGuard,\\nmethodTag);\\n\\n\\ndefineProperties(method,{\\nname:{value:methodTag},\\nlength:{value:behaviorMethod.length}});\\n\\nreturn method;};\\n\\n\\n/**\\n * @template {Record<PropertyKey, CallableFunction>} T\\n * @param {string} tag\\n * @param {ContextProvider} contextProvider\\n * @param {T} behaviorMethods\\n * @param {boolean} [thisfulMethods]\\n * @param {InterfaceGuard<{ [M in keyof T]: MethodGuard }>} [interfaceGuard]\\n */\\nconst defendPrototype=(\\ntag,\\ncontextProvider,\\nbehaviorMethods,\\nthisfulMethods=false,\\ninterfaceGuard=undefined)=>\\n{\\nconst prototype={};\\nconst methodNames=local.getMethodNames(behaviorMethods).filter(\\n/* By ignoring any method that seems to be a constructor, we can use a*/\\n/* class.prototype as a behaviorMethods.*/\\n(key)=>{\\nif(key!=='constructor'){\\nreturn true;}\\n\\nconst constructor=behaviorMethods.constructor;\\nreturn!(\\nconstructor.prototype&&\\nconstructor.prototype.constructor===constructor);});\\n\\n\\n\\n/** @type {Record<PropertyKey, MethodGuard> | undefined} */\\nlet methodGuards;\\n/** @type {IMPORT('@endo/patterns').DefaultGuardType} */\\nlet defaultGuards;\\nif(interfaceGuard){\\nconst{\\ninterfaceName,\\nmethodGuards:mg,\\nsymbolMethodGuards,\\nsloppy,\\ndefaultGuards:dg=sloppy?'passable':defaultGuards}=\\ngetGuardPayloads.getInterfaceGuardPayload(interfaceGuard);\\nmethodGuards=harden({\\n...mg,\\n...(symbolMethodGuards&&\\nfromEntries(checkKey.getCopyMapEntries(symbolMethodGuards)))});\\n\\ndefaultGuards=dg;\\n{\\nconst methodGuardNames=ownKeys(methodGuards);\\nconst unimplemented=listDifference.listDifference(methodGuardNames,methodNames);\\nunimplemented.length===0||\\nindex.throwRedacted`methods ${index.quote(unimplemented)} not implemented by ${index.quote(tag)}`;\\nif(defaultGuards===undefined){\\nconst unguarded=listDifference.listDifference(methodNames,methodGuardNames);\\nunguarded.length===0||\\nindex.throwRedacted`methods ${index.quote(unguarded)} not guarded by ${index.quote(interfaceName)}`;}}}\\n\\n\\n\\n\\nfor(const prop of methodNames){\\nconst originalMethod=behaviorMethods[prop];\\nconst{shiftedMethod}={\\nshiftedMethod(...args){\\nreturn originalMethod(this,...args);}};\\n\\n\\nconst behaviorMethod=thisfulMethods?originalMethod:shiftedMethod;\\n/* TODO some tool does not yet understand the `?.[` syntax*/\\n/* See https://github.com/endojs/endo/pull/2247#discussion_r1583724424*/\\nlet methodGuard=methodGuards&&methodGuards[prop];\\nif(!methodGuard){\\nswitch(defaultGuards){\\ncase undefined:{\\nif(thisfulMethods){\\nmethodGuard=PassableMethodGuard;}else\\n{\\nmethodGuard=RawMethodGuard;}\\n\\nbreak;}\\n\\ncase'passable':{\\nmethodGuard=PassableMethodGuard;\\nbreak;}\\n\\ncase'raw':{\\nmethodGuard=RawMethodGuard;\\nbreak;}\\n\\ndefault:{\\nthrow index.throwRedacted`Unrecognized defaultGuards ${index.quote(defaultGuards)}`;}}}\\n\\n\\n\\nprototype[prop]=bindMethod(\\n`In ${index.quote(prop)} method of (${tag})`,\\ncontextProvider,\\nbehaviorMethod,\\nmethodGuard);}\\n\\n\\n\\nif(!passStyleHelpers.hasOwnPropertyOf(prototype,getInterface.GET_INTERFACE_GUARD)){\\nconst getInterfaceGuardMethod={\\n[getInterface.GET_INTERFACE_GUARD](){\\n/* Note: May be `undefined`*/\\nreturn interfaceGuard;}}[\\n\\ngetInterface.GET_INTERFACE_GUARD];\\nprototype[getInterface.GET_INTERFACE_GUARD]=bindMethod(\\n`In ${index.quote(getInterface.GET_INTERFACE_GUARD)} method of (${tag})`,\\ncontextProvider,\\ngetInterfaceGuardMethod,\\nPassableMethodGuard);}\\n\\n\\n\\nreturn makeFar.Far(\\ntag,\\n/** @type {T & IMPORT('./get-interface.js').GetInterfaceGuard<T>} */\\nprototype);};\\n\\n\\n\\nharden(defendPrototype);\\n\\n/**\\n * @template {Record<FacetName, Methods>} F\\n * @param {string} tag\\n * @param {{ [K in keyof F]: KitContextProvider }} contextProviderKit\\n * @param {F} behaviorMethodsKit\\n * @param {boolean} [thisfulMethods]\\n * @param {{ [K in keyof F]: InterfaceGuard<Record<keyof F[K], MethodGuard>> }} [interfaceGuardKit]\\n */\\nconst defendPrototypeKit=(\\ntag,\\ncontextProviderKit,\\nbehaviorMethodsKit,\\nthisfulMethods=false,\\ninterfaceGuardKit=undefined)=>\\n{\\nconst facetNames=ownKeys(behaviorMethodsKit).sort();\\nfacetNames.length>1||index.throwRedacted`A multi-facet object must have multiple facets`;\\nif(interfaceGuardKit){\\nconst interfaceNames=ownKeys(interfaceGuardKit);\\nconst extraInterfaceNames=listDifference.listDifference(facetNames,interfaceNames);\\nextraInterfaceNames.length===0||\\nindex.throwRedacted`Interfaces ${index.quote(extraInterfaceNames)} not implemented by ${index.quote(tag)}`;\\nconst extraFacetNames=listDifference.listDifference(interfaceNames,facetNames);\\nextraFacetNames.length===0||\\nindex.throwRedacted`Facets ${index.quote(extraFacetNames)} of ${index.quote(tag)} not guarded by interfaces`;}\\n\\nconst contextMapNames=ownKeys(contextProviderKit);\\nconst extraContextNames=listDifference.listDifference(facetNames,contextMapNames);\\nextraContextNames.length===0||\\nindex.throwRedacted`Contexts ${index.quote(extraContextNames)} not implemented by ${index.quote(tag)}`;\\nconst extraFacetNames=listDifference.listDifference(contextMapNames,facetNames);\\nextraFacetNames.length===0||\\nindex.throwRedacted`Facets ${index.quote(extraFacetNames)} of ${index.quote(tag)} missing contexts`;\\nconst protoKit=objectMap.objectMap(behaviorMethodsKit,(behaviorMethods,facetName)=>\\ndefendPrototype(\\n`${tag} ${String(facetName)}`,\\ncontextProviderKit[facetName],\\nbehaviorMethods,\\nthisfulMethods,\\ninterfaceGuardKit&&interfaceGuardKit[facetName]));\\n\\n\\nreturn protoKit;};exports.defendPrototype=defendPrototype;exports.defendPrototypeKit=defendPrototypeKit;\",\n \"node_modules/@endo/exo/src/get-interface.js\": \"'use strict';\\n\\nObject.defineProperty(exports,'__esModule',{value:true});/* @ts-check*/ /**\\n * The name of the automatically added default meta-method for\\n * obtaining an exo's interface, if it has one.\\n *\\n * Intended to be similar to `GET_METHOD_NAMES` from `@endo/pass-style`.\\n *\\n * TODO Name to be bikeshed. Perhaps even whether it is a\\n * string or symbol to be bikeshed. See\\n * https://github.com/endojs/endo/pull/1809#discussion_r1388052454\\n *\\n * TODO Beware that an exo's interface can change across an upgrade,\\n * so remotes that cache it can become stale.\\n */\\nconst GET_INTERFACE_GUARD='__getInterfaceGuard__';\\n\\n/**\\n * @template {Record<PropertyKey, CallableFunction>} M\\n * @typedef {{\\n * [GET_INTERFACE_GUARD]?: () =>\\n * IMPORT('@endo/patterns').InterfaceGuard<{\\n * [K in keyof M]: IMPORT('@endo/patterns').MethodGuard\\n * }> | undefined\\n * }} GetInterfaceGuard\\n */exports.GET_INTERFACE_GUARD=GET_INTERFACE_GUARD;\",\n \"node_modules/@endo/exo/src/types.js\": \"'use strict';/** @file Empty twin for .d.ts */\",\n \"node_modules/@endo/exo/tools.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var exoTools=require('./src/exo-tools.js');exports.defendPrototype=exoTools.defendPrototype;exports.defendPrototypeKit=exoTools.defendPrototypeKit;\",\n \"node_modules/@endo/far/src/index.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var noShim=require('../../eventual-send/src/no-shim.js');\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nrequire('../../pass-style/index.js');/* TODO re-export from eventual-send, may require .d.ts*/ /**\\n * @template Primary\\n * @template [Local=IMPORT('@endo/eventual-send').DataOnly<Primary>]\\n * @typedef {IMPORT('@endo/eventual-send').FarRef<Primary, Local>} FarRef\\n * Declare an object that is potentially a far reference of type Primary whose\\n * auxilliary data has type Local. This should be used only for consumers of\\n * Far objects in arguments and declarations; the only creators of Far objects\\n * are distributed object creator components like the `Far` or `Remotable`\\n * functions.\\n */ /**\\n * @template T\\n * @typedef {IMPORT('@endo/eventual-send').ERef<T>} ERef\\n * Declare that `T` may or may not be a Promise. This should be used only for\\n * consumers of arguments and declarations; return values should specifically be\\n * `Promise<T>` or `T` itself.\\n */ /**\\n * @template T\\n * @typedef {IMPORT('@endo/eventual-send').EOnly<T>} EOnly\\n * Declare a near object that must only be invoked with E, even locally. It\\n * supports the `T` interface but additionally permits `T`'s methods to return\\n * `PromiseLike`s even if `T` declares them as only synchronous.\\n */exports.E=noShim.E;\",\n \"node_modules/@endo/import-bundle/src/compartment-wrapper.js\": \"'use strict';\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nObject.defineProperty(exports,'__esModule',{value:true});/** @import {ModuleDescriptor} from 'ses' */ /* In order to facilitate migration from the deprecated signature*/ /* of the compartment constructor,*/ /* new Compartent(globals?, modules?, options?)*/ /* to the new signature:*/ /* new Compartment(options?)*/ /* where globals and modules are expressed in the options bag instead of*/ /* positional arguments, this function detects the temporary sigil __options__*/ /* on the first argument and coerces compartments arguments into a single*/ /* compartments object.*/\\nconst compartmentOptions=(...args)=>{\\nif(args.length===0){\\nreturn{};}\\n\\nif(\\nargs.length===1&&\\ntypeof args[0]==='object'&&\\nargs[0]!==null&&\\n'__options__'in args[0])\\n{\\nconst{__options__,...options}=args[0];\\nassert(\\n__options__===true,\\n`Compartment constructor only supports true __options__ sigil, got ${__options__}`);\\n\\nreturn options;}else\\n{\\nconst[\\nglobals=/** @type {Map<string, any>} */{},\\nmodules=/** @type {Map<string, ModuleDescriptor>} */{},\\noptions={}]=\\nargs;\\nassert.equal(\\noptions.modules,\\nundefined,\\n`Compartment constructor must receive either a module map argument or modules option, not both`);\\n\\nassert.equal(\\noptions.globals,\\nundefined,\\n`Compartment constructor must receive either globals argument or option, not both`);\\n\\nreturn{\\n...options,\\nglobals,\\nmodules};}};\\n\\n\\n\\n\\nfunction wrapInescapableCompartment(\\nOldCompartment,\\ninescapableTransforms,\\ninescapableGlobalProperties)\\n{\\n/* This is the new Compartment constructor. We name it `Compartment` so*/\\n/* that it's .name property is correct, but we hold it in 'NewCompartment'*/\\n/* so that lint doesn't think we're shadowing the original.*/\\nconst NewCompartment=function Compartment(...args){\\nconst{transforms:oldTransforms=[],...otherOptions}=\\ncompartmentOptions(...args);\\nconst newTransforms=[...oldTransforms,...inescapableTransforms];\\nconst newOptions={\\n...otherOptions,\\ntransforms:newTransforms,\\n__options__:true};\\n\\n\\n/* The real Compartment is defined as a class, so 'new Compartment()'*/\\n/* works but not 'Compartment()'. We can behave the same way. It would be*/\\n/* nice to delegate the 'throw' to the original constructor by knowing*/\\n/* calling it the wrong way, but I don't know how to do that.*/\\nif(new.target===undefined){\\n/* `newCompartment` was called as a function*/\\nthrow Error('Compartment must be called as a constructor');}\\n\\n\\n/* It, or a subclass, was called as a constructor*/\\n\\nconst c=Reflect.construct(OldCompartment,[newOptions],new.target);\\n/* The confinement applies to all compartments too. This relies upon the*/\\n/* child's normal Compartment behaving the same way as the parent's,*/\\n/* which will cease to be the case soon (their module tables are*/\\n/* different). TODO: update this when that happens, we need something*/\\n/* like c.globalThis.Compartment = wrap(c.globalThis.Compartment), but*/\\n/* there are details to work out.*/\\nc.globalThis.Compartment=NewCompartment;\\n\\n/* Use Reflect.ownKeys, not Object.keys, because we want both*/\\n/* string-named and symbol-named properties. Note that*/\\n/* Reflect.ownKeys also includes non-enumerable keys.*/\\n/* This differs from the longer term agreement discussed at*/\\n/* https://www.youtube.com/watch?v=xlR21uDigGE in these ways:*/\\n/* - The option in question should be named `inescapableGlobals` since*/\\n/* we want to reserve `*Properties` for descriptor copying rather*/\\n/* than value copying.*/\\n/* - We don't plan to support such `*Properties` options at this time.*/\\n/* Rather, we should deprecate (and eventually remove) this one*/\\n/* once we introduce`inescapableGlobals`.*/\\n/* - We plan to move these options to the `Compartment` constructor itself,*/\\n/* in which case their support in import-bundle will just forward*/\\n/* to `Compartment`.*/\\n/* - Following the `assign`-like semantics agree on in that meeting,*/\\n/* this should only copy enumerable own properties, whereas the loop*/\\n/* below copies all own properties.*/\\n/* The loop here does follow this agreement by differing from `assign` in*/\\n/* making all the target properties non-enumerable. The agreement would*/\\n/* further align the normal `Compartment` endowments argument to also*/\\n/* make the target properties non-enumerable.*/\\nfor(const prop of Reflect.ownKeys(inescapableGlobalProperties)){\\nObject.defineProperty(c.globalThis,prop,{\\nvalue:inescapableGlobalProperties[prop],\\nwritable:true,\\n/* properties of globalThis are generally non-enumerable*/\\nenumerable:false,\\nconfigurable:true});}\\n\\n\\n\\nreturn c;};\\n\\n\\n/* ensure `(c isinstance Compartment)` remains true*/\\nNewCompartment.prototype=OldCompartment.prototype;\\n\\n/* SECURITY NOTE: if this were used outside of SES, this might leave*/\\n/* c.prototype.constructor pointing at the original (untamed) Compartment,*/\\n/* which would allow a breach. Kris says this will be hard to fix until he*/\\n/* rewrites the compartment shim, possibly as a plain function instead of a*/\\n/* class. Under SES, OldCompartment.prototype.constructor is tamed*/\\n\\nreturn NewCompartment;}\\n\\n\\n/* swingset would do this to each dynamic vat*/\\n/* c.globalThis.Compartment = wrapCompartment(c.globalThis.Compartment, ..);*/exports.wrapInescapableCompartment=wrapInescapableCompartment;\",\n \"node_modules/@endo/import-bundle/src/index.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../compartment-mapper/import-archive.js');require('../../base64/index.js');var index=require('../../errors/index.js');var compartmentWrapper=require('./compartment-wrapper.js');var decode=require('../../base64/src/decode.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nimportArchive=require('../../compartment-mapper/src/import-archive.js');/* XXX Omit from typecheck for TypeScript packages depending upon*/ /* importBundle takes the output of bundle-source, and returns a namespace*/ /* object (with .default, and maybe other properties for named exports)*/\\n\\nasync function importBundle(bundle,options={},powers={}){\\nawait null;\\nconst{\\nbundleUrl=undefined,\\nfilePrefix,\\nendowments:optEndowments={},\\n/* transforms are indeed __shimTransforms__, intended to apply to both*/\\n/* evaluated programs and modules shimmed to programs.*/\\ntransforms=[],\\ninescapableTransforms=[],\\ninescapableGlobalProperties={},\\nexpectedSha512=undefined}=\\noptions;\\nconst{\\ncomputeSha512=undefined,\\ncomputeSourceLocation=undefined,\\ncomputeSourceMapLocation=undefined}=\\npowers;\\nconst endowments={\\nTextEncoder,\\nTextDecoder,\\nURL:globalThis.URL,/* Absent only in XSnap*/\\nBase64:globalThis.Base64,/* Present only in XSnap*/\\natob:globalThis.atob,\\nbtoa:globalThis.btoa,\\n...optEndowments};\\n\\n\\nlet CompartmentToUse=Compartment;\\nif(\\ninescapableTransforms.length||\\nObject.keys(inescapableGlobalProperties).length)\\n{\\n/* @ts-expect-error TS2322 no match for the signature*/\\nCompartmentToUse=compartmentWrapper.wrapInescapableCompartment(\\nCompartment,\\ninescapableTransforms,\\ninescapableGlobalProperties);}\\n\\n\\n\\nconst{moduleFormat}=bundle;\\nif(moduleFormat==='endoZipBase64'){\\nconst{endoZipBase64}=bundle;\\nconst bytes=decode.decodeBase64(endoZipBase64);\\nconst archive=await importArchive.parseArchive(bytes,bundleUrl,{\\ncomputeSha512,\\nexpectedSha512,\\ncomputeSourceLocation,\\ncomputeSourceMapLocation});\\n\\n/* Call import by property to bypass SES censoring for dynamic import.*/\\n/* eslint-disable-next-line dot-notation*/\\nconst{namespace}=await archive['import']({\\nglobals:endowments,\\n__shimTransforms__:transforms,\\n/* @ts-expect-error TS2740 missing properties from type*/\\nCompartment:CompartmentToUse});\\n\\n/* namespace.default has the default export*/\\nreturn namespace;}\\n\\n\\nlet c;\\nconst{source,sourceMap}=bundle;\\nif(moduleFormat==='getExport'){\\n/* The 'getExport' format is a string which defines a wrapper function*/\\n/* named `getExport()`. This function provides a `module` to the*/\\n/* linearized source file, executes that source, then returns*/\\n/* `module.exports`. To get the function object out of a program-mode*/\\n/* evaluation, we must wrap the function definition in parentheses*/\\n/* (making it an expression). We also want to append the `sourceMap`*/\\n/* comment so `evaluate` can attach useful debug information. Finally, to*/\\n/* extract the namespace object, we need to invoke this function.*/}else\\nif(moduleFormat==='nestedEvaluate'){\\n/* The 'nestedEvaluate' format is similar, except the wrapper function*/\\n/* (now named `getExportWithNestedEvaluate`) wraps more than a single*/\\n/* linearized string. Each source module is processed (converting*/\\n/* `import` into `require`) and added to a table named `sourceBundle`.*/\\n/* Each module will be evaluated separately (so they can get distinct*/\\n/* sourceMap strings), using a mandatory endowment named*/\\n/* `nestedEvaluate`. The wrapper function should be called with*/\\n/* `filePrefix`, which will be used as the sourceMap for the top-level*/\\n/* module. The sourceMap name for other modules will be derived from*/\\n/* `filePrefix` and the relative import path of each module.*/\\nendowments.nestedEvaluate=(src)=>c.evaluate(src);}else\\n{\\nindex.throwRedacted`unrecognized moduleFormat '${moduleFormat}'`;}\\n\\n\\nc=new CompartmentToUse(endowments,{},{transforms});\\nharden(c.globalThis);\\nconst actualSource=`(${source})\\\\n${sourceMap||''}`;\\nconst namespace=c.evaluate(actualSource)(filePrefix);\\n/* namespace.default has the default export*/\\nreturn namespace;}\\n\\n\\n/* importBundle(bundle, { metering: { getMeter, meteringOptions } });\\nimportBundle(bundle, { transforms: [ meterTransform ], lexicals: { getMeter } });\\nimportBundle(bundle, { mandatoryTransforms: [ meterTransform ], mandatoryLexicals: { getMeter } });\\n // then importBundle builds the Compartment wrapper\\n XS:\\n xs.setMeter();\\nxs.callWithMeter(meter, ns.dispatch);\\nxs.callWithKeeper(keeper, ns.dispatch); // keeper.getMeter() -> meter, then ns.dispatch()\\n// keeper.startCrank(metadata.tshirtsize)\\n// // keeper sets meter to some fixed value\\n// initialMeter = keeper.getMeter()\\n// ns.dispatch() // drains initialMeter\\n// maybe: keeper.endCrank() ???\\n */exports.importBundle=importBundle;\",\n \"node_modules/@endo/marshal/index.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var encodeToCapData=require('./src/encodeToCapData.js');var marshal=require('./src/marshal.js');var marshalStringify=require('./src/marshal-stringify.js');var marshalJustin=require('./src/marshal-justin.js');var encodePassable=require('./src/encodePassable.js');var rankOrder=require('./src/rankOrder.js');require('./src/types.js');require('../pass-style/index.js');exports.QCLASS=encodeToCapData.QCLASS;exports.makeMarshal=marshal.makeMarshal;exports.parse=marshalStringify.parse;exports.stringify=marshalStringify.stringify;exports.decodeToJustin=marshalJustin.decodeToJustin;exports.isEncodedRemotable=encodePassable.isEncodedRemotable;exports.makeDecodePassable=encodePassable.makeDecodePassable;exports.makeEncodePassable=encodePassable.makeEncodePassable;exports.makePassableKit=encodePassable.makePassableKit;exports.recordNames=encodePassable.recordNames;exports.recordValues=encodePassable.recordValues;exports.zeroPad=encodePassable.zeroPad;exports.assertRankSorted=rankOrder.assertRankSorted;exports.compareAntiRank=rankOrder.compareAntiRank;exports.compareRank=rankOrder.compareRank;exports.getPassStyleCover=rankOrder.getPassStyleCover;exports.intersectRankCovers=rankOrder.intersectRankCovers;exports.isRankSorted=rankOrder.isRankSorted;exports.makeFullOrderComparatorKit=rankOrder.makeFullOrderComparatorKit;exports.sortByRank=rankOrder.sortByRank;exports.trivialComparator=rankOrder.trivialComparator;exports.unionRankCovers=rankOrder.unionRankCovers;\",\n \"node_modules/@endo/marshal/src/encodePassable.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../pass-style/index.js');var index=require('../../errors/index.js');var passStyleOf=require('../../pass-style/src/passStyleOf.js');var typeGuards=require('../../pass-style/src/typeGuards.js');var passStyleHelpers=require('../../pass-style/src/passStyle-helpers.js');var makeTagged=require('../../pass-style/src/makeTagged.js');var error=require('../../pass-style/src/error.js');var symbol=require('../../pass-style/src/symbol.js');/* eslint-disable no-bitwise */\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nconst{isArray}=Array;\\nconst{fromEntries,is}=Object;\\nconst{ownKeys}=Reflect;\\n\\n/* eslint-disable-next-line no-control-regex*/\\nconst rC0=/[\\\\x00-\\\\x1F]/;\\n\\n/**\\n * Return the suffix of a string starting at a particular index.\\n * This both expresses intent and potentially avoids slow `substring` in XS.\\n * https://github.com/endojs/endo/issues/1984\\n *\\n * @param {string} str\\n * @param {number} index\\n * @returns {string}\\n */\\nconst getSuffix=(str,index)=>index===0?str:str.substring(index);\\n\\n/**\\n * Assuming that `record` is a CopyRecord, we have only\\n * string-named own properties. `recordNames` returns those name *reverse*\\n * sorted, because that's how records are compared, encoded, and sorted.\\n *\\n * @template {Passable} T\\n * @param {CopyRecord<T>} record\\n * @returns {string[]}\\n */\\nconst recordNames=(record)=>\\n/* https://github.com/endojs/endo/pull/1260#discussion_r1003657244*/\\n/* compares two ways of reverse sorting, and shows that `.sort().reverse()`*/\\n/* is currently faster on Moddable XS, while the other way,*/\\n/* `.sort(reverseComparator)`, is faster on v8. We currently care more about*/\\n/* XS performance, so we reverse sort using `.sort().reverse()`.*/\\nharden(/** @type {string[]} */ownKeys(record).sort().reverse());\\nharden(recordNames);\\n\\n/**\\n * Assuming that `record` is a CopyRecord and `names` is `recordNames(record)`,\\n * return the corresponding array of property values.\\n *\\n * @template {Passable} T\\n * @param {CopyRecord<T>} record\\n * @param {string[]} names\\n * @returns {T[]}\\n */\\nconst recordValues=(record,names)=>\\nharden(names.map((name)=>record[name]));\\nharden(recordValues);\\n\\nconst zeroes=Array(16).\\nfill(undefined).\\nmap((_,i)=>'0'.repeat(i));\\n\\n/**\\n * @param {unknown} n\\n * @param {number} size\\n * @returns {string}\\n */\\nconst zeroPad=(n,size)=>{\\nconst nStr=`${n}`;\\nconst fillLen=size-nStr.length;\\nif(fillLen===0)return nStr;\\nassert(fillLen>0&&fillLen<zeroes.length);\\nreturn`${zeroes[fillLen]}${nStr}`;};\\n\\nharden(zeroPad);\\n\\n/* This is the JavaScript analog to a C union: a way to map between a float as a*/\\n/* number and the bits that represent the float as a buffer full of bytes. Note*/\\n/* that the mutation of static state here makes this invalid Jessie code, but*/\\n/* doing it this way saves the nugatory and gratuitous allocations that would*/\\n/* happen every time you do a conversion -- and in practical terms it's safe*/\\n/* because we put the value in one side and then immediately take it out the*/\\n/* other; there is no actual state retained in the classic sense and thus no*/\\n/* re-entrancy issue.*/\\nconst asNumber=new Float64Array(1);\\nconst asBits=new BigUint64Array(asNumber.buffer);\\n\\n/* JavaScript numbers are encoded by outputting the base-16*/\\n/* representation of the binary value of the underlying IEEE floating point*/\\n/* representation. For negative values, all bits of this representation are*/\\n/* complemented prior to the base-16 conversion, while for positive values, the*/\\n/* sign bit is complemented. This ensures both that negative values sort before*/\\n/* positive values and that negative values sort according to their negative*/\\n/* magnitude rather than their positive magnitude. This results in an ASCII*/\\n/* encoding whose lexicographic sort order is the same as the numeric sort order*/\\n/* of the corresponding numbers.*/\\n\\n/* TODO Choose the same canonical NaN encoding that cosmWasm and ewasm chose.*/\\nconst CanonicalNaNBits='fff8000000000000';\\n\\n/**\\n * @param {number} n\\n * @returns {string}\\n */\\nconst encodeBinary64=(n)=>{\\n/* Normalize -0 to 0 and NaN to a canonical encoding*/\\nif(is(n,-0)){\\nn=0;}else\\nif(is(n,NaN)){\\nreturn`f${CanonicalNaNBits}`;}\\n\\nasNumber[0]=n;\\nlet bits=asBits[0];\\nif(n<0){\\nbits^=0xffffffffffffffffn;}else\\n{\\nbits^=0x8000000000000000n;}\\n\\nreturn`f${zeroPad(bits.toString(16),16)}`;};\\n\\n\\n/**\\n * @param {string} encoded\\n * @param {number} [skip]\\n * @returns {number}\\n */\\nconst decodeBinary64=(encoded,skip=0)=>{\\nencoded.charAt(skip)==='f'||index.throwRedacted`Encoded number expected: ${encoded}`;\\nlet bits=BigInt(`0x${getSuffix(encoded,skip+1)}`);\\nif(encoded.charAt(skip+1)<'8'){\\nbits^=0xffffffffffffffffn;}else\\n{\\nbits^=0x8000000000000000n;}\\n\\nasBits[0]=bits;\\nconst result=asNumber[0];\\n!is(result,-0)||\\nindex.throwRedacted`Unexpected negative zero: ${getSuffix(encoded,skip)}`;\\nreturn result;};\\n\\n\\n/**\\n * Encode a JavaScript bigint using a variant of Elias delta coding, with an\\n * initial component for the length of the digit count as a unary string, a\\n * second component for the decimal digit count, and a third component for the\\n * decimal digits preceded by a gratuitous separating colon.\\n * To ensure that the lexicographic sort order of encoded values matches the\\n * numeric sort order of the corresponding numbers, the characters of the unary\\n * prefix are different for negative values (type \\\"n\\\" followed by any number of\\n * \\\"#\\\"s [which sort before decimal digits]) vs. positive and zero values (type\\n * \\\"p\\\" followed by any number of \\\"~\\\"s [which sort after decimal digits]) and\\n * each decimal digit of the encoding for a negative value is replaced with its\\n * ten's complement (so that negative values of the same scale sort by\\n * *descending* absolute value).\\n *\\n * @param {bigint} n\\n * @returns {string}\\n */\\nconst encodeBigInt=(n)=>{\\nconst abs=n<0n?-n:n;\\nconst nDigits=abs.toString().length;\\nconst lDigits=nDigits.toString().length;\\nif(n<0n){\\nreturn`n${\\n/* A \\\"#\\\" for each digit beyond the first*/\\n/* in the decimal *count* of decimal digits.*/\\n'#'.repeat(lDigits-1)\\n}${\\n/* The ten's complement of the count of digits.*/\\n(10**lDigits-nDigits).toString().padStart(lDigits,'0')\\n}:${\\n/* The ten's complement of the digits.*/\\n(10n**BigInt(nDigits)+n).toString().padStart(nDigits,'0')\\n}`;}else\\n{\\nreturn`p${\\n/* A \\\"~\\\" for each digit beyond the first*/\\n/* in the decimal *count* of decimal digits.*/\\n'~'.repeat(lDigits-1)\\n}${\\n/* The count of digits.*/\\nnDigits\\n}:${\\n/* The digits.*/\\nn\\n}`;}};\\n\\n\\n\\nconst rBigIntPayload=/([0-9]+)(:([0-9]+$|)|)/s;\\n\\n/**\\n * @param {string} encoded\\n * @returns {bigint}\\n */\\nconst decodeBigInt=(encoded)=>{\\nconst typePrefix=encoded.charAt(0);/* faster than encoded[0]*/\\ntypePrefix==='p'||\\ntypePrefix==='n'||\\nindex.throwRedacted`Encoded bigint expected: ${encoded}`;\\n\\nconst{\\nindex:lDigits,\\n1:snDigits,\\n2:tail,\\n3:digits}=\\nencoded.match(rBigIntPayload)||index.throwRedacted`Digit count expected: ${encoded}`;\\n\\nsnDigits.length===lDigits||\\nindex.throwRedacted`Unary-prefixed decimal digit count expected: ${encoded}`;\\nlet nDigits=parseInt(snDigits,10);\\nif(typePrefix==='n'){\\n/* TODO Assert to reject forbidden encodings*/\\n/* like \\\"n0:\\\" and \\\"n00:…\\\" and \\\"n91:…\\\" through \\\"n99:…\\\"?*/\\nnDigits=10**/** @type {number} */lDigits-nDigits;}\\n\\n\\ntail.charAt(0)===':'||index.throwRedacted`Separator expected: ${encoded}`;\\ndigits.length===nDigits||\\nindex.throwRedacted`Fixed-length digit sequence expected: ${encoded}`;\\nlet n=BigInt(digits);\\nif(typePrefix==='n'){\\n/* TODO Assert to reject forbidden encodings*/\\n/* like \\\"n9:0\\\" and \\\"n8:00\\\" and \\\"n8:91\\\" through \\\"n8:99\\\"?*/\\nn=-(10n**BigInt(nDigits)-n);}\\n\\n\\nreturn n;};\\n\\n\\n/**\\n * A sparse array for which every present index maps a code point in the ASCII\\n * range to a corresponding escape sequence.\\n *\\n * Escapes all characters from U+0000 NULL to U+001F INFORMATION SEPARATOR ONE\\n * like `!<character offset by 0x21>` to avoid JSON.stringify expansion as\\n * `\\\\uHHHH`, and specially escapes U+0020 SPACE (the array element terminator)\\n * as `!_` and U+0021 EXCLAMATION MARK (the escape prefix) as `!|` (both chosen\\n * for visual approximation).\\n * Relative lexicographic ordering is preserved by this mapping of any character\\n * at or before `!` in the contiguous range [0x00..0x21] to a respective\\n * character in [0x21..0x40, 0x5F, 0x7C] preceded by `!` (which is itself in the\\n * replaced range).\\n * Similarly, escapes `^` as `_@` and `_` as `__` because `^` indicates the\\n * start of an encoded array.\\n *\\n * @type {Array<string>}\\n */\\nconst stringEscapes=Array(0x22).\\nfill(undefined).\\nmap((_,cp)=>{\\nswitch(String.fromCharCode(cp)){\\ncase' ':\\nreturn'!_';\\ncase'!':\\nreturn'!|';\\ndefault:\\nreturn`!${String.fromCharCode(cp+0x21)}`;}});\\n\\n\\nstringEscapes['^'.charCodeAt(0)]='_@';\\nstringEscapes['_'.charCodeAt(0)]='__';\\n\\n/**\\n * Encodes a string with escape sequences for use in the \\\"compactOrdered\\\" format.\\n *\\n * @type {(str: string) => string}\\n */\\nconst encodeCompactStringSuffix=(str)=>\\nstr.replace(/[\\\\0-!^_]/g,(ch)=>stringEscapes[ch.charCodeAt(0)]);\\n\\n/**\\n * Decodes a string from the \\\"compactOrdered\\\" format.\\n *\\n * @type {(encoded: string) => string}\\n */\\nconst decodeCompactStringSuffix=(encoded)=>{\\nreturn encoded.replace(/([\\\\0-!_])(.|\\\\n)?/g,(esc,prefix,suffix)=>{\\nswitch(esc){\\ncase'!_':\\nreturn' ';\\ncase'!|':\\nreturn'!';\\ncase'_@':\\nreturn'^';\\ncase'__':\\nreturn'_';\\ndefault:{\\nconst ch=/** @type {string} */suffix;\\n/* The range of valid `!`-escape suffixes is [(0x00+0x21)..(0x1F+0x21)], i.e.*/\\n/* [0x21..0x40] (U+0021 EXCLAMATION MARK to U+0040 COMMERCIAL AT).*/\\nprefix==='!'&&suffix!==undefined&&ch>='!'&&ch<='@'||\\nindex.throwRedacted`invalid string escape: ${index.quote(esc)}`;\\nreturn String.fromCharCode(ch.charCodeAt(0)-0x21);}}});};\\n\\n\\n\\n\\n\\n/**\\n * Trivially identity-encodes a string for use in the \\\"legacyOrdered\\\" format.\\n *\\n * @type {(str: string) => string}\\n */\\nconst encodeLegacyStringSuffix=(str)=>str;\\n\\n/**\\n * Trivially identity-decodes a string from the \\\"legacyOrdered\\\" format.\\n *\\n * @type {(encoded: string) => string}\\n */\\nconst decodeLegacyStringSuffix=(encoded)=>encoded;\\n\\n/**\\n * Encodes an array into a sequence of encoded elements for use in the \\\"compactOrdered\\\"\\n * format, each terminated by a space (which is part of the escaped range in\\n * \\\"compactOrdered\\\" encoded strings).\\n *\\n * @param {Passable[]} array\\n * @param {(p: Passable) => string} encodePassable\\n * @returns {string}\\n */\\nconst encodeCompactArray=(array,encodePassable)=>{\\nconst chars=['^'];\\nfor(const element of array){\\nconst enc=encodePassable(element);\\nchars.push(enc,' ');}\\n\\nreturn chars.join('');};\\n\\n\\n/**\\n * @param {string} encoded\\n * @param {(encoded: string) => Passable} decodePassable\\n * @param {number} [skip]\\n * @returns {Array}\\n */\\nconst decodeCompactArray=(encoded,decodePassable,skip=0)=>{\\nconst elements=[];\\nlet depth=0;\\n/* Scan encoded rather than its tail to avoid slow `substring` in XS.*/\\n/* https://github.com/endojs/endo/issues/1984*/\\nlet nextIndex=skip+1;\\nlet currentElementStart=skip+1;\\nfor(const{0:ch,index:i}of encoded.matchAll(/[\\\\^ ]/g)){\\nconst index$1=/** @type {number} */i;\\nif(index$1<=skip){\\nif(index$1===skip){\\nch==='^'||index.throwRedacted`Encoded array expected: ${getSuffix(encoded,skip)}`;}}else\\n\\nif(ch==='^'){\\n/* This is the start of a nested array.*/\\n/* TODO: Since the syntax of nested arrays must be validated as part of*/\\n/* decoding the outer one, consider decoding them here into a shared cache*/\\n/* rather than discarding information about their contents until the later*/\\n/* decodePassable.*/\\ndepth+=1;}else\\n{\\n/* This is a terminated element.*/\\nif(index$1===nextIndex){\\n/* A terminator after `[` or an another terminator indicates that an array is done.*/\\ndepth-=1;\\ndepth>=0||\\n/* prettier-ignore*/\\nindex.throwRedacted`unexpected array element terminator: ${encoded.slice(skip,index$1+2)}`;}\\n\\nif(depth===0){\\n/* We have a complete element of the topmost array.*/\\nelements.push(\\ndecodePassable(encoded.slice(currentElementStart,index$1)));\\n\\ncurrentElementStart=index$1+1;}}\\n\\n\\n/* Advance the index.*/\\nnextIndex=index$1+1;}\\n\\ndepth===0||index.throwRedacted`unterminated array: ${getSuffix(encoded,skip)}`;\\nnextIndex===encoded.length||\\nindex.throwRedacted`unterminated array element: ${getSuffix(\\nencoded,\\ncurrentElementStart)\\n}`;\\nreturn harden(elements);};\\n\\n\\n/**\\n * Performs the original array encoding, which escapes all encoded array\\n * elements rather than just strings (`\\\\u0000` as the element terminator and\\n * `\\\\u0001` as the escape prefix for `\\\\u0000` or `\\\\u0001`).\\n * This necessitated an undesirable amount of iteration and expansion; see\\n * https://github.com/endojs/endo/pull/1260#discussion_r960369826\\n *\\n * @param {Passable[]} array\\n * @param {(p: Passable) => string} encodePassable\\n * @returns {string}\\n */\\nconst encodeLegacyArray=(array,encodePassable)=>{\\nconst chars=['['];\\nfor(const element of array){\\nconst enc=encodePassable(element);\\nfor(const c of enc){\\nif(c==='\\\\u0000'||c==='\\\\u0001'){\\nchars.push('\\\\u0001');}\\n\\nchars.push(c);}\\n\\nchars.push('\\\\u0000');}\\n\\nreturn chars.join('');};\\n\\n\\n/**\\n * @param {string} encoded\\n * @param {(encoded: string) => Passable} decodePassable\\n * @param {number} [skip]\\n * @returns {Array}\\n */\\nconst decodeLegacyArray=(encoded,decodePassable,skip=0)=>{\\nconst elements=[];\\nconst elemChars=[];\\n/* Use a string iterator to avoid slow indexed access in XS.*/\\n/* https://github.com/endojs/endo/issues/1984*/\\nlet stillToSkip=skip+1;\\nlet inEscape=false;\\nfor(const c of encoded){\\nif(stillToSkip>0){\\nstillToSkip-=1;\\nif(stillToSkip===0){\\nc==='['||index.throwRedacted`Encoded array expected: ${getSuffix(encoded,skip)}`;}}else\\n\\nif(inEscape){\\nc==='\\\\u0000'||\\nc==='\\\\u0001'||\\nindex.throwRedacted`Unexpected character after u0001 escape: ${c}`;\\nelemChars.push(c);}else\\nif(c==='\\\\u0000'){\\nconst encodedElement=elemChars.join('');\\nelemChars.length=0;\\nconst element=decodePassable(encodedElement);\\nelements.push(element);}else\\nif(c==='\\\\u0001'){\\ninEscape=true;\\n/* eslint-disable-next-line no-continue*/\\ncontinue;}else\\n{\\nelemChars.push(c);}\\n\\ninEscape=false;}\\n\\n!inEscape||index.throwRedacted`unexpected end of encoding ${getSuffix(encoded,skip)}`;\\nelemChars.length===0||\\nindex.throwRedacted`encoding terminated early: ${getSuffix(encoded,skip)}`;\\nreturn harden(elements);};\\n\\n\\nconst encodeRecord=(record,encodeArray,encodePassable)=>{\\nconst names=recordNames(record);\\nconst values=recordValues(record,names);\\nreturn`(${encodeArray(harden([names,values]),encodePassable)}`;};\\n\\n\\nconst decodeRecord=(encoded,decodeArray,decodePassable,skip=0)=>{\\nassert(encoded.charAt(skip)==='(');\\n/* Skip the \\\"(\\\" inside `decodeArray` to avoid slow `substring` in XS.*/\\n/* https://github.com/endojs/endo/issues/1984*/\\nconst unzippedEntries=decodeArray(encoded,decodePassable,skip+1);\\nunzippedEntries.length===2||\\nindex.throwRedacted`expected keys,values pair: ${getSuffix(encoded,skip)}`;\\nconst[keys,vals]=unzippedEntries;\\n\\npassStyleOf.passStyleOf(keys)==='copyArray'&&\\npassStyleOf.passStyleOf(vals)==='copyArray'&&\\nkeys.length===vals.length&&\\nkeys.every((key)=>typeof key==='string')||\\nindex.throwRedacted`not a valid record encoding: ${getSuffix(encoded,skip)}`;\\nconst mapEntries=keys.map((key,i)=>[key,vals[i]]);\\nconst record=harden(fromEntries(mapEntries));\\ntypeGuards.assertRecord(record,'decoded record');\\nreturn record;};\\n\\n\\nconst encodeTagged=(tagged,encodeArray,encodePassable)=>\\n`:${encodeArray(harden([passStyleHelpers.getTag(tagged),tagged.payload]),encodePassable)}`;\\n\\nconst decodeTagged=(encoded,decodeArray,decodePassable,skip=0)=>{\\nassert(encoded.charAt(skip)===':');\\n/* Skip the \\\":\\\" inside `decodeArray` to avoid slow `substring` in XS.*/\\n/* https://github.com/endojs/endo/issues/1984*/\\nconst taggedPayload=decodeArray(encoded,decodePassable,skip+1);\\ntaggedPayload.length===2||\\nindex.throwRedacted`expected tag,payload pair: ${getSuffix(encoded,skip)}`;\\nconst[tag,payload]=taggedPayload;\\npassStyleOf.passStyleOf(tag)==='string'||\\nindex.throwRedacted`not a valid tagged encoding: ${getSuffix(encoded,skip)}`;\\nreturn makeTagged.makeTagged(tag,payload);};\\n\\n\\nconst makeEncodeRemotable=(unsafeEncodeRemotable,verifyEncoding)=>{\\nconst encodeRemotable=(r,innerEncode)=>{\\nconst encoding=unsafeEncodeRemotable(r,innerEncode);\\ntypeof encoding==='string'&&encoding.charAt(0)==='r'||\\nindex.throwRedacted`Remotable encoding must start with \\\"r\\\": ${encoding}`;\\nverifyEncoding(encoding,'Remotable');\\nreturn encoding;};\\n\\nreturn encodeRemotable;};\\n\\n\\nconst makeEncodePromise=(unsafeEncodePromise,verifyEncoding)=>{\\nconst encodePromise=(p,innerEncode)=>{\\nconst encoding=unsafeEncodePromise(p,innerEncode);\\ntypeof encoding==='string'&&encoding.charAt(0)==='?'||\\nindex.throwRedacted`Promise encoding must start with \\\"?\\\": ${encoding}`;\\nverifyEncoding(encoding,'Promise');\\nreturn encoding;};\\n\\nreturn encodePromise;};\\n\\n\\nconst makeEncodeError=(unsafeEncodeError,verifyEncoding)=>{\\nconst encodeError=(err,innerEncode)=>{\\nconst encoding=unsafeEncodeError(err,innerEncode);\\ntypeof encoding==='string'&&encoding.charAt(0)==='!'||\\nindex.throwRedacted`Error encoding must start with \\\"!\\\": ${encoding}`;\\nverifyEncoding(encoding,'Error');\\nreturn encoding;};\\n\\nreturn encodeError;};\\n\\n\\n/**\\n * @typedef {object} EncodeOptions\\n * @property {(\\n * remotable: Remotable,\\n * encodeRecur: (p: Passable) => string,\\n * ) => string} [encodeRemotable]\\n * @property {(\\n * promise: Promise,\\n * encodeRecur: (p: Passable) => string,\\n * ) => string} [encodePromise]\\n * @property {(\\n * error: Error,\\n * encodeRecur: (p: Passable) => string,\\n * ) => string} [encodeError]\\n * @property {'legacyOrdered' | 'compactOrdered'} [format]\\n */\\n\\n/**\\n * @param {(str: string) => string} encodeStringSuffix\\n * @param {(arr: unknown[], encodeRecur: (p: Passable) => string) => string} encodeArray\\n * @param {Required<EncodeOptions> & {verifyEncoding?: (encoded: string, label: string) => void}} options\\n * @returns {(p: Passable) => string}\\n */\\nconst makeInnerEncode=(encodeStringSuffix,encodeArray,options)=>{\\nconst{\\nencodeRemotable:unsafeEncodeRemotable,\\nencodePromise:unsafeEncodePromise,\\nencodeError:unsafeEncodeError,\\nverifyEncoding=()=>{}}=\\noptions;\\nconst encodeRemotable=makeEncodeRemotable(\\nunsafeEncodeRemotable,\\nverifyEncoding);\\n\\nconst encodePromise=makeEncodePromise(unsafeEncodePromise,verifyEncoding);\\nconst encodeError=makeEncodeError(unsafeEncodeError,verifyEncoding);\\n\\nconst innerEncode=(passable)=>{\\nif(error.isErrorLike(passable)){\\n/* We pull out this special case to accommodate errors that are not*/\\n/* valid Passables. For example, because they're not frozen.*/\\n/* The special case can only ever apply at the root, and therefore*/\\n/* outside the recursion, since an error could only be deeper in*/\\n/* a passable structure if it were passable.*/\\n/**/\\n/* We pull out this special case because, for these errors, we're much*/\\n/* more interested in reporting whatever diagnostic information they*/\\n/* carry than we are about reporting problems encountered in reporting*/\\n/* this information.*/\\nreturn encodeError(passable,innerEncode);}\\n\\nconst passStyle=passStyleOf.passStyleOf(passable);\\nswitch(passStyle){\\ncase'null':{\\nreturn'v';}\\n\\ncase'undefined':{\\nreturn'z';}\\n\\ncase'number':{\\nreturn encodeBinary64(passable);}\\n\\ncase'string':{\\nreturn`s${encodeStringSuffix(passable)}`;}\\n\\ncase'boolean':{\\nreturn`b${passable}`;}\\n\\ncase'bigint':{\\nreturn encodeBigInt(passable);}\\n\\ncase'remotable':{\\nreturn encodeRemotable(passable,innerEncode);}\\n\\ncase'error':{\\nreturn encodeError(passable,innerEncode);}\\n\\ncase'promise':{\\nreturn encodePromise(passable,innerEncode);}\\n\\ncase'symbol':{\\n/* Strings and symbols share encoding logic.*/\\nconst name=symbol.nameForPassableSymbol(passable);\\nassert.typeof(name,'string');\\nreturn`y${encodeStringSuffix(name)}`;}\\n\\ncase'copyArray':{\\nreturn encodeArray(passable,innerEncode);}\\n\\ncase'copyRecord':{\\nreturn encodeRecord(passable,encodeArray,innerEncode);}\\n\\ncase'tagged':{\\nreturn encodeTagged(passable,encodeArray,innerEncode);}\\n\\ndefault:{\\nthrow index.throwRedacted`a ${index.quote(passStyle)} cannot be used as a collection passable`;}}};\\n\\n\\n\\nreturn innerEncode;};\\n\\n\\n/**\\n * @typedef {object} DecodeOptions\\n * @property {(\\n * encodedRemotable: string,\\n * decodeRecur: (e: string) => Passable\\n * ) => Remotable} [decodeRemotable]\\n * @property {(\\n * encodedPromise: string,\\n * decodeRecur: (e: string) => Passable\\n * ) => Promise} [decodePromise]\\n * @property {(\\n * encodedError: string,\\n * decodeRecur: (e: string) => Passable\\n * ) => Error} [decodeError]\\n */\\n\\nconst liberalDecoders=/** @type {Required<DecodeOptions>} */\\n/** @type {unknown} */{\\ndecodeRemotable:(_encoding,_innerDecode)=>undefined,\\ndecodePromise:(_encoding,_innerDecode)=>undefined,\\ndecodeError:(_encoding,_innerDecode)=>undefined};\\n\\n\\n\\n/**\\n * @param {(encoded: string) => string} decodeStringSuffix\\n * @param {(encoded: string, decodeRecur: (e: string) => Passable, skip?: number) => unknown[]} decodeArray\\n * @param {Required<DecodeOptions>} options\\n * @returns {(encoded: string, skip?: number) => Passable}\\n */\\nconst makeInnerDecode=(decodeStringSuffix,decodeArray,options)=>{\\nconst{decodeRemotable,decodePromise,decodeError}=options;\\n/** @type {(encoded: string, skip?: number) => Passable} */\\nconst innerDecode=(encoded,skip=0)=>{\\nswitch(encoded.charAt(skip)){\\ncase'v':{\\nreturn null;}\\n\\ncase'z':{\\nreturn undefined;}\\n\\ncase'f':{\\nreturn decodeBinary64(encoded,skip);}\\n\\ncase's':{\\nreturn decodeStringSuffix(getSuffix(encoded,skip+1));}\\n\\ncase'b':{\\nconst substring=getSuffix(encoded,skip+1);\\nif(substring==='true'){\\nreturn true;}else\\nif(substring==='false'){\\nreturn false;}\\n\\nthrow index.throwRedacted`expected encoded boolean to be \\\"btrue\\\" or \\\"bfalse\\\": ${substring}`;}\\n\\ncase'n':\\ncase'p':{\\nreturn decodeBigInt(getSuffix(encoded,skip));}\\n\\ncase'r':{\\nreturn decodeRemotable(getSuffix(encoded,skip),innerDecode);}\\n\\ncase'?':{\\nreturn decodePromise(getSuffix(encoded,skip),innerDecode);}\\n\\ncase'!':{\\nreturn decodeError(getSuffix(encoded,skip),innerDecode);}\\n\\ncase'y':{\\n/* Strings and symbols share decoding logic.*/\\nconst name=decodeStringSuffix(getSuffix(encoded,skip+1));\\nreturn symbol.passableSymbolForName(name);}\\n\\ncase'[':\\ncase'^':{\\n/* @ts-expect-error Type 'unknown[]' is not Passable*/\\nreturn decodeArray(encoded,innerDecode,skip);}\\n\\ncase'(':{\\nreturn decodeRecord(encoded,decodeArray,innerDecode,skip);}\\n\\ncase':':{\\nreturn decodeTagged(encoded,decodeArray,innerDecode,skip);}\\n\\ndefault:{\\nthrow index.throwRedacted`invalid database key: ${getSuffix(encoded,skip)}`;}}};\\n\\n\\n\\nreturn innerDecode;};\\n\\n\\n/**\\n * @typedef {object} PassableKit\\n * @property {ReturnType<makeInnerEncode>} encodePassable\\n * @property {ReturnType<makeInnerDecode>} decodePassable\\n */\\n\\n/**\\n * @param {EncodeOptions & DecodeOptions} [options]\\n * @returns {PassableKit}\\n */\\nconst makePassableKit=(options={})=>{\\nconst{\\nencodeRemotable=(r,_)=>index.throwRedacted`remotable unexpected: ${r}`,\\nencodePromise=(p,_)=>index.throwRedacted`promise unexpected: ${p}`,\\nencodeError=(err,_)=>index.throwRedacted`error unexpected: ${err}`,\\nformat='legacyOrdered',\\n\\ndecodeRemotable=(encoding,_)=>index.throwRedacted`remotable unexpected: ${encoding}`,\\ndecodePromise=(encoding,_)=>index.throwRedacted`promise unexpected: ${encoding}`,\\ndecodeError=(encoding,_)=>index.throwRedacted`error unexpected: ${encoding}`}=\\noptions;\\n\\n/** @type {PassableKit['encodePassable']} */\\nlet encodePassable;\\nconst encodeOptions={encodeRemotable,encodePromise,encodeError,format};\\nif(format==='compactOrdered'){\\nconst liberalDecode=makeInnerDecode(\\ndecodeCompactStringSuffix,\\ndecodeCompactArray,\\nliberalDecoders);\\n\\n/**\\n * @param {string} encoding\\n * @param {string} label\\n * @returns {void}\\n */\\nconst verifyEncoding=(encoding,label)=>{\\n!encoding.match(rC0)||\\nindex.throwRedacted`${index.bare(\\nlabel)\\n} encoding must not contain a C0 control character: ${encoding}`;\\nconst decoded=decodeCompactArray(`^v ${encoding} v `,liberalDecode);\\nisArray(decoded)&&\\ndecoded.length===3&&\\ndecoded[0]===null&&\\ndecoded[2]===null||\\nindex.throwRedacted`${index.bare(label)} encoding must be embeddable: ${encoding}`;};\\n\\nconst encodeCompact=makeInnerEncode(\\nencodeCompactStringSuffix,\\nencodeCompactArray,\\n{...encodeOptions,verifyEncoding});\\n\\nencodePassable=(passable)=>`~${encodeCompact(passable)}`;}else\\nif(format==='legacyOrdered'){\\nencodePassable=makeInnerEncode(\\nencodeLegacyStringSuffix,\\nencodeLegacyArray,\\nencodeOptions);}else\\n\\n{\\nthrow index.throwRedacted`Unrecognized format: ${index.quote(format)}`;}\\n\\n\\nconst decodeOptions={decodeRemotable,decodePromise,decodeError};\\nconst decodeCompact=makeInnerDecode(\\ndecodeCompactStringSuffix,\\ndecodeCompactArray,\\ndecodeOptions);\\n\\nconst decodeLegacy=makeInnerDecode(\\ndecodeLegacyStringSuffix,\\ndecodeLegacyArray,\\ndecodeOptions);\\n\\nconst decodePassable=(encoded)=>{\\n/* A leading \\\"~\\\" indicates the v2 encoding (with escaping in strings rather than arrays).*/\\n/* Skip it inside `decodeCompact` to avoid slow `substring` in XS.*/\\n/* https://github.com/endojs/endo/issues/1984*/\\nif(encoded.charAt(0)==='~'){\\nreturn decodeCompact(encoded,1);}\\n\\nreturn decodeLegacy(encoded);};\\n\\n\\nreturn harden({encodePassable,decodePassable});};\\n\\nharden(makePassableKit);\\n\\n/**\\n * @param {EncodeOptions} [encodeOptions]\\n * @returns {PassableKit['encodePassable']}\\n */\\nconst makeEncodePassable=(encodeOptions)=>{\\nconst{encodePassable}=makePassableKit(encodeOptions);\\nreturn encodePassable;};\\n\\nharden(makeEncodePassable);\\n\\n/**\\n * @param {DecodeOptions} [decodeOptions]\\n * @returns {PassableKit['decodePassable']}\\n */\\nconst makeDecodePassable=(decodeOptions)=>{\\nconst{decodePassable}=makePassableKit(decodeOptions);\\nreturn decodePassable;};\\n\\nharden(makeDecodePassable);\\n\\nconst isEncodedRemotable=(encoded)=>encoded.charAt(0)==='r';\\nharden(isEncodedRemotable);\\n\\n/* /////////////////////////////////////////////////////////////////////////////*/\\n\\n/**\\n * @type {Record<PassStyle, string>}\\n * The single prefix characters to be used for each PassStyle category.\\n * `bigint` is a two-character string because each of those characters\\n * individually is a valid bigint prefix (`n` for \\\"negative\\\" and `p` for\\n * \\\"positive\\\"), and copyArray is a two-character string because one encoding\\n * prefixes arrays with `[` while the other uses `^` (which is prohibited from\\n * appearing in an encoded string).\\n * The ordering of these prefixes is the same as the rankOrdering of their\\n * respective PassStyles, and rankOrder.js imports the table for this purpose.\\n *\\n * In addition, `|` is the remotable->ordinal mapping prefix:\\n * This is not used in covers but it is\\n * reserved from the same set of strings. Note that the prefix is > any\\n * prefix used by any cover so that ordinal mapping keys are always outside\\n * the range of valid collection entry keys.\\n */\\nconst passStylePrefixes={\\nerror:'!',\\ncopyRecord:'(',\\ntagged:':',\\npromise:'?',\\ncopyArray:'[^',\\nboolean:'b',\\nnumber:'f',\\nbigint:'np',\\nremotable:'r',\\nstring:'s',\\nnull:'v',\\nsymbol:'y',\\nundefined:'z'};\\n\\nObject.setPrototypeOf(passStylePrefixes,null);\\nharden(passStylePrefixes);exports.isEncodedRemotable=isEncodedRemotable;exports.makeDecodePassable=makeDecodePassable;exports.makeEncodePassable=makeEncodePassable;exports.makePassableKit=makePassableKit;exports.passStylePrefixes=passStylePrefixes;exports.recordNames=recordNames;exports.recordValues=recordValues;exports.zeroPad=zeroPad;\",\n \"node_modules/@endo/marshal/src/encodeToCapData.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../pass-style/index.js');var index=require('../../errors/index.js');var passStyleHelpers=require('../../pass-style/src/passStyle-helpers.js');var passStyleOf=require('../../pass-style/src/passStyleOf.js');var symbol=require('../../pass-style/src/symbol.js');var error=require('../../pass-style/src/error.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nmakeTagged=require('../../pass-style/src/makeTagged.js');/*/ <reference types=\\\"ses\\\"/>*/ /** @import {Passable, RemotableObject} from '@endo/pass-style' */ /** @import {Encoding, EncodingUnion} from './types.js' */\\n\\nconst{ownKeys}=Reflect;\\nconst{isArray}=Array;\\nconst{\\ngetOwnPropertyDescriptors,\\ndefineProperties,\\nis,\\nentries,\\nfromEntries,\\nfreeze}=\\nObject;\\n\\n/**\\n * Special property name that indicates an encoding that needs special\\n * decoding.\\n */\\nconst QCLASS='@qclass';\\n\\n\\n/**\\n * @param {Encoding} encoded\\n * @returns {encoded is EncodingUnion}\\n */\\nconst hasQClass=(encoded)=>passStyleHelpers.hasOwnPropertyOf(encoded,QCLASS);\\n\\n/**\\n * @param {Encoding} encoded\\n * @param {string} qclass\\n * @returns {boolean}\\n */\\nconst qclassMatches=(encoded,qclass)=>\\npassStyleHelpers.isObject(encoded)&&\\n!isArray(encoded)&&\\nhasQClass(encoded)&&\\nencoded[QCLASS]===qclass;\\n\\n/**\\n * @typedef {object} EncodeToCapDataOptions\\n * @property {(\\n * remotable: RemotableObject,\\n * encodeRecur: (p: Passable) => Encoding\\n * ) => Encoding} [encodeRemotableToCapData]\\n * @property {(\\n * promise: Promise,\\n * encodeRecur: (p: Passable) => Encoding\\n * ) => Encoding} [encodePromiseToCapData]\\n * @property {(\\n * error: Error,\\n * encodeRecur: (p: Passable) => Encoding\\n * ) => Encoding} [encodeErrorToCapData]\\n */\\n\\nconst dontEncodeRemotableToCapData=(rem)=>index.throwRedacted`remotable unexpected: ${rem}`;\\n\\nconst dontEncodePromiseToCapData=(prom)=>index.throwRedacted`promise unexpected: ${prom}`;\\n\\nconst dontEncodeErrorToCapData=(err)=>index.throwRedacted`error object unexpected: ${err}`;\\n\\n/**\\n * @param {EncodeToCapDataOptions} [encodeOptions]\\n * @returns {(passable: Passable) => Encoding}\\n */\\nconst makeEncodeToCapData=(encodeOptions={})=>{\\nconst{\\nencodeRemotableToCapData=dontEncodeRemotableToCapData,\\nencodePromiseToCapData=dontEncodePromiseToCapData,\\nencodeErrorToCapData=dontEncodeErrorToCapData}=\\nencodeOptions;\\n\\n/**\\n * Must encode `val` into plain JSON data *canonically*, such that\\n * `JSON.stringify(encode(v1)) === JSON.stringify(encode(v1))`. For most\\n * encodings, the order of properties of each node of the output\\n * structure is determined by the algorithm below without special\\n * arrangement, usually by being expressed directly as an object literal.\\n * The exception is copyRecords, whose natural enumeration order\\n * can differ between copyRecords that our distributed object semantics\\n * considers to be equivalent.\\n * Since, for each copyRecord, we only accept string property names,\\n * not symbols, we can canonically sort the names first.\\n * JSON.stringify will then visit these in that sorted order.\\n *\\n * Encoding with a canonical-JSON encoder would also solve this canonicalness\\n * problem in a more modular and encapsulated manner. Note that the\\n * actual order produced here, though it agrees with canonical-JSON on\\n * copyRecord property ordering, differs from canonical-JSON as a whole\\n * in that the other record properties are visited in the order in which\\n * they are literally written below. TODO perhaps we should indeed switch\\n * to a canonical JSON encoder, and not delicately depend on the order\\n * in which these object literals are written.\\n *\\n * Readers must not care about this order anyway. We impose this requirement\\n * mainly to reduce non-determinism exposed outside a vat.\\n *\\n * @param {any} passable\\n * @returns {Encoding} except that `encodeToCapData` does not generally\\n * `harden` this result before returning. Rather, `encodeToCapData` is not\\n * directly exposed.\\n * What's exposed instead is a wrapper that freezes the output before\\n * returning. If this turns out to impede static analysis for `harden` safety,\\n * we can always put the (now redundant) hardens back in. They don't hurt.\\n */\\nconst encodeToCapDataRecur=(passable)=>{\\n/* First we handle all primitives. Some can be represented directly as*/\\n/* JSON, and some must be encoded as [QCLASS] composites.*/\\nconst passStyle=passStyleOf.passStyleOf(passable);\\nswitch(passStyle){\\ncase'null':\\ncase'boolean':\\ncase'string':{\\n/* pass through to JSON*/\\nreturn passable;}\\n\\ncase'undefined':{\\nreturn{[QCLASS]:'undefined'};}\\n\\ncase'number':{\\n/* Special-case numbers with no digit-based representation.*/\\nif(Number.isNaN(passable)){\\nreturn{[QCLASS]:'NaN'};}else\\nif(passable===Infinity){\\nreturn{[QCLASS]:'Infinity'};}else\\nif(passable===-Infinity){\\nreturn{[QCLASS]:'-Infinity'};}\\n\\n/* Pass through everything else, replacing -0 with 0.*/\\nreturn is(passable,-0)?0:passable;}\\n\\ncase'bigint':{\\nreturn{\\n[QCLASS]:'bigint',\\ndigits:String(passable)};}\\n\\n\\ncase'symbol':{\\nsymbol.assertPassableSymbol(passable);\\nconst name=/** @type {string} */symbol.nameForPassableSymbol(passable);\\nreturn{\\n[QCLASS]:'symbol',\\nname};}\\n\\n\\ncase'copyRecord':{\\nif(passStyleHelpers.hasOwnPropertyOf(passable,QCLASS)){\\n/* Hilbert hotel*/\\nconst{[QCLASS]:qclassValue,...rest}=passable;\\n/** @type {Encoding} */\\nconst result={\\n[QCLASS]:'hilbert',\\noriginal:encodeToCapDataRecur(qclassValue)};\\n\\nif(ownKeys(rest).length>=1){\\n/* We harden the entire capData encoding before we return it.*/\\n/* `encodeToCapData` requires that its input be Passable, and*/\\n/* therefore hardened.*/\\n/* The `freeze` here is needed anyway, because the `rest` is*/\\n/* freshly constructed by the `...` above, and we're using it*/\\n/* as imput in another call to `encodeToCapData`.*/\\nresult.rest=encodeToCapDataRecur(freeze(rest));}\\n\\nreturn result;}\\n\\n/* Currently copyRecord allows only string keys so this will*/\\n/* work. If we allow sortable symbol keys, this will need to*/\\n/* become more interesting.*/\\nconst names=ownKeys(passable).sort();\\nreturn fromEntries(\\nnames.map((name)=>[name,encodeToCapDataRecur(passable[name])]));}\\n\\n\\ncase'copyArray':{\\nreturn passable.map(encodeToCapDataRecur);}\\n\\ncase'tagged':{\\nreturn{\\n[QCLASS]:'tagged',\\ntag:passStyleHelpers.getTag(passable),\\npayload:encodeToCapDataRecur(passable.payload)};}\\n\\n\\ncase'remotable':{\\nconst encoded=encodeRemotableToCapData(\\npassable,\\nencodeToCapDataRecur);\\n\\nif(qclassMatches(encoded,'slot')){\\nreturn encoded;}\\n\\n/* `throw` is noop since `Fail` throws. But linter confused*/\\nthrow index.throwRedacted`internal: Remotable encoding must be an object with ${index.quote(\\nQCLASS)\\n} ${index.quote('slot')}: ${encoded}`;}\\n\\ncase'promise':{\\nconst encoded=encodePromiseToCapData(passable,encodeToCapDataRecur);\\nif(qclassMatches(encoded,'slot')){\\nreturn encoded;}\\n\\nthrow index.throwRedacted`internal: Promise encoding must be an object with ${index.quote(\\nQCLASS,\\n'slot')\\n}: ${encoded}`;}\\n\\ncase'error':{\\nconst encoded=encodeErrorToCapData(passable,encodeToCapDataRecur);\\nif(qclassMatches(encoded,'error')){\\nreturn encoded;}\\n\\nthrow index.throwRedacted`internal: Error encoding must be an object with ${index.quote(\\nQCLASS,\\n'error')\\n}: ${encoded}`;}\\n\\ndefault:{\\nthrow assert.fail(\\nindex.redacted`internal: Unrecognized passStyle ${index.quote(passStyle)}`,\\nTypeError);}}};\\n\\n\\n\\n\\nconst encodeToCapData=(passable)=>{\\nif(error.isErrorLike(passable)){\\n/* We pull out this special case to accommodate errors that are not*/\\n/* valid Passables. For example, because they're not frozen.*/\\n/* The special case can only ever apply at the root, and therefore*/\\n/* outside the recursion, since an error could only be deeper in*/\\n/* a passable structure if it were passable.*/\\n/**/\\n/* We pull out this special case because, for these errors, we're much*/\\n/* more interested in reporting whatever diagnostic information they*/\\n/* carry than we are about reporting problems encountered in reporting*/\\n/* this information.*/\\nreturn harden(encodeErrorToCapData(passable,encodeToCapDataRecur));}\\n\\nreturn harden(encodeToCapDataRecur(passable));};\\n\\nreturn harden(encodeToCapData);};\\n\\nharden(makeEncodeToCapData);\\n\\n/**\\n * @typedef {object} DecodeOptions\\n * @property {(\\n * encodedRemotable: Encoding,\\n * decodeRecur: (e: Encoding) => Passable\\n * ) => (Promise|RemotableObject)} [decodeRemotableFromCapData]\\n * @property {(\\n * encodedPromise: Encoding,\\n * decodeRecur: (e: Encoding) => Passable\\n * ) => (Promise|RemotableObject)} [decodePromiseFromCapData]\\n * @property {(\\n * encodedError: Encoding,\\n * decodeRecur: (e: Encoding) => Passable\\n * ) => Error} [decodeErrorFromCapData]\\n */\\n\\nconst dontDecodeRemotableOrPromiseFromCapData=(slotEncoding)=>\\nindex.throwRedacted`remotable or promise unexpected: ${slotEncoding}`;\\nconst dontDecodeErrorFromCapData=(errorEncoding)=>\\nindex.throwRedacted`error unexpected: ${errorEncoding}`;\\n\\n/**\\n * The current encoding does not give the decoder enough into to distinguish\\n * whether a slot represents a promise or a remotable. As an implementation\\n * restriction until this is fixed, if either is provided, both must be\\n * provided and they must be the same.\\n *\\n * This seems like the best starting point to incrementally evolve to an\\n * API where these can reliably differ.\\n * See https://github.com/Agoric/agoric-sdk/issues/4334\\n *\\n * @param {DecodeOptions} [decodeOptions]\\n * @returns {(encoded: Encoding) => Passable}\\n */\\nconst makeDecodeFromCapData=(decodeOptions={})=>{\\nconst{\\ndecodeRemotableFromCapData=dontDecodeRemotableOrPromiseFromCapData,\\ndecodePromiseFromCapData=dontDecodeRemotableOrPromiseFromCapData,\\ndecodeErrorFromCapData=dontDecodeErrorFromCapData}=\\ndecodeOptions;\\n\\ndecodeRemotableFromCapData===decodePromiseFromCapData||\\nindex.throwRedacted`An implementation restriction for now: If either decodeRemotableFromCapData or decodePromiseFromCapData is provided, both must be provided and they must be the same: ${index.quote(\\ndecodeRemotableFromCapData)\\n} vs ${index.quote(decodePromiseFromCapData)}`;\\n\\n/**\\n * `decodeFromCapData` may rely on `jsonEncoded` being the result of a\\n * plain call to JSON.parse. However, it *cannot* rely on `jsonEncoded`\\n * having been produced by JSON.stringify on the output of `encodeToCapData`\\n * above, i.e., `decodeFromCapData` cannot rely on `jsonEncoded` being a\\n * valid marshalled representation. Rather, `decodeFromCapData` must\\n * validate that.\\n *\\n * @param {Encoding} jsonEncoded must be hardened\\n */\\nconst decodeFromCapData=(jsonEncoded)=>{\\nif(!passStyleHelpers.isObject(jsonEncoded)){\\n/* primitives pass through*/\\nreturn jsonEncoded;}\\n\\nif(isArray(jsonEncoded)){\\nreturn jsonEncoded.map((encodedVal)=>decodeFromCapData(encodedVal));}else\\nif(hasQClass(jsonEncoded)){\\nconst qclass=jsonEncoded[QCLASS];\\ntypeof qclass==='string'||\\nindex.throwRedacted`invalid ${index.quote(QCLASS)} typeof ${index.quote(typeof qclass)}`;\\nswitch(qclass){\\n/* Encoding of primitives not handled by JSON*/\\ncase'undefined':{\\nreturn undefined;}\\n\\ncase'NaN':{\\nreturn NaN;}\\n\\ncase'Infinity':{\\nreturn Infinity;}\\n\\ncase'-Infinity':{\\nreturn-Infinity;}\\n\\ncase'bigint':{\\nconst{digits}=jsonEncoded;\\ntypeof digits==='string'||\\nindex.throwRedacted`invalid digits typeof ${index.quote(typeof digits)}`;\\nreturn BigInt(digits);}\\n\\ncase'@@asyncIterator':{\\n/* Deprecated qclass. TODO make conditional*/\\n/* on environment variable. Eventually remove, but after confident*/\\n/* that there are no more supported senders.*/\\n/**/\\nreturn Symbol.asyncIterator;}\\n\\ncase'symbol':{\\nconst{name}=jsonEncoded;\\nreturn symbol.passableSymbolForName(name);}\\n\\ncase'tagged':{\\nconst{tag,payload}=jsonEncoded;\\nreturn makeTagged.makeTagged(tag,decodeFromCapData(payload));}\\n\\ncase'slot':{\\n/* See note above about how the current encoding cannot reliably*/\\n/* distinguish which we should call, so in the non-default case*/\\n/* both must be the same and it doesn't matter which we call.*/\\nconst decoded=decodeRemotableFromCapData(\\njsonEncoded,\\ndecodeFromCapData);\\n\\n/* BEWARE: capdata does not check that `decoded` is*/\\n/* a promise or a remotable, since that would break some*/\\n/* capdata clients. We are deprecating capdata, and these clients*/\\n/* will need to update before switching to smallcaps.*/\\nreturn decoded;}\\n\\ncase'error':{\\nconst decoded=decodeErrorFromCapData(\\njsonEncoded,\\ndecodeFromCapData);\\n\\nif(passStyleOf.passStyleOf(decoded)==='error'){\\nreturn decoded;}\\n\\nthrow index.throwRedacted`internal: decodeErrorFromCapData option must return an error: ${decoded}`;}\\n\\ncase'hilbert':{\\nconst{original,rest}=jsonEncoded;\\npassStyleHelpers.hasOwnPropertyOf(jsonEncoded,'original')||\\nindex.throwRedacted`Invalid Hilbert Hotel encoding ${jsonEncoded}`;\\n/* Don't harden since we're not done mutating it*/\\nconst result={[QCLASS]:decodeFromCapData(original)};\\nif(passStyleHelpers.hasOwnPropertyOf(jsonEncoded,'rest')){\\nconst isNonEmptyObject=\\ntypeof rest==='object'&&\\nrest!==null&&\\nownKeys(rest).length>=1;\\nif(!isNonEmptyObject){\\nthrow index.throwRedacted`Rest encoding must be a non-empty object: ${rest}`;}\\n\\nconst restObj=decodeFromCapData(rest);\\n/* TODO really should assert that `passStyleOf(rest)` is*/\\n/* `'copyRecord'` but we'd have to harden it and it is too*/\\n/* early to do that.*/\\n!passStyleHelpers.hasOwnPropertyOf(restObj,QCLASS)||\\nindex.throwRedacted`Rest must not contain its own definition of ${index.quote(QCLASS)}`;\\ndefineProperties(result,getOwnPropertyDescriptors(restObj));}\\n\\nreturn result;}\\n\\n/* @ts-expect-error This is the error case we're testing for*/\\ncase'ibid':{\\nthrow index.throwRedacted`The capData protocol no longer supports ${index.quote(QCLASS)} ${index.quote(\\nqclass)\\n}`;}\\n\\ndefault:{\\nthrow assert.fail(\\nindex.redacted`unrecognized ${index.quote(QCLASS)} ${index.quote(qclass)}`,\\nTypeError);}}}else\\n\\n\\n\\n{\\nassert(typeof jsonEncoded==='object'&&jsonEncoded!==null);\\nconst decodeEntry=([name,encodedVal])=>{\\ntypeof name==='string'||\\nindex.throwRedacted`Property ${index.quote(name)} of ${jsonEncoded} must be a string`;\\nreturn[name,decodeFromCapData(encodedVal)];};\\n\\nconst decodedEntries=entries(jsonEncoded).map(decodeEntry);\\nreturn fromEntries(decodedEntries);}};\\n\\n\\nreturn harden(decodeFromCapData);};exports.QCLASS=QCLASS;exports.makeDecodeFromCapData=makeDecodeFromCapData;exports.makeEncodeToCapData=makeEncodeToCapData;\",\n \"node_modules/@endo/marshal/src/encodeToSmallcaps.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../pass-style/index.js');var index=require('../../errors/index.js');var passStyleHelpers=require('../../pass-style/src/passStyle-helpers.js');var passStyleOf=require('../../pass-style/src/passStyleOf.js');var symbol=require('../../pass-style/src/symbol.js');var error=require('../../pass-style/src/error.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nmakeTagged=require('../../pass-style/src/makeTagged.js');/* @ts-check*/ /** @import {Passable, Remotable} from '@endo/pass-style' */ /* FIXME define actual types*/ /** @typedef {any} SmallcapsEncoding */ /** @typedef {any} SmallcapsEncodingUnion */\\n\\nconst{ownKeys}=Reflect;\\nconst{isArray}=Array;\\nconst{is,entries,fromEntries}=Object;\\n\\nconst BANG='!'.charCodeAt(0);\\nconst DASH='-'.charCodeAt(0);\\n\\n/**\\n * An `encodeToSmallcaps` function takes a passable and returns a\\n * JSON-representable object (i.e., round-tripping it through\\n * `JSON.stringify` and `JSON.parse` with no replacers or revivers\\n * returns an equivalent structure except for object identity).\\n * We call this representation a Smallcaps Encoding.\\n *\\n * A `decodeFromSmallcaps` function takes as argument what it\\n * *assumes* is the result of a plain `JSON.parse` with no resolver. It then\\n * must validate that it is a valid Smallcaps Encoding, and if it is,\\n * return a corresponding passable.\\n *\\n * Smallcaps considers the characters between `!` (ascii code 33, BANG)\\n * and `-` (ascii code 45, DASH) to be special prefixes allowing\\n * representation of JSON-incompatible data using strings.\\n * These characters, in order, are `!\\\"#$%&'()*+,-`\\n * Of these, smallcaps currently uses the following:\\n *\\n * * `!` - escaped string\\n * * `+` - non-negative bigint\\n * * `-` - negative bigint\\n * * `#` - manifest constant\\n * * `%` - symbol\\n * * `$` - remotable\\n * * `&` - promise\\n *\\n * All other special characters (`\\\"'()*,`) are reserved for future use.\\n *\\n * The manifest constants that smallcaps currently uses for values:\\n * * `#undefined`\\n * * `#NaN`\\n * * `#Infinity`\\n * * `#-Infinity`\\n *\\n * and for property names analogous to capdata @qclass:\\n * * `#tag`\\n * * `#error`\\n *\\n * All other encoded strings beginning with `#` are reserved for\\n * future use.\\n *\\n * @param {string} encodedStr\\n * @returns {boolean}\\n */\\nconst startsSpecial=(encodedStr)=>{\\nif(encodedStr===''){\\nreturn false;}\\n\\n/* charCodeAt(0) and number compare is a bit faster.*/\\nconst code=encodedStr.charCodeAt(0);\\n/* eslint-disable-next-line yoda*/\\nreturn BANG<=code&&code<=DASH;};\\n\\n\\n/**\\n * @typedef {object} EncodeToSmallcapsOptions\\n * @property {(\\n * remotable: Remotable,\\n * encodeRecur: (p: Passable) => SmallcapsEncoding\\n * ) => SmallcapsEncoding} [encodeRemotableToSmallcaps]\\n * @property {(\\n * promise: Promise,\\n * encodeRecur: (p: Passable) => SmallcapsEncoding\\n * ) => SmallcapsEncoding} [encodePromiseToSmallcaps]\\n * @property {(\\n * error: Error,\\n * encodeRecur: (p: Passable) => SmallcapsEncoding\\n * ) => SmallcapsEncoding} [encodeErrorToSmallcaps]\\n */\\n\\nconst dontEncodeRemotableToSmallcaps=(rem)=>\\nindex.throwRedacted`remotable unexpected: ${rem}`;\\n\\nconst dontEncodePromiseToSmallcaps=(prom)=>index.throwRedacted`promise unexpected: ${prom}`;\\n\\nconst dontEncodeErrorToSmallcaps=(err)=>\\nindex.throwRedacted`error object unexpected: ${index.quote(err)}`;\\n\\n/**\\n * @param {EncodeToSmallcapsOptions} [encodeOptions]\\n * encodeOptions is actually optional, but not marked as such to work around\\n * https://github.com/microsoft/TypeScript/issues/50286\\n *\\n * @returns {(passable: Passable) => SmallcapsEncoding}\\n */\\nconst makeEncodeToSmallcaps=(encodeOptions={})=>{\\nconst{\\nencodeRemotableToSmallcaps=dontEncodeRemotableToSmallcaps,\\nencodePromiseToSmallcaps=dontEncodePromiseToSmallcaps,\\nencodeErrorToSmallcaps=dontEncodeErrorToSmallcaps}=\\nencodeOptions;\\n\\nconst assertEncodedError=(encoding)=>{\\ntypeof encoding==='object'&&passStyleHelpers.hasOwnPropertyOf(encoding,'#error')||\\nindex.throwRedacted`internal: Error encoding must have \\\"#error\\\" property: ${index.quote(\\nencoding)\\n}`;\\n/* Assert that the #error property decodes to a string.*/\\nconst message=encoding['#error'];\\ntypeof message==='string'&&(\\n!startsSpecial(message)||message.charAt(0)==='!')||\\nindex.throwRedacted`internal: Error encoding must have string message: ${index.quote(message)}`;};\\n\\n\\n/**\\n * Must encode `val` into plain JSON data *canonically*, such that\\n * `JSON.stringify(encode(v1)) === JSON.stringify(encode(v1))`. For most\\n * encodings, the order of properties of each node of the output\\n * structure is determined by the algorithm below without special\\n * arrangement, usually by being expressed directly as an object literal.\\n * The exception is copyRecords, whose natural enumeration order\\n * can differ between copyRecords that our distributed object semantics\\n * considers to be equivalent.\\n * Since, for each copyRecord, we only accept string property names,\\n * not symbols, we can canonically sort the names first.\\n * JSON.stringify will then visit these in that sorted order.\\n *\\n * Encoding with a canonical-JSON encoder would also solve this canonicalness\\n * problem in a more modular and encapsulated manner. Note that the\\n * actual order produced here, though it agrees with canonical-JSON on\\n * copyRecord property ordering, differs from canonical-JSON as a whole\\n * in that the other record properties are visited in the order in which\\n * they are literally written below. TODO perhaps we should indeed switch\\n * to a canonical JSON encoder, and not delicately depend on the order\\n * in which these object literals are written.\\n *\\n * Readers must not care about this order anyway. We impose this requirement\\n * mainly to reduce non-determinism exposed outside a vat.\\n *\\n * @param {any} passable\\n * @returns {SmallcapsEncoding} except that `encodeToSmallcaps` does not generally\\n * `harden` this result before returning. Rather, `encodeToSmallcaps` is not\\n * directly exposed.\\n * What's exposed instead is a wrapper that freezes the output before\\n * returning. If this turns out to impede static analysis for `harden` safety,\\n * we can always put the (now redundant) hardens back in. They don't hurt.\\n */\\nconst encodeToSmallcapsRecur=(passable)=>{\\n/* First we handle all primitives. Some can be represented directly as*/\\n/* JSON, and some must be encoded into smallcaps strings.*/\\nconst passStyle=passStyleOf.passStyleOf(passable);\\nswitch(passStyle){\\ncase'null':\\ncase'boolean':{\\n/* pass through to JSON*/\\nreturn passable;}\\n\\ncase'string':{\\nif(startsSpecial(passable)){\\n/* Strings that start with a special char are quoted with `!`.*/\\n/* Since `!` is itself a special character, this trivially does*/\\n/* the Hilbert hotel. Also, since the special characters are*/\\n/* a continuous subrange of ascii, this quoting is sort-order*/\\n/* preserving.*/\\nreturn`!${passable}`;}\\n\\n/* All other strings pass through to JSON*/\\nreturn passable;}\\n\\ncase'undefined':{\\nreturn'#undefined';}\\n\\ncase'number':{\\n/* Special-case numbers with no digit-based representation.*/\\nif(Number.isNaN(passable)){\\nreturn'#NaN';}else\\nif(passable===Infinity){\\nreturn'#Infinity';}else\\nif(passable===-Infinity){\\nreturn'#-Infinity';}\\n\\n/* Pass through everything else, replacing -0 with 0.*/\\nreturn is(passable,-0)?0:passable;}\\n\\ncase'bigint':{\\nconst str=String(passable);\\nreturn(/** @type {bigint} */passable<0n?str:`+${str}`);}\\n\\ncase'symbol':{\\nsymbol.assertPassableSymbol(passable);\\nconst name=/** @type {string} */symbol.nameForPassableSymbol(passable);\\nreturn`%${name}`;}\\n\\ncase'copyRecord':{\\n/* Currently copyRecord allows only string keys so this will*/\\n/* work. If we allow sortable symbol keys, this will need to*/\\n/* become more interesting.*/\\nconst names=ownKeys(passable).sort();\\nreturn fromEntries(\\nnames.map((name)=>[\\nencodeToSmallcapsRecur(name),\\nencodeToSmallcapsRecur(passable[name])]));}\\n\\n\\n\\ncase'copyArray':{\\nreturn passable.map(encodeToSmallcapsRecur);}\\n\\ncase'tagged':{\\nreturn{\\n'#tag':encodeToSmallcapsRecur(passStyleHelpers.getTag(passable)),\\npayload:encodeToSmallcapsRecur(passable.payload)};}\\n\\n\\ncase'remotable':{\\nconst result=encodeRemotableToSmallcaps(\\npassable,\\nencodeToSmallcapsRecur);\\n\\nif(typeof result==='string'&&result.charAt(0)==='$'){\\nreturn result;}\\n\\n/* `throw` is noop since `Fail` throws. But linter confused*/\\nthrow index.throwRedacted`internal: Remotable encoding must start with \\\"$\\\": ${result}`;}\\n\\ncase'promise':{\\nconst result=encodePromiseToSmallcaps(\\npassable,\\nencodeToSmallcapsRecur);\\n\\nif(typeof result==='string'&&result.charAt(0)==='&'){\\nreturn result;}\\n\\nthrow index.throwRedacted`internal: Promise encoding must start with \\\"&\\\": ${result}`;}\\n\\ncase'error':{\\nconst result=encodeErrorToSmallcaps(passable,encodeToSmallcapsRecur);\\nassertEncodedError(result);\\nreturn result;}\\n\\ndefault:{\\nthrow assert.fail(\\nindex.redacted`internal: Unrecognized passStyle ${index.quote(passStyle)}`,\\nTypeError);}}};\\n\\n\\n\\n\\nconst encodeToSmallcaps=(passable)=>{\\nif(error.isErrorLike(passable)){\\n/* We pull out this special case to accommodate errors that are not*/\\n/* valid Passables. For example, because they're not frozen.*/\\n/* The special case can only ever apply at the root, and therefore*/\\n/* outside the recursion, since an error could only be deeper in*/\\n/* a passable structure if it were passable.*/\\n/**/\\n/* We pull out this special case because, for these errors, we're much*/\\n/* more interested in reporting whatever diagnostic information they*/\\n/* carry than we are about reporting problems encountered in reporting*/\\n/* this information.*/\\nconst result=harden(\\nencodeErrorToSmallcaps(passable,encodeToSmallcapsRecur));\\n\\nassertEncodedError(result);\\nreturn result;}\\n\\nreturn harden(encodeToSmallcapsRecur(passable));};\\n\\nreturn harden(encodeToSmallcaps);};\\n\\nharden(makeEncodeToSmallcaps);\\n\\n/**\\n * @typedef {object} DecodeFromSmallcapsOptions\\n * @property {(\\n * encodedRemotable: SmallcapsEncoding,\\n * decodeRecur: (e :SmallcapsEncoding) => Passable\\n * ) => Remotable} [decodeRemotableFromSmallcaps]\\n * @property {(\\n * encodedPromise: SmallcapsEncoding,\\n * decodeRecur: (e :SmallcapsEncoding) => Passable\\n * ) => Promise} [decodePromiseFromSmallcaps]\\n * @property {(\\n * encodedError: SmallcapsEncoding,\\n * decodeRecur: (e :SmallcapsEncoding) => Passable\\n * ) => Error} [decodeErrorFromSmallcaps]\\n */\\n\\nconst dontDecodeRemotableFromSmallcaps=(encoding)=>\\nindex.throwRedacted`remotable unexpected: ${encoding}`;\\nconst dontDecodePromiseFromSmallcaps=(encoding)=>\\nindex.throwRedacted`promise unexpected: ${encoding}`;\\nconst dontDecodeErrorFromSmallcaps=(encoding)=>\\nindex.throwRedacted`error unexpected: ${index.quote(encoding)}`;\\n\\n/**\\n * @param {DecodeFromSmallcapsOptions} [decodeOptions]\\n * @returns {(encoded: SmallcapsEncoding) => Passable}\\n */\\nconst makeDecodeFromSmallcaps=(decodeOptions={})=>{\\nconst{\\ndecodeRemotableFromSmallcaps=dontDecodeRemotableFromSmallcaps,\\ndecodePromiseFromSmallcaps=dontDecodePromiseFromSmallcaps,\\ndecodeErrorFromSmallcaps=dontDecodeErrorFromSmallcaps}=\\ndecodeOptions;\\n\\n/**\\n * `decodeFromSmallcaps` may rely on `encoding` being the result of a\\n * plain call to JSON.parse. However, it *cannot* rely on `encoding`\\n * having been produced by JSON.stringify on the output of `encodeToSmallcaps`\\n * above, i.e., `decodeFromSmallcaps` cannot rely on `encoding` being a\\n * valid marshalled representation. Rather, `decodeFromSmallcaps` must\\n * validate that.\\n *\\n * @param {SmallcapsEncoding} encoding must be hardened\\n */\\nconst decodeFromSmallcaps=(encoding)=>{\\nswitch(typeof encoding){\\ncase'boolean':\\ncase'number':{\\nreturn encoding;}\\n\\ncase'string':{\\nif(!startsSpecial(encoding)){\\nreturn encoding;}\\n\\nconst c=encoding.charAt(0);\\nswitch(c){\\ncase'!':{\\n/* un-hilbert-ify the string*/\\nreturn encoding.slice(1);}\\n\\ncase'%':{\\nreturn symbol.passableSymbolForName(encoding.slice(1));}\\n\\ncase'#':{\\nswitch(encoding){\\ncase'#undefined':{\\nreturn undefined;}\\n\\ncase'#NaN':{\\nreturn NaN;}\\n\\ncase'#Infinity':{\\nreturn Infinity;}\\n\\ncase'#-Infinity':{\\nreturn-Infinity;}\\n\\ndefault:{\\nthrow assert.fail(\\nindex.redacted`unknown constant \\\"${index.quote(encoding)}\\\"`,\\nTypeError);}}}\\n\\n\\n\\n\\ncase'+':\\ncase'-':{\\nreturn BigInt(encoding);}\\n\\ncase'$':{\\nconst result=decodeRemotableFromSmallcaps(\\nencoding,\\ndecodeFromSmallcaps);\\n\\n/* @ts-ignore XXX SmallCapsEncoding*/\\nif(passStyleOf.passStyleOf(result)!=='remotable'){\\nindex.throwRedacted`internal: decodeRemotableFromSmallcaps option must return a remotable: ${result}`;}\\n\\nreturn result;}\\n\\ncase'&':{\\nconst result=decodePromiseFromSmallcaps(\\nencoding,\\ndecodeFromSmallcaps);\\n\\nif(passStyleOf.passStyleOf(result)!=='promise'){\\nindex.throwRedacted`internal: decodePromiseFromSmallcaps option must return a promise: ${result}`;}\\n\\nreturn result;}\\n\\ndefault:{\\nthrow index.throwRedacted`Special char ${index.quote(\\nc)\\n} reserved for future use: ${encoding}`;}}}\\n\\n\\n\\ncase'object':{\\nif(encoding===null){\\nreturn encoding;}\\n\\n\\nif(isArray(encoding)){\\nreturn encoding.map((val)=>decodeFromSmallcaps(val));}\\n\\n\\nif(passStyleHelpers.hasOwnPropertyOf(encoding,'#tag')){\\nconst{'#tag':tag,payload,...rest}=encoding;\\ntypeof tag==='string'||\\nindex.throwRedacted`Value of \\\"#tag\\\", the tag, must be a string: ${encoding}`;\\nownKeys(rest).length===0||\\nindex.throwRedacted`#tag record unexpected properties: ${index.quote(ownKeys(rest))}`;\\nreturn makeTagged.makeTagged(\\ndecodeFromSmallcaps(tag),\\ndecodeFromSmallcaps(payload));}\\n\\n\\n\\nif(passStyleHelpers.hasOwnPropertyOf(encoding,'#error')){\\nconst result=decodeErrorFromSmallcaps(\\nencoding,\\ndecodeFromSmallcaps);\\n\\npassStyleOf.passStyleOf(result)==='error'||\\nindex.throwRedacted`internal: decodeErrorFromSmallcaps option must return an error: ${result}`;\\nreturn result;}\\n\\n\\nconst decodeEntry=([encodedName,encodedVal])=>{\\ntypeof encodedName==='string'||\\nindex.throwRedacted`Property name ${index.quote(\\nencodedName)\\n} of ${encoding} must be a string`;\\nencodedName.charAt(0)!=='#'||\\nindex.throwRedacted`Unrecognized record type ${index.quote(encodedName)}: ${encoding}`;\\nconst name=decodeFromSmallcaps(encodedName);\\ntypeof name==='string'||\\nindex.throwRedacted`Decoded property name ${name} from ${encoding} must be a string`;\\nreturn[name,decodeFromSmallcaps(encodedVal)];};\\n\\nconst decodedEntries=entries(encoding).map(decodeEntry);\\nreturn fromEntries(decodedEntries);}\\n\\ndefault:{\\nthrow assert.fail(\\nindex.redacted`internal: unrecognized JSON typeof ${index.quote(\\ntypeof encoding)\\n}: ${encoding}`,\\nTypeError);}}};\\n\\n\\n\\n\\nreturn harden(decodeFromSmallcaps);};exports.makeDecodeFromSmallcaps=makeDecodeFromSmallcaps;exports.makeEncodeToSmallcaps=makeEncodeToSmallcaps;\",\n \"node_modules/@endo/marshal/src/marshal-justin.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var index$1=require('../../nat/src/index.js');require('../../pass-style/index.js');var index=require('../../errors/index.js');var encodeToCapData=require('./encodeToCapData.js');var passStyleHelpers=require('../../pass-style/src/passStyle-helpers.js');var error=require('../../pass-style/src/error.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nsymbol=require('../../pass-style/src/symbol.js');/*/ <reference types=\\\"ses\\\"/>*/ /** @import {Encoding} from './types.js' */\\n\\nconst{ownKeys}=Reflect;\\nconst{isArray}=Array;\\nconst{stringify:quote}=JSON;\\n\\n/**\\n * @typedef {object} Indenter\\n * @property {(openBracket: string) => number} open\\n * @property {() => number} line\\n * @property {(token: string) => number} next\\n * @property {(closeBracket: string) => number} close\\n * @property {() => string} done\\n */\\n\\n/**\\n * Generous whitespace for readability\\n *\\n * @returns {Indenter}\\n */\\nconst makeYesIndenter=()=>{\\nconst strings=[];\\nlet level=0;\\nlet needSpace=false;\\nconst line=()=>{\\nneedSpace=false;\\nreturn strings.push('\\\\n',' '.repeat(level));};\\n\\nreturn harden({\\nopen:(openBracket)=>{\\nlevel+=1;\\nif(needSpace){\\nstrings.push(' ');}\\n\\nneedSpace=false;\\nreturn strings.push(openBracket);},\\n\\nline,\\nnext:(token)=>{\\nif(needSpace&&token!==','){\\nstrings.push(' ');}\\n\\nneedSpace=true;\\nreturn strings.push(token);},\\n\\nclose:(closeBracket)=>{\\nassert(level>=1);\\nlevel-=1;\\nline();\\nreturn strings.push(closeBracket);},\\n\\ndone:()=>{\\nassert.equal(level,0);\\nreturn strings.join('');}});};\\n\\n\\n\\n\\n/**\\n * If the last character of one token together with the first character\\n * of the next token matches this pattern, then the two tokens must be\\n * separated by whitespace to preserve their meaning. Otherwise the\\n * whitespace in unnecessary.\\n *\\n * The `<!` and `->` cases prevent the accidental formation of an\\n * html-like comment. I don't think the double angle brackets are actually\\n * needed but I haven't thought about it enough to remove them.\\n */\\nconst badPairPattern=/^(?:\\\\w\\\\w|<<|>>|\\\\+\\\\+|--|<!|->)$/;\\n\\n/**\\n * Minimum whitespace needed to preseve meaning.\\n *\\n * @returns {Indenter}\\n */\\nconst makeNoIndenter=()=>{\\n/** @type {string[]} */\\nconst strings=[];\\nreturn harden({\\nopen:(openBracket)=>strings.push(openBracket),\\nline:()=>strings.length,\\nnext:(token)=>{\\nif(strings.length>=1){\\nconst last=strings[strings.length-1];\\n/* eslint-disable-next-line @endo/restrict-comparison-operands -- error*/\\nif(last.length>=1&&token.length>=1){\\nconst pair=`${last[last.length-1]}${token[0]}`;\\nif(badPairPattern.test(pair)){\\nstrings.push(' ');}}}\\n\\n\\n\\nreturn strings.push(token);},\\n\\nclose:(closeBracket)=>{\\nif(strings.length>=1&&strings[strings.length-1]===','){\\nstrings.pop();}\\n\\nreturn strings.push(closeBracket);},\\n\\ndone:()=>strings.join('')});};\\n\\n\\n\\nconst identPattern=/^[a-zA-Z]\\\\w*$/;\\nharden(identPattern);\\nconst AtAtPrefixPattern=/^@@(.*)$/;\\nharden(AtAtPrefixPattern);\\n\\n/**\\n * @param {Encoding} encoding\\n * @param {boolean=} shouldIndent\\n * @param {any[]} [slots]\\n * @returns {string}\\n */\\nconst decodeToJustin=(encoding,shouldIndent=false,slots=[])=>{\\n/**\\n * The first pass does some input validation.\\n * Its control flow should mirror `recur` as closely as possible\\n * and the two should be maintained together. They must visit everything\\n * in the same order.\\n *\\n * TODO now that ibids are gone, we should fold this back together into\\n * one validating pass.\\n *\\n * @param {Encoding} rawTree\\n * @returns {void}\\n */\\nconst prepare=(rawTree)=>{\\nif(!passStyleHelpers.isObject(rawTree)){\\nreturn;}\\n\\n/* Assertions of the above to narrow the type.*/\\nassert.typeof(rawTree,'object');\\nassert(rawTree!==null);\\nif(encodeToCapData.QCLASS in rawTree){\\nconst qclass=rawTree[encodeToCapData.QCLASS];\\ntypeof qclass==='string'||\\nindex.throwRedacted`invalid qclass typeof ${index.quote(typeof qclass)}`;\\nassert(!isArray(rawTree));\\nswitch(rawTree['@qclass']){\\ncase'undefined':\\ncase'NaN':\\ncase'Infinity':\\ncase'-Infinity':{\\nreturn;}\\n\\ncase'bigint':{\\nconst{digits}=rawTree;\\ntypeof digits==='string'||\\nindex.throwRedacted`invalid digits typeof ${index.quote(typeof digits)}`;\\nreturn;}\\n\\ncase'@@asyncIterator':{\\nreturn;}\\n\\ncase'symbol':{\\nconst{name}=rawTree;\\nassert.typeof(name,'string');\\nconst sym=symbol.passableSymbolForName(name);\\nassert.typeof(sym,'symbol');\\nreturn;}\\n\\ncase'tagged':{\\nconst{tag,payload}=rawTree;\\nassert.typeof(tag,'string');\\nprepare(payload);\\nreturn;}\\n\\ncase'slot':{\\nconst{index,iface}=rawTree;\\nassert.typeof(index,'number');\\nindex$1.Nat(index);\\nif(iface!==undefined){\\nassert.typeof(iface,'string');}\\n\\nreturn;}\\n\\ncase'hilbert':{\\nconst{original,rest}=rawTree;\\n'original'in rawTree||\\nindex.throwRedacted`Invalid Hilbert Hotel encoding ${rawTree}`;\\nprepare(original);\\nif('rest'in rawTree){\\nif(typeof rest!=='object'){\\nthrow index.throwRedacted`Rest ${rest} encoding must be an object`;}\\n\\nif(rest===null){\\nthrow index.throwRedacted`Rest ${rest} encoding must not be null`;}\\n\\nif(isArray(rest)){\\nthrow index.throwRedacted`Rest ${rest} encoding must not be an array`;}\\n\\nif(encodeToCapData.QCLASS in rest){\\nthrow index.throwRedacted`Rest encoding ${rest} must not contain ${index.quote(encodeToCapData.QCLASS)}`;}\\n\\nconst names=ownKeys(rest);\\nfor(const name of names){\\ntypeof name==='string'||\\nindex.throwRedacted`Property name ${name} of ${rawTree} must be a string`;\\nprepare(rest[name]);}}\\n\\n\\nreturn;}\\n\\ncase'error':{\\nconst{name,message}=rawTree;\\nif(typeof name!=='string'){\\nthrow index.throwRedacted`invalid error name typeof ${index.quote(typeof name)}`;}\\n\\nerror.getErrorConstructor(name)!==undefined||\\nindex.throwRedacted`Must be the name of an Error constructor ${name}`;\\ntypeof message==='string'||\\nindex.throwRedacted`invalid error message typeof ${index.quote(typeof message)}`;\\nreturn;}\\n\\n\\ndefault:{\\nassert.fail(index.redacted`unrecognized ${index.quote(encodeToCapData.QCLASS)} ${index.quote(qclass)}`,TypeError);}}}else\\n\\n\\nif(isArray(rawTree)){\\nconst{length}=rawTree;\\nfor(let i=0;i<length;i+=1){\\nprepare(rawTree[i]);}}else\\n\\n{\\nconst names=ownKeys(rawTree);\\nfor(const name of names){\\nif(typeof name!=='string'){\\nthrow index.throwRedacted`Property name ${name} of ${rawTree} must be a string`;}\\n\\nprepare(rawTree[name]);}}};\\n\\n\\n\\n\\nconst makeIndenter=shouldIndent?makeYesIndenter:makeNoIndenter;\\nlet out=makeIndenter();\\n\\n/**\\n * This is the second pass recursion after the first pass `prepare`.\\n * The first pass did some input validation so\\n * here we can safely assume everything those things are validated.\\n *\\n * @param {Encoding} rawTree\\n * @returns {number}\\n */\\nconst decode=(rawTree)=>{\\n/* eslint-disable-next-line no-use-before-define*/\\nreturn recur(rawTree);};\\n\\n\\nconst decodeProperty=(name,value)=>{\\nout.line();\\nif(name==='__proto__'){\\n/* JavaScript interprets `{__proto__: x, ...}`*/\\n/* as making an object inheriting from `x`, whereas*/\\n/* in JSON it is simply a property name. Preserve the*/\\n/* JSON meaning.*/\\nout.next(`[\\\"__proto__\\\"]:`);}else\\nif(identPattern.test(name)){\\nout.next(`${name}:`);}else\\n{\\nout.next(`${quote(name)}:`);}\\n\\ndecode(value);\\nout.next(',');};\\n\\n\\n/**\\n * Modeled after `fullRevive` in marshal.js\\n *\\n * @param {Encoding} rawTree\\n * @returns {number}\\n */\\nconst recur=(rawTree)=>{\\nif(!passStyleHelpers.isObject(rawTree)){\\n/* primitives get quoted*/\\nreturn out.next(quote(rawTree));}\\n\\n/* Assertions of the above to narrow the type.*/\\nassert.typeof(rawTree,'object');\\nassert(rawTree!==null);\\nif(encodeToCapData.QCLASS in rawTree){\\nconst qclass=rawTree[encodeToCapData.QCLASS];\\nassert.typeof(qclass,'string');\\nassert(!isArray(rawTree));\\n/* Switching on `encoded[QCLASS]` (or anything less direct, like*/\\n/* `qclass`) does not discriminate rawTree in typescript@4.2.3 and*/\\n/* earlier.*/\\nswitch(rawTree['@qclass']){\\n/* Encoding of primitives not handled by JSON*/\\ncase'undefined':\\ncase'NaN':\\ncase'Infinity':\\ncase'-Infinity':{\\n/* Their qclass is their expression source.*/\\nreturn out.next(qclass);}\\n\\ncase'bigint':{\\nconst{digits}=rawTree;\\nassert.typeof(digits,'string');\\nreturn out.next(`${BigInt(digits)}n`);}\\n\\ncase'@@asyncIterator':{\\n/* TODO deprecated. Eventually remove.*/\\nreturn out.next('Symbol.asyncIterator');}\\n\\ncase'symbol':{\\nconst{name}=rawTree;\\nassert.typeof(name,'string');\\nconst sym=symbol.passableSymbolForName(name);\\nassert.typeof(sym,'symbol');\\nconst registeredName=Symbol.keyFor(sym);\\nif(registeredName===undefined){\\nconst match=AtAtPrefixPattern.exec(name);\\nassert(match!==null);\\nconst suffix=match[1];\\nassert(Symbol[suffix]===sym);\\nassert(identPattern.test(suffix));\\nreturn out.next(`Symbol.${suffix}`);}\\n\\nreturn out.next(`Symbol.for(${quote(registeredName)})`);}\\n\\ncase'tagged':{\\nconst{tag,payload}=rawTree;\\nout.next(`makeTagged(${quote(tag)},`);\\ndecode(payload);\\nreturn out.next(')');}\\n\\n\\ncase'slot':{\\nlet{iface}=rawTree;\\nconst index=Number(index$1.Nat(rawTree.index));\\nconst nestedRender=(arg)=>{\\nconst oldOut=out;\\ntry{\\nout=makeNoIndenter();\\ndecode(arg);\\nreturn out.done();}finally\\n{\\nout=oldOut;}};\\n\\n\\nif(index<slots.length){\\nconst slot=nestedRender(slots[index]);\\nif(iface===undefined){\\nreturn out.next(`slotToVal(${slot})`);}\\n\\niface=nestedRender(iface);\\nreturn out.next(`slotToVal(${slot},${iface})`);}else\\nif(iface===undefined){\\nreturn out.next(`slot(${index})`);}\\n\\niface=nestedRender(iface);\\nreturn out.next(`slot(${index},${iface})`);}\\n\\n\\ncase'hilbert':{\\nconst{original,rest}=rawTree;\\nout.open('{');\\ndecodeProperty(encodeToCapData.QCLASS,original);\\nif('rest'in rawTree){\\nassert.typeof(rest,'object');\\nassert(rest!==null);\\nconst names=ownKeys(rest);\\nfor(const name of names){\\nif(typeof name!=='string'){\\nthrow index.throwRedacted`Property name ${index.quote(\\nname)\\n} of ${rest} must be a string`;}\\n\\ndecodeProperty(name,rest[name]);}}\\n\\n\\nreturn out.close('}');}\\n\\n\\ncase'error':{\\nconst{\\nname,\\nmessage,\\ncause=undefined,\\nerrors=undefined}=\\nrawTree;\\ncause===undefined||\\nindex.throwRedacted`error cause not yet implemented in marshal-justin`;\\nname!==`AggregateError`||\\nindex.throwRedacted`AggregateError not yet implemented in marshal-justin`;\\nerrors===undefined||\\nindex.throwRedacted`error errors not yet implemented in marshal-justin`;\\nreturn out.next(`${name}(${quote(message)})`);}\\n\\n\\ndefault:{\\nthrow assert.fail(\\nindex.redacted`unrecognized ${index.quote(encodeToCapData.QCLASS)} ${index.quote(qclass)}`,\\nTypeError);}}}else\\n\\n\\n\\nif(isArray(rawTree)){\\nconst{length}=rawTree;\\nif(length===0){\\nreturn out.next('[]');}else\\n{\\nout.open('[');\\nfor(let i=0;i<length;i+=1){\\nout.line();\\ndecode(rawTree[i]);\\nout.next(',');}\\n\\nreturn out.close(']');}}else\\n\\n{\\n/* rawTree is an `EncodingRecord` which only has string keys,*/\\n/* but since ownKeys is not generic, it can't propagate that*/\\nconst names=/** @type {string[]} */ownKeys(rawTree);\\nif(names.length===0){\\nreturn out.next('{}');}else\\n{\\nout.open('{');\\nfor(const name of names){\\ndecodeProperty(name,rawTree[name]);}\\n\\nreturn out.close('}');}}};\\n\\n\\n\\nprepare(encoding);\\ndecode(encoding);\\nreturn out.done();};\\n\\nharden(decodeToJustin);exports.decodeToJustin=decodeToJustin;\",\n \"node_modules/@endo/marshal/src/marshal-stringify.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var index=require('../../errors/index.js');var\\n\\n\\n\\n\\n\\n\\nmarshal=require('./marshal.js');/*/ <reference types=\\\"ses\\\"/>*/ /** @import {Passable} from '@endo/pass-style' */ /** @type {IMPORT('./types.js').ConvertValToSlot<any>} */\\nconst doNotConvertValToSlot=(val)=>\\nindex.throwRedacted`Marshal's stringify rejects presences and promises ${val}`;\\n\\n/** @type {IMPORT('./types.js').ConvertSlotToVal<any>} */\\nconst doNotConvertSlotToVal=(slot,_iface)=>\\nindex.throwRedacted`Marshal's parse must not encode any slots ${slot}`;\\n\\nconst badArrayHandler=harden({\\nget:(_target,name,_receiver)=>{\\nif(name==='length'){\\nreturn 0;}\\n\\n/* `throw` is noop since `Fail` throws. But linter confused*/\\nthrow index.throwRedacted`Marshal's parse must not encode any slot positions ${name}`;}});\\n\\n\\n\\nconst badArray=harden(new Proxy(harden([]),badArrayHandler));\\n\\nconst{serialize,unserialize}=marshal.makeMarshal(\\ndoNotConvertValToSlot,\\ndoNotConvertSlotToVal,\\n{\\nerrorTagging:'off',\\n/* TODO fix tests to works with smallcaps.*/\\nserializeBodyFormat:'capdata'});\\n\\n\\n\\n/**\\n * @param {Passable} val\\n * @returns {string}\\n */\\nconst stringify=(val)=>serialize(val).body;\\nharden(stringify);\\n\\n/**\\n * @param {string} str\\n * @returns {unknown}\\n */\\nconst parse=(str)=>\\nunserialize(\\nharden({\\nbody:str,\\nslots:badArray}));\\n\\n\\nharden(parse);exports.parse=parse;exports.stringify=stringify;\",\n \"node_modules/@endo/marshal/src/marshal.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var index$1=require('../../nat/src/index.js');require('../../pass-style/index.js');var index=require('../../errors/index.js');var objectMap=require('../../common/object-map.js');var encodeToCapData=require('./encodeToCapData.js');var encodeToSmallcaps=require('./encodeToSmallcaps.js');var remotable=require('../../pass-style/src/remotable.js');var error=require('../../pass-style/src/error.js');var passStyleOf=require('../../pass-style/src/passStyleOf.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\npassStyleHelpers=require('../../pass-style/src/passStyle-helpers.js');/*/ <reference types=\\\"ses\\\"/>*/ /**\\n * @import {ConvertSlotToVal, ConvertValToSlot, FromCapData, MakeMarshalOptions, ToCapData} from './types.js';\\n * @import {Passable, PassableCap, RemotableObject} from '@endo/pass-style';\\n * @import {InterfaceSpec} from '@endo/pass-style';\\n * @import {Encoding} from './types.js';\\n */\\n\\nconst{defineProperties}=Object;\\nconst{isArray}=Array;\\nconst{ownKeys}=Reflect;\\n\\n/** @type {ConvertValToSlot<any>} */\\nconst defaultValToSlotFn=(x)=>x;\\n/** @type {ConvertSlotToVal<any>} */\\nconst defaultSlotToValFn=(x,_)=>x;\\n\\n/**\\n * @template Slot\\n * @param {ConvertValToSlot<Slot>} [convertValToSlot]\\n * @param {ConvertSlotToVal<Slot>} [convertSlotToVal]\\n * @param {MakeMarshalOptions} options\\n */\\nconst makeMarshal=(\\nconvertValToSlot=defaultValToSlotFn,\\nconvertSlotToVal=defaultSlotToValFn,\\n{\\nerrorTagging='on',\\nmarshalName='anon-marshal',\\n/* TODO Temporary hack.*/\\n/* See https://github.com/Agoric/agoric-sdk/issues/2780*/\\nerrorIdNum=10000,\\n/* We prefer that the caller instead log to somewhere hidden*/\\n/* to be revealed when correlating with the received error.*/\\nmarshalSaveError=(err)=>\\nconsole.log('Temporary logging of sent error',err),\\n/* Default to 'capdata' because it was implemented first.*/\\n/* Sometimes, ontogeny does recapitulate phylogeny ;)*/\\nserializeBodyFormat='capdata'}=\\n{})=>\\n{\\nassert.typeof(marshalName,'string');\\nerrorTagging==='on'||\\nerrorTagging==='off'||\\nindex.throwRedacted`The errorTagging option can only be \\\"on\\\" or \\\"off\\\" ${errorTagging}`;\\nconst nextErrorId=()=>{\\nerrorIdNum+=1;\\nreturn`error:${marshalName}#${errorIdNum}`;};\\n\\n\\n/**\\n * @type {ToCapData<Slot>}\\n */\\nconst toCapData=(root)=>{\\nconst slots=[];\\n/* maps val (promise or remotable) to index of slots[]*/\\nconst slotMap=new Map();\\n\\n/**\\n * @param {PassableCap} passable\\n * @returns {{index: number, repeat: boolean}}\\n */\\nconst encodeSlotCommon=(passable)=>{\\nlet index=slotMap.get(passable);\\nif(index!==undefined){\\n/* TODO assert that it's the same iface as before*/\\nassert.typeof(index,'number');\\nreturn harden({index,repeat:true});}\\n\\n\\nindex=slots.length;\\nconst slot=convertValToSlot(passable);\\nslots.push(slot);\\nslotMap.set(passable,index);\\nreturn harden({index,repeat:false});};\\n\\n\\n/**\\n * Even if an Error is not actually passable, we'd rather send\\n * it anyway because the diagnostic info carried by the error\\n * is more valuable than diagnosing why the error isn't\\n * passable. See comments in isErrorLike.\\n *\\n * @param {Error} err\\n * @param {(p: Passable) => unknown} encodeRecur\\n * @returns {{errorId?: string, message: string, name: string}}\\n */\\nconst encodeErrorCommon=(err,encodeRecur)=>{\\nconst message=encodeRecur(`${err.message}`);\\nassert.typeof(message,'string');\\nconst name=encodeRecur(`${err.name}`);\\nassert.typeof(name,'string');\\n/* TODO Must encode `cause`, `errors`, but*/\\n/* only once all possible counterparty decoders are tolerant of*/\\n/* receiving them.*/\\nif(errorTagging==='on'){\\n/* We deliberately do not share the stack, but it would*/\\n/* be useful to log the stack locally so someone who has*/\\n/* privileged access to the throwing Vat can correlate*/\\n/* the problem with the remote Vat that gets this*/\\n/* summary. If we do that, we could allocate some random*/\\n/* identifier and include it in the message, to help*/\\n/* with the correlation.*/\\nconst errorId=encodeRecur(nextErrorId());\\nassert.typeof(errorId,'string');\\nindex.note(err,index.redacted`Sent as ${errorId}`);\\nmarshalSaveError(err);\\nreturn harden({errorId,message,name});}else\\n{\\nreturn harden({message,name});}};\\n\\n\\n\\nif(serializeBodyFormat==='capdata'){\\n/**\\n * @param {PassableCap} passable\\n * @param {InterfaceSpec} [iface]\\n * @returns {Encoding}\\n */\\nconst encodeSlotToCapData=(passable,iface=undefined)=>{\\nconst{index,repeat}=encodeSlotCommon(passable);\\n\\nif(repeat===true||iface===undefined){\\nreturn harden({[encodeToCapData.QCLASS]:'slot',index});}else\\n{\\nreturn harden({[encodeToCapData.QCLASS]:'slot',iface,index});}};\\n\\n\\n\\n/** @type {(promise: RemotableObject, encodeRecur: (p: Passable) => Encoding) => Encoding} */\\nconst encodeRemotableToCapData=(val,_encodeRecur)=>\\nencodeSlotToCapData(val,remotable.getInterfaceOf(val));\\n\\n/** @type {(promise: Promise, encodeRecur: (p: Passable) => Encoding) => Encoding} */\\nconst encodePromiseToCapData=(promise,_encodeRecur)=>\\nencodeSlotToCapData(promise);\\n\\n/**\\n * Even if an Error is not actually passable, we'd rather send\\n * it anyway because the diagnostic info carried by the error\\n * is more valuable than diagnosing why the error isn't\\n * passable. See comments in isErrorLike.\\n *\\n * @param {Error} err\\n * @param {(p: Passable) => Encoding} encodeRecur\\n * @returns {Encoding}\\n */\\nconst encodeErrorToCapData=(err,encodeRecur)=>{\\nconst errData=encodeErrorCommon(err,encodeRecur);\\nreturn harden({[encodeToCapData.QCLASS]:'error',...errData});};\\n\\n\\nconst encodeToCapData$1=encodeToCapData.makeEncodeToCapData({\\nencodeRemotableToCapData,\\nencodePromiseToCapData,\\nencodeErrorToCapData});\\n\\n\\nconst encoded=encodeToCapData$1(root);\\nconst body=JSON.stringify(encoded);\\nreturn harden({\\nbody,\\nslots});}else\\n\\nif(serializeBodyFormat==='smallcaps'){\\n/**\\n * @param {string} prefix\\n * @param {PassableCap} passable\\n * @param {InterfaceSpec} [iface]\\n * @returns {string}\\n */\\nconst encodeSlotToSmallcaps=(prefix,passable,iface=undefined)=>{\\nconst{index,repeat}=encodeSlotCommon(passable);\\n\\n/* TODO explore removing this special case*/\\nif(repeat===true||iface===undefined){\\nreturn`${prefix}${index}`;}\\n\\nreturn`${prefix}${index}.${iface}`;};\\n\\n\\nconst encodeRemotableToSmallcaps=(remotable$1,_encodeRecur)=>\\nencodeSlotToSmallcaps('$',remotable$1,remotable.getInterfaceOf(remotable$1));\\n\\nconst encodePromiseToSmallcaps=(promise,_encodeRecur)=>\\nencodeSlotToSmallcaps('&',promise);\\n\\nconst encodeErrorToSmallcaps=(err,encodeRecur)=>{\\nconst errData=encodeErrorCommon(err,encodeRecur);\\nconst{message,...rest}=errData;\\nreturn harden({'#error':message,...rest});};\\n\\n\\nconst encodeToSmallcaps$1=encodeToSmallcaps.makeEncodeToSmallcaps({\\nencodeRemotableToSmallcaps,\\nencodePromiseToSmallcaps,\\nencodeErrorToSmallcaps});\\n\\n\\nconst encoded=encodeToSmallcaps$1(root);\\nconst smallcapsBody=JSON.stringify(encoded);\\nreturn harden({\\n/* Valid JSON cannot begin with a '#', so this is a valid signal*/\\n/* indicating smallcaps format.*/\\nbody:`#${smallcapsBody}`,\\nslots});}else\\n\\n{\\n/* The `throw` is a noop since `Fail` throws. Added for confused linters.*/\\nthrow index.throwRedacted`Unrecognized serializeBodyFormat: ${index.quote(serializeBodyFormat)}`;}};\\n\\n\\n\\nconst makeFullRevive=(slots)=>{\\n/** @type {Map<number, RemotableObject | Promise>} */\\nconst valMap=new Map();\\n\\n/**\\n * @param {{iface?: string, index: number}} slotData\\n * @returns {RemotableObject | Promise}\\n */\\nconst decodeSlotCommon=(slotData)=>{\\nconst{iface=undefined,index:index$2,...rest}=slotData;\\nownKeys(rest).length===0||\\nindex.throwRedacted`unexpected encoded slot properties ${index.quote(ownKeys(rest))}`;\\nconst extant=valMap.get(index$2);\\nif(extant){\\nreturn extant;}\\n\\n/* TODO SECURITY HAZARD: must enfoce that remotable vs promise*/\\n/* is according to the encoded string.*/\\nconst slot=slots[Number(index$1.Nat(index$2))];\\nconst val=convertSlotToVal(slot,iface);\\nvalMap.set(index$2,val);\\nreturn val;};\\n\\n\\n/**\\n * @param {{\\n * errorId?: string,\\n * message: string,\\n * name: string,\\n * cause: unknown,\\n * errors: unknown,\\n * }} errData\\n * @param {(e: unknown) => Passable} decodeRecur\\n * @returns {Error}\\n */\\nconst decodeErrorCommon=(errData,decodeRecur)=>{\\nconst{\\nerrorId=undefined,\\nmessage,\\nname,\\ncause=undefined,\\nerrors=undefined,\\n...rest}=\\nerrData;\\n/* See https://github.com/endojs/endo/pull/2052*/\\n/* capData does not transform strings. The immediately following calls*/\\n/* to `decodeRecur` are for reuse by other encodings that do,*/\\n/* such as smallcaps.*/\\nconst dName=decodeRecur(name);\\nconst dMessage=decodeRecur(message);\\n/* errorId is a late addition so be tolerant of its absence.*/\\nconst dErrorId=/** @type {string} */errorId&&decodeRecur(errorId);\\nif(typeof dName!=='string'){\\nthrow index.throwRedacted`invalid error name typeof ${index.quote(typeof dName)}`;}\\n\\nif(typeof dMessage!=='string'){\\nthrow index.throwRedacted`invalid error message typeof ${index.quote(typeof dMessage)}`;}\\n\\nconst errConstructor=error.getErrorConstructor(dName)||Error;\\nconst errorName=\\ndErrorId===undefined?\\n`Remote${errConstructor.name}`:\\n`Remote${errConstructor.name}(${dErrorId})`;\\nconst options={\\nerrorName,\\nsanitize:false};\\n\\nif(cause){\\noptions.cause=decodeRecur(cause);}\\n\\nif(errors){\\noptions.errors=decodeRecur(errors);}\\n\\nconst rawError=index.makeError(dMessage,errConstructor,options);\\n/* Note that this does not decodeRecur rest's property names.*/\\n/* This would be inconsistent with smallcaps' expected handling,*/\\n/* but is fine here since it is only used for `annotateError`,*/\\n/* which is for diagnostic info that is otherwise unobservable.*/\\nconst descs=objectMap.objectMap(rest,(data)=>({\\nvalue:decodeRecur(data),\\nwritable:false,\\nenumerable:false,\\nconfigurable:false}));\\n\\ndefineProperties(rawError,descs);\\nharden(rawError);\\nreturn passStyleOf.toPassableError(rawError);};\\n\\n\\n/* The current encoding does not give the decoder enough into to distinguish*/\\n/* whether a slot represents a promise or a remotable. As an implementation*/\\n/* restriction until this is fixed, if either is provided, both must be*/\\n/* provided and they must be the same.*/\\n/* See https://github.com/Agoric/agoric-sdk/issues/4334*/\\nconst decodeRemotableOrPromiseFromCapData=(rawTree,_decodeRecur)=>{\\nconst{[encodeToCapData.QCLASS]:_,...slotData}=rawTree;\\nreturn decodeSlotCommon(slotData);};\\n\\n\\nconst decodeErrorFromCapData=(rawTree,decodeRecur)=>{\\nconst{[encodeToCapData.QCLASS]:_,...errData}=rawTree;\\nreturn decodeErrorCommon(errData,decodeRecur);};\\n\\n\\nconst reviveFromCapData=encodeToCapData.makeDecodeFromCapData({\\ndecodeRemotableFromCapData:decodeRemotableOrPromiseFromCapData,\\ndecodePromiseFromCapData:decodeRemotableOrPromiseFromCapData,\\ndecodeErrorFromCapData});\\n\\n\\nconst makeDecodeSlotFromSmallcaps=(prefix)=>{\\n/**\\n * @param {string} stringEncoding\\n * @param {(e: unknown) => Passable} _decodeRecur\\n * @returns {RemotableObject | Promise}\\n */\\nreturn(stringEncoding,_decodeRecur)=>{\\nassert(stringEncoding.charAt(0)===prefix);\\n/* slots: $slotIndex.iface or $slotIndex*/\\nconst i=stringEncoding.indexOf('.');\\nconst index=Number(stringEncoding.slice(1,i<0?undefined:i));\\n/* i < 0 means there was no iface included.*/\\nconst iface=i<0?undefined:stringEncoding.slice(i+1);\\nreturn decodeSlotCommon({iface,index});};};\\n\\n\\nconst decodeRemotableFromSmallcaps=makeDecodeSlotFromSmallcaps('$');\\nconst decodePromiseFromSmallcaps=makeDecodeSlotFromSmallcaps('&');\\n\\nconst decodeErrorFromSmallcaps=(encoding,decodeRecur)=>{\\nconst{'#error':message,...restErrData}=encoding;\\n!passStyleHelpers.hasOwnPropertyOf(restErrData,'message')||\\nindex.throwRedacted`unexpected encoded error property ${index.quote('message')}`;\\nreturn decodeErrorCommon({message,...restErrData},decodeRecur);};\\n\\n\\nconst reviveFromSmallcaps=encodeToSmallcaps.makeDecodeFromSmallcaps({\\n/* @ts-ignore XXX SmallCapsEncoding*/\\ndecodeRemotableFromSmallcaps,\\n/* @ts-ignore XXX SmallCapsEncoding*/\\ndecodePromiseFromSmallcaps,\\ndecodeErrorFromSmallcaps});\\n\\n\\nreturn harden({reviveFromCapData,reviveFromSmallcaps});};\\n\\n\\n/**\\n * @type {FromCapData<Slot>}\\n */\\nconst fromCapData=(data)=>{\\nconst{body,slots}=data;\\ntypeof body==='string'||\\nindex.throwRedacted`unserialize() given non-capdata (.body is ${body}, not string)`;\\nisArray(data.slots)||\\nindex.throwRedacted`unserialize() given non-capdata (.slots are not Array)`;\\nconst{reviveFromCapData,reviveFromSmallcaps}=makeFullRevive(slots);\\nlet result;\\n/* JSON cannot begin with a '#', so this is an unambiguous signal.*/\\nif(body.charAt(0)==='#'){\\nconst smallcapsBody=body.slice(1);\\nconst encoding=harden(JSON.parse(smallcapsBody));\\nresult=harden(reviveFromSmallcaps(encoding));}else\\n{\\nconst rawTree=harden(JSON.parse(body));\\nresult=harden(reviveFromCapData(rawTree));}\\n\\n/* See https://github.com/Agoric/agoric-sdk/issues/4337*/\\n/* which should be considered fixed once we've completed the switch*/\\n/* to smallcaps.*/\\npassStyleOf.assertPassable(result);\\nreturn(/** @type {PassableCap} */result);};\\n\\n\\nreturn harden({\\ntoCapData,\\nfromCapData,\\n\\n/* for backwards compatibility*/\\n/** @deprecated use toCapData */\\nserialize:toCapData,\\n/** @deprecated use fromCapData */\\nunserialize:fromCapData});};exports.makeMarshal=makeMarshal;\",\n \"node_modules/@endo/marshal/src/rankOrder.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../pass-style/index.js');var index=require('../../errors/index.js');var encodePassable=require('./encodePassable.js');var passStyleOf=require('../../pass-style/src/passStyleOf.js');var passStyleHelpers=require('../../pass-style/src/passStyle-helpers.js');var\\n\\n\\n\\n\\n\\n\\n\\nsymbol=require('../../pass-style/src/symbol.js');/**\\n * @import {Passable, PassStyle} from '@endo/pass-style'\\n * @import {FullCompare, RankCompare, RankCover} from './types.js'\\n */\\n\\nconst{entries,fromEntries,setPrototypeOf,is}=Object;\\n\\n/**\\n * @typedef {object} RankComparatorKit\\n * @property {RankCompare} comparator\\n * @property {RankCompare} antiComparator\\n */\\n\\n/**\\n * @typedef {object} FullComparatorKit\\n * @property {FullCompare} comparator\\n * @property {FullCompare} antiComparator\\n */\\n\\n/**\\n * @typedef {[number, number]} IndexCover\\n */\\n\\n/**\\n * This is the equality comparison used by JavaScript's Map and Set\\n * abstractions, where NaN is the same as NaN and -0 is the same as\\n * 0. Marshal serializes -0 as zero, so the semantics of our distributed\\n * object system does not distinguish 0 from -0.\\n *\\n * `sameValueZero` is the EcmaScript spec name for this equality comparison,\\n * but TODO we need a better name for the API.\\n *\\n * @param {any} x\\n * @param {any} y\\n * @returns {boolean}\\n */\\nconst sameValueZero=(x,y)=>x===y||is(x,y);\\n\\nconst trivialComparator=(left,right)=>\\n/* eslint-disable-next-line no-nested-ternary, @endo/restrict-comparison-operands*/\\nleft<right?-1:left===right?0:1;\\n\\n/**\\n * @typedef {Record<PassStyle, { index: number, cover: RankCover }>} PassStyleRanksRecord\\n */\\n\\nconst passStyleRanks=/** @type {PassStyleRanksRecord} */\\nfromEntries(\\nentries(encodePassable.passStylePrefixes)\\n/* Sort entries by ascending prefix.*/.\\nsort(([_leftStyle,leftPrefixes],[_rightStyle,rightPrefixes])=>{\\nreturn trivialComparator(leftPrefixes,rightPrefixes);}).\\n\\nmap(([passStyle,prefixes],index$1)=>{\\n/* Cover all strings that start with any character in `prefixes`,*/\\n/* verifying that it is sorted so that is*/\\n/* all s such that prefixes.at(0) ≤ s < successor(prefixes.at(-1)).*/\\nprefixes===[...prefixes].sort().join('')||\\nindex.throwRedacted`unsorted prefixes for passStyle ${index.quote(passStyle)}: ${index.quote(prefixes)}`;\\nconst cover=[\\nprefixes.charAt(0),\\nString.fromCharCode(prefixes.charCodeAt(prefixes.length-1)+1)];\\n\\nreturn[passStyle,{index:index$1,cover}];}));\\n\\n\\n\\nsetPrototypeOf(passStyleRanks,null);\\nharden(passStyleRanks);\\n\\n/**\\n * Associate with each passStyle a RankCover that may be an overestimate,\\n * and whose results therefore need to be filtered down. For example, because\\n * there is not a smallest or biggest bigint, bound it by `NaN` (the last place\\n * number) and `''` (the empty string, which is the first place string). Thus,\\n * a range query using this range may include these values, which would then\\n * need to be filtered out.\\n *\\n * @param {PassStyle} passStyle\\n * @returns {RankCover}\\n */\\nconst getPassStyleCover=(passStyle)=>passStyleRanks[passStyle].cover;\\nharden(getPassStyleCover);\\n\\n/**\\n * @type {WeakMap<RankCompare,WeakSet<Passable[]>>}\\n */\\nconst memoOfSorted=new WeakMap();\\n\\n/**\\n * @type {WeakMap<RankCompare,RankCompare>}\\n */\\nconst comparatorMirrorImages=new WeakMap();\\n\\n/**\\n * @param {RankCompare=} compareRemotables\\n * An option to create a comparator in which an internal order is\\n * assigned to remotables. This defaults to a comparator that\\n * always returns `0`, meaning that all remotables are tied\\n * for the same rank.\\n * @returns {RankComparatorKit}\\n */\\nconst makeComparatorKit=(compareRemotables=(_x,_y)=>0)=>{\\n/** @type {RankCompare} */\\nconst comparator=(left,right)=>{\\nif(sameValueZero(left,right)){\\nreturn 0;}\\n\\nconst leftStyle=passStyleOf.passStyleOf(left);\\nconst rightStyle=passStyleOf.passStyleOf(right);\\nif(leftStyle!==rightStyle){\\nreturn trivialComparator(\\npassStyleRanks[leftStyle].index,\\npassStyleRanks[rightStyle].index);}\\n\\n\\n/* eslint-disable @endo/restrict-comparison-operands --\\n * We know `left` and `right` are comparable.\\n */\\nswitch(leftStyle){\\ncase'remotable':{\\nreturn compareRemotables(left,right);}\\n\\ncase'undefined':\\ncase'null':\\ncase'error':\\ncase'promise':{\\n/* For each of these passStyles, all members of that passStyle are tied*/\\n/* for the same rank.*/\\nreturn 0;}\\n\\ncase'boolean':\\ncase'bigint':\\ncase'string':{\\n/* Within each of these passStyles, the rank ordering agrees with*/\\n/* JavaScript's relational operators `<` and `>`.*/\\nif(left<right){\\nreturn-1;}else\\n{\\nassert(left>right);\\nreturn 1;}}\\n\\n\\ncase'symbol':{\\nreturn comparator(\\nsymbol.nameForPassableSymbol(left),\\nsymbol.nameForPassableSymbol(right));}\\n\\n\\ncase'number':{\\n/* `NaN`'s rank is after all other numbers.*/\\nif(Number.isNaN(left)){\\nassert(!Number.isNaN(right));\\nreturn 1;}else\\nif(Number.isNaN(right)){\\nreturn-1;}\\n\\n/* The rank ordering of non-NaN numbers agrees with JavaScript's*/\\n/* relational operators '<' and '>'.*/\\nif(left<right){\\nreturn-1;}else\\n{\\nassert(left>right);\\nreturn 1;}}\\n\\n\\ncase'copyRecord':{\\n/* Lexicographic by inverse sorted order of property names, then*/\\n/* lexicographic by corresponding values in that same inverse*/\\n/* order of their property names. Comparing names by themselves first,*/\\n/* all records with the exact same set of property names sort next to*/\\n/* each other in a rank-sort of copyRecords.*/\\n\\n/* The copyRecord invariants enforced by passStyleOf ensure that*/\\n/* all the property names are strings. We need the reverse sorted order*/\\n/* of these names, which we then compare lexicographically. This ensures*/\\n/* that if the names of record X are a subset of the names of record Y,*/\\n/* then record X will have an earlier rank and sort to the left of Y.*/\\nconst leftNames=encodePassable.recordNames(left);\\nconst rightNames=encodePassable.recordNames(right);\\n\\nconst result=comparator(leftNames,rightNames);\\nif(result!==0){\\nreturn result;}\\n\\nreturn comparator(\\nencodePassable.recordValues(left,leftNames),\\nencodePassable.recordValues(right,rightNames));}\\n\\n\\ncase'copyArray':{\\n/* Lexicographic*/\\nconst len=Math.min(left.length,right.length);\\nfor(let i=0;i<len;i+=1){\\nconst result=comparator(left[i],right[i]);\\nif(result!==0){\\nreturn result;}}\\n\\n\\n/* If all matching elements were tied, then according to their lengths.*/\\n/* If array X is a prefix of array Y, then X has an earlier rank than Y.*/\\nreturn comparator(left.length,right.length);}\\n\\ncase'tagged':{\\n/* Lexicographic by `[Symbol.toStringTag]` then `.payload`.*/\\nconst labelComp=comparator(passStyleHelpers.getTag(left),passStyleHelpers.getTag(right));\\nif(labelComp!==0){\\nreturn labelComp;}\\n\\nreturn comparator(left.payload,right.payload);}\\n\\ndefault:{\\nthrow index.throwRedacted`Unrecognized passStyle: ${index.quote(leftStyle)}`;}}\\n\\n\\n/* eslint-enable */};\\n\\n\\n/** @type {RankCompare} */\\nconst antiComparator=(x,y)=>comparator(y,x);\\n\\nmemoOfSorted.set(comparator,new WeakSet());\\nmemoOfSorted.set(antiComparator,new WeakSet());\\ncomparatorMirrorImages.set(comparator,antiComparator);\\ncomparatorMirrorImages.set(antiComparator,comparator);\\n\\nreturn harden({comparator,antiComparator});};\\n\\n/**\\n * @param {RankCompare} comparator\\n * @returns {RankCompare=}\\n */\\nconst comparatorMirrorImage=(comparator)=>\\ncomparatorMirrorImages.get(comparator);\\n\\n/**\\n * @param {Passable[]} passables\\n * @param {RankCompare} compare\\n * @returns {boolean}\\n */\\nconst isRankSorted=(passables,compare)=>{\\nconst subMemoOfSorted=memoOfSorted.get(compare);\\nassert(subMemoOfSorted!==undefined);\\nif(subMemoOfSorted.has(passables)){\\nreturn true;}\\n\\nassert(passStyleOf.passStyleOf(passables)==='copyArray');\\nfor(let i=1;i<passables.length;i+=1){\\nif(compare(passables[i-1],passables[i])>=1){\\nreturn false;}}\\n\\n\\nsubMemoOfSorted.add(passables);\\nreturn true;};\\n\\nharden(isRankSorted);\\n\\n/**\\n * @param {Passable[]} sorted\\n * @param {RankCompare} compare\\n */\\nconst assertRankSorted=(sorted,compare)=>\\nisRankSorted(sorted,compare)||\\n/* TODO assert on bug could lead to infinite recursion. Fix.*/\\n/* eslint-disable-next-line no-use-before-define*/\\nindex.throwRedacted`Must be rank sorted: ${sorted} vs ${sortByRank(sorted,compare)}`;\\nharden(assertRankSorted);\\n\\n/**\\n * TODO SECURITY BUG: https://github.com/Agoric/agoric-sdk/issues/4260\\n * sortByRank currently uses `Array.prototype.sort` directly, and\\n * so only works correctly when given a `compare` function that considers\\n * `undefined` strictly bigger (`>`) than everything else. This is\\n * because `Array.prototype.sort` bizarrely moves all `undefined`s to\\n * the end of the array regardless, without consulting the `compare`\\n * function. This is a genuine bug for us NOW because sometimes we sort\\n * in reverse order by passing a reversed rank comparison function.\\n *\\n * @template {Passable} T\\n * @param {Iterable<T>} passables\\n * @param {RankCompare} compare\\n * @returns {T[]}\\n */\\nconst sortByRank=(passables,compare)=>{\\nif(Array.isArray(passables)){\\nharden(passables);\\n/* Calling isRankSorted gives it a chance to get memoized for*/\\n/* this `compare` function even if it was already memoized for a different*/\\n/* `compare` function.*/\\nif(isRankSorted(passables,compare)){\\nreturn passables;}}\\n\\n\\nconst unsorted=[...passables];\\nunsorted.forEach(harden);\\nconst sorted=harden(unsorted.sort(compare));\\nconst subMemoOfSorted=memoOfSorted.get(compare);\\nassert(subMemoOfSorted!==undefined);\\nsubMemoOfSorted.add(sorted);\\nreturn sorted;};\\n\\nharden(sortByRank);\\n\\n/**\\n * See\\n * https://en.wikipedia.org/wiki/Binary_search_algorithm#Procedure_for_finding_the_leftmost_element\\n *\\n * @param {Passable[]} sorted\\n * @param {RankCompare} compare\\n * @param {Passable} key\\n * @param {(\\\"leftMost\\\" | \\\"rightMost\\\")=} bias\\n * @returns {number}\\n */\\nconst rankSearch=(sorted,compare,key,bias='leftMost')=>{\\nassertRankSorted(sorted,compare);\\nlet left=0;\\nlet right=sorted.length;\\nwhile(left<right){\\nconst m=Math.floor((left+right)/2);\\nconst comp=compare(sorted[m],key);\\nif(comp<=-1||comp===0&&bias==='rightMost'){\\nleft=m+1;}else\\n{\\nassert(comp>=1||comp===0&&bias==='leftMost');\\nright=m;}}\\n\\n\\nreturn bias==='leftMost'?left:right-1;};\\n\\n\\n/**\\n * @param {Passable[]} sorted\\n * @param {RankCompare} compare\\n * @param {RankCover} rankCover\\n * @returns {IndexCover}\\n */\\nconst getIndexCover=(sorted,compare,[leftKey,rightKey])=>{\\nassertRankSorted(sorted,compare);\\nconst leftIndex=rankSearch(sorted,compare,leftKey,'leftMost');\\nconst rightIndex=rankSearch(sorted,compare,rightKey,'rightMost');\\nreturn[leftIndex,rightIndex];};\\n\\nharden(getIndexCover);\\n\\n/** @type {RankCover} */\\nconst FullRankCover=harden(['','{']);\\n\\n/**\\n * @param {Passable[]} sorted\\n * @param {IndexCover} indexCover\\n * @returns {Iterable<[number, Passable]>}\\n */\\nconst coveredEntries=(sorted,[leftIndex,rightIndex])=>{\\n/** @type {Iterable<[number, Passable]>} */\\nconst iterable=harden({\\n[Symbol.iterator]:()=>{\\nlet i=leftIndex;\\nreturn harden({\\nnext:()=>{\\nif(i<=rightIndex){\\nconst element=sorted[i];\\ni+=1;\\nreturn harden({value:[i,element],done:false});}else\\n{\\nreturn harden({value:undefined,done:true});}}});}});\\n\\n\\n\\n\\n\\nreturn iterable;};\\n\\nharden(coveredEntries);\\n\\n/**\\n * @template {Passable} T\\n * @param {RankCompare} compare\\n * @param {T} a\\n * @param {T} b\\n * @returns {T}\\n */\\nconst maxRank=(compare,a,b)=>compare(a,b)>=0?a:b;\\n\\n/**\\n * @template {Passable} T\\n * @param {RankCompare} compare\\n * @param {T} a\\n * @param {T} b\\n * @returns {T}\\n */\\nconst minRank=(compare,a,b)=>compare(a,b)<=0?a:b;\\n\\n/**\\n * @param {RankCompare} compare\\n * @param {RankCover[]} covers\\n * @returns {RankCover}\\n */\\nconst unionRankCovers=(compare,covers)=>{\\n/**\\n * @param {RankCover} a\\n * @param {RankCover} b\\n * @returns {RankCover}\\n */\\nconst unionRankCoverPair=([leftA,rightA],[leftB,rightB])=>[\\nminRank(compare,leftA,leftB),\\nmaxRank(compare,rightA,rightB)];\\n\\nreturn covers.reduce(unionRankCoverPair,['{','']);};\\n\\nharden(unionRankCovers);\\n\\n/**\\n * @param {RankCompare} compare\\n * @param {RankCover[]} covers\\n * @returns {RankCover}\\n */\\nconst intersectRankCovers=(compare,covers)=>{\\n/**\\n * @param {RankCover} a\\n * @param {RankCover} b\\n * @returns {RankCover}\\n */\\nconst intersectRankCoverPair=([leftA,rightA],[leftB,rightB])=>[\\nmaxRank(compare,leftA,leftB),\\nminRank(compare,rightA,rightB)];\\n\\nreturn covers.reduce(intersectRankCoverPair,['','{']);};\\n\\n\\nconst{comparator:compareRank,antiComparator:compareAntiRank}=\\nmakeComparatorKit();\\n\\n/**\\n * Create a comparator kit in which remotables are fully ordered\\n * by the order in which they are first seen by *this* comparator kit.\\n * BEWARE: This is observable mutable state, so such a comparator kit\\n * should never be shared among subsystems that should not be able\\n * to communicate.\\n *\\n * Note that this order does not meet the requirements for store\\n * ordering, since it has no memory of deleted keys.\\n *\\n * These full order comparator kit is strictly more precise that the\\n * rank order comparator kits above. As a result, any array which is\\n * sorted by such a full order will pass the isRankSorted test with\\n * a corresponding rank order.\\n *\\n * An array which is sorted by a *fresh* full order comparator, i.e.,\\n * one that has not yet seen any remotables, will of course remain\\n * sorted by according to *that* full order comparator. An array *of\\n * scalars* sorted by a fresh full order will remain sorted even\\n * according to a new fresh full order comparator, since it will see\\n * the remotables in the same order again. Unfortunately, this is\\n * not true of arrays of passables in general.\\n *\\n * @param {boolean=} longLived\\n * @returns {FullComparatorKit}\\n */\\nconst makeFullOrderComparatorKit=(longLived=false)=>{\\nlet numSeen=0;\\n/* When dynamically created with short lifetimes (the default) a WeakMap*/\\n/* would perform poorly, and the leak created by a Map only lasts as long*/\\n/* as the Map.*/\\nconst MapConstructor=longLived?WeakMap:Map;\\nconst seen=new MapConstructor();\\nconst tag=(r)=>{\\nif(seen.has(r)){\\nreturn seen.get(r);}\\n\\nnumSeen+=1;\\nseen.set(r,numSeen);\\nreturn numSeen;};\\n\\nconst compareRemotables=(x,y)=>compareRank(tag(x),tag(y));\\nreturn makeComparatorKit(compareRemotables);};\\n\\nharden(makeFullOrderComparatorKit);exports.FullRankCover=FullRankCover;exports.assertRankSorted=assertRankSorted;exports.comparatorMirrorImage=comparatorMirrorImage;exports.compareAntiRank=compareAntiRank;exports.compareRank=compareRank;exports.coveredEntries=coveredEntries;exports.getIndexCover=getIndexCover;exports.getPassStyleCover=getPassStyleCover;exports.intersectRankCovers=intersectRankCovers;exports.isRankSorted=isRankSorted;exports.makeComparatorKit=makeComparatorKit;exports.makeFullOrderComparatorKit=makeFullOrderComparatorKit;exports.sortByRank=sortByRank;exports.trivialComparator=trivialComparator;exports.unionRankCovers=unionRankCovers;\",\n \"node_modules/@endo/marshal/src/types.js\": \"\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n'use strict';/* @ts-check*/ /** @import {Passable, PassableCap} from '@endo/pass-style' */ /**\\n * @template Slot\\n * @template {PassableCap} [Value=any]\\n * @callback ConvertValToSlot\\n * @param {Value} val\\n * @returns {Slot}\\n */ /**\\n * @template Slot\\n * @template {PassableCap} [Value=any]\\n * @callback ConvertSlotToVal\\n * @param {Slot} slot\\n * @param {string} [iface]\\n * @returns {Value}\\n */ /**\\n * @template T\\n * @typedef {{ '@qclass': T }} EncodingClass\\n */ /**\\n * @typedef {EncodingClass<'NaN'> |\\n * EncodingClass<'undefined'> |\\n * EncodingClass<'Infinity'> |\\n * EncodingClass<'-Infinity'> |\\n * EncodingClass<'bigint'> & { digits: string } |\\n * EncodingClass<'@@asyncIterator'> |\\n * EncodingClass<'symbol'> & { name: string } |\\n * EncodingClass<'error'> & { name: string,\\n * message: string,\\n * errorId?: string,\\n * cause?: Encoding,\\n * errors?: Encoding[],\\n * } |\\n * EncodingClass<'slot'> & { index: number,\\n * iface?: string\\n * } |\\n * EncodingClass<'hilbert'> & { original: Encoding,\\n * rest?: Encoding\\n * } |\\n * EncodingClass<'tagged'> & { tag: string,\\n * payload: Encoding\\n * }\\n * } EncodingUnion\\n *\\n * Note that the '@@asyncIterator' encoding is deprecated. Use 'symbol' instead.\\n *\\n * The 'hilbert' encoding is a reference to the Hilbert Hotel\\n * of https://www.ias.edu/ideas/2016/pires-hilbert-hotel .\\n * It represents data that has its own '@qclass' property by separately storing\\n * the `original` value of that property and\\n * a `rest` record containing all other properties.\\n */ /**\\n * @typedef {boolean | number | null | string | EncodingUnion} EncodingElement\\n */ /**\\n * @template T\\n * @typedef {T | { [x: PropertyKey]: TreeOf<T> }} TreeOf\\n */ /**\\n * @typedef {TreeOf<EncodingElement>} Encoding\\n *\\n * The JSON-representable structure describing the complete shape and\\n * pass-by-copy data of a Passable (i.e., everything except the contents of its\\n * PassableCap leafs, which are marshalled into referenced Slots).\\n *\\n * '@qclass' is a privileged property name in our encoding scheme, so\\n * it is disallowed in encoding records and any data that has such a property\\n * must instead use the 'hilbert' encoding described above.\\n */ /**\\n * @template Slot\\n * @typedef {object} CapData\\n * @property {string} body A JSON.stringify of an Encoding\\n * @property {Slot[]} slots\\n */ /**\\n * @template Slot\\n * @callback ToCapData\\n * @param {Passable} val\\n * @returns {CapData<Slot>}\\n */ /**\\n * @template Slot\\n * @callback FromCapData\\n * @param {CapData<Slot>} data\\n * @returns {any} a Passable\\n */ /**\\n * @template Slot\\n * @typedef {object} Marshal\\n * @property {ToCapData<Slot>} serialize use toCapData\\n * @property {FromCapData<Slot>} unserialize use fromCapData\\n * @property {ToCapData<Slot>} toCapData\\n * @property {FromCapData<Slot>} fromCapData\\n */ /**\\n * @typedef {object} MakeMarshalOptions\\n * @property {'on'|'off'} [errorTagging] controls whether serialized errors\\n * also carry tagging information, made from `marshalName` and numbers\\n * generated (currently by counting) starting at `errorIdNum`. The\\n * `errorTagging` option defaults to `'on'`. Serialized\\n * errors are also logged to `marshalSaveError` only if tagging is `'on'`.\\n * @property {string=} marshalName Used to identify sent errors.\\n * @property {number=} errorIdNum Ascending numbers staring from here\\n * identify the sending of errors relative to this marshal instance.\\n * @property {(err: Error) => void=} marshalSaveError If `errorTagging` is\\n * `'on'`, then errors serialized by this marshal instance are also\\n * logged by calling `marshalSaveError` *after* `annotateError` associated\\n * that error with its errorId. Thus, if `marshalSaveError` in turn logs\\n * to the normal console, which is the default, then the console will\\n * show that note showing the associated errorId.\\n * @property {'capdata'|'smallcaps'} [serializeBodyFormat]\\n * Formatting to use in the \\\"body\\\" property in objects returned from\\n * `serialize`. The body string for each case:\\n * * 'capdata' - a JSON string, from an encoding of passables\\n * into JSON, where some values are represented as objects with a\\n * `'@qclass` property.\\n * * 'smallcaps' - a JSON string prefixed with `'#'`, which is\\n * an unambiguous signal since a valid JSON string cannot begin with\\n * `'#'`.\\n */ /**\\n * @typedef {[string, string]} RankCover\\n * RankCover represents the inclusive lower bound and *inclusive* upper bound\\n * of a string-comparison range that covers all possible encodings for\\n * a set of values.\\n */ /**\\n * @typedef {-1 | 0 | 1} RankComparison\\n * The result of a `RankCompare` function that defines a rank-order, i.e.,\\n * a total preorder in which different elements are always comparable but\\n * can be tied for the same rank. See `RankCompare`.\\n */ /**\\n * @callback RankCompare\\n * Returns `-1`, `0`, or `1` depending on whether the rank of `left`\\n * is respectively before, tied-with, or after the rank of `right`.\\n *\\n * This comparison function is valid as argument to\\n * `Array.prototype.sort`. This is sometimes described as a \\\"total order\\\"\\n * but, depending on your definitions, this is technically incorrect because\\n * it may return `0` to indicate that two distinguishable elements such as\\n * `-0` and `0` are tied (i.e., are in the same equivalence class\\n * for the purposes of this ordering). If each such equivalence class is\\n * a *rank* and ranks are disjoint, then this \\\"rank order\\\" is a\\n * true total order over these ranks. In mathematics this goes by several\\n * other names such as \\\"total preorder\\\".\\n *\\n * This function establishes a total rank order over all passables.\\n * To do so it makes arbitrary choices, such as that all strings\\n * are after all numbers. Thus, this order is not intended to be\\n * used directly as a comparison with useful semantics. However, it must be\\n * closely enough related to such comparisons to aid in implementing\\n * lookups based on those comparisons. For example, in order to get a total\\n * order among ranks, we put `NaN` after all other JavaScript \\\"number\\\" values\\n * (i.e., IEEE 754 floating-point values). But otherwise, we rank JavaScript\\n * numbers by signed magnitude, with `0` and `-0` tied. A semantically useful\\n * ordering would also compare magnitudes, and so agree with the rank ordering\\n * of all values other than `NaN`. An array sorted by rank would enable range\\n * queries by magnitude.\\n * @param {any} left\\n * @param {any} right\\n * @returns {RankComparison}\\n */ /**\\n * @typedef {RankCompare} FullCompare\\n * A `FullCompare` function satisfies all the invariants stated below for\\n * `RankCompare`'s relation with KeyCompare.\\n * In addition, its equality is as precise as the `KeyCompare`\\n * comparison defined below, in that, for all Keys `x` and `y`,\\n * `FullCompare(x, y) === 0` iff `KeyCompare(x, y) === 0`.\\n *\\n * For non-keys a `FullCompare` should be exactly as imprecise as\\n * `RankCompare`. For example, both will treat all errors as in the same\\n * equivalence class. Both will treat all promises as in the same\\n * equivalence class. Both will order taggeds the same way, which is admittedly\\n * weird, as some taggeds will be considered keys and other taggeds will be\\n * considered non-keys.\\n */\",\n \"node_modules/@endo/nat/src/index.js\": \"'use strict';\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nObject.defineProperty(exports,'__esModule',{value:true});/* Copyright (C) 2011 Google Inc.*/ /* Copyright (C) 2018 Agoric*/ /**/ /* Licensed under the Apache License, Version 2.0 (the \\\"License\\\");*/ /* you may not use this file except in compliance with the License.*/ /* You may obtain a copy of the License at*/ /**/ /* http://www.apache.org/licenses/LICENSE-2.0*/ /**/ /* Unless required by applicable law or agreed to in writing, software*/ /* distributed under the License is distributed on an \\\"AS IS\\\" BASIS,*/ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.*/ /* See the License for the specific language governing permissions and*/ /* limitations under the License.*/ /* @ts-check*/ /**\\n * Is `allegedNum` a number in the [contiguous range of exactly and\\n * unambiguously\\n * representable](https://esdiscuss.org/topic/more-numeric-constants-please-especially-epsilon#content-14)\\n * natural numbers (non-negative integers)?\\n *\\n * To qualify `allegedNum` must either be a\\n * non-negative `bigint`, or a non-negative `number` representing an integer\\n * within range of [integers safely representable in\\n * floating point](https://tc39.es/ecma262/#sec-number.issafeinteger).\\n *\\n * @param {unknown} allegedNum\\n * @returns {boolean}\\n */\\nfunction isNat(allegedNum){\\nif(typeof allegedNum==='bigint'){\\nreturn allegedNum>=0;}\\n\\nif(typeof allegedNum!=='number'){\\nreturn false;}\\n\\n\\nreturn Number.isSafeInteger(allegedNum)&&allegedNum>=0;}\\n\\n\\n/**\\n * If `allegedNumber` passes the `isNat` test, then return it as a bigint.\\n * Otherwise throw an appropriate error.\\n *\\n * If `allegedNum` is neither a bigint nor a number, `Nat` throws a `TypeError`.\\n * Otherwise, if it is not a [safely\\n * representable](https://esdiscuss.org/topic/more-numeric-constants-please-especially-epsilon#content-14)\\n * non-negative integer, `Nat` throws a `RangeError`.\\n * Otherwise, it is converted to a bigint if necessary and returned.\\n *\\n * @param {unknown} allegedNum\\n * @returns {bigint}\\n */\\nfunction Nat(allegedNum){\\nif(typeof allegedNum==='bigint'){\\nif(allegedNum<0){\\nthrow RangeError(`${allegedNum} is negative`);}\\n\\nreturn allegedNum;}\\n\\n\\nif(typeof allegedNum==='number'){\\nif(!Number.isSafeInteger(allegedNum)){\\nthrow RangeError(`${allegedNum} is not a safe integer`);}\\n\\nif(allegedNum<0){\\nthrow RangeError(`${allegedNum} is negative`);}\\n\\nreturn BigInt(allegedNum);}\\n\\n\\nthrow TypeError(\\n`${allegedNum} is a ${typeof allegedNum} but must be a bigint or a number`);}exports.Nat=Nat;exports.isNat=isNat;\",\n \"node_modules/@endo/pass-style/endow.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var passStyleOf=require('./src/passStyleOf.js');exports.PassStyleOfEndowmentSymbol=passStyleOf.PassStyleOfEndowmentSymbol;\",\n \"node_modules/@endo/pass-style/index.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var iterHelpers=require('./src/iter-helpers.js');var passStyleHelpers=require('./src/passStyle-helpers.js');var error=require('./src/error.js');var remotable=require('./src/remotable.js');var symbol=require('./src/symbol.js');var string=require('./src/string.js');var passStyleOf=require('./src/passStyleOf.js');var makeTagged=require('./src/makeTagged.js');var makeFar=require('./src/make-far.js');var typeGuards=require('./src/typeGuards.js');var deeplyFulfilled=require('./src/deeplyFulfilled.js');require('./src/types.js');exports.filterIterable=iterHelpers.filterIterable;exports.mapIterable=iterHelpers.mapIterable;exports.PASS_STYLE=passStyleHelpers.PASS_STYLE;exports.assertChecker=passStyleHelpers.assertChecker;exports.getTag=passStyleHelpers.getTag;exports.hasOwnPropertyOf=passStyleHelpers.hasOwnPropertyOf;exports.isObject=passStyleHelpers.isObject;exports.getErrorConstructor=error.getErrorConstructor;exports.isErrorLike=error.isErrorLike;exports.getInterfaceOf=remotable.getInterfaceOf;exports.assertPassableSymbol=symbol.assertPassableSymbol;exports.isPassableSymbol=symbol.isPassableSymbol;exports.nameForPassableSymbol=symbol.nameForPassableSymbol;exports.passableSymbolForName=symbol.passableSymbolForName;exports.assertPassableString=string.assertPassableString;exports.assertWellFormedString=string.assertWellFormedString;exports.isWellFormedString=string.isWellFormedString;exports.assertPassable=passStyleOf.assertPassable;exports.isPassable=passStyleOf.isPassable;exports.passStyleOf=passStyleOf.passStyleOf;exports.toPassableError=passStyleOf.toPassableError;exports.toThrowable=passStyleOf.toThrowable;exports.makeTagged=makeTagged.makeTagged;exports.Far=makeFar.Far;exports.GET_METHOD_NAMES=makeFar.GET_METHOD_NAMES;exports.Remotable=makeFar.Remotable;exports.ToFarFunction=makeFar.ToFarFunction;exports.assertCopyArray=typeGuards.assertCopyArray;exports.assertRecord=typeGuards.assertRecord;exports.assertRemotable=typeGuards.assertRemotable;exports.isCopyArray=typeGuards.isCopyArray;exports.isRecord=typeGuards.isRecord;exports.isRemotable=typeGuards.isRemotable;exports.deeplyFulfilled=deeplyFulfilled.deeplyFulfilled;\",\n \"node_modules/@endo/pass-style/src/copyArray.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var index=require('../../errors/index.js');var passStyleHelpers=require('./passStyle-helpers.js');/*/ <reference types=\\\"ses\\\"/>*/\\n\\n\\n\\n\\nconst{getPrototypeOf}=Object;\\nconst{ownKeys}=Reflect;\\nconst{isArray,prototype:arrayPrototype}=Array;\\n\\n/**\\n * @param {unknown} candidate\\n * @param {IMPORT('./types.js').Checker} [check]\\n * @returns {boolean}\\n */\\nconst canBeValid=(candidate,check=undefined)=>\\nisArray(candidate)||\\n!!check&&check(false,index.redacted`Array expected: ${candidate}`);\\n\\n/**\\n *\\n * @type {IMPORT('./internal-types.js').PassStyleHelper}\\n */\\nconst CopyArrayHelper=harden({\\nstyleName:'copyArray',\\n\\ncanBeValid,\\n\\nassertValid:(candidate,passStyleOfRecur)=>{\\ncanBeValid(candidate,passStyleHelpers.assertChecker);\\ngetPrototypeOf(candidate)===arrayPrototype||\\nassert.fail(index.redacted`Malformed array: ${candidate}`,TypeError);\\n/* Since we're already ensured candidate is an array, it should not be*/\\n/* possible for the following get to fail.*/\\nconst len=/** @type {number} */\\npassStyleHelpers.getOwnDataDescriptor(candidate,'length',false,passStyleHelpers.assertChecker).value;\\n\\n/* Validate that each index property is own/data/enumerable*/\\n/* and its associated value is recursively passable.*/\\nfor(let i=0;i<len;i+=1){\\npassStyleOfRecur(\\npassStyleHelpers.getOwnDataDescriptor(candidate,i,true,passStyleHelpers.assertChecker).value);}\\n\\n\\n/* Expect one key per index plus one for 'length'.*/\\nownKeys(candidate).length===len+1||\\nassert.fail(index.redacted`Arrays must not have non-indexes: ${candidate}`,TypeError);}});exports.CopyArrayHelper=CopyArrayHelper;\",\n \"node_modules/@endo/pass-style/src/copyRecord.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var passStyleHelpers=require('./passStyle-helpers.js');/*/ <reference types=\\\"ses\\\"/>*/\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nconst{ownKeys}=Reflect;\\nconst{getPrototypeOf,prototype:objectPrototype}=Object;\\n\\n/**\\n * @param {unknown} candidate\\n * @param {Checker} [check]\\n */\\nconst checkObjectPrototype=(candidate,check=undefined)=>{\\nreturn(\\ngetPrototypeOf(candidate)===objectPrototype||\\n!!check&&\\npassStyleHelpers.CX(check)`Records must inherit from Object.prototype: ${candidate}`);};\\n\\n\\n\\n/**\\n * @param {unknown} candidate\\n * @param {PropertyKey} key\\n * @param {unknown} value\\n * @param {Checker} [check]\\n */\\nconst checkPropertyCanBeValid=(candidate,key,value,check=undefined)=>{\\nreturn(\\n(typeof key==='string'||\\n!!check&&\\npassStyleHelpers.CX(\\ncheck)\\n`Records can only have string-named properties: ${candidate}`)&&(\\n!passStyleHelpers.canBeMethod(value)||\\n!!check&&\\n/* TODO: Update message now that there is no such thing as \\\"implicit Remotable\\\".*/\\npassStyleHelpers.CX(\\ncheck)\\n`Records cannot contain non-far functions because they may be methods of an implicit Remotable: ${candidate}`));};\\n\\n\\n\\n/**\\n *\\n * @type {IMPORT('./internal-types.js').PassStyleHelper}\\n */\\nconst CopyRecordHelper=harden({\\nstyleName:'copyRecord',\\n\\ncanBeValid:(candidate,check=undefined)=>{\\nreturn(\\ncheckObjectPrototype(candidate,check)&&\\n/* Reject any candidate with a symbol-keyed property or method-like property*/\\n/* (such input is potentially a Remotable).*/\\nownKeys(candidate).every((key)=>\\ncheckPropertyCanBeValid(candidate,key,candidate[key],check)));},\\n\\n\\n\\n\\nassertValid:(candidate,passStyleOfRecur)=>{\\ncheckObjectPrototype(candidate,passStyleHelpers.assertChecker);\\n\\n/* Validate that each own property is appropriate, data/enumerable,*/\\n/* and has a recursively passable associated value.*/\\nfor(const name of ownKeys(candidate)){\\nconst{value}=passStyleHelpers.getOwnDataDescriptor(\\ncandidate,\\nname,\\ntrue,\\npassStyleHelpers.assertChecker);\\n\\ncheckPropertyCanBeValid(candidate,name,value,passStyleHelpers.assertChecker);\\npassStyleOfRecur(value);}}});exports.CopyRecordHelper=CopyRecordHelper;\",\n \"node_modules/@endo/pass-style/src/deeplyFulfilled.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var index=require('../../errors/index.js');var noShim=require('../../eventual-send/src/no-shim.js');require('../../promise-kit/index.js');var passStyleHelpers=require('./passStyle-helpers.js');var passStyleOf=require('./passStyleOf.js');var makeTagged=require('./makeTagged.js');var\\n\\n\\n\\n\\n\\n\\nisPromise=require('../../promise-kit/src/is-promise.js');/**\\n * @import {Passable, Primitive, CopyRecord, CopyArray, CopyTagged, RemotableObject} from '@endo/pass-style'\\n */\\n\\nconst{ownKeys}=Reflect;\\nconst{fromEntries}=Object;\\n\\n/**\\n * Currently copied from @agoric/internal utils.js.\\n * TODO Should migrate here and then, if needed, reexported there.\\n *\\n * @template T\\n * @typedef {{ [KeyType in keyof T]: T[KeyType] } & {}} Simplify flatten the\\n * type output to improve type hints shown in editors\\n * https://github.com/sindresorhus/type-fest/blob/main/source/simplify.d.ts\\n */\\n\\n/**\\n * Currently copied from @agoric/internal utils.js.\\n * TODO Should migrate here and then, if needed, reexported there.\\n *\\n * @typedef {(...args: any[]) => any} Callable\\n */\\n\\n/**\\n * Currently copied from @agoric/internal utils.js.\\n * TODO Should migrate here and then, if needed, reexported there.\\n *\\n * @template {{}} T\\n * @typedef {{\\n * [K in keyof T]: T[K] extends Callable ? T[K] : DeeplyAwaited<T[K]>;\\n * }} DeeplyAwaitedObject\\n */\\n\\n/**\\n * Currently copied from @agoric/internal utils.js.\\n * TODO Should migrate here and then, if needed, reexported there.\\n *\\n * @template T\\n * @typedef {T extends PromiseLike<any>\\n * ? Awaited<T>\\n * : T extends {}\\n * ? Simplify<DeeplyAwaitedObject<T>>\\n * : Awaited<T>} DeeplyAwaited\\n */\\n\\n/**\\n * Given a Passable `val` whose pass-by-copy structure may contain leaf\\n * promises, return a promise for a replacement Passable,\\n * where that replacement is *deeply fulfilled*, i.e., its\\n * pass-by-copy structure does not contain any promises.\\n *\\n * This is a deep form of `Promise.all` specialized for Passables. For each\\n * encountered promise, replace it with the deeply fulfilled form of\\n * its fulfillment.\\n * If any of the promises reject, then the promise for the replacement\\n * rejects. If any of the promises never settle, then the promise for\\n * the replacement never settles.\\n *\\n * If the replacement would not be Passable, i.e., if `val` is not\\n * Passable, or if any of the transitive promises fulfill to something\\n * that is not Passable, then the returned promise rejects.\\n *\\n * If `val` or its parts are non-key Passables only *because* they contain\\n * promises, the deeply fulfilled forms of val or its parts may be keys. This\\n * is for the higher \\\"@endo/patterns\\\" level of abstraction to determine,\\n * because it defines the `Key` notion in question.\\n *\\n * @template {Passable} [T=Passable]\\n * @param {T} val\\n * @returns {Promise<DeeplyAwaited<T>>}\\n */\\nconst deeplyFulfilled=async(val)=>{\\n/* TODO Figure out why we need these at-expect-error directives below*/\\n/* and fix if possible.*/\\n/* https://github.com/endojs/endo/issues/1257 may be relevant.*/\\n\\nif(!passStyleHelpers.isObject(val)){\\nreturn(/** @type {DeeplyAwaited<T>} */val);}\\n\\nif(isPromise.isPromise(val)){\\nreturn noShim.E.when(val,(nonp)=>deeplyFulfilled(nonp));}\\n\\nconst passStyle=passStyleOf.passStyleOf(val);\\nswitch(passStyle){\\ncase'copyRecord':{\\nconst rec=/** @type {CopyRecord} */val;\\nconst names=/** @type {string[]} */ownKeys(rec);\\nconst valPs=names.map((name)=>deeplyFulfilled(rec[name]));\\n/* @ts-expect-error not assignable to type 'DeeplyAwaited<T>'*/\\nreturn noShim.E.when(Promise.all(valPs),(vals)=>\\nharden(fromEntries(vals.map((c,i)=>[names[i],c]))));}\\n\\n\\ncase'copyArray':{\\nconst arr=/** @type {CopyArray} */val;\\nconst valPs=arr.map((p)=>deeplyFulfilled(p));\\n/* @ts-expect-error not assignable to type 'DeeplyAwaited<T>'*/\\nreturn noShim.E.when(Promise.all(valPs),(vals)=>harden(vals));}\\n\\ncase'tagged':{\\nconst tgd=/** @type {CopyTagged} */val;\\nconst tag=passStyleHelpers.getTag(tgd);\\n/* @ts-expect-error not assignable to type 'DeeplyAwaited<T>'*/\\nreturn noShim.E.when(deeplyFulfilled(tgd.payload),(payload)=>\\nmakeTagged.makeTagged(tag,payload));}\\n\\n\\ncase'remotable':{\\nconst rem=/** @type {RemotableObject} */val;\\n/* @ts-expect-error not assignable to type 'DeeplyAwaited<T>'*/\\nreturn rem;}\\n\\ncase'error':{\\nconst err=/** @type {Error} */val;\\n/* @ts-expect-error not assignable to type 'DeeplyAwaited<T>'*/\\nreturn err;}\\n\\ncase'promise':{\\nconst prom=/** @type {Promise} */ /** @type {unknown} */val;\\nreturn noShim.E.when(prom,(nonp)=>deeplyFulfilled(nonp));}\\n\\ndefault:{\\nthrow assert.fail(index.redacted`Unexpected passStyle ${index.quote(passStyle)}`,TypeError);}}};\\n\\n\\n\\nharden(deeplyFulfilled);exports.deeplyFulfilled=deeplyFulfilled;\",\n \"node_modules/@endo/pass-style/src/error.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var index=require('../../errors/index.js');var\\n\\n\\n\\n\\n\\npassStyleHelpers=require('./passStyle-helpers.js');/*/ <reference types=\\\"ses\\\"/>*/ /** @import {PassStyleHelper} from './internal-types.js' */ /** @import {Checker, PassStyle, PassStyleOf} from './types.js' */\\n\\nconst{getPrototypeOf,getOwnPropertyDescriptors,hasOwn,entries}=Object;\\n\\n/* TODO: Maintenance hazard: Coordinate with the list of errors in the SES*/\\n/* whilelist.*/\\nconst errorConstructors=new Map(\\n/* Cast because otherwise TS is confused by AggregateError*/\\n/* See https://github.com/endojs/endo/pull/2042#discussion_r1484933028*/\\n/** @type {Array<[string, IMPORT('ses').GenericErrorConstructor]>} */\\n[\\n['Error',Error],\\n['EvalError',EvalError],\\n['RangeError',RangeError],\\n['ReferenceError',ReferenceError],\\n['SyntaxError',SyntaxError],\\n['TypeError',TypeError],\\n['URIError',URIError]\\n\\n/* https://github.com/endojs/endo/issues/550*/\\n/* To accommodate platforms prior to AggregateError, we comment out the*/\\n/* following line and instead conditionally add it to the map below.*/\\n/* ['AggregateError', AggregateError],*/]);\\n\\n\\n\\nif(typeof AggregateError!=='undefined'){\\n/* Conditional, to accommodate platforms prior to AggregateError*/\\nerrorConstructors.set('AggregateError',AggregateError);}\\n\\n\\n/**\\n * Because the error constructor returned by this function might be\\n * `AggregateError`, which has different construction parameters\\n * from the other error constructors, do not use it directly to try\\n * to make an error instance. Rather, use `makeError` which encapsulates\\n * this non-uniformity.\\n *\\n * @param {string} name\\n * @returns {IMPORT('ses').GenericErrorConstructor | undefined}\\n */\\nconst getErrorConstructor=(name)=>errorConstructors.get(name);\\nharden(getErrorConstructor);\\n\\n/**\\n * @param {unknown} candidate\\n * @param {Checker} [check]\\n * @returns {boolean}\\n */\\nconst checkErrorLike=(candidate,check=undefined)=>{\\n/* TODO: Need a better test than instanceof*/\\nreturn(\\ncandidate instanceof Error||\\n!!check&&passStyleHelpers.CX(check)`Error expected: ${candidate}`);};\\n\\n\\nharden(checkErrorLike);\\n/*/ <reference types=\\\"ses\\\"/>*/\\n\\n/**\\n * Validating error objects are passable raises a tension between security\\n * vs preserving diagnostic information. For errors, we need to remember\\n * the error itself exists to help us diagnose a bug that's likely more\\n * pressing than a validity bug in the error itself. Thus, whenever it is safe\\n * to do so, we prefer to let the error-like test succeed and to couch these\\n * complaints as notes on the error.\\n *\\n * To resolve this, such a malformed error object will still pass\\n * `isErrorLike` so marshal can use this for top level error to report from,\\n * even if it would not actually validate.\\n * Instead, the diagnostics that `assertError` would have reported are\\n * attached as notes to the malformed error. Thus, a malformed\\n * error is passable by itself, but not as part of a passable structure.\\n *\\n * @param {unknown} candidate\\n * @returns {boolean}\\n */\\nconst isErrorLike=(candidate)=>checkErrorLike(candidate);\\nharden(isErrorLike);\\n\\n/**\\n * @param {string} propName\\n * @param {PropertyDescriptor} desc\\n * @param {(val: any) => PassStyle} passStyleOfRecur\\n * @param {Checker} [check]\\n * @returns {boolean}\\n */\\nconst checkRecursivelyPassableErrorPropertyDesc=(\\npropName,\\ndesc,\\npassStyleOfRecur,\\ncheck=undefined)=>\\n{\\nif(desc.enumerable){\\nreturn(\\n!!check&&\\npassStyleHelpers.CX(check)`Passable Error ${index.quote(\\npropName)\\n} own property must not be enumerable: ${desc}`);}\\n\\n\\nif(!hasOwn(desc,'value')){\\nreturn(\\n!!check&&\\npassStyleHelpers.CX(check)`Passable Error ${index.quote(\\npropName)\\n} own property must be a data property: ${desc}`);}\\n\\n\\nconst{value}=desc;\\nswitch(propName){\\ncase'message':\\ncase'stack':{\\nreturn(\\ntypeof value==='string'||\\n!!check&&\\npassStyleHelpers.CX(check)`Passable Error ${index.quote(\\npropName)\\n} own property must be a string: ${value}`);}\\n\\n\\ncase'cause':{\\n/* eslint-disable-next-line no-use-before-define*/\\nreturn checkRecursivelyPassableError(value,passStyleOfRecur,check);}\\n\\ncase'errors':{\\nif(!Array.isArray(value)||passStyleOfRecur(value)!=='copyArray'){\\nreturn(\\n!!check&&\\npassStyleHelpers.CX(check)`Passable Error ${index.quote(\\npropName)\\n} own property must be a copyArray: ${value}`);}\\n\\n\\nreturn value.every((err)=>\\n/* eslint-disable-next-line no-use-before-define*/\\ncheckRecursivelyPassableError(err,passStyleOfRecur,check));}\\n\\n\\ndefault:{\\nbreak;}}\\n\\n\\nreturn(\\n!!check&&\\npassStyleHelpers.CX(check)`Passable Error has extra unpassed property ${index.quote(propName)}`);};\\n\\n\\nharden(checkRecursivelyPassableErrorPropertyDesc);\\n\\n/**\\n * @param {unknown} candidate\\n * @param {(val: any) => PassStyle} passStyleOfRecur\\n * @param {Checker} [check]\\n * @returns {boolean}\\n */\\nconst checkRecursivelyPassableError=(\\ncandidate,\\npassStyleOfRecur,\\ncheck=undefined)=>\\n{\\nif(!checkErrorLike(candidate,check)){\\nreturn false;}\\n\\nconst proto=getPrototypeOf(candidate);\\nconst{name}=proto;\\nconst errConstructor=getErrorConstructor(name);\\nif(errConstructor===undefined||errConstructor.prototype!==proto){\\nreturn(\\n!!check&&\\npassStyleHelpers.CX(\\ncheck)\\n`Passable Error must inherit from an error class .prototype: ${candidate}`);}\\n\\n\\nconst descs=getOwnPropertyDescriptors(candidate);\\nif(!('message'in descs)){\\nreturn(\\n!!check&&\\npassStyleHelpers.CX(\\ncheck)\\n`Passable Error must have an own \\\"message\\\" string property: ${candidate}`);}\\n\\n\\n\\nreturn entries(descs).every(([propName,desc])=>\\ncheckRecursivelyPassableErrorPropertyDesc(\\npropName,\\ndesc,\\npassStyleOfRecur,\\ncheck));};\\n\\n\\n\\nharden(checkRecursivelyPassableError);\\n\\n/**\\n * @type {PassStyleHelper}\\n */\\nconst ErrorHelper=harden({\\nstyleName:'error',\\n\\ncanBeValid:checkErrorLike,\\n\\nassertValid:(candidate,passStyleOfRecur)=>\\ncheckRecursivelyPassableError(candidate,passStyleOfRecur,passStyleHelpers.assertChecker)});exports.ErrorHelper=ErrorHelper;exports.checkRecursivelyPassableError=checkRecursivelyPassableError;exports.checkRecursivelyPassableErrorPropertyDesc=checkRecursivelyPassableErrorPropertyDesc;exports.getErrorConstructor=getErrorConstructor;exports.isErrorLike=isErrorLike;\",\n \"node_modules/@endo/pass-style/src/iter-helpers.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var\\n\\nmakeFar=require('./make-far.js');/**\\n * The result iterator has as many elements as the `baseIterator` and\\n * have the same termination -- the same completion value or failure\\n * reason. But the non-final values are the corresponding non-final\\n * values from `baseIterator` as transformed by `func`.\\n *\\n * @template T,U\\n * @param {Iterable<T>} baseIterable\\n * @param {(value: T) => U} func\\n * @returns {Iterable<U>}\\n */\\nconst mapIterable=(baseIterable,func)=>\\n/** @type {Iterable<U>} */\\nmakeFar.Far('mapped iterable',{\\n[Symbol.iterator]:()=>{\\nconst baseIterator=baseIterable[Symbol.iterator]();\\nreturn makeFar.Far('mapped iterator',{\\nnext:()=>{\\nconst{value:baseValue,done}=baseIterator.next();\\nconst value=done?baseValue:func(baseValue);\\nreturn harden({value,done});}});}});\\n\\n\\n\\n\\nharden(mapIterable);\\n\\n/**\\n * The result iterator has a subset of the non-final values from the\\n * `baseIterator` --- those for which `pred(value)` was truthy. The result\\n * has the same termination as the `baseIterator` -- the same completion value\\n * or failure reason.\\n *\\n * @template T\\n * @param {Iterable<T>} baseIterable\\n * @param {(value: T) => boolean} pred\\n * @returns {Iterable<T>}\\n */\\nconst filterIterable=(baseIterable,pred)=>\\n/** @type {Iterable<U>} */\\nmakeFar.Far('filtered iterable',{\\n[Symbol.iterator]:()=>{\\nconst baseIterator=baseIterable[Symbol.iterator]();\\nreturn makeFar.Far('filtered iterator',{\\nnext:()=>{\\nfor(;;){\\nconst result=baseIterator.next();\\nconst{value,done}=result;\\nif(done||pred(value)){\\nreturn result;}}}});}});\\n\\n\\n\\n\\n\\n\\nharden(filterIterable);exports.filterIterable=filterIterable;exports.mapIterable=mapIterable;\",\n \"node_modules/@endo/pass-style/src/make-far.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../eventual-send/utils.js');var index=require('../../errors/index.js');var passStyleHelpers=require('./passStyle-helpers.js');var remotable=require('./remotable.js');var\\n\\n\\n\\n\\n\\n\\n\\nlocal=require('../../eventual-send/src/local.js');/*/ <reference types=\\\"ses\\\"/>*/ /** @import {RemotableBrand} from '@endo/eventual-send' */ /** @import {InterfaceSpec, RemotableObject} from './types.js' */\\n\\nconst{prototype:functionPrototype}=Function;\\nconst{\\ngetPrototypeOf,\\nsetPrototypeOf,\\ncreate,\\nisFrozen,\\nprototype:objectPrototype}=\\nObject;\\n\\n/**\\n * Now that the remotableProto does not provide its own `toString` method,\\n * ensure it always inherits from something. The original prototype of\\n * `remotable` if there was one, or `Object.prototype` otherwise.\\n *\\n * @param {object} remotable\\n * @param {InterfaceSpec} iface\\n * @returns {object}\\n */\\nconst makeRemotableProto=(remotable,iface)=>{\\nlet oldProto=getPrototypeOf(remotable);\\nif(typeof remotable==='object'){\\nif(oldProto===null){\\noldProto=objectPrototype;}\\n\\noldProto===objectPrototype||\\nindex.throwRedacted`For now, remotables cannot inherit from anything unusual, in ${remotable}`;}else\\nif(typeof remotable==='function'){\\noldProto!==null||\\nindex.throwRedacted`Original function must not inherit from null: ${remotable}`;\\noldProto===functionPrototype||\\ngetPrototypeOf(oldProto)===functionPrototype||\\nindex.throwRedacted`Far functions must originally inherit from Function.prototype, in ${remotable}`;}else\\n{\\nindex.throwRedacted`unrecognized typeof ${remotable}`;}\\n\\nreturn harden(\\ncreate(oldProto,{\\n[passStyleHelpers.PASS_STYLE]:{value:'remotable'},\\n[Symbol.toStringTag]:{value:iface}}));};\\n\\n\\n\\n\\nconst assertCanBeRemotable=(candidate)=>\\nremotable.RemotableHelper.canBeValid(candidate,passStyleHelpers.assertChecker);\\n\\n/**\\n * Create and register a Remotable. After this, getInterfaceOf(remotable)\\n * returns iface.\\n *\\n * // https://github.com/Agoric/agoric-sdk/issues/804\\n *\\n * @template {{}} T\\n * @template {InterfaceSpec} I\\n * @param {I} [iface] The interface specification for\\n * the remotable. For now, a string iface must be \\\"Remotable\\\" or begin with\\n * \\\"Alleged: \\\" or \\\"DebugName: \\\", to serve as the alleged name. More\\n * general ifaces are not yet implemented. This is temporary. We include the\\n * \\\"Alleged\\\" or \\\"DebugName\\\" as a reminder that we do not yet have SwingSet\\n * or Comms Vat\\n * support for ensuring this is according to the vat hosting the object.\\n * Currently, Alice can tell Bob about Carol, where VatA (on Alice's behalf)\\n * misrepresents Carol's `iface`. VatB and therefore Bob will then see\\n * Carol's `iface` as misrepresented by VatA.\\n * @param {undefined} [props] Currently may only be undefined.\\n * That plan is that own-properties are copied to the remotable\\n * @param {T} [remotable] The object used as the remotable\\n * @returns {T & RemotableObject<I> & RemotableBrand<{}, T>}} remotable, modified for debuggability\\n */\\nconst Remotable=(\\n/* @ts-expect-error I could have different subtype than string*/\\niface='Remotable',\\nprops=undefined,\\nremotable$1=/** @type {T} */{})=>\\n{\\nremotable.assertIface(iface);\\nassert(iface);\\n/* TODO: When iface is richer than just string, we need to get the allegedName*/\\n/* in a different way.*/\\nprops===undefined||index.throwRedacted`Remotable props not yet implemented ${props}`;\\n\\n/* Fail fast: check that the unmodified object is able to become a Remotable.*/\\nassertCanBeRemotable(remotable$1);\\n\\n/* Ensure that the remotable isn't already marked.*/\\n!(passStyleHelpers.PASS_STYLE in remotable$1)||\\nindex.throwRedacted`Remotable ${remotable$1} is already marked as a ${index.quote(\\nremotable$1[passStyleHelpers.PASS_STYLE])\\n}`;\\n/* `isFrozen` always returns true with a fake `harden`, but we want that case*/\\n/* to succeed anyway. Faking `harden` is only correctness preserving*/\\n/* if the code in question contains no bugs that the real `harden` would*/\\n/* have caught.*/\\n/* @ts-ignore `isFake` purposely not in the type*/\\nharden.isFake||\\n/* Ensure that the remotable isn't already frozen.*/\\n!isFrozen(remotable$1)||\\nindex.throwRedacted`Remotable ${remotable$1} is already frozen`;\\nconst remotableProto=makeRemotableProto(remotable$1,iface);\\n\\n/* Take a static copy of the enumerable own properties as data properties.*/\\n/* const propDescs = getOwnPropertyDescriptors({ ...props });*/\\nconst mutateHardenAndCheck=(target)=>{\\n/* defineProperties(target, propDescs);*/\\nsetPrototypeOf(target,remotableProto);\\nharden(target);\\nassertCanBeRemotable(target);};\\n\\n\\n/* Fail fast: check a fresh remotable to see if our rules fit.*/\\nmutateHardenAndCheck({});\\n\\n/* Actually finish the new remotable.*/\\nmutateHardenAndCheck(remotable$1);\\n\\n/* COMMITTED!*/\\n/* We're committed, so keep the interface for future reference.*/\\nassert(iface!==undefined);/* To make TypeScript happy*/\\nreturn(/** @type {any} */remotable$1);};\\n\\nharden(Remotable);\\n\\n/**\\n * The name of the automatically added default meta-method for obtaining a\\n * list of all methods of an object declared with `Far`, or an object that\\n * inherits from an object declared with `Far`.\\n *\\n * Modeled on `GET_INTERFACE_GUARD` from `@endo/exo`.\\n *\\n * TODO Name to be bikeshed. Perhaps even whether it is a\\n * string or symbol to be bikeshed. See\\n * https://github.com/endojs/endo/pull/1809#discussion_r1388052454\\n *\\n * HAZARD: Beware that an exo's interface can change across an upgrade,\\n * so remotes that cache it can become stale.\\n */\\nconst GET_METHOD_NAMES='__getMethodNames__';\\n\\n/**\\n * Note that `getMethodNamesMethod` is a thisful method! It must be so that\\n * it works as expected with far-object inheritance.\\n *\\n * @returns {(string|symbol)[]}\\n */\\nconst getMethodNamesMethod=harden({\\n[GET_METHOD_NAMES](){\\nreturn local.getMethodNames(this);}})[\\n\\nGET_METHOD_NAMES];\\n\\nconst getMethodNamesDescriptor=harden({\\nvalue:getMethodNamesMethod,\\nenumerable:false,\\nconfigurable:false,\\nwritable:false});\\n\\n\\n/**\\n * Mark an object to be exposed for remote interaction\\n * and give it a suggestive interface name for debugging.\\n *\\n * All properties of the object have to be methods, not data.\\n *\\n * The object must not be hardened before it is marked.\\n * It will be hardened after marking.\\n *\\n * For far objects (as opposed to far functions), also adds\\n * `__getMethodNames__` method that returns an array of all the method names,\\n * if there is not yet any method named `__getMethodNames__`.\\n *\\n * @example\\n * Far('Employee', { getManager })\\n * @template {{}} T\\n * @param {string} farName This name will be prepended with `Alleged: `\\n * for now to form the `Remotable` `iface` argument.\\n * @param {T} [remotable] The object to be marked as remotable\\n */\\nconst Far=(farName,remotable=undefined)=>{\\nconst r=remotable===undefined?/** @type {T} */{}:remotable;\\nif(typeof r==='object'&&!(GET_METHOD_NAMES in r)){\\n/* This test excludes far functions, since we currently consider them*/\\n/* to only have a call-behavior, with no callable methods.*/\\n/* Beware: Mutates the input argument! But `Remotable`*/\\n/* * requires the object to be mutable*/\\n/* * does further mutations,*/\\n/* * hardens the mutated object before returning it.*/\\n/* so this mutation is not unprecedented. But it is surprising!*/\\nObject.defineProperty(r,GET_METHOD_NAMES,getMethodNamesDescriptor);}\\n\\nreturn Remotable(`Alleged: ${farName}`,undefined,r);};\\n\\nharden(Far);\\n\\n/**\\n * Coerce `func` to a far function that preserves its call behavior.\\n * If it is already a far function, return it. Otherwise make and return a\\n * new far function that wraps `func` and forwards calls to it. This\\n * works even if `func` is already frozen. `ToFarFunction` is to be used\\n * when the function comes from elsewhere under less control. For functions\\n * you author in place, better to use `Far` on their function literal directly.\\n *\\n * @template {(...args: any[]) => any} F\\n * @param {string} farName to be used only if `func` is not already a\\n * far function.\\n * @param {F} func\\n * @returns {F & RemotableObject & RemotableBrand<{}, F>}\\n */\\nconst ToFarFunction=(farName,func)=>{\\nif(remotable.getInterfaceOf(func)!==undefined){\\n/* @ts-expect-error checked cast*/\\nreturn func;}\\n\\n/* @ts-expect-error could be different subtype*/\\nreturn Far(farName,(...args)=>func(...args));};\\n\\nharden(ToFarFunction);exports.Far=Far;exports.GET_METHOD_NAMES=GET_METHOD_NAMES;exports.Remotable=Remotable;exports.ToFarFunction=ToFarFunction;\",\n \"node_modules/@endo/pass-style/src/makeTagged.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var index=require('../../errors/index.js');var passStyleHelpers=require('./passStyle-helpers.js');var passStyleOf=require('./passStyleOf.js');/*/ <reference types=\\\"ses\\\"/>*/\\n\\n\\n\\n\\n\\nconst{create,prototype:objectPrototype}=Object;\\n\\n/**\\n * @template {string} T\\n * @template {IMPORT('./types.js').Passable} P\\n * @param {T} tag\\n * @param {P} payload\\n * @returns {IMPORT('./types.js').CopyTagged<T,P>}\\n */\\nconst makeTagged=(tag,payload)=>{\\ntypeof tag==='string'||\\nindex.throwRedacted`The tag of a tagged record must be a string: ${tag}`;\\npassStyleOf.assertPassable(harden(payload));\\nreturn harden(\\ncreate(objectPrototype,{\\n[passStyleHelpers.PASS_STYLE]:{value:'tagged'},\\n[Symbol.toStringTag]:{value:tag},\\npayload:{value:payload,enumerable:true}}));};\\n\\n\\n\\nharden(makeTagged);exports.makeTagged=makeTagged;\",\n \"node_modules/@endo/pass-style/src/passStyle-helpers.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var index=require('../../errors/index.js');/*/ <reference types=\\\"ses\\\"/>*/\\n\\n\\n\\n\\n\\n\\nconst{isArray}=Array;\\nconst{prototype:functionPrototype}=Function;\\nconst{\\ngetOwnPropertyDescriptor,\\ngetPrototypeOf,\\nhasOwnProperty:objectHasOwnProperty,\\nisFrozen,\\nprototype:objectPrototype}=\\nObject;\\nconst{apply}=Reflect;\\nconst{toStringTag:toStringTagSymbol}=Symbol;\\n\\nconst typedArrayPrototype=getPrototypeOf(Uint8Array.prototype);\\nconst typedArrayToStringTagDesc=getOwnPropertyDescriptor(\\ntypedArrayPrototype,\\ntoStringTagSymbol);\\n\\nassert(typedArrayToStringTagDesc);\\nconst getTypedArrayToStringTag=typedArrayToStringTagDesc.get;\\nassert(typeof getTypedArrayToStringTag==='function');\\n\\nconst hasOwnPropertyOf=(obj,prop)=>\\napply(objectHasOwnProperty,obj,[prop]);\\nharden(hasOwnPropertyOf);\\n\\n/* TODO try typing this; `=> val is {} too narrow, implies no properties*/\\nconst isObject=(val)=>Object(val)===val;\\nharden(isObject);\\n\\n/**\\n * Duplicates packages/ses/src/make-hardener.js to avoid a dependency.\\n *\\n * @param {unknown} object\\n */\\nconst isTypedArray=(object)=>{\\n/* The object must pass a brand check or toStringTag will return undefined.*/\\nconst tag=apply(getTypedArrayToStringTag,object,[]);\\nreturn tag!==undefined;};\\n\\nharden(isTypedArray);\\n\\nconst PASS_STYLE=Symbol.for('passStyle');\\n\\n/**\\n * For a function to be a valid method, it must not be passable.\\n * Otherwise, we risk confusing pass-by-copy data carrying\\n * far functions with attempts at far objects with methods.\\n *\\n * TODO HAZARD Because we check this on the way to hardening a remotable,\\n * we cannot yet check that `func` is hardened. However, without\\n * doing so, it's inheritance might change after the `PASS_STYLE`\\n * check below.\\n *\\n * @param {any} func\\n * @returns {boolean}\\n */\\nconst canBeMethod=(func)=>\\ntypeof func==='function'&&!(PASS_STYLE in func);\\nharden(canBeMethod);\\n\\n/**\\n * Below we have a series of predicate functions and their (curried) assertion\\n * functions. The semantics of the assertion function is just to assert that\\n * the corresponding predicate function would have returned true. But it\\n * reproduces the internal tests so failures can give a better error message.\\n *\\n * @type {Checker}\\n */\\nconst assertChecker=(cond,details)=>{\\nassert(cond,details);\\nreturn true;};\\n\\nharden(assertChecker);\\n\\n/**\\n * Returns a template literal tag function to fail the provided Checker with details.\\n * The name must be short for ergonomic inline use as in:\\n * ```\\n * return checkCondition(...) || (!!check && CX(check)`...`);\\n * ```\\n *\\n * @param {Checker} check\\n */\\nconst CX=(check)=>{\\nconst reject=(T,...subs)=>check(false,index.redacted(T,...subs));\\nreturn reject;};\\n\\nharden(CX);\\n\\n/**\\n * Verifies the presence and enumerability of an own data property\\n * and returns its descriptor.\\n *\\n * @param {object} candidate\\n * @param {string|number|symbol} propName\\n * @param {boolean} shouldBeEnumerable\\n * @param {Checker} [check]\\n * @returns {PropertyDescriptor}\\n */\\nconst getOwnDataDescriptor=(\\ncandidate,\\npropName,\\nshouldBeEnumerable,\\ncheck)=>\\n{\\nconst desc=/** @type {PropertyDescriptor} */\\ngetOwnPropertyDescriptor(candidate,propName);\\n\\nreturn(desc!==undefined||\\n!!check&&CX(check)`${index.quote(propName)} property expected: ${candidate}`)&&(\\nhasOwnPropertyOf(desc,'value')||\\n!!check&&\\nCX(\\ncheck)\\n`${index.quote(propName)} must not be an accessor property: ${candidate}`)&&(\\nshouldBeEnumerable?\\ndesc.enumerable||\\n!!check&&\\nCX(\\ncheck)\\n`${index.quote(propName)} must be an enumerable property: ${candidate}`:\\n!desc.enumerable||\\n!!check&&\\nCX(\\ncheck)\\n`${index.quote(propName)} must not be an enumerable property: ${candidate}`)?\\ndesc:\\n/** @type {PropertyDescriptor} */ /** @type {unknown} */undefined;};\\n\\nharden(getOwnDataDescriptor);\\n\\n/**\\n * @template {IMPORT('./types.js').InterfaceSpec} T\\n * @param {IMPORT('./types.js').PassStyled<any, T>} tagRecord\\n * @returns {T}\\n */\\nconst getTag=(tagRecord)=>tagRecord[Symbol.toStringTag];\\nharden(getTag);\\n\\nconst checkPassStyle=(obj,passStyle,expectedPassStyle,check)=>{\\nreturn(\\npassStyle===expectedPassStyle||\\n!!check&&\\nCX(check)`Expected ${index.quote(expectedPassStyle)}, not ${index.quote(passStyle)}: ${obj}`);};\\n\\n\\nharden(checkPassStyle);\\n\\nconst makeCheckTagRecord=(checkProto)=>{\\n/**\\n * @param {IMPORT('./types.js').PassStyled<any, any>} tagRecord\\n * @param {PassStyle} expectedPassStyle\\n * @param {Checker} [check]\\n * @returns {boolean}\\n */\\nconst checkTagRecord=(tagRecord,expectedPassStyle,check)=>{\\nreturn(\\n(isObject(tagRecord)||\\n!!check&&\\nCX(check)`A non-object cannot be a tagRecord: ${tagRecord}`)&&(\\nisFrozen(tagRecord)||\\n!!check&&CX(check)`A tagRecord must be frozen: ${tagRecord}`)&&(\\n!isArray(tagRecord)||\\n!!check&&CX(check)`An array cannot be a tagRecord: ${tagRecord}`)&&\\ncheckPassStyle(\\ntagRecord,\\ngetOwnDataDescriptor(tagRecord,PASS_STYLE,false,check).value,\\nexpectedPassStyle,\\ncheck)&&(\\n\\ntypeof getOwnDataDescriptor(tagRecord,Symbol.toStringTag,false,check).\\nvalue==='string'||\\n!!check&&\\nCX(\\ncheck)\\n`A [Symbol.toStringTag]-named property must be a string: ${tagRecord}`)&&\\ncheckProto(tagRecord,getPrototypeOf(tagRecord),check));};\\n\\n\\nreturn harden(checkTagRecord);};\\n\\n\\nconst checkTagRecord=makeCheckTagRecord(\\n(val,proto,check)=>\\nproto===objectPrototype||\\n!!check&&\\ncheck(false,index.redacted`A tagRecord must inherit from Object.prototype: ${val}`));\\n\\nharden(checkTagRecord);\\n\\nconst checkFunctionTagRecord=makeCheckTagRecord(\\n(val,proto,check)=>\\nproto===functionPrototype||\\nproto!==null&&getPrototypeOf(proto)===functionPrototype||\\n!!check&&\\ncheck(\\nfalse,\\nindex.redacted`For functions, a tagRecord must inherit from Function.prototype: ${val}`));\\n\\n\\nharden(checkFunctionTagRecord);exports.CX=CX;exports.PASS_STYLE=PASS_STYLE;exports.assertChecker=assertChecker;exports.canBeMethod=canBeMethod;exports.checkFunctionTagRecord=checkFunctionTagRecord;exports.checkPassStyle=checkPassStyle;exports.checkTagRecord=checkTagRecord;exports.getOwnDataDescriptor=getOwnDataDescriptor;exports.getTag=getTag;exports.hasOwnPropertyOf=hasOwnPropertyOf;exports.isObject=isObject;exports.isTypedArray=isTypedArray;\",\n \"node_modules/@endo/pass-style/src/passStyleOf.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../promise-kit/index.js');var index=require('../../errors/index.js');var passStyleHelpers=require('./passStyle-helpers.js');var copyArray=require('./copyArray.js');var copyRecord=require('./copyRecord.js');var tagged=require('./tagged.js');var error=require('./error.js');var remotable=require('./remotable.js');var symbol=require('./symbol.js');var safePromise=require('./safe-promise.js');var string=require('./string.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nisPromise=require('../../promise-kit/src/is-promise.js');/* global globalThis */ /** @import {PassStyleHelper} from './internal-types.js' */ /** @import {CopyArray, CopyRecord, CopyTagged, Passable} from './types.js' */ /** @import {PassStyle} from './types.js' */ /** @import {PassStyleOf} from './types.js' */ /** @import {PrimitiveStyle} from './types.js' */ /** @typedef {Exclude<PassStyle, PrimitiveStyle | \\\"promise\\\">} HelperPassStyle */\\n\\nconst{ownKeys}=Reflect;\\nconst{isFrozen,getOwnPropertyDescriptors,values}=Object;\\n\\n/**\\n * @param {PassStyleHelper[]} passStyleHelpers\\n * @returns {Record<HelperPassStyle, PassStyleHelper> }\\n */\\n\\nconst makeHelperTable=(passStyleHelpers)=>{\\n/** @type {Record<HelperPassStyle, any> & {__proto__: null}} */\\nconst HelperTable={\\n__proto__:null,\\ncopyArray:undefined,\\ncopyRecord:undefined,\\ntagged:undefined,\\nerror:undefined,\\nremotable:undefined};\\n\\nfor(const helper of passStyleHelpers){\\nconst{styleName}=helper;\\nstyleName in HelperTable||index.throwRedacted`Unrecognized helper: ${index.quote(styleName)}`;\\nHelperTable[styleName]===undefined||\\nindex.throwRedacted`conflicting helpers for ${index.quote(styleName)}`;\\nHelperTable[styleName]=helper;}\\n\\nfor(const styleName of ownKeys(HelperTable)){\\nHelperTable[styleName]!==undefined||\\nindex.throwRedacted`missing helper for ${index.quote(styleName)}`;}\\n\\n\\nreturn harden(HelperTable);};\\n\\n\\n/**\\n * @param {PassStyleHelper[]} passStyleHelpers The passStyleHelpers to register,\\n * in priority order.\\n * NOTE These must all be \\\"trusted\\\",\\n * complete, and non-colliding. `makePassStyleOf` may *assume* that each helper\\n * does what it is supposed to do. `makePassStyleOf` is not trying to defend\\n * itself against malicious helpers, though it does defend against some\\n * accidents.\\n * @returns {PassStyleOf}\\n */\\nconst makePassStyleOf=(passStyleHelpers$1)=>{\\nconst HelperTable=makeHelperTable(passStyleHelpers$1);\\nconst remotableHelper=HelperTable.remotable;\\n\\n/**\\n * Purely for performance. However it is mutable static state, and\\n * it does have some observability on proxies. TODO need to assess\\n * whether this creates a static communications channel.\\n *\\n * passStyleOf does a full recursive walk of pass-by-copy\\n * structures, in order to validate that they are acyclic. In addition\\n * it is used by other algorithms to recursively walk these pass-by-copy\\n * structures, so without this cache, these algorithms could be\\n * O(N**2) or worse.\\n *\\n * @type {WeakMap<WeakKey, PassStyle>}\\n */\\nconst passStyleMemo=new WeakMap();\\n\\n/**\\n * @type {PassStyleOf}\\n */\\n/* @ts-expect-error cast*/\\nconst passStyleOf=(passable)=>{\\n/* Even when a WeakSet is correct, when the set has a shorter lifetime*/\\n/* than its keys, we prefer a Set due to expected implementation*/\\n/* tradeoffs.*/\\nconst inProgress=new Set();\\n\\nconst passStyleOfRecur=(inner)=>{\\nconst innerIsObject=passStyleHelpers.isObject(inner);\\nif(innerIsObject){\\nconst innerStyle=passStyleMemo.get(inner);\\nif(innerStyle){\\nreturn innerStyle;}\\n\\n!inProgress.has(inner)||\\nindex.throwRedacted`Pass-by-copy data cannot be cyclic ${inner}`;\\ninProgress.add(inner);}\\n\\n/* eslint-disable-next-line no-use-before-define*/\\nconst passStyle=passStyleOfInternal(inner);\\nif(innerIsObject){\\npassStyleMemo.set(inner,passStyle);\\ninProgress.delete(inner);}\\n\\nreturn passStyle;};\\n\\n\\nconst passStyleOfInternal=(inner)=>{\\nconst typestr=typeof inner;\\nswitch(typestr){\\ncase'undefined':\\ncase'boolean':\\ncase'number':\\ncase'bigint':{\\nreturn typestr;}\\n\\ncase'string':{\\nstring.assertPassableString(inner);\\nreturn'string';}\\n\\ncase'symbol':{\\nsymbol.assertPassableSymbol(inner);\\nreturn'symbol';}\\n\\ncase'object':{\\nif(inner===null){\\nreturn'null';}\\n\\nif(!isFrozen(inner)){\\nassert.fail(\\n/* TypedArrays get special treatment in harden()*/\\n/* and a corresponding special error message here.*/\\npassStyleHelpers.isTypedArray(inner)?\\nindex.redacted`Cannot pass mutable typed arrays like ${inner}.`:\\nindex.redacted`Cannot pass non-frozen objects like ${inner}. Use harden()`);}\\n\\n\\nif(isPromise.isPromise(inner)){\\nsafePromise.assertSafePromise(inner);\\nreturn'promise';}\\n\\ntypeof inner.then!=='function'||\\nindex.throwRedacted`Cannot pass non-promise thenables`;\\nconst passStyleTag=inner[passStyleHelpers.PASS_STYLE];\\nif(passStyleTag!==undefined){\\nassert.typeof(passStyleTag,'string');\\nconst helper=HelperTable[passStyleTag];\\nhelper!==undefined||\\nindex.throwRedacted`Unrecognized PassStyle: ${index.quote(passStyleTag)}`;\\nhelper.assertValid(inner,passStyleOfRecur);\\nreturn(/** @type {PassStyle} */passStyleTag);}\\n\\nfor(const helper of passStyleHelpers$1){\\nif(helper.canBeValid(inner)){\\nhelper.assertValid(inner,passStyleOfRecur);\\nreturn helper.styleName;}}\\n\\n\\nremotableHelper.assertValid(inner,passStyleOfRecur);\\nreturn'remotable';}\\n\\ncase'function':{\\nisFrozen(inner)||\\nindex.throwRedacted`Cannot pass non-frozen objects like ${inner}. Use harden()`;\\ntypeof inner.then!=='function'||\\nindex.throwRedacted`Cannot pass non-promise thenables`;\\nremotableHelper.assertValid(inner,passStyleOfRecur);\\nreturn'remotable';}\\n\\ndefault:{\\nthrow assert.fail(index.redacted`Unrecognized typeof ${index.quote(typestr)}`,TypeError);}}};\\n\\n\\n\\n\\nreturn passStyleOfRecur(passable);};\\n\\nreturn harden(passStyleOf);};\\n\\n\\nconst PassStyleOfEndowmentSymbol=Symbol.for('@endo passStyleOf');\\n\\n/**\\n * If there is already a PassStyleOfEndowmentSymbol property on the global,\\n * then presumably it was endowed for us by liveslots with a `passStyleOf`\\n * function, so we should use and export that one instead.\\n * Other software may have left it for us here,\\n * but it would require write access to our global, or the ability to\\n * provide endowments to our global, both of which seems adequate as a test of\\n * whether it is authorized to serve the same role as liveslots.\\n *\\n * NOTE HAZARD: This use by liveslots does rely on `passStyleOf` being\\n * deterministic. If it is not, then in a liveslot-like virtualized\\n * environment, it can be used to detect GC.\\n *\\n * @type {PassStyleOf}\\n */\\nconst passStyleOf=\\nglobalThis&&globalThis[PassStyleOfEndowmentSymbol]||\\nmakePassStyleOf([\\ncopyArray.CopyArrayHelper,\\ncopyRecord.CopyRecordHelper,\\ntagged.TaggedHelper,\\nerror.ErrorHelper,\\nremotable.RemotableHelper]);\\n\\n\\nconst assertPassable=(val)=>{\\npassStyleOf(val);/* throws if val is not a passable*/};\\n\\nharden(assertPassable);\\n\\n/**\\n * Is `specimen` Passable? This returns true iff `passStyleOf(specimen)`\\n * returns a string. This returns `false` iff `passStyleOf(specimen)` throws.\\n * Under no normal circumstance should `isPassable(specimen)` throw.\\n *\\n * TODO Deprecate and ultimately delete @agoric/base-zone's `isPassable' in\\n * favor of this one.\\n * See https://github.com/endojs/endo/issues/2096\\n *\\n * TODO implement an isPassable that does not rely on try/catch.\\n * This implementation is just a standin until then.\\n * See https://github.com/endojs/endo/issues/2096\\n *\\n * @param {any} specimen\\n * @returns {specimen is Passable}\\n */\\nconst isPassable=(specimen)=>{\\ntry{\\n/* In fact, it never returns undefined. It either returns a*/\\n/* string or throws.*/\\nreturn passStyleOf(specimen)!==undefined;}\\ncatch(_){\\nreturn false;}};\\n\\n\\nharden(isPassable);\\n\\n/**\\n * @param {string} name\\n * @param {PropertyDescriptor} desc\\n * @returns {boolean}\\n */\\nconst isPassableErrorPropertyDesc=(name,desc)=>\\nerror.checkRecursivelyPassableErrorPropertyDesc(name,desc,passStyleOf);\\n\\n/**\\n * After hardening, if `err` is a passable error, return it.\\n *\\n * Otherwise, return a new passable error that propagates the diagnostic\\n * info of the original, and is linked to the original as a note.\\n *\\n * TODO Adopt a more flexible notion of passable error, in which\\n * a passable error can contain other own data properties with\\n * throwable values.\\n *\\n * @param {Error} err\\n * @returns {Error}\\n */\\nconst toPassableError=(err)=>{\\nharden(err);\\nif(error.checkRecursivelyPassableError(err,passStyleOf)){\\nreturn err;}\\n\\nconst{name,message}=err;\\nconst{cause:causeDesc,errors:errorsDesc}=\\ngetOwnPropertyDescriptors(err);\\nlet cause;\\nlet errors;\\nif(causeDesc&&isPassableErrorPropertyDesc('cause',causeDesc)){\\ncause=causeDesc.value;}\\n\\nif(errorsDesc&&isPassableErrorPropertyDesc('errors',errorsDesc)){\\nerrors=errorsDesc.value;}\\n\\n\\nconst errConstructor=error.getErrorConstructor(`${name}`)||Error;\\nconst newError=index.makeError(`${message}`,errConstructor,{\\n/* @ts-ignore Assuming cause is Error | undefined*/\\ncause,\\nerrors});\\n\\n/* Still needed, because `makeError` only does a shallow freeze.*/\\nharden(newError);\\n/* Even the cleaned up error copy, if sent to the console, should*/\\n/* cause hidden diagnostic information of the original error*/\\n/* to be logged.*/\\nindex.note(newError,index.redacted`copied from error ${err}`);\\npassStyleOf(newError)==='error'||\\nindex.throwRedacted`Expected ${newError} to be a passable error`;\\nreturn newError;};\\n\\nharden(toPassableError);\\n\\n/**\\n * After hardening, if `specimen` is throwable, return it.\\n * A specimen is throwable iff it is Passable and contains no PassableCaps,\\n * i.e., no Remotables or Promises.\\n * IOW, if it contains only copy-data and passable errors.\\n *\\n * Otherwise, if `specimen` is *almost* throwable, for example, it is\\n * an error that can be made throwable by `toPassableError`, then\\n * return `specimen` converted to a throwable.\\n *\\n * Otherwise, throw a diagnostic indicating a failure to coerce.\\n *\\n * This is in support of the exo boundary throwing only throwables, to ease\\n * security review.\\n *\\n * TODO Adopt a more flexitble notion of throwable, in which\\n * data containers containing non-passable errors can themselves be coerced\\n * to throwable by coercing to a similar containers containing\\n * the results of coercing those errors to passable errors.\\n *\\n * @param {unknown} specimen\\n * @returns {Passable<never, Error>}\\n */\\nconst toThrowable=(specimen)=>{\\nharden(specimen);\\nif(error.isErrorLike(specimen)){\\nreturn toPassableError(/** @type {Error} */specimen);}\\n\\n/* Note that this step will fail if `specimen` would be a passable container*/\\n/* except that it contains non-passable errors that could be converted.*/\\n/* This will need to be fixed to do the TODO above.*/\\nconst passStyle=passStyleOf(specimen);\\nif(passStyleHelpers.isObject(specimen)){\\nswitch(passStyle){\\ncase'copyArray':{\\nconst elements=/** @type {CopyArray} */specimen;\\nfor(const element of elements){\\nelement===toThrowable(element)||\\nindex.throwRedacted`nested toThrowable coercion not yet supported ${element}`;}\\n\\nbreak;}\\n\\ncase'copyRecord':{\\nconst rec=/** @type {CopyRecord} */specimen;\\nfor(const val of values(rec)){\\nval===toThrowable(val)||\\nindex.throwRedacted`nested toThrowable coercion not yet supported ${val}`;}\\n\\nbreak;}\\n\\ncase'tagged':{\\nconst tg=/** @type {CopyTagged} */specimen;\\nconst{payload}=tg;\\npayload===toThrowable(payload)||\\nindex.throwRedacted`nested toThrowable coercion not yet supported ${payload}`;\\nbreak;}\\n\\ncase'error':{\\nconst er=/** @type {Error} */specimen;\\ner===toThrowable(er)||\\nindex.throwRedacted`nested toThrowable coercion not yet supported ${er}`;\\nbreak;}\\n\\ndefault:{\\nthrow index.throwRedacted`A ${index.quote(passStyle)} is not throwable: ${specimen}`;}}}\\n\\n\\n\\nreturn(/** @type {Passable<never,never>} */specimen);};\\n\\nharden(toThrowable);exports.PassStyleOfEndowmentSymbol=PassStyleOfEndowmentSymbol;exports.assertPassable=assertPassable;exports.isPassable=isPassable;exports.passStyleOf=passStyleOf;exports.toPassableError=toPassableError;exports.toThrowable=toThrowable;\",\n \"node_modules/@endo/pass-style/src/remotable.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var index=require('../../errors/index.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\npassStyleHelpers=require('./passStyle-helpers.js');/*/ <reference types=\\\"ses\\\"/>*/ /**\\n * @import {Checker} from './types.js'\\n * @import {InterfaceSpec, PassStyled} from './types.js'\\n * @import {PassStyleHelper} from './internal-types.js'\\n * @import {RemotableObject as Remotable} from './types.js'\\n */\\n\\nconst{ownKeys}=Reflect;\\nconst{isArray}=Array;\\nconst{\\ngetPrototypeOf,\\nisFrozen,\\nprototype:objectPrototype,\\ngetOwnPropertyDescriptors}=\\nObject;\\n\\n/**\\n * @param {InterfaceSpec} iface\\n * @param {Checker} [check]\\n */\\nconst checkIface=(iface,check)=>{\\nreturn(\\n/* TODO other possible ifaces, once we have third party veracity*/\\n(typeof iface==='string'||\\n!!check&&\\npassStyleHelpers.CX(\\ncheck)\\n`For now, interface ${iface} must be a string; unimplemented`)&&(\\niface==='Remotable'||\\niface.startsWith('Alleged: ')||\\niface.startsWith('DebugName: ')||\\n!!check&&\\npassStyleHelpers.CX(check)`For now, iface ${index.quote(\\niface)\\n} must be \\\"Remotable\\\" or begin with \\\"Alleged: \\\" or \\\"DebugName: \\\"; unimplemented`));};\\n\\n\\n\\n/**\\n * An `iface` must be pure. Right now it must be a string, which is pure.\\n * Later we expect to include some other values that qualify as `PureData`,\\n * which is a pass-by-copy superstructure ending only in primitives or\\n * empty pass-by-copy composites. No remotables, promises, or errors.\\n * We *assume* for now that the pass-by-copy superstructure contains no\\n * proxies.\\n *\\n * @param {InterfaceSpec} iface\\n */\\nconst assertIface=(iface)=>checkIface(iface,passStyleHelpers.assertChecker);\\nharden(assertIface);\\n\\n/**\\n * @param {object | Function} original\\n * @param {Checker} [check]\\n * @returns {boolean}\\n */\\nconst checkRemotableProtoOf=(original,check)=>{\\npassStyleHelpers.isObject(original)||\\nindex.throwRedacted`Remotables must be objects or functions: ${original}`;\\n\\n/* A valid remotable object must inherit from a \\\"tag record\\\" -- a*/\\n/* plain-object prototype consisting of only*/\\n/* a `PASS_STYLE` property with value \\\"remotable\\\" and a suitable `Symbol.toStringTag`*/\\n/* property. The remotable could inherit directly from such a tag record, or*/\\n/* it could inherit from another valid remotable, that therefore itself*/\\n/* inherits directly or indirectly from such a tag record.*/\\n/**/\\n/* TODO: It would be nice to typedef this shape, but we can't declare a type*/\\n/* with PASS_STYLE from JSDoc.*/\\n/**/\\n/* @type {{ [PASS_STYLE]: string,*/\\n/* [Symbol.toStringTag]: string,*/\\n/* }}*/\\n/**/\\nconst proto=getPrototypeOf(original);\\nif(\\nproto===objectPrototype||\\nproto===null||\\nproto===Function.prototype)\\n{\\nreturn(\\n!!check&&\\npassStyleHelpers.CX(check)`Remotables must be explicitly declared: ${index.quote(original)}`);}\\n\\n\\n\\nif(typeof original==='object'){\\nconst protoProto=getPrototypeOf(proto);\\nif(protoProto!==objectPrototype&&protoProto!==null){\\n/* eslint-disable-next-line no-use-before-define*/\\nreturn checkRemotable(proto,check);}\\n\\nif(!passStyleHelpers.checkTagRecord(proto,'remotable',check)){\\nreturn false;}}else\\n\\nif(typeof original==='function'){\\nif(!passStyleHelpers.checkFunctionTagRecord(proto,'remotable',check)){\\nreturn false;}}\\n\\n\\n\\n/* Typecasts needed due to https://github.com/microsoft/TypeScript/issues/1863*/\\nconst passStyleKey=/** @type {unknown} */passStyleHelpers.PASS_STYLE;\\nconst tagKey=/** @type {unknown} */Symbol.toStringTag;\\nconst{\\n/* checkTagRecord already verified PASS_STYLE and Symbol.toStringTag own data properties.*/\\n[/** @type {string} */passStyleKey]:_passStyleDesc,\\n[/** @type {string} */tagKey]:{value:iface},\\n...restDescs}=\\ngetOwnPropertyDescriptors(proto);\\n\\nreturn(\\n(ownKeys(restDescs).length===0||\\n!!check&&\\npassStyleHelpers.CX(\\ncheck)\\n`Unexpected properties on Remotable Proto ${ownKeys(restDescs)}`)&&\\ncheckIface(iface,check));};\\n\\n\\n\\n/**\\n * Keep a weak set of confirmed remotables for marshal performance\\n * (without which we would incur a redundant verification in\\n * getInterfaceOf).\\n * We don't remember rejections because they are possible to correct\\n * with e.g. `harden`.\\n *\\n * @type {WeakSet<Remotable>}\\n */\\nconst confirmedRemotables=new WeakSet();\\n\\n/**\\n * @param {any} val\\n * @param {Checker} [check]\\n * @returns {val is Remotable}\\n */\\nconst checkRemotable=(val,check)=>{\\nif(confirmedRemotables.has(val)){\\nreturn true;}\\n\\nif(!isFrozen(val)){\\nreturn(\\n!!check&&passStyleHelpers.CX(check)`cannot serialize non-frozen objects like ${val}`);}\\n\\n\\n/* eslint-disable-next-line no-use-before-define*/\\nif(!RemotableHelper.canBeValid(val,check)){\\nreturn false;}\\n\\nconst result=checkRemotableProtoOf(val,check);\\nif(result){\\nconfirmedRemotables.add(val);}\\n\\nreturn result;};\\n\\n\\n/**\\n * Simple semantics, just tell what interface spec a Remotable has,\\n * or undefined if not deemed to be a Remotable.\\n *\\n * @type {{\\n * <T extends string>(val: PassStyled<any, T>): T;\\n * (val: any): InterfaceSpec | undefined;\\n * }}\\n */\\nconst getInterfaceOf=(val)=>{\\nif(\\n!passStyleHelpers.isObject(val)||\\nval[passStyleHelpers.PASS_STYLE]!=='remotable'||\\n!checkRemotable(val))\\n{\\n/* @ts-expect-error narrowed*/\\nreturn undefined;}\\n\\n/* @ts-expect-error narrowed*/\\nreturn passStyleHelpers.getTag(val);};\\n\\nharden(getInterfaceOf);\\n\\n/**\\n *\\n * @type {PassStyleHelper}\\n */\\nconst RemotableHelper=harden({\\nstyleName:'remotable',\\n\\ncanBeValid:(candidate,check=undefined)=>{\\nconst validType=\\n(passStyleHelpers.isObject(candidate)||\\n!!check&&\\npassStyleHelpers.CX(check)`cannot serialize non-objects as Remotable ${candidate}`)&&(\\n!isArray(candidate)||\\n!!check&&\\npassStyleHelpers.CX(check)`cannot serialize arrays as Remotable ${candidate}`);\\nif(!validType){\\nreturn false;}\\n\\n\\nconst descs=getOwnPropertyDescriptors(candidate);\\nif(typeof candidate==='object'){\\n/* Every own property (regardless of enumerability)*/\\n/* must have a function value.*/\\nreturn ownKeys(descs).every((key)=>{\\nreturn(\\n/* Typecast needed due to https://github.com/microsoft/TypeScript/issues/1863*/\\n(passStyleHelpers.hasOwnPropertyOf(descs[/** @type {string} */key],'value')||\\n!!check&&\\npassStyleHelpers.CX(check)`cannot serialize Remotables with accessors like ${index.quote(\\nString(key))\\n} in ${candidate}`)&&(\\nkey===Symbol.toStringTag&&checkIface(candidate[key],check)||\\n(passStyleHelpers.canBeMethod(candidate[key])||\\n!!check&&\\npassStyleHelpers.CX(check)`cannot serialize Remotables with non-methods like ${index.quote(\\nString(key))\\n} in ${candidate}`)&&(\\nkey!==passStyleHelpers.PASS_STYLE||\\n!!check&&\\npassStyleHelpers.CX(check)`A pass-by-remote cannot shadow ${index.quote(passStyleHelpers.PASS_STYLE)}`)));});}else\\n\\n\\nif(typeof candidate==='function'){\\n/* Far functions cannot be methods, and cannot have methods.*/\\n/* They must have exactly expected `.name` and `.length` properties*/\\nconst{\\nname:nameDesc,\\nlength:lengthDesc,\\n/* @ts-ignore TS doesn't like symbols as computed indexes??*/\\n[Symbol.toStringTag]:toStringTagDesc,\\n...restDescs}=\\ndescs;\\nconst restKeys=ownKeys(restDescs);\\nreturn(\\n(nameDesc&&typeof nameDesc.value==='string'||\\n!!check&&\\npassStyleHelpers.CX(check)`Far function name must be a string, in ${candidate}`)&&(\\nlengthDesc&&typeof lengthDesc.value==='number'||\\n!!check&&\\npassStyleHelpers.CX(\\ncheck)\\n`Far function length must be a number, in ${candidate}`)&&(\\ntoStringTagDesc===undefined||\\n(typeof toStringTagDesc.value==='string'||\\n!!check&&\\npassStyleHelpers.CX(\\ncheck)\\n`Far function @@toStringTag must be a string, in ${candidate}`)&&\\ncheckIface(toStringTagDesc.value,check))&&(\\nrestKeys.length===0||\\n!!check&&\\npassStyleHelpers.CX(\\ncheck)\\n`Far functions unexpected properties besides .name and .length ${restKeys}`));}\\n\\n\\nreturn!!check&&passStyleHelpers.CX(check)`unrecognized typeof ${candidate}`;},\\n\\n\\nassertValid:(candidate)=>checkRemotable(candidate,passStyleHelpers.assertChecker),\\n\\nevery:(_passable,_fn)=>true});exports.RemotableHelper=RemotableHelper;exports.assertIface=assertIface;exports.getInterfaceOf=getInterfaceOf;\",\n \"node_modules/@endo/pass-style/src/safe-promise.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../promise-kit/index.js');var index=require('../../errors/index.js');var passStyleHelpers=require('./passStyle-helpers.js');var\\n\\n\\n\\n\\n\\nisPromise=require('../../promise-kit/src/is-promise.js');/*/ <reference types=\\\"ses\\\"/>*/ /** @import {Checker} from './types.js' */\\n\\nconst{isFrozen,getPrototypeOf,getOwnPropertyDescriptor}=Object;\\nconst{ownKeys}=Reflect;\\nconst{toStringTag}=Symbol;\\n\\n/**\\n * @param {Promise} pr The value to examine\\n * @param {Checker} check\\n * @returns {pr is Promise} Whether it is a safe promise\\n */\\nconst checkPromiseOwnKeys=(pr,check)=>{\\nconst keys=ownKeys(pr);\\n\\nif(keys.length===0){\\nreturn true;}\\n\\n\\n/**\\n * This excludes those symbol-named own properties that are also found on\\n * `Promise.prototype`, so that overrides of these properties can be\\n * explicitly tolerated if they pass the `checkSafeOwnKey` check below.\\n * In particular, we wish to tolerate\\n * * An overriding `toStringTag` non-enumerable data property\\n * with a string value.\\n * * Those own properties that might be added by Node's async_hooks.\\n */\\nconst unknownKeys=keys.filter(\\n(key)=>typeof key!=='symbol'||!passStyleHelpers.hasOwnPropertyOf(Promise.prototype,key));\\n\\n\\nif(unknownKeys.length!==0){\\nreturn passStyleHelpers.CX(\\ncheck)\\n`${pr} - Must not have any own properties: ${index.quote(unknownKeys)}`;}\\n\\n\\n/**\\n * Explicitly tolerate a `toStringTag` symbol-named non-enumerable\\n * data property whose value is a string. Otherwise, tolerate those\\n * symbol-named properties that might be added by NodeJS's async_hooks,\\n * if they obey the expected safety properties.\\n *\\n * At the time of this writing, Node's async_hooks contains the\\n * following code, which we can safely tolerate\\n *\\n * ```js\\n * function destroyTracking(promise, parent) {\\n * trackPromise(promise, parent);\\n * const asyncId = promise[async_id_symbol];\\n * const destroyed = { destroyed: false };\\n * promise[destroyedSymbol] = destroyed;\\n * registerDestroyHook(promise, asyncId, destroyed);\\n * }\\n * ```\\n *\\n * @param {string|symbol} key\\n */\\nconst checkSafeOwnKey=(key)=>{\\nif(key===toStringTag){\\n/* TODO should we also enforce anything on the contents of the string,*/\\n/* such as that it must start with `'Promise'`?*/\\nconst tagDesc=getOwnPropertyDescriptor(pr,toStringTag);\\nassert(tagDesc!==undefined);\\nreturn(\\n(passStyleHelpers.hasOwnPropertyOf(tagDesc,'value')||\\npassStyleHelpers.CX(\\ncheck)\\n`Own @@toStringTag must be a data property, not an accessor: ${index.quote(tagDesc)}`)&&(\\ntypeof tagDesc.value==='string'||\\npassStyleHelpers.CX(\\ncheck)\\n`Own @@toStringTag value must be a string: ${index.quote(tagDesc.value)}`)&&(\\n!tagDesc.enumerable||\\npassStyleHelpers.CX(check)`Own @@toStringTag must not be enumerable: ${index.quote(tagDesc)}`));}\\n\\n\\nconst val=pr[key];\\nif(val===undefined||typeof val==='number'){\\nreturn true;}\\n\\nif(\\ntypeof val==='object'&&\\nval!==null&&\\nisFrozen(val)&&\\ngetPrototypeOf(val)===Object.prototype)\\n{\\nconst subKeys=ownKeys(val);\\nif(subKeys.length===0){\\nreturn true;}\\n\\n\\nif(\\nsubKeys.length===1&&\\nsubKeys[0]==='destroyed'&&\\nval.destroyed===false)\\n{\\nreturn true;}}\\n\\n\\nreturn passStyleHelpers.CX(\\ncheck)\\n`Unexpected Node async_hooks additions to promise: ${pr}.${index.quote(\\nString(key))\\n} is ${val}`;};\\n\\n\\nreturn keys.every(checkSafeOwnKey);};\\n\\n\\n/**\\n * Under Hardened JS a promise is \\\"safe\\\" if its `then` method can be called\\n * synchronously without giving the promise an opportunity for a\\n * reentrancy attack during that call.\\n *\\n * https://github.com/Agoric/agoric-sdk/issues/9\\n * raises the issue of testing that a specimen is a safe promise\\n * such that the test also does not give the specimen a\\n * reentrancy opportunity. That is well beyond the ambition here.\\n * TODO Though if we figure out a nice solution, it might be good to\\n * use it here as well.\\n *\\n * @param {unknown} pr The value to examine\\n * @param {Checker} check\\n * @returns {pr is Promise} Whether it is a safe promise\\n */\\nconst checkSafePromise=(pr,check)=>{\\nreturn(\\n(isFrozen(pr)||passStyleHelpers.CX(check)`${pr} - Must be frozen`)&&(\\nisPromise.isPromise(pr)||passStyleHelpers.CX(check)`${pr} - Must be a promise`)&&(\\ngetPrototypeOf(pr)===Promise.prototype||\\npassStyleHelpers.CX(check)`${pr} - Must inherit from Promise.prototype: ${index.quote(\\ngetPrototypeOf(pr))\\n}`)&&\\ncheckPromiseOwnKeys(/** @type {Promise} */pr,check));};\\n\\n\\nharden(checkSafePromise);\\n\\n/**\\n * Determine if the argument is a Promise.\\n *\\n * @param {unknown} pr The value to examine\\n * @returns {pr is Promise} Whether it is a promise\\n */\\nconst isSafePromise=(pr)=>checkSafePromise(pr,(x)=>x);\\nharden(isSafePromise);\\n\\nconst assertSafePromise=(pr)=>checkSafePromise(pr,passStyleHelpers.assertChecker);exports.assertSafePromise=assertSafePromise;exports.isSafePromise=isSafePromise;\",\n \"node_modules/@endo/pass-style/src/string.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../env-options/index.js');var index=require('../../errors/index.js');var\\n\\n\\nenvOptions=require('../../env-options/src/env-options.js');/* know about`isWellFormed`*/\\nconst hasWellFormedStringMethod=!!String.prototype.isWellFormed;\\n\\n/**\\n * Is the argument a well-formed string?\\n *\\n * Unfortunately, the\\n * [standard built-in `String.prototype.isWellFormed`](https://github.com/tc39/proposal-is-usv-string)\\n * does a ToString on its input, causing it to judge non-strings to be\\n * well-formed strings if they coerce to a well-formed strings. This\\n * recapitulates the mistake in having the global `isNaN` coerce its inputs,\\n * causing it to judge non-string to be NaN if they coerce to NaN.\\n *\\n * This `isWellFormedString` function only judges well-formed strings to be\\n * well-formed strings. For all non-strings it returns false.\\n *\\n * @param {unknown} str\\n * @returns {str is string}\\n */\\nconst isWellFormedString=hasWellFormedStringMethod?\\n(str)=>typeof str==='string'&&str.isWellFormed():\\n(str)=>{\\nif(typeof str!=='string'){\\nreturn false;}\\n\\nfor(const ch of str){\\n/* The string iterator iterates by Unicode code point, not*/\\n/* UTF16 code unit. But if it encounters an unpaired surrogate,*/\\n/* it will produce it.*/\\nconst cp=/** @type {number} */ch.codePointAt(0);\\nif(cp>=0xd800&&cp<=0xdfff){\\n/* All surrogates are in this range. The string iterator only*/\\n/* produces a character in this range for unpaired surrogates,*/\\n/* which only happens if the string is not well-formed.*/\\nreturn false;}}\\n\\n\\nreturn true;};\\n\\nharden(isWellFormedString);\\n\\n/**\\n * Returns normally when `isWellFormedString(str)` would return true.\\n * Throws a diagnostic error when `isWellFormedString(str)` would return false.\\n *\\n * @param {unknown} str\\n * @returns {asserts str is string}\\n */\\nconst assertWellFormedString=(str)=>{\\nisWellFormedString(str)||index.throwRedacted`Expected well-formed unicode string: ${str}`;};\\n\\nharden(assertWellFormedString);\\n\\nconst ONLY_WELL_FORMED_STRINGS_PASSABLE=\\nenvOptions.getEnvironmentOption('ONLY_WELL_FORMED_STRINGS_PASSABLE','disabled',[\\n'enabled'])===\\n'enabled';\\n\\n/**\\n * For now,\\n * if `ONLY_WELL_FORMED_STRINGS_PASSABLE` environment option is `'enabled'`,\\n * then `assertPassableString` is the same as `assertWellFormedString`.\\n * Otherwise `assertPassableString` just asserts that `str` is a string.\\n *\\n * Currently, `ONLY_WELL_FORMED_STRINGS_PASSABLE` defaults to `'disabled'`\\n * because we do not yet know the performance impact. Later, if we decide we\\n * can afford it, we'll first change the default to `'enabled'` and ultimately\\n * remove the switch altogether. Be prepared for these changes.\\n *\\n * TODO once the switch is removed, simplify `assertPassableString` to\\n * simply be `assertWellFormedString`.\\n *\\n * @param { unknown } str\\n * @returns {asserts str is string }\\n */\\nconst assertPassableString=(str)=>{\\ntypeof str==='string'||index.throwRedacted`Expected string ${str}`;\\n!ONLY_WELL_FORMED_STRINGS_PASSABLE||assertWellFormedString(str);};\\n\\nharden(assertPassableString);exports.assertPassableString=assertPassableString;exports.assertWellFormedString=assertWellFormedString;exports.isWellFormedString=isWellFormedString;\",\n \"node_modules/@endo/pass-style/src/symbol.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var index=require('../../errors/index.js');\\n\\nconst{ownKeys}=Reflect;\\n\\n/**\\n * The well known symbols are static symbol values on the `Symbol` constructor.\\n */\\nconst wellKnownSymbolNames=new Map(\\nownKeys(Symbol).\\nfilter(\\n(name)=>typeof name==='string'&&typeof Symbol[name]==='symbol').\\n\\nfilter((name)=>{\\n/* @ts-expect-error It doesn't know name cannot be a symbol*/\\n!name.startsWith('@@')||\\nindex.throwRedacted`Did not expect Symbol to have a symbol-valued property name starting with \\\"@@\\\" ${index.quote(\\nname)\\n}`;\\nreturn true;})\\n\\n/* @ts-ignore It doesn't know name cannot be a symbol*/.\\nmap((name)=>[Symbol[name],`@@${name}`]));\\n\\n\\n/**\\n * The passable symbols are the well known symbols (the symbol values\\n * of static properties of the `Symbol` constructor) and the registered\\n * symbols.\\n *\\n * @param {any} sym\\n * @returns {boolean}\\n */\\nconst isPassableSymbol=(sym)=>\\ntypeof sym==='symbol'&&(\\ntypeof Symbol.keyFor(sym)==='string'||wellKnownSymbolNames.has(sym));\\nharden(isPassableSymbol);\\n\\nconst assertPassableSymbol=(sym)=>\\nisPassableSymbol(sym)||\\nindex.throwRedacted`Only registered symbols or well-known symbols are passable: ${index.quote(sym)}`;\\nharden(assertPassableSymbol);\\n\\n/**\\n * If `sym` is a passable symbol, return a string that uniquely identifies this\\n * symbol. If `sym` is a non-passable symbol, return `undefined`.\\n *\\n * The passable symbols are the well known symbols (the symbol values\\n * of static properties of the `Symbol` constructor) and the registered\\n * symbols. Since the registration string of a registered symbol can be any\\n * string, if we simply used that to identify those symbols, there would not\\n * be any remaining strings left over to identify the well-known symbols.\\n * Instead, we reserve strings beginning with `\\\"@@\\\"` for purposes of this\\n * encoding. We identify a well known symbol such as `Symbol.iterator`\\n * by prefixing the property name with `\\\"@@\\\"`, such as `\\\"@@iterator\\\"`.\\n * For registered symbols whose name happens to begin with `\\\"@@\\\"`, such\\n * as `Symbol.for('@@iterator')` or `Symbol.for('@@foo')`, we identify\\n * them by prefixing them with an extra `\\\"@@\\\"`, such as\\n * `\\\"@@@@iterator\\\"` or `\\\"@@@@foo\\\"`. (This is the Hilbert Hotel encoding\\n * technique.)\\n *\\n * @param {symbol} sym\\n * @returns {string=}\\n */\\nconst nameForPassableSymbol=(sym)=>{\\nconst name=Symbol.keyFor(sym);\\nif(name===undefined){\\nreturn wellKnownSymbolNames.get(sym);}\\n\\nif(name.startsWith('@@')){\\nreturn`@@${name}`;}\\n\\nreturn name;};\\n\\nharden(nameForPassableSymbol);\\n\\nconst AtAtPrefixPattern=/^@@(.*)$/;\\nharden(AtAtPrefixPattern);\\n\\n/**\\n * If `name` is a string that could have been produced by\\n * `nameForPassableSymbol`, return the symbol argument it was produced to\\n * represent.\\n *\\n * If `name` does not begin with `\\\"@@\\\"`, then just the corresponding\\n * registered symbol, `Symbol.for(name)`.\\n * If `name` is `\\\"@@\\\"` followed by a well known symbol's property name on\\n * `Symbol` such `\\\"@@iterator\\\", return that well known symbol such as\\n * `Symbol.iterator`\\n * If `name` begins with `\\\"@@@@\\\"` it encodes the registered symbol whose\\n * name begins with `\\\"@@\\\"` instead.\\n * Otherwise, if name begins with `\\\"@@\\\"` it may encode a registered symbol\\n * from a future version of JavaScript, but it is not one we can decode\\n * yet, so throw.\\n *\\n * @param {string} name\\n * @returns {symbol=}\\n */\\nconst passableSymbolForName=(name)=>{\\nif(typeof name!=='string'){\\nreturn undefined;}\\n\\nconst match=AtAtPrefixPattern.exec(name);\\nif(match){\\nconst suffix=match[1];\\nif(suffix.startsWith('@@')){\\nreturn Symbol.for(suffix);}else\\n{\\nconst sym=Symbol[suffix];\\nif(typeof sym==='symbol'){\\nreturn sym;}\\n\\nindex.throwRedacted`Reserved for well known symbol ${index.quote(suffix)}: ${index.quote(name)}`;}}\\n\\n\\nreturn Symbol.for(name);};\\n\\nharden(passableSymbolForName);exports.assertPassableSymbol=assertPassableSymbol;exports.isPassableSymbol=isPassableSymbol;exports.nameForPassableSymbol=nameForPassableSymbol;exports.passableSymbolForName=passableSymbolForName;\",\n \"node_modules/@endo/pass-style/src/tagged.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var index=require('../../errors/index.js');var passStyleHelpers=require('./passStyle-helpers.js');/*/ <reference types=\\\"ses\\\"/>*/\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nconst{ownKeys}=Reflect;\\nconst{getOwnPropertyDescriptors}=Object;\\n\\n/**\\n *\\n * @type {IMPORT('./internal-types.js').PassStyleHelper}\\n */\\nconst TaggedHelper=harden({\\nstyleName:'tagged',\\n\\ncanBeValid:(candidate,check=undefined)=>\\npassStyleHelpers.checkPassStyle(candidate,candidate[passStyleHelpers.PASS_STYLE],'tagged',check),\\n\\nassertValid:(candidate,passStyleOfRecur)=>{\\npassStyleHelpers.checkTagRecord(candidate,'tagged',passStyleHelpers.assertChecker);\\n\\n/* Typecasts needed due to https://github.com/microsoft/TypeScript/issues/1863*/\\nconst passStyleKey=/** @type {unknown} */passStyleHelpers.PASS_STYLE;\\nconst tagKey=/** @type {unknown} */Symbol.toStringTag;\\nconst{\\n/* checkTagRecord already verified PASS_STYLE and Symbol.toStringTag own data properties.*/\\n[/** @type {string} */passStyleKey]:_passStyleDesc,\\n[/** @type {string} */tagKey]:_labelDesc,\\npayload:_payloadDesc,/* value checked by recursive walk at the end*/\\n...restDescs}=\\ngetOwnPropertyDescriptors(candidate);\\nownKeys(restDescs).length===0||\\nindex.throwRedacted`Unexpected properties on tagged record ${ownKeys(restDescs)}`;\\n\\n/* Validate that the 'payload' property is own/data/enumerable*/\\n/* and its associated value is recursively passable.*/\\npassStyleOfRecur(\\npassStyleHelpers.getOwnDataDescriptor(candidate,'payload',true,passStyleHelpers.assertChecker).value);}});exports.TaggedHelper=TaggedHelper;\",\n \"node_modules/@endo/pass-style/src/typeGuards.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var index=require('../../errors/index.js');var\\n\\n\\n\\n\\npassStyleOf=require('./passStyleOf.js');/** @import {CopyArray, CopyRecord, Passable, RemotableObject} from './types.js' */ /**\\n * Check whether the argument is a pass-by-copy array, AKA a \\\"copyArray\\\"\\n * in @endo/marshal terms\\n *\\n * @param {any} arr\\n * @returns {arr is CopyArray<any>}\\n */\\nconst isCopyArray=(arr)=>passStyleOf.passStyleOf(arr)==='copyArray';\\nharden(isCopyArray);\\n\\n/**\\n * Check whether the argument is a pass-by-copy record, AKA a\\n * \\\"copyRecord\\\" in @endo/marshal terms\\n *\\n * @param {any} record\\n * @returns {record is CopyRecord<any>}\\n */\\nconst isRecord=(record)=>passStyleOf.passStyleOf(record)==='copyRecord';\\nharden(isRecord);\\n\\n/**\\n * Check whether the argument is a remotable.\\n *\\n * @param {Passable} remotable\\n * @returns {remotable is RemotableObject}\\n */\\nconst isRemotable=(remotable)=>passStyleOf.passStyleOf(remotable)==='remotable';\\nharden(isRemotable);\\n\\n/**\\n * @param {any} array\\n * @param {string=} optNameOfArray\\n * @returns {asserts array is CopyArray<any>}\\n */\\nconst assertCopyArray=(array,optNameOfArray='Alleged array')=>{\\nconst passStyle=passStyleOf.passStyleOf(array);\\npassStyle==='copyArray'||\\nindex.throwRedacted`${index.quote(optNameOfArray)} ${array} must be a pass-by-copy array, not ${index.quote(\\npassStyle)\\n}`;};\\n\\nharden(assertCopyArray);\\n\\n/**\\n * @param {any} record\\n * @param {string=} optNameOfRecord\\n * @returns {asserts record is CopyRecord<any>}\\n */\\nconst assertRecord=(record,optNameOfRecord='Alleged record')=>{\\nconst passStyle=passStyleOf.passStyleOf(record);\\npassStyle==='copyRecord'||\\nindex.throwRedacted`${index.quote(optNameOfRecord)} ${record} must be a pass-by-copy record, not ${index.quote(\\npassStyle)\\n}`;};\\n\\nharden(assertRecord);\\n\\n/**\\n * @param {Passable} remotable\\n * @param {string=} optNameOfRemotable\\n * @returns {asserts remotable is RemotableObject}\\n */\\nconst assertRemotable=(\\nremotable,\\noptNameOfRemotable='Alleged remotable')=>\\n{\\nconst passStyle=passStyleOf.passStyleOf(remotable);\\npassStyle==='remotable'||\\nindex.throwRedacted`${index.quote(optNameOfRemotable)} ${remotable} must be a remotable, not ${index.quote(\\npassStyle)\\n}`;};\\n\\nharden(assertRemotable);exports.assertCopyArray=assertCopyArray;exports.assertRecord=assertRecord;exports.assertRemotable=assertRemotable;exports.isCopyArray=isCopyArray;exports.isRecord=isRecord;exports.isRemotable=isRemotable;\",\n \"node_modules/@endo/pass-style/src/types.js\": \"'use strict';/** @file Empty twin for .d.ts */\",\n \"node_modules/@endo/patterns/index.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var checkKey=require('./src/keys/checkKey.js');var copySet=require('./src/keys/copySet.js');var copyBag=require('./src/keys/copyBag.js');var compareKeys=require('./src/keys/compareKeys.js');var mergeSetOperators=require('./src/keys/merge-set-operators.js');var mergeBagOperators=require('./src/keys/merge-bag-operators.js');var patternMatchers=require('./src/patterns/patternMatchers.js');var getGuardPayloads=require('./src/patterns/getGuardPayloads.js');require('./src/types.js');var listDifference=require('../common/list-difference.js');var objectMap=require('../common/object-map.js');exports.assertCopyBag=checkKey.assertCopyBag;exports.assertCopyMap=checkKey.assertCopyMap;exports.assertCopySet=checkKey.assertCopySet;exports.assertKey=checkKey.assertKey;exports.assertScalarKey=checkKey.assertScalarKey;exports.getCopyBagEntries=checkKey.getCopyBagEntries;exports.getCopyMapEntries=checkKey.getCopyMapEntries;exports.getCopySetKeys=checkKey.getCopySetKeys;exports.isCopyBag=checkKey.isCopyBag;exports.isCopyMap=checkKey.isCopyMap;exports.isCopySet=checkKey.isCopySet;exports.isKey=checkKey.isKey;exports.makeCopyBag=checkKey.makeCopyBag;exports.makeCopyBagFromElements=checkKey.makeCopyBagFromElements;exports.makeCopyMap=checkKey.makeCopyMap;exports.makeCopySet=checkKey.makeCopySet;exports.coerceToElements=copySet.coerceToElements;exports.coerceToBagEntries=copyBag.coerceToBagEntries;exports.bagCompare=compareKeys.bagCompare;exports.compareKeys=compareKeys.compareKeys;exports.keyEQ=compareKeys.keyEQ;exports.keyGT=compareKeys.keyGT;exports.keyGTE=compareKeys.keyGTE;exports.keyLT=compareKeys.keyLT;exports.keyLTE=compareKeys.keyLTE;exports.setCompare=compareKeys.setCompare;exports.elementsCompare=mergeSetOperators.elementsCompare;exports.elementsDisjointSubtract=mergeSetOperators.elementsDisjointSubtract;exports.elementsDisjointUnion=mergeSetOperators.elementsDisjointUnion;exports.elementsIntersection=mergeSetOperators.elementsIntersection;exports.elementsIsDisjoint=mergeSetOperators.elementsIsDisjoint;exports.elementsIsSuperset=mergeSetOperators.elementsIsSuperset;exports.elementsUnion=mergeSetOperators.elementsUnion;exports.setDisjointSubtract=mergeSetOperators.setDisjointSubtract;exports.setDisjointUnion=mergeSetOperators.setDisjointUnion;exports.setIntersection=mergeSetOperators.setIntersection;exports.setIsDisjoint=mergeSetOperators.setIsDisjoint;exports.setIsSuperset=mergeSetOperators.setIsSuperset;exports.setUnion=mergeSetOperators.setUnion;exports.bagDisjointSubtract=mergeBagOperators.bagDisjointSubtract;exports.bagIntersection=mergeBagOperators.bagIntersection;exports.bagIsSuperbag=mergeBagOperators.bagIsSuperbag;exports.bagUnion=mergeBagOperators.bagUnion;exports.M=patternMatchers.M;exports.assertAwaitArgGuard=patternMatchers.assertAwaitArgGuard;exports.assertInterfaceGuard=patternMatchers.assertInterfaceGuard;exports.assertMethodGuard=patternMatchers.assertMethodGuard;exports.assertPattern=patternMatchers.assertPattern;exports.assertRawGuard=patternMatchers.assertRawGuard;exports.getRankCover=patternMatchers.getRankCover;exports.isAwaitArgGuard=patternMatchers.isAwaitArgGuard;exports.isPattern=patternMatchers.isPattern;exports.isRawGuard=patternMatchers.isRawGuard;exports.kindOf=patternMatchers.kindOf;exports.matches=patternMatchers.matches;exports.mustMatch=patternMatchers.mustMatch;exports.getAwaitArgGuardPayload=getGuardPayloads.getAwaitArgGuardPayload;exports.getInterfaceGuardPayload=getGuardPayloads.getInterfaceGuardPayload;exports.getInterfaceMethodKeys=getGuardPayloads.getInterfaceMethodKeys;exports.getMethodGuardPayload=getGuardPayloads.getMethodGuardPayload;exports.listDifference=listDifference.listDifference;exports.objectMap=objectMap.objectMap;\",\n \"node_modules/@endo/patterns/src/keys/checkKey.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../../marshal/index.js');var identChecker=require('../../../common/ident-checker.js');var index=require('../../../errors/index.js');var copySet=require('./copySet.js');var copyBag=require('./copyBag.js');var passStyleHelpers=require('../../../pass-style/src/passStyle-helpers.js');var passStyleOf=require('../../../pass-style/src/passStyleOf.js');var rankOrder=require('../../../marshal/src/rankOrder.js');var makeFar=require('../../../pass-style/src/make-far.js');var makeTagged=require('../../../pass-style/src/makeTagged.js');/*/ <reference types=\\\"ses\\\"/>*/\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nconst{ownKeys}=Reflect;\\n\\n/**\\n * @import {Passable, Primitive} from '@endo/pass-style'\\n * @import {Checker} from '@endo/marshal'\\n * @import {CopyBag, CopyMap, CopySet, Key, ScalarKey} from '../types.js'\\n */\\n\\n/* ////////////////// Primitive and Scalar keys ////////////////////////////////*/\\n\\n/**\\n * @param {Passable} val\\n * @param {Checker} check\\n * @returns {boolean}\\n */\\nconst checkPrimitiveKey=(val,check)=>{\\nif(passStyleHelpers.isObject(val)){\\nreturn(\\ncheck!==identChecker.identChecker&&\\ncheck(false,index.redacted`A ${index.quote(typeof val)} cannot be a primitive: ${val}`));}\\n\\n\\n/* TODO There is not yet a checkPassable, but perhaps there should be.*/\\n/* If that happens, we should call it here instead.*/\\npassStyleOf.assertPassable(val);\\nreturn true;};\\n\\n\\n/**\\n * @param {any} val\\n * @returns {val is Primitive}\\n */\\nconst isPrimitiveKey=(val)=>checkPrimitiveKey(val,identChecker.identChecker);\\nharden(isPrimitiveKey);\\n\\n/**\\n * @param {Passable} val\\n * @returns {asserts val is Primitive}\\n */\\nconst assertPrimitiveKey=(val)=>{\\ncheckPrimitiveKey(val,passStyleHelpers.assertChecker);};\\n\\nharden(assertPrimitiveKey);\\n\\n/**\\n * @param {any} val\\n * @param {Checker} check\\n * @returns {boolean}\\n */\\nconst checkScalarKey=(val,check)=>{\\nif(isPrimitiveKey(val)){\\nreturn true;}\\n\\nconst passStyle=passStyleOf.passStyleOf(val);\\nif(passStyle==='remotable'){\\nreturn true;}\\n\\nreturn check(false,index.redacted`A ${index.quote(passStyle)} cannot be a scalar key: ${val}`);};\\n\\n\\n/**\\n * @param {any} val\\n * @returns {val is ScalarKey}\\n */\\nconst isScalarKey=(val)=>checkScalarKey(val,identChecker.identChecker);\\nharden(isScalarKey);\\n\\n/**\\n * @param {Passable} val\\n * @returns {asserts val is ScalarKey}\\n */\\nconst assertScalarKey=(val)=>{\\ncheckScalarKey(val,passStyleHelpers.assertChecker);};\\n\\nharden(assertScalarKey);\\n\\n/* ////////////////////////////// Keys /////////////////////////////////////////*/\\n\\n/* @ts-expect-error Key does not satisfy WeakKey*/\\n/** @type {WeakSet<Key>} */\\n/* @ts-expect-error Key does not satisfy WeakKey*/\\nconst keyMemo=new WeakSet();\\n\\n/**\\n * @param {unknown} val\\n * @param {Checker} check\\n * @returns {boolean}\\n */\\nconst checkKey=(val,check)=>{\\nif(!passStyleHelpers.isObject(val)){\\n/* TODO There is not yet a checkPassable, but perhaps there should be.*/\\n/* If that happens, we should call it here instead.*/\\npassStyleOf.assertPassable(val);\\nreturn true;}\\n\\n/* @ts-expect-error narrowed*/\\nif(keyMemo.has(val)){\\nreturn true;}\\n\\n/* eslint-disable-next-line no-use-before-define*/\\nconst result=checkKeyInternal(val,check);\\nif(result){\\n/* Don't cache the undefined cases, so that if it is tried again*/\\n/* with `assertChecker` it'll throw a diagnostic again*/\\n/* @ts-expect-error narrowed*/\\nkeyMemo.add(val);}\\n\\n/* Note that we do not memoize a negative judgement, so that if it is tried*/\\n/* again with a checker, it will still produce a useful diagnostic.*/\\nreturn result;};\\n\\nharden(checkKey);\\n\\n/**\\n * @type {{\\n * (val: Passable): val is Key;\\n * (val: any): boolean;\\n * }}\\n */\\nconst isKey=(val)=>checkKey(val,identChecker.identChecker);\\nharden(isKey);\\n\\n/**\\n * @param {Key} val\\n * @returns {asserts val is Key}\\n */\\nconst assertKey=(val)=>{\\ncheckKey(val,passStyleHelpers.assertChecker);};\\n\\nharden(assertKey);\\n\\n/* //////////////////////////// CopySet ////////////////////////////////////////*/\\n\\n/* Moved to here so they can check that the copySet contains only keys*/\\n/* without creating an import cycle.*/\\n\\n/** @type {WeakSet<CopySet>} */\\nconst copySetMemo=new WeakSet();\\n\\n/**\\n * @param {any} s\\n * @param {Checker} check\\n * @returns {boolean}\\n */\\nconst checkCopySet=(s,check)=>{\\nif(copySetMemo.has(s)){\\nreturn true;}\\n\\nconst result=\\n(passStyleOf.passStyleOf(s)==='tagged'&&passStyleHelpers.getTag(s)==='copySet'||\\ncheck(false,index.redacted`Not a copySet: ${s}`))&&\\ncopySet.checkElements(s.payload,check)&&\\ncheckKey(s.payload,check);\\nif(result){\\ncopySetMemo.add(s);}\\n\\nreturn result;};\\n\\nharden(checkCopySet);\\n\\n/**\\n * @param {any} s\\n * @returns {s is CopySet}\\n */\\nconst isCopySet=(s)=>checkCopySet(s,identChecker.identChecker);\\nharden(isCopySet);\\n\\n/**\\n * @callback AssertCopySet\\n * @param {Passable} s\\n * @returns {asserts s is CopySet}\\n */\\n\\n/** @type {AssertCopySet} */\\nconst assertCopySet=(s)=>{\\ncheckCopySet(s,passStyleHelpers.assertChecker);};\\n\\nharden(assertCopySet);\\n\\n/**\\n * @template {Key} K\\n * @param {CopySet<K>} s\\n * @returns {K[]}\\n */\\nconst getCopySetKeys=(s)=>{\\nassertCopySet(s);\\nreturn s.payload;};\\n\\nharden(getCopySetKeys);\\n\\n/**\\n * @template {Key} K\\n * @param {CopySet<K>} s\\n * @param {(key: K, index: number) => boolean} fn\\n * @returns {boolean}\\n */\\nconst everyCopySetKey=(s,fn)=>\\ngetCopySetKeys(s).every((key,index)=>fn(key,index));\\nharden(everyCopySetKey);\\n\\n/**\\n * @template {Key} K\\n * @param {Iterable<K>} elementIter\\n * @returns {CopySet<K>}\\n */\\nconst makeCopySet=(elementIter)=>{\\nconst result=copySet.makeSetOfElements(elementIter);\\nassertCopySet(result);\\nreturn result;};\\n\\nharden(makeCopySet);\\n\\n/* //////////////////////////// CopyBag ////////////////////////////////////////*/\\n\\n/* Moved to here so they can check that the copyBag contains only keys*/\\n/* without creating an import cycle.*/\\n\\n/** @type {WeakSet<CopyBag>} */\\nconst copyBagMemo=new WeakSet();\\n\\n/**\\n * @param {any} b\\n * @param {Checker} check\\n * @returns {boolean}\\n */\\nconst checkCopyBag=(b,check)=>{\\nif(copyBagMemo.has(b)){\\nreturn true;}\\n\\nconst result=\\n(passStyleOf.passStyleOf(b)==='tagged'&&passStyleHelpers.getTag(b)==='copyBag'||\\ncheck(false,index.redacted`Not a copyBag: ${b}`))&&\\ncopyBag.checkBagEntries(b.payload,check)&&\\ncheckKey(b.payload,check);\\nif(result){\\ncopyBagMemo.add(b);}\\n\\nreturn result;};\\n\\nharden(checkCopyBag);\\n\\n/**\\n * @param {any} b\\n * @returns {b is CopyBag}\\n */\\nconst isCopyBag=(b)=>checkCopyBag(b,identChecker.identChecker);\\nharden(isCopyBag);\\n\\n/**\\n * @callback AssertCopyBag\\n * @param {Passable} b\\n * @returns {asserts b is CopyBag}\\n */\\n\\n/** @type {AssertCopyBag} */\\nconst assertCopyBag=(b)=>{\\ncheckCopyBag(b,passStyleHelpers.assertChecker);};\\n\\nharden(assertCopyBag);\\n\\n/**\\n * @template {Key} K\\n * @param {CopyBag<K>} b\\n * @returns {CopyBag<K>['payload']}\\n */\\nconst getCopyBagEntries=(b)=>{\\nassertCopyBag(b);\\nreturn b.payload;};\\n\\nharden(getCopyBagEntries);\\n\\n/**\\n * @template {Key} K\\n * @param {CopyBag<K>} b\\n * @param {(entry: [K, bigint], index: number) => boolean} fn\\n * @returns {boolean}\\n */\\nconst everyCopyBagEntry=(b,fn)=>\\ngetCopyBagEntries(b).every((entry,index)=>fn(entry,index));\\nharden(everyCopyBagEntry);\\n\\n/**\\n * @template {Key} K\\n * @param {Iterable<[K,bigint]>} bagEntryIter\\n * @returns {CopyBag<K>}\\n */\\nconst makeCopyBag=(bagEntryIter)=>{\\nconst result=copyBag.makeBagOfEntries(bagEntryIter);\\nassertCopyBag(result);\\nreturn result;};\\n\\nharden(makeCopyBag);\\n\\n/**\\n * @template {Key} K\\n * @param {Iterable<K>} elementIter\\n * @returns {CopyBag<K>}\\n */\\nconst makeCopyBagFromElements=(elementIter)=>{\\n/* This fullOrder contains history dependent state. It is specific*/\\n/* to this one call and does not survive it.*/\\nconst fullCompare=rankOrder.makeFullOrderComparatorKit().antiComparator;\\nconst sorted=rankOrder.sortByRank(elementIter,fullCompare);\\n/** @type {[K,bigint][]} */\\nconst entries=[];\\nfor(let i=0;i<sorted.length;){\\nconst k=sorted[i];\\nlet j=i+1;\\nwhile(j<sorted.length&&fullCompare(k,sorted[j])===0){\\nj+=1;}\\n\\nentries.push([k,BigInt(j-i)]);\\ni=j;}\\n\\nreturn makeCopyBag(entries);};\\n\\nharden(makeCopyBagFromElements);\\n\\n/* //////////////////////////// CopyMap ////////////////////////////////////////*/\\n\\n/* Moved to here so they can check that the copyMap's keys contains only keys*/\\n/* without creating an import cycle.*/\\n\\n/** @type {WeakSet<CopyMap>} */\\nconst copyMapMemo=new WeakSet();\\n\\n/**\\n * @param {any} m\\n * @param {Checker} check\\n * @returns {boolean}\\n */\\nconst checkCopyMap=(m,check)=>{\\nif(copyMapMemo.has(m)){\\nreturn true;}\\n\\nif(!(passStyleOf.passStyleOf(m)==='tagged'&&passStyleHelpers.getTag(m)==='copyMap')){\\nreturn check(false,index.redacted`Not a copyMap: ${m}`);}\\n\\nconst{payload}=m;\\nif(passStyleOf.passStyleOf(payload)!=='copyRecord'){\\nreturn check(false,index.redacted`A copyMap's payload must be a record: ${m}`);}\\n\\nconst{keys,values,...rest}=payload;\\nconst result=\\n(ownKeys(rest).length===0||\\ncheck(\\nfalse,\\nindex.redacted`A copyMap's payload must only have .keys and .values: ${m}`))&&\\n\\ncopySet.checkElements(keys,check)&&\\ncheckKey(keys,check)&&(\\npassStyleOf.passStyleOf(values)==='copyArray'||\\ncheck(false,index.redacted`A copyMap's .values must be a copyArray: ${m}`))&&(\\nkeys.length===values.length||\\ncheck(\\nfalse,\\nindex.redacted`A copyMap must have the same number of keys and values: ${m}`));\\n\\nif(result){\\ncopyMapMemo.add(m);}\\n\\nreturn result;};\\n\\nharden(checkCopyMap);\\n\\n/**\\n * @param {any} m\\n * @returns {m is CopyMap<Key, Passable>}\\n */\\nconst isCopyMap=(m)=>checkCopyMap(m,identChecker.identChecker);\\nharden(isCopyMap);\\n\\n/**\\n * @param {Passable} m\\n * @returns {asserts m is CopyMap<Key, Passable>}\\n */\\nconst assertCopyMap=(m)=>{\\ncheckCopyMap(m,passStyleHelpers.assertChecker);};\\n\\nharden(assertCopyMap);\\n\\n/**\\n * @template {Key} K\\n * @template {Passable} V\\n * @param {CopyMap<K,V>} m\\n * @returns {K[]}\\n */\\nconst getCopyMapKeys=(m)=>{\\nassertCopyMap(m);\\nreturn m.payload.keys;};\\n\\nharden(getCopyMapKeys);\\n\\n/**\\n * @template {Key} K\\n * @template {Passable} V\\n * @param {CopyMap<K,V>} m\\n * @returns {V[]}\\n */\\nconst getCopyMapValues=(m)=>{\\nassertCopyMap(m);\\nreturn m.payload.values;};\\n\\nharden(getCopyMapValues);\\n\\n/**\\n * Returns an array of a CopyMap's entries in storage order.\\n *\\n * @template {Key} K\\n * @template {Passable} V\\n * @param {CopyMap<K,V>} m\\n * @returns {Array<[K,V]>}\\n */\\nconst getCopyMapEntryArray=(m)=>{\\nassertCopyMap(m);\\nconst{\\npayload:{keys,values}}=\\nm;\\nreturn harden(keys.map((key,i)=>[key,values[i]]));};\\n\\nharden(getCopyMapEntryArray);\\n\\n/**\\n * @template {Key} K\\n * @template {Passable} V\\n * @param {CopyMap<K,V>} m\\n * @returns {Iterable<[K,V]>}\\n */\\nconst getCopyMapEntries=(m)=>{\\nassertCopyMap(m);\\nconst{\\npayload:{keys,values}}=\\nm;\\nconst{length}=/** @type {Array} */keys;\\nreturn makeFar.Far('CopyMap entries iterable',{\\n[Symbol.iterator]:()=>{\\nlet i=0;\\nreturn makeFar.Far('CopyMap entries iterator',{\\nnext:()=>{\\n/** @type {IteratorResult<[K,V],void>} */\\nlet result;\\nif(i<length){\\nresult=harden({done:false,value:[keys[i],values[i]]});\\ni+=1;\\nreturn result;}else\\n{\\nresult=harden({done:true,value:undefined});}\\n\\nreturn result;}});}});};\\n\\n\\n\\n\\n\\nharden(getCopyMapEntries);\\n\\n/**\\n * @template {Key} K\\n * @template {Passable} V\\n * @param {CopyMap<K,V>} m\\n * @param {(key: K, index: number) => boolean} fn\\n * @returns {boolean}\\n */\\nconst everyCopyMapKey=(m,fn)=>\\ngetCopyMapKeys(m).every((key,index)=>fn(key,index));\\nharden(everyCopyMapKey);\\n\\n/**\\n * @template {Key} K\\n * @template {Passable} V\\n * @param {CopyMap<K,V>} m\\n * @param {(value: V, index: number) => boolean} fn\\n * @returns {boolean}\\n */\\nconst everyCopyMapValue=(m,fn)=>\\ngetCopyMapValues(m).every((value,index)=>fn(value,index));\\nharden(everyCopyMapValue);\\n\\n/**\\n * @template {Key} K\\n * @template {Passable} V\\n * @param {CopyMap<K,V>} m\\n * @returns {CopySet<K>}\\n */\\nconst copyMapKeySet=(m)=>\\n/* A copyMap's keys are already in the internal form used by copySets.*/\\nmakeTagged.makeTagged('copySet',m.payload.keys);\\nharden(copyMapKeySet);\\n\\n/**\\n * @template {Key} K\\n * @template {Passable} V\\n * @param {Iterable<[K, V]>} entries\\n * @returns {CopyMap<K,V>}\\n */\\nconst makeCopyMap=(entries)=>{\\n/* This is weird, but reverse rank sorting the entries is a good first step*/\\n/* for getting the rank sorted keys together with the values*/\\n/* organized by those keys. Also, among values associated with*/\\n/* keys in the same equivalence class, those are rank sorted.*/\\n/* TODO This*/\\n/* could solve the copyMap cover issue explained in patternMatchers.js.*/\\n/* But only if we include this criteria in our validation of copyMaps,*/\\n/* which we currently do not.*/\\nconst sortedEntries=rankOrder.sortByRank(entries,rankOrder.compareAntiRank);\\nconst keys=sortedEntries.map(([k,_v])=>k);\\nconst values=sortedEntries.map(([_k,v])=>v);\\nconst result=makeTagged.makeTagged('copyMap',{keys,values});\\nassertCopyMap(result);\\nreturn result;};\\n\\nharden(makeCopyMap);\\n\\n/* //////////////////////// Keys Recur /////////////////////////////////////////*/\\n\\n/**\\n * @param {any} val\\n * @param {Checker} check\\n * @returns {boolean}\\n */\\nconst checkKeyInternal=(val,check)=>{\\nconst checkIt=(child)=>checkKey(child,check);\\n\\nconst passStyle=passStyleOf.passStyleOf(val);\\nswitch(passStyle){\\ncase'copyRecord':{\\n/* A copyRecord is a key iff all its children are keys*/\\nreturn Object.values(val).every(checkIt);}\\n\\ncase'copyArray':{\\n/* A copyArray is a key iff all its children are keys*/\\nreturn val.every(checkIt);}\\n\\ncase'tagged':{\\nconst tag=passStyleHelpers.getTag(val);\\nswitch(tag){\\ncase'copySet':{\\nreturn checkCopySet(val,check);}\\n\\ncase'copyBag':{\\nreturn checkCopyBag(val,check);}\\n\\ncase'copyMap':{\\nreturn(\\ncheckCopyMap(val,check)&&\\n/* For a copyMap to be a key, all its keys and values must*/\\n/* be keys. Keys already checked by `checkCopyMap` since*/\\n/* that's a copyMap requirement in general.*/\\neveryCopyMapValue(val,checkIt));}\\n\\n\\ndefault:{\\nreturn(\\ncheck!==identChecker.identChecker&&\\ncheck(false,index.redacted`A passable tagged ${index.quote(tag)} is not a key: ${val}`));}}}\\n\\n\\n\\n\\ncase'remotable':{\\n/* All remotables are keys.*/\\nreturn true;}\\n\\ncase'error':\\ncase'promise':{\\nreturn check(false,index.redacted`A ${index.quote(passStyle)} cannot be a key`);}\\n\\ndefault:{\\n/* Unexpected tags are just non-keys, but an unexpected passStyle*/\\n/* is always an error.*/\\nthrow index.throwRedacted`unexpected passStyle ${index.quote(passStyle)}: ${val}`;}}};exports.assertCopyBag=assertCopyBag;exports.assertCopyMap=assertCopyMap;exports.assertCopySet=assertCopySet;exports.assertKey=assertKey;exports.assertPrimitiveKey=assertPrimitiveKey;exports.assertScalarKey=assertScalarKey;exports.checkCopyBag=checkCopyBag;exports.checkCopyMap=checkCopyMap;exports.checkCopySet=checkCopySet;exports.checkKey=checkKey;exports.checkScalarKey=checkScalarKey;exports.copyMapKeySet=copyMapKeySet;exports.everyCopyBagEntry=everyCopyBagEntry;exports.everyCopyMapKey=everyCopyMapKey;exports.everyCopyMapValue=everyCopyMapValue;exports.everyCopySetKey=everyCopySetKey;exports.getCopyBagEntries=getCopyBagEntries;exports.getCopyMapEntries=getCopyMapEntries;exports.getCopyMapEntryArray=getCopyMapEntryArray;exports.getCopyMapKeys=getCopyMapKeys;exports.getCopyMapValues=getCopyMapValues;exports.getCopySetKeys=getCopySetKeys;exports.isCopyBag=isCopyBag;exports.isCopyMap=isCopyMap;exports.isCopySet=isCopySet;exports.isKey=isKey;exports.isPrimitiveKey=isPrimitiveKey;exports.isScalarKey=isScalarKey;exports.makeCopyBag=makeCopyBag;exports.makeCopyBagFromElements=makeCopyBagFromElements;exports.makeCopyMap=makeCopyMap;exports.makeCopySet=makeCopySet;\",\n \"node_modules/@endo/patterns/src/keys/compareKeys.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../../marshal/index.js');var index=require('../../../errors/index.js');var checkKey=require('./checkKey.js');var keycollectionOperators=require('./keycollection-operators.js');var rankOrder=require('../../../marshal/src/rankOrder.js');var passStyleOf=require('../../../pass-style/src/passStyleOf.js');var passStyleHelpers=require('../../../pass-style/src/passStyle-helpers.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nencodePassable=require('../../../marshal/src/encodePassable.js');/*/ <reference types=\\\"ses\\\"/>*/ /** @import {CopySet, Key, KeyCompare} from '../types.js' */ /**\\n * CopySet X is smaller than CopySet Y iff all of these conditions hold:\\n * 1. For every x in X, x is also in Y.\\n * 2. There is a y in Y that is not in X.\\n *\\n * X is equivalent to Y iff the condition 1 holds but condition 2 does not.\\n */\\nconst setCompare=keycollectionOperators.makeCompareCollection(\\n/** @type {<K extends Key>(s: CopySet<K>) => Array<[K, 1]>} */\\n(s)=>harden(checkKey.getCopySetKeys(s).map((key)=>[key,1])),\\n\\n0,\\nrankOrder.trivialComparator);\\n\\nharden(setCompare);\\n\\n/**\\n * CopyBag X is smaller than CopyBag Y iff all of these conditions hold\\n * (where `count(A, a)` is shorthand for the count associated with `a` in `A`):\\n * 1. For every x in X, x is also in Y and count(X, x) <= count(Y, x).\\n * 2. There is a y in Y such that y is not in X or count(X, y) < count(Y, y).\\n *\\n * X is equivalent to Y iff the condition 1 holds but condition 2 does not.\\n */\\nconst bagCompare=keycollectionOperators.makeCompareCollection(\\ncheckKey.getCopyBagEntries,\\n0n,\\nrankOrder.trivialComparator);\\n\\nharden(bagCompare);\\n\\n/* TODO The desired semantics for CopyMap comparison have not yet been decided.*/\\n/* See https://github.com/endojs/endo/pull/1737#pullrequestreview-1596595411*/\\n/* The below is a currently-unused extension of CopyBag semantics (i.e., absent*/\\n/* entries treated as present with a value that is smaller than everything).*/\\n/**\\n * A unique local value that is guaranteed to not exist in any inbound data\\n * structure (which would not be the case if we used `Symbol.for`).\\n */\\nconst ABSENT=Symbol('absent');\\n/**\\n * CopyMap X is smaller than CopyMap Y iff all of these conditions hold:\\n * 1. X and Y are both Keys (i.e., neither contains non-comparable data).\\n * 2. For every x in X, x is also in Y and X[x] is smaller than or equivalent to Y[x].\\n * 3. There is a y in Y such that y is not in X or X[y] is smaller than Y[y].\\n *\\n * X is equivalent to Y iff conditions 1 and 2 hold but condition 3 does not.\\n */\\n/* eslint-disable-next-line no-underscore-dangle*/\\nconst _mapCompare=keycollectionOperators.makeCompareCollection(\\ncheckKey.getCopyMapEntryArray,\\nABSENT,\\n(leftValue,rightValue)=>{\\nif(leftValue===ABSENT&&rightValue===ABSENT){\\nthrow index.throwRedacted`Internal: Unexpected absent entry pair`;}else\\nif(leftValue===ABSENT){\\nreturn-1;}else\\nif(rightValue===ABSENT){\\nreturn 1;}else\\n{\\n/* eslint-disable-next-line no-use-before-define*/\\nreturn compareKeys(leftValue,rightValue);}});\\n\\n\\n\\nharden(_mapCompare);\\n\\n/** @type {KeyCompare} */\\nconst compareKeys=(left,right)=>{\\ncheckKey.assertKey(left);\\ncheckKey.assertKey(right);\\nconst leftStyle=passStyleOf.passStyleOf(left);\\nconst rightStyle=passStyleOf.passStyleOf(right);\\nif(leftStyle!==rightStyle){\\n/* Different passStyles are incommensurate*/\\nreturn NaN;}\\n\\nswitch(leftStyle){\\ncase'undefined':\\ncase'null':\\ncase'boolean':\\ncase'bigint':\\ncase'string':\\ncase'symbol':{\\n/* for these, keys compare the same as rank*/\\nreturn rankOrder.compareRank(left,right);}\\n\\ncase'number':{\\nconst rankComp=rankOrder.compareRank(left,right);\\nif(rankComp===0){\\nreturn 0;}\\n\\nif(Number.isNaN(left)||Number.isNaN(right)){\\n/* NaN is equal to itself, but incommensurate with everything else*/\\nassert(!Number.isNaN(left)||!Number.isNaN(right));\\nreturn NaN;}\\n\\n/* Among non-NaN numbers, key order is the same as rank order. Note that*/\\n/* in both orders, `-0` is in the same equivalence class as `0`.*/\\nreturn rankComp;}\\n\\ncase'remotable':{\\nif(left===right){\\nreturn 0;}\\n\\n/* If two remotables are not identical, then as keys they are*/\\n/* incommensurate.*/\\nreturn NaN;}\\n\\ncase'copyArray':{\\n/* Lexicographic by key order. Rank order of arrays is lexicographic by*/\\n/* rank order.*/\\n/* Because the invariants above apply to the elements of the array,*/\\n/* they apply to the array as a whole.*/\\n/* @ts-expect-error narrowed*/\\nconst len=Math.min(left.length,right.length);\\nfor(let i=0;i<len;i+=1){\\n/* @ts-expect-error narrowed*/\\nconst result=compareKeys(left[i],right[i]);\\nif(result!==0){\\nreturn result;}}\\n\\n\\n/* If all matching elements are keyEQ, then according to their lengths.*/\\n/* Thus, if array X is a prefix of array Y, then X is smaller than Y.*/\\n/* @ts-expect-error narrowed*/\\nreturn rankOrder.compareRank(left.length,right.length);}\\n\\ncase'copyRecord':{\\n/* Pareto partial order comparison.*/\\n/* @ts-expect-error narrowed*/\\nconst leftNames=encodePassable.recordNames(left);\\n/* @ts-expect-error narrowed*/\\nconst rightNames=encodePassable.recordNames(right);\\n\\n/* eslint-disable-next-line no-use-before-define*/\\nif(!keyEQ(leftNames,rightNames)){\\n/* If they do not have exactly the same properties,*/\\n/* they are incommensurate.*/\\n/* Note that rank sorting of copyRecords groups all copyRecords with*/\\n/* the same keys together, enabling range searching over copyRecords*/\\n/* to avoid more irrelevant ones.*/\\nreturn NaN;}\\n\\n/* @ts-expect-error narrowed*/\\nconst leftValues=encodePassable.recordValues(left,leftNames);\\n/* @ts-expect-error narrowed*/\\nconst rightValues=encodePassable.recordValues(right,rightNames);\\n/* Presume that both copyRecords have the same key order*/\\n/* until encountering a property disproving that hypothesis.*/\\nlet result=0;\\nfor(let i=0;i<leftValues.length;i+=1){\\nconst comp=compareKeys(leftValues[i],rightValues[i]);\\nif(Number.isNaN(comp)){\\nreturn NaN;}\\n\\nif(result!==comp&&comp!==0){\\nif(result===0){\\nresult=comp;}else\\n{\\nassert(\\nresult===-1&&comp===1||result===1&&comp===-1);\\n\\nreturn NaN;}}}\\n\\n\\n\\n/* If copyRecord X is smaller than copyRecord Y, then they must have the*/\\n/* same property names and every value in X must be smaller or equal to*/\\n/* the corresponding value in Y (with at least one value smaller).*/\\n/* The rank order of X and Y is based on lexicographic rank order of*/\\n/* their values, as organized by reverse lexicographic order of their*/\\n/* property names.*/\\n/* Thus if compareKeys(X,Y) < 0 then compareRank(X,Y) < 0.*/\\nreturn result;}\\n\\ncase'tagged':{\\n/* @ts-expect-error narrowed*/\\nconst leftTag=passStyleHelpers.getTag(left);\\n/* @ts-expect-error narrowed*/\\nconst rightTag=passStyleHelpers.getTag(right);\\nif(leftTag!==rightTag){\\n/* different tags are incommensurate*/\\nreturn NaN;}\\n\\nswitch(leftTag){\\ncase'copySet':{\\n/* @ts-expect-error narrowed*/\\nreturn setCompare(left,right);}\\n\\ncase'copyBag':{\\n/* @ts-expect-error narrowed*/\\nreturn bagCompare(left,right);}\\n\\ncase'copyMap':{\\n/* TODO The desired semantics for CopyMap comparison have not yet been decided.*/\\n/* See https://github.com/endojs/endo/pull/1737#pullrequestreview-1596595411*/\\nthrow index.throwRedacted`Map comparison not yet implemented: ${left} vs ${right}`;}\\n\\ndefault:{\\nthrow index.throwRedacted`unexpected tag ${index.quote(leftTag)}: ${left}`;}}}\\n\\n\\n\\ndefault:{\\nthrow index.throwRedacted`unexpected passStyle ${index.quote(leftStyle)}: ${left}`;}}};\\n\\n\\n\\nharden(compareKeys);\\n\\nconst keyLT=(left,right)=>compareKeys(left,right)<0;\\nharden(keyLT);\\n\\nconst keyLTE=(left,right)=>compareKeys(left,right)<=0;\\nharden(keyLTE);\\n\\nconst keyEQ=(left,right)=>compareKeys(left,right)===0;\\nharden(keyEQ);\\n\\nconst keyGTE=(left,right)=>compareKeys(left,right)>=0;\\nharden(keyGTE);\\n\\nconst keyGT=(left,right)=>compareKeys(left,right)>0;\\nharden(keyGT);exports.bagCompare=bagCompare;exports.compareKeys=compareKeys;exports.keyEQ=keyEQ;exports.keyGT=keyGT;exports.keyGTE=keyGTE;exports.keyLT=keyLT;exports.keyLTE=keyLTE;exports.setCompare=setCompare;\",\n \"node_modules/@endo/patterns/src/keys/copyBag.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../../marshal/index.js');var index=require('../../../errors/index.js');var rankOrder=require('../../../marshal/src/rankOrder.js');var passStyleHelpers=require('../../../pass-style/src/passStyle-helpers.js');var passStyleOf=require('../../../pass-style/src/passStyleOf.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nmakeTagged=require('../../../pass-style/src/makeTagged.js');/**\\n * @import {Passable} from '@endo/pass-style'\\n * @import {Checker} from '@endo/marshal'\\n * @import {CopyBag, Key, FullCompare} from '../types.js'\\n */ /**\\n * @template {Key} T\\n * @param {[T,bigint][]} bagEntries\\n * @param {FullCompare | undefined} fullCompare If provided and `bagEntries` is already\\n * known to be sorted by this `fullCompare`, then we should get a memo hit\\n * rather than a resorting. However, currently, we still enumerate the entire\\n * array each time.\\n *\\n * TODO: If doing this reduntantly turns out to be expensive, we\\n * could memoize this no-duplicate-keys finding as well, independent\\n * of the `fullOrder` use to reach this finding.\\n * @param {Checker} check\\n * @returns {boolean}\\n */const checkNoDuplicateKeys=(bagEntries,fullCompare,check)=>{/* This fullOrder contains history dependent state. It is specific*/ /* to this one call and does not survive it.*/ /* TODO Once all our tooling is ready for `&&=`, the following*/\\n/* line should be rewritten using it.*/\\nfullCompare=fullCompare||rankOrder.makeFullOrderComparatorKit().antiComparator;\\n\\n/* Since the key is more significant than the value (the count),*/\\n/* sorting by fullOrder is guaranteed to make duplicate keys*/\\n/* adjacent independent of their counts.*/\\nbagEntries=rankOrder.sortByRank(bagEntries,fullCompare);\\nconst{length}=bagEntries;\\nfor(let i=1;i<length;i+=1){\\nconst k0=bagEntries[i-1][0];\\nconst k1=bagEntries[i][0];\\nif(fullCompare(k0,k1)===0){\\nreturn check(false,index.redacted`value has duplicate keys: ${k0}`);}}\\n\\n\\nreturn true;};\\n\\n\\n/**\\n * @template {Key} T\\n * @param {[T,bigint][]} bagEntries\\n * @param {FullCompare} [fullCompare]\\n * @returns {void}\\n */\\nconst assertNoDuplicateKeys=(bagEntries,fullCompare=undefined)=>{\\ncheckNoDuplicateKeys(bagEntries,fullCompare,passStyleHelpers.assertChecker);};\\n\\n\\n/**\\n * @param {[Passable,bigint][]} bagEntries\\n * @param {Checker} check\\n * @returns {boolean}\\n */\\nconst checkBagEntries=(bagEntries,check)=>{\\nif(passStyleOf.passStyleOf(bagEntries)!=='copyArray'){\\nreturn check(\\nfalse,\\nindex.redacted`The entries of a copyBag must be a copyArray: ${bagEntries}`);}\\n\\n\\nif(!rankOrder.isRankSorted(bagEntries,rankOrder.compareAntiRank)){\\nreturn check(\\nfalse,\\nindex.redacted`The entries of a copyBag must be sorted in reverse rank order: ${bagEntries}`);}\\n\\n\\nfor(const entry of bagEntries){\\nif(\\npassStyleOf.passStyleOf(entry)!=='copyArray'||\\nentry.length!==2||\\ntypeof entry[1]!=='bigint')\\n{\\nreturn check(\\nfalse,\\nindex.redacted`Each entry of a copyBag must be pair of a key and a bigint representing a count: ${entry}`);}\\n\\n\\nif(entry[1]<1){\\nreturn check(\\nfalse,\\nindex.redacted`Each entry of a copyBag must have a positive count: ${entry}`);}}\\n\\n\\n\\n/* @ts-expect-error XXX Key types*/\\nreturn checkNoDuplicateKeys(bagEntries,undefined,check);};\\n\\nharden(checkBagEntries);\\n\\n/* eslint-disable-next-line jsdoc/require-returns-check -- doesn't understand asserts*/\\n/**\\n * @param {[Passable,bigint][]} bagEntries\\n * @returns {asserts bagEntries is [Passable,bigint][]}\\n */\\nconst assertBagEntries=(bagEntries)=>{\\ncheckBagEntries(bagEntries,passStyleHelpers.assertChecker);};\\n\\nharden(assertBagEntries);\\n\\n/**\\n * @template {Key} K\\n * @param {Iterable<[K, bigint]>} bagEntriesList\\n */\\nconst coerceToBagEntries=(bagEntriesList)=>{\\nconst bagEntries=rankOrder.sortByRank(bagEntriesList,rankOrder.compareAntiRank);\\nassertBagEntries(bagEntries);\\nreturn bagEntries;};\\n\\nharden(coerceToBagEntries);\\n\\n/**\\n * @template {Key} K\\n * @param {Iterable<[K, bigint]>} bagEntryIter\\n * @returns {CopyBag<K>}\\n */\\nconst makeBagOfEntries=(bagEntryIter)=>\\nmakeTagged.makeTagged('copyBag',coerceToBagEntries(bagEntryIter));\\nharden(makeBagOfEntries);exports.assertBagEntries=assertBagEntries;exports.assertNoDuplicateKeys=assertNoDuplicateKeys;exports.checkBagEntries=checkBagEntries;exports.coerceToBagEntries=coerceToBagEntries;exports.makeBagOfEntries=makeBagOfEntries;\",\n \"node_modules/@endo/patterns/src/keys/copySet.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../../marshal/index.js');var index=require('../../../errors/index.js');var rankOrder=require('../../../marshal/src/rankOrder.js');var passStyleHelpers=require('../../../pass-style/src/passStyle-helpers.js');var passStyleOf=require('../../../pass-style/src/passStyleOf.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nmakeTagged=require('../../../pass-style/src/makeTagged.js');/**\\n * @import {Passable} from '@endo/pass-style'\\n * @import {Checker} from '@endo/marshal'\\n * @import {CopySet, FullCompare, Key} from '../types.js'\\n */ /**\\n * @template {Passable} T\\n * @param {T[]} elements\\n * @param {FullCompare | undefined} fullCompare If provided and `elements` is already known\\n * to be sorted by this `fullCompare`, then we should get a memo hit rather\\n * than a resorting. However, currently, we still enumerate the entire array\\n * each time.\\n *\\n * TODO: If doing this reduntantly turns out to be expensive, we\\n * could memoize this no-duplicate finding as well, independent\\n * of the `fullOrder` use to reach this finding.\\n * @param {Checker} check\\n * @returns {boolean}\\n */const checkNoDuplicates=(elements,fullCompare,check)=>{/* This fullOrder contains history dependent state. It is specific*/ /* to this one call and does not survive it.*/ /* TODO Once all our tooling is ready for `&&=`, the following*/\\n/* line should be rewritten using it.*/\\nfullCompare=fullCompare||rankOrder.makeFullOrderComparatorKit().antiComparator;\\n\\nelements=rankOrder.sortByRank(elements,fullCompare);\\nconst{length}=elements;\\nfor(let i=1;i<length;i+=1){\\nconst k0=elements[i-1];\\nconst k1=elements[i];\\nif(fullCompare(k0,k1)===0){\\nreturn check(false,index.redacted`value has duplicate keys: ${k0}`);}}\\n\\n\\nreturn true;};\\n\\n\\n/**\\n * @template {Passable} T\\n * @param {T[]} elements\\n * @param {FullCompare} [fullCompare]\\n * @returns {void}\\n */\\nconst assertNoDuplicates=(elements,fullCompare=undefined)=>{\\ncheckNoDuplicates(elements,fullCompare,passStyleHelpers.assertChecker);};\\n\\n\\n/**\\n * @param {Passable[]} elements\\n * @param {Checker} check\\n * @returns {boolean}\\n */\\nconst checkElements=(elements,check)=>{\\nif(passStyleOf.passStyleOf(elements)!=='copyArray'){\\nreturn check(\\nfalse,\\nindex.redacted`The keys of a copySet or copyMap must be a copyArray: ${elements}`);}\\n\\n\\nif(!rankOrder.isRankSorted(elements,rankOrder.compareAntiRank)){\\nreturn check(\\nfalse,\\nindex.redacted`The keys of a copySet or copyMap must be sorted in reverse rank order: ${elements}`);}\\n\\n\\nreturn checkNoDuplicates(elements,undefined,check);};\\n\\nharden(checkElements);\\n\\nconst assertElements=(elements)=>{\\ncheckElements(elements,passStyleHelpers.assertChecker);};\\n\\nharden(assertElements);\\n\\n/**\\n * @template {Key} K\\n * @param {Iterable<K>} elementsList\\n */\\nconst coerceToElements=(elementsList)=>{\\nconst elements=rankOrder.sortByRank(elementsList,rankOrder.compareAntiRank);\\nassertElements(elements);\\nreturn elements;};\\n\\nharden(coerceToElements);\\n\\n/**\\n * @template {Key} K\\n * @param {Iterable<K>} elementIter\\n * @returns {CopySet<K>}\\n */\\nconst makeSetOfElements=(elementIter)=>\\nmakeTagged.makeTagged('copySet',coerceToElements(elementIter));\\nharden(makeSetOfElements);exports.assertElements=assertElements;exports.assertNoDuplicates=assertNoDuplicates;exports.checkElements=checkElements;exports.coerceToElements=coerceToElements;exports.makeSetOfElements=makeSetOfElements;\",\n \"node_modules/@endo/patterns/src/keys/keycollection-operators.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../../marshal/index.js');var makeIterator=require('../../../common/make-iterator.js');var makeArrayIterator=require('../../../common/make-array-iterator.js');var index=require('../../../errors/index.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nrankOrder=require('../../../marshal/src/rankOrder.js');/* @ts-check*/ /**\\n * Refines a sequence of entries that is already sorted over its keys by the\\n * `rankCompare` preorder, where there may be internal runs tied for the same\\n * rank, into an iterable that resolves those ties using `fullCompare`.\\n *\\n * @template [V=unknown]\\n * @param {Array<[Key, V]>} entries\\n * @param {RankCompare} rankCompare\\n * @param {FullCompare} fullCompare\\n * @returns {IterableIterator<[Key, V]>}\\n */\\nconst generateFullSortedEntries=(entries,rankCompare,fullCompare)=>{\\n/* @ts-expect-error XXX Key types*/\\nrankOrder.assertRankSorted(entries,rankCompare);\\nconst{length}=entries;\\nlet i=0;\\nlet sameRankIterator;\\nreturn makeIterator.makeIterator(()=>{\\nif(sameRankIterator){\\nconst result=sameRankIterator.next();\\nif(!result.done){\\nreturn result;}\\n\\nsameRankIterator=undefined;}\\n\\nif(i<length){\\nconst entry=entries[i];\\n/* Look ahead for same-rank ties.*/\\nlet j=i+1;\\nwhile(j<length&&rankCompare(entry[0],entries[j][0])===0){\\nj+=1;}\\n\\nif(j===i+1){\\n/* No ties found.*/\\ni=j;\\nreturn harden({done:false,value:entry});}\\n\\nconst ties=entries.slice(i,j);\\ni=j;\\n\\n/* Sort the ties by `fullCompare`, enforce key uniqueness, and delegate to*/\\n/* a sub-iterator.*/\\n/* @ts-expect-error XXX Key types*/\\nconst sortedTies=rankOrder.sortByRank(ties,fullCompare);\\nfor(let k=1;k<sortedTies.length;k+=1){\\n/* @ts-expect-error XXX Key types*/\\nconst[key0]=sortedTies[k-1];\\nconst[key1]=sortedTies[k];\\nMath.sign(fullCompare(key0,key1))||\\nindex.throwRedacted`Duplicate entry key: ${key0}`;}\\n\\nsameRankIterator=makeArrayIterator.makeArrayIterator(sortedTies);\\nreturn sameRankIterator.next();}\\n\\nreturn harden({done:true,value:undefined});});};\\n\\n\\nharden(generateFullSortedEntries);\\n\\n/**\\n * Returns an iterator that merges reverse-rank-sorted [key, value] entries of\\n * two KeyCollections into a reverse-full-sorted [key, value1, value2] entries\\n * by the key they have in common, representing the value for an absent entry in\\n * either collection as `absentValue`.\\n *\\n * @template [C=KeyCollection]\\n * @template [V=unknown]\\n * @param {C} c1\\n * @param {C} c2\\n * @param {(collection: C) => Array<[Key, V]>} getEntries\\n * @param {any} absentValue\\n * @returns {IterableIterator<[Key, V | absentValue, V | absentValue]>}\\n */\\nconst generateCollectionPairEntries=(\\nc1,\\nc2,\\ngetEntries,\\nabsentValue)=>\\n{\\nconst e1=getEntries(c1);\\nconst e2=getEntries(c2);\\n\\n/* Establish a history-dependent comparison scoped to the active invocation*/\\n/* and use it to map reverse-preordered entries into an iterator with a*/\\n/* narrower total order.*/\\nconst fullCompare=rankOrder.makeFullOrderComparatorKit().antiComparator;\\nconst x=generateFullSortedEntries(e1,rankOrder.compareAntiRank,fullCompare);\\nconst y=generateFullSortedEntries(e2,rankOrder.compareAntiRank,fullCompare);\\n\\n/* Maintain a single-result { done, key, value } buffer for each iterator*/\\n/* so they can be merged.*/\\nlet xDone;\\nlet xKey;\\nlet xValue;\\nlet yDone;\\nlet yKey;\\nlet yValue;\\nconst nonEntry=[undefined,undefined];\\nconst nextX=()=>{\\n!xDone||index.throwRedacted`Internal: nextX must not be called once done`;\\nconst result=xValue;\\n({done:xDone,value:[xKey,xValue]=nonEntry}=x.next());\\nreturn result;};\\n\\nnextX();\\nconst nextY=()=>{\\n!yDone||index.throwRedacted`Internal: nextY must not be called once done`;\\nconst result=yValue;\\n({done:yDone,value:[yKey,yValue]=nonEntry}=y.next());\\nreturn result;};\\n\\nnextY();\\nreturn makeIterator.makeIterator(()=>{\\nlet done=false;\\n/** @type {[Key, V | absentValue, V | absentValue]} */\\nlet value;\\nif(xDone&&yDone){\\ndone=true;\\nvalue=[undefined,absentValue,absentValue];}else\\nif(xDone){\\nvalue=[yKey,absentValue,nextY()];}else\\nif(yDone){\\nvalue=[xKey,nextX(),absentValue];}else\\n{\\n/* Compare the keys to determine if we should return a merged result*/\\n/* or a one-sided result.*/\\nconst comp=fullCompare(xKey,yKey);\\nif(comp===0){\\nvalue=[xKey,nextX(),nextY()];}else\\nif(comp<0){\\nvalue=[xKey,nextX(),absentValue];}else\\nif(comp>0){\\nvalue=[yKey,absentValue,nextY()];}else\\n{\\nthrow index.throwRedacted`Unexpected key comparison ${index.quote(comp)} for ${xKey} vs ${yKey}`;}}\\n\\n\\nreturn harden({done,value});});};\\n\\n\\nharden(generateCollectionPairEntries);\\n\\n/**\\n * Returns a function for comparing two KeyCollections of the same type using\\n * the provided entries factory and same-key entry value comparator (where the\\n * value for an absent entry in one collection is `absentValue`).\\n *\\n * If the corresponding entries for any single key are incomparable or the\\n * comparison result has the opposite sign of the result for a different key,\\n * then the KeyCollections are incomparable. Otherwise, the collections compare\\n * by the result of any non-equal entry comparison, or compare equal if there is\\n * no non-equal entry comparison result.\\n * For example, given CopyBags X and Y and a value comparator that goes by count\\n * (defaulting absent keys to a count of 0), X is smaller than Y (`result < 0`)\\n * iff there are no keys in X that are either absent from Y\\n * (`compareValues(xCount, absentValue) > 0`) or present in Y with a lower count\\n * (`compareValues(xCount, yCount) > 0`) AND there is at least one key in Y that\\n * is either absent from X (`compareValues(absentValue, yCount) < 0`) or present\\n * with a lower count (`compareValues(xCount, yCount) < 0`).\\n *\\n * This can be generalized to virtual collections in the future by replacing\\n * `getEntries => Array` with `generateEntries => IterableIterator`.\\n *\\n * @template [C=KeyCollection]\\n * @template [V=unknown]\\n * @param {(collection: C) => Array<[Key, V]>} getEntries\\n * @param {any} absentValue\\n * @param {KeyCompare} compareValues\\n * @returns {(left: C, right: C) => KeyComparison}\\n */\\nconst makeCompareCollection=(getEntries,absentValue,compareValues)=>\\nharden((left,right)=>{\\nconst merged=generateCollectionPairEntries(\\nleft,\\nright,\\ngetEntries,\\nabsentValue);\\n\\nlet leftIsBigger=false;\\nlet rightIsBigger=false;\\nfor(const[_key,leftValue,rightValue]of merged){\\nconst comp=compareValues(leftValue,rightValue);\\nif(comp===0){\\n/* eslint-disable-next-line no-continue*/\\ncontinue;}else\\nif(comp<0){\\n/* Based on this key, left < right.*/\\nrightIsBigger=true;}else\\nif(comp>0){\\n/* Based on this key, left > right.*/\\nleftIsBigger=true;}else\\n{\\nNumber.isNaN(comp)||\\n/* prettier-ignore*/\\nindex.throwRedacted`Unexpected value comparison ${index.quote(comp)} for ${leftValue} vs ${rightValue}`;\\nreturn NaN;}\\n\\nif(leftIsBigger&&rightIsBigger){\\nreturn NaN;}}\\n\\n\\n/* eslint-disable-next-line no-nested-ternary*/\\nreturn leftIsBigger?1:rightIsBigger?-1:0;});\\n\\nharden(makeCompareCollection);exports.generateCollectionPairEntries=generateCollectionPairEntries;exports.makeCompareCollection=makeCompareCollection;\",\n \"node_modules/@endo/patterns/src/keys/merge-bag-operators.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../../marshal/index.js');var index=require('../../../errors/index.js');var copyBag=require('./copyBag.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nrankOrder=require('../../../marshal/src/rankOrder.js');/**\\n * @import {Passable} from '@endo/pass-style';\\n * @import {RankCompare} from '@endo/marshal'\\n * @import {FullCompare, Key} from '../types.js'\\n */ /* Based on merge-set-operators.js, but altered for the bag representation.*/ /* TODO share more code with that file and keycollection-operators.js.*/ /**\\n * Asserts that `bagEntries` is already rank sorted by `rankCompare`, where\\n * there\\n * may be contiguous regions of bagEntries whose keys are tied for the same\\n * rank.\\n * Returns an iterable that will enumerate all the bagEntries in order\\n * according to `fullOrder`, which should differ from `rankOrder` only\\n * by being more precise.\\n *\\n * This should be equivalent to resorting the entire `bagEntries` array\\n * according\\n * to `fullOrder`. However, it optimizes for the case where these contiguous\\n * runs that need to be resorted are either absent or small.\\n *\\n * @template {Key} T\\n * @param {[T,bigint][]} bagEntries\\n * @param {RankCompare} rankCompare\\n * @param {FullCompare} fullCompare\\n * @returns {Iterable<[T,bigint]>}\\n */const bagWindowResort=(bagEntries,rankCompare,fullCompare)=>{rankOrder.assertRankSorted(bagEntries,rankCompare);const{length}=bagEntries;let i=0;\\nlet optInnerIterator;\\nreturn harden({\\n[Symbol.iterator]:()=>\\nharden({\\nnext:()=>{\\nif(optInnerIterator){\\nconst result=optInnerIterator.next();\\nif(result.done){\\noptInnerIterator=undefined;\\n/* fall through*/}else\\n{\\nreturn result;}}\\n\\n\\nif(i<length){\\nconst entry=bagEntries[i];\\nlet j=i+1;\\nwhile(\\nj<length&&\\nrankCompare(entry[0],bagEntries[j][0])===0)\\n{\\nj+=1;}\\n\\nif(j===i+1){\\ni=j;\\nreturn harden({done:false,value:entry});}\\n\\nconst similarRun=bagEntries.slice(i,j);\\ni=j;\\nconst resorted=rankOrder.sortByRank(similarRun,fullCompare);\\n/* Providing the same `fullCompare` should cause a memo hit*/\\n/* within `assertNoDuplicates` enabling it to avoid a*/\\n/* redundant resorting.*/\\ncopyBag.assertNoDuplicateKeys(resorted,fullCompare);\\n/* This is the raw JS array iterator whose `.next()` method*/\\n/* does not harden the IteratorResult, in violation of our*/\\n/* conventions. Fixing this is expensive and I'm confident the*/\\n/* unfrozen value does not escape this file, so I'm leaving this*/\\n/* as is.*/\\noptInnerIterator=resorted[Symbol.iterator]();\\nreturn optInnerIterator.next();}else\\n{\\nreturn harden({done:true,value:[null,0n]});}}})});};\\n\\n\\n\\n\\n\\n\\n/**\\n * Returns an iterable whose iteration results are [key, xCount, yCount] tuples\\n * representing the next key in the local full order, as well as how many\\n * times it occurred in the x input iterator and the y input iterator.\\n *\\n * For sets, these counts are always 0 or 1, but this representation\\n * generalizes nicely for bags.\\n *\\n * @template {Key} T\\n * @param {[T,bigint][]} xbagEntries\\n * @param {[T,bigint][]} ybagEntries\\n * @returns {Iterable<[T,bigint,bigint]>}\\n */\\nconst merge=(xbagEntries,ybagEntries)=>{\\n/* This fullOrder contains history dependent state. It is specific*/\\n/* to this one `merge` call and does not survive it.*/\\nconst fullCompare=rankOrder.makeFullOrderComparatorKit().antiComparator;\\n\\nconst xs=bagWindowResort(xbagEntries,rankOrder.compareAntiRank,fullCompare);\\nconst ys=bagWindowResort(ybagEntries,rankOrder.compareAntiRank,fullCompare);\\nreturn harden({\\n[Symbol.iterator]:()=>{\\n/* These six `let` variables are buffering one ahead from the underlying*/\\n/* iterators. Each iteration reports one or the other or both, and*/\\n/* then refills the buffers of those it advanced.*/\\n/** @type {T} */\\nlet x;\\nlet xc;\\nlet xDone;\\n/** @type {T} */\\nlet y;\\nlet yc;\\nlet yDone;\\n\\nconst xi=xs[Symbol.iterator]();\\nconst nextX=()=>{\\n!xDone||index.throwRedacted`Internal: nextX should not be called once done`;\\n({\\ndone:xDone,\\nvalue:[x,xc]}=\\nxi.next());};\\n\\nnextX();\\n\\nconst yi=ys[Symbol.iterator]();\\nconst nextY=()=>{\\n!yDone||index.throwRedacted`Internal: nextY should not be called once done`;\\n({\\ndone:yDone,\\nvalue:[y,yc]}=\\nyi.next());};\\n\\nnextY();\\n\\nreturn harden({\\nnext:()=>{\\n/** @type {boolean} */\\nlet done=false;\\n/** @type {[T,bigint,bigint]} */\\nlet value;\\nif(xDone&&yDone){\\ndone=true;\\n/* @ts-expect-error Because the terminating value does not matter*/\\nvalue=[null,0n,0n];}else\\nif(xDone){\\n/* only ys are left*/\\nvalue=[y,0n,yc];\\nnextY();}else\\nif(yDone){\\n/* only xs are left*/\\nvalue=[x,xc,0n];\\nnextX();}else\\n{\\nconst comp=fullCompare(x,y);\\nif(comp===0){\\n/* x and y are equivalent, so report both*/\\nvalue=[x,xc,yc];\\nnextX();\\nnextY();}else\\nif(comp<0){\\n/* x is earlier, so report it*/\\nvalue=[x,xc,0n];\\nnextX();}else\\n{\\n/* y is earlier, so report it*/\\ncomp>0||index.throwRedacted`Internal: Unexpected comp ${index.quote(comp)}`;\\nvalue=[y,0n,yc];\\nnextY();}}\\n\\n\\nreturn harden({done,value});}});}});};\\n\\n\\n\\n\\n\\nharden(merge);\\n\\n/* We should be able to use this for iterIsSuperset as well.*/\\n/* The generalization is free.*/\\n/**\\n * @template T\\n * @param {Iterable<[T,bigint,bigint]>} xyi\\n * @returns {boolean}\\n */\\nconst bagIterIsSuperbag=(xyi)=>{\\nfor(const[_m,xc,yc]of xyi){\\nif(xc<yc){\\n/* something in y is not in x, so x is not a superbag of y*/\\nreturn false;}}\\n\\n\\nreturn true;};\\n\\n\\n/* We should be able to use this for iterIsDisjoint as well.*/\\n/* The code is identical.*/\\n/**\\n * @template T\\n * @param {Iterable<[T,bigint,bigint]>} xyi\\n * @returns {boolean}\\n */\\nconst bagIterIsDisjoint=(xyi)=>{\\nfor(const[_m,xc,yc]of xyi){\\nif(xc>=1n&&yc>=1n){\\n/* Something in both, so not disjoint*/\\nreturn false;}}\\n\\n\\nreturn true;};\\n\\n\\n/**\\n * @template T\\n * @param {[T,bigint,bigint][]} xyi\\n * @returns {[T,bigint][]}\\n */\\nconst bagIterUnion=(xyi)=>{\\n/** @type {[T,bigint][]} */\\nconst result=[];\\nfor(const[m,xc,yc]of xyi){\\nresult.push([m,xc+yc]);}\\n\\nreturn result;};\\n\\n\\n/**\\n * @template T\\n * @param {Iterable<[T,bigint,bigint]>} xyi\\n * @returns {[T,bigint][]}\\n */\\nconst bagIterIntersection=(xyi)=>{\\n/** @type {[T,bigint][]} */\\nconst result=[];\\nfor(const[m,xc,yc]of xyi){\\nconst mc=xc<=yc?xc:yc;\\nresult.push([m,mc]);}\\n\\nreturn result;};\\n\\n\\n/**\\n * @template T\\n * @param {Iterable<[T,bigint,bigint]>} xyi\\n * @returns {[T,bigint][]}\\n */\\nconst bagIterDisjointSubtract=(xyi)=>{\\n/** @type {[T,bigint][]} */\\nconst result=[];\\nfor(const[m,xc,yc]of xyi){\\nconst mc=xc-yc;\\nmc>=0n||index.throwRedacted`right element ${m} was not in left`;\\nif(mc>=1n){\\n/* the x was not in y*/\\nresult.push([m,mc]);}}\\n\\n\\nreturn result;};\\n\\n\\nconst mergeify=(bagIterOp)=>(xbagEntries,ybagEntries)=>\\nbagIterOp(merge(xbagEntries,ybagEntries));\\n\\nconst bagEntriesIsSuperbag=mergeify(bagIterIsSuperbag);\\nconst bagEntriesIsDisjoint=mergeify(bagIterIsDisjoint);\\nconst bagEntriesUnion=mergeify(bagIterUnion);\\nconst bagEntriesIntersection=mergeify(bagIterIntersection);\\nconst bagEntriesDisjointSubtract=mergeify(bagIterDisjointSubtract);\\n\\nconst rawBagify=(bagEntriesOp)=>(xbag,ybag)=>\\nbagEntriesOp(xbag.payload,ybag.payload);\\n\\nconst bagify=(bagEntriesOp)=>(xbag,ybag)=>\\ncopyBag.makeBagOfEntries(bagEntriesOp(xbag.payload,ybag.payload));\\n\\nconst bagIsSuperbag=rawBagify(bagEntriesIsSuperbag);\\nconst bagIsDisjoint=rawBagify(bagEntriesIsDisjoint);\\nconst bagUnion=bagify(bagEntriesUnion);\\nconst bagIntersection=bagify(bagEntriesIntersection);\\nconst bagDisjointSubtract=bagify(bagEntriesDisjointSubtract);exports.bagDisjointSubtract=bagDisjointSubtract;exports.bagIntersection=bagIntersection;exports.bagIsDisjoint=bagIsDisjoint;exports.bagIsSuperbag=bagIsSuperbag;exports.bagUnion=bagUnion;\",\n \"node_modules/@endo/patterns/src/keys/merge-set-operators.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../../marshal/index.js');var index=require('../../../errors/index.js');var copySet=require('./copySet.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nrankOrder=require('../../../marshal/src/rankOrder.js');/**\\n * @import {Passable} from '@endo/pass-style';\\n * @import {RankCompare} from '@endo/marshal'\\n * @import {FullCompare, KeyComparison} from '../types.js'\\n */ /* TODO share more code with keycollection-operators.js.*/ /**\\n * Asserts that `elements` is already rank sorted by `rankCompare`, where there\\n * may be contiguous regions of elements tied for the same rank.\\n * Returns an iterable that will enumerate all the elements in order\\n * according to `fullOrder`, which should differ from `rankOrder` only\\n * by being more precise.\\n *\\n * This should be equivalent to resorting the entire `elements` array according\\n * to `fullOrder`. However, it optimizes for the case where these contiguous\\n * runs that need to be resorted are either absent or small.\\n *\\n * @template {Passable} T\\n * @param {T[]} elements\\n * @param {RankCompare} rankCompare\\n * @param {FullCompare} fullCompare\\n * @returns {Iterable<T>}\\n */const windowResort=(elements,rankCompare,fullCompare)=>{rankOrder.assertRankSorted(elements,rankCompare);const{length}=elements;let i=0;\\nlet optInnerIterator;\\nreturn harden({\\n[Symbol.iterator]:()=>\\nharden({\\nnext:()=>{\\nif(optInnerIterator){\\nconst result=optInnerIterator.next();\\nif(result.done){\\noptInnerIterator=undefined;\\n/* fall through*/}else\\n{\\nreturn result;}}\\n\\n\\nif(i<length){\\nconst value=elements[i];\\nlet j=i+1;\\nwhile(j<length&&rankCompare(value,elements[j])===0){\\nj+=1;}\\n\\nif(j===i+1){\\ni=j;\\nreturn harden({done:false,value});}\\n\\nconst similarRun=elements.slice(i,j);\\ni=j;\\nconst resorted=rankOrder.sortByRank(similarRun,fullCompare);\\n/* Providing the same `fullCompare` should cause a memo hit*/\\n/* within `assertNoDuplicates` enabling it to avoid a*/\\n/* redundant resorting.*/\\ncopySet.assertNoDuplicates(resorted,fullCompare);\\n/* This is the raw JS array iterator whose `.next()` method*/\\n/* does not harden the IteratorResult, in violation of our*/\\n/* conventions. Fixing this is expensive and I'm confident the*/\\n/* unfrozen value does not escape this file, so I'm leaving this*/\\n/* as is.*/\\noptInnerIterator=resorted[Symbol.iterator]();\\nreturn optInnerIterator.next();}else\\n{\\nreturn harden({done:true,value:null});}}})});};\\n\\n\\n\\n\\n\\n\\n/**\\n * Returns an iterable whose iteration results are [key, xCount, yCount] tuples\\n * representing the next key in the local full order, as well as how many\\n * times it occurred in the x input iterator and the y input iterator.\\n *\\n * For sets, these counts are always 0 or 1, but this representation\\n * generalizes nicely for bags.\\n *\\n * @template {Passable} T\\n * @param {T[]} xelements\\n * @param {T[]} yelements\\n * @returns {Iterable<[T,bigint,bigint]>}\\n */\\nconst merge=(xelements,yelements)=>{\\n/* This fullOrder contains history dependent state. It is specific*/\\n/* to this one `merge` call and does not survive it.*/\\nconst fullCompare=rankOrder.makeFullOrderComparatorKit().antiComparator;\\n\\nconst xs=windowResort(xelements,rankOrder.compareAntiRank,fullCompare);\\nconst ys=windowResort(yelements,rankOrder.compareAntiRank,fullCompare);\\nreturn harden({\\n[Symbol.iterator]:()=>{\\n/* These four `let` variables are buffering one ahead from the underlying*/\\n/* iterators. Each iteration reports one or the other or both, and*/\\n/* then refills the buffers of those it advanced.*/\\n/** @type {T} */\\nlet x;\\nlet xDone;\\n/** @type {T} */\\nlet y;\\nlet yDone;\\n\\nconst xi=xs[Symbol.iterator]();\\nconst nextX=()=>{\\n!xDone||index.throwRedacted`Internal: nextX should not be called once done`;\\n({done:xDone,value:x}=xi.next());};\\n\\nnextX();\\n\\nconst yi=ys[Symbol.iterator]();\\nconst nextY=()=>{\\n!yDone||index.throwRedacted`Internal: nextY should not be called once done`;\\n({done:yDone,value:y}=yi.next());};\\n\\nnextY();\\n\\nreturn harden({\\nnext:()=>{\\n/** @type {boolean} */\\nlet done=false;\\n/** @type {[T,bigint,bigint]} */\\nlet value;\\nif(xDone&&yDone){\\ndone=true;\\n/* @ts-expect-error Because the terminating value does not matter*/\\nvalue=[null,0n,0n];}else\\nif(xDone){\\n/* only ys are left*/\\nvalue=[y,0n,1n];\\nnextY();}else\\nif(yDone){\\n/* only xs are left*/\\nvalue=[x,1n,0n];\\nnextX();}else\\n{\\nconst comp=fullCompare(x,y);\\nif(comp===0){\\n/* x and y are equivalent, so report both*/\\nvalue=[x,1n,1n];\\nnextX();\\nnextY();}else\\nif(comp<0){\\n/* x is earlier, so report it*/\\nvalue=[x,1n,0n];\\nnextX();}else\\n{\\n/* y is earlier, so report it*/\\ncomp>0||index.throwRedacted`Internal: Unexpected comp ${index.quote(comp)}`;\\nvalue=[y,0n,1n];\\nnextY();}}\\n\\n\\nreturn harden({done,value});}});}});};\\n\\n\\n\\n\\n\\nharden(merge);\\n\\nconst iterIsSuperset=(xyi)=>{\\nfor(const[_m,xc,_yc]of xyi){\\nif(xc===0n){\\n/* something in y is not in x, so x is not a superset of y*/\\nreturn false;}}\\n\\n\\nreturn true;};\\n\\n\\n/**\\n * @template T\\n * @param {Iterable<[T,bigint,bigint]>} xyi\\n * @returns {boolean}\\n */\\nconst iterIsDisjoint=(xyi)=>{\\nfor(const[_m,xc,yc]of xyi){\\nif(xc>=1n&&yc>=1n){\\n/* Something in both, so not disjoint*/\\nreturn false;}}\\n\\n\\nreturn true;};\\n\\n\\n/**\\n * @template T\\n * @param {Iterable<[T,bigint,bigint]>} xyi\\n * @returns {KeyComparison}\\n */\\nconst iterCompare=(xyi)=>{\\nlet loneY=false;\\nlet loneX=false;\\nfor(const[_m,xc,yc]of xyi){\\nif(xc===0n){\\n/* something in y is not in x, so x is not a superset of y*/\\nloneY=true;}\\n\\nif(yc===0n){\\n/* something in x is not in y, so y is not a superset of x*/\\nloneX=true;}\\n\\nif(loneX&&loneY){\\nreturn NaN;}}\\n\\n\\nif(loneX){\\nreturn 1;}else\\nif(loneY){\\nreturn-1;}else\\n{\\n!loneX&&!loneY||\\nindex.throwRedacted`Internal: Unexpected lone pair ${index.quote([loneX,loneY])}`;\\nreturn 0;}};\\n\\n\\n\\n/**\\n * @template T\\n * @param {Iterable<[T,bigint,bigint]>} xyi\\n * @returns {T[]}\\n */\\nconst iterUnion=(xyi)=>{\\nconst result=[];\\nfor(const[m,xc,yc]of xyi){\\nif(xc>=0n){\\nresult.push(m);}else\\n{\\nyc>=0n||index.throwRedacted`Internal: Unexpected count ${index.quote(yc)}`;\\n/* if x and y were both ready, then they were equivalent and*/\\n/* above clause already took care of it. Otherwise push here.*/\\nresult.push(m);}}\\n\\n\\nreturn result;};\\n\\n\\n/**\\n * @template T\\n * @param {Iterable<[T,bigint,bigint]>} xyi\\n * @returns {T[]}\\n */\\nconst iterDisjointUnion=(xyi)=>{\\nconst result=[];\\nfor(const[m,xc,yc]of xyi){\\nxc===0n||yc===0n||index.throwRedacted`Sets must not have common elements: ${m}`;\\nif(xc>=1n){\\nresult.push(m);}else\\n{\\nyc>=1n||index.throwRedacted`Internal: Unexpected count ${index.quote(yc)}`;\\nresult.push(m);}}\\n\\n\\nreturn result;};\\n\\n\\n/**\\n * @template T\\n * @param {Iterable<[T,bigint,bigint]>} xyi\\n * @returns {T[]}\\n */\\nconst iterIntersection=(xyi)=>{\\nconst result=[];\\nfor(const[m,xc,yc]of xyi){\\nif(xc>=1n&&yc>=1n){\\n/* If they are both present, then they were equivalent*/\\nresult.push(m);}}\\n\\n\\nreturn result;};\\n\\n\\n/**\\n * @template T\\n * @param {Iterable<[T,bigint,bigint]>} xyi\\n * @returns {T[]}\\n */\\nconst iterDisjointSubtract=(xyi)=>{\\nconst result=[];\\nfor(const[m,xc,yc]of xyi){\\nxc>=1n||index.throwRedacted`right element ${m} was not in left`;\\nif(yc===0n){\\n/* the x was not in y*/\\nresult.push(m);}}\\n\\n\\nreturn result;};\\n\\n\\nconst mergeify=(iterOp)=>(xelements,yelements)=>\\niterOp(merge(xelements,yelements));\\n\\nconst elementsIsSuperset=mergeify(iterIsSuperset);\\nconst elementsIsDisjoint=mergeify(iterIsDisjoint);\\nconst elementsCompare=mergeify(iterCompare);\\nconst elementsUnion=mergeify(iterUnion);\\nconst elementsDisjointUnion=mergeify(iterDisjointUnion);\\nconst elementsIntersection=mergeify(iterIntersection);\\nconst elementsDisjointSubtract=mergeify(iterDisjointSubtract);\\n\\nconst rawSetify=(elementsOp)=>(xset,yset)=>\\nelementsOp(xset.payload,yset.payload);\\n\\nconst setify=(elementsOp)=>(xset,yset)=>\\ncopySet.makeSetOfElements(elementsOp(xset.payload,yset.payload));\\n\\nconst setIsSuperset=rawSetify(elementsIsSuperset);\\nconst setIsDisjoint=rawSetify(elementsIsDisjoint);\\nconst setUnion=setify(elementsUnion);\\nconst setDisjointUnion=setify(elementsDisjointUnion);\\nconst setIntersection=setify(elementsIntersection);\\nconst setDisjointSubtract=setify(elementsDisjointSubtract);exports.elementsCompare=elementsCompare;exports.elementsDisjointSubtract=elementsDisjointSubtract;exports.elementsDisjointUnion=elementsDisjointUnion;exports.elementsIntersection=elementsIntersection;exports.elementsIsDisjoint=elementsIsDisjoint;exports.elementsIsSuperset=elementsIsSuperset;exports.elementsUnion=elementsUnion;exports.setDisjointSubtract=setDisjointSubtract;exports.setDisjointUnion=setDisjointUnion;exports.setIntersection=setIntersection;exports.setIsDisjoint=setIsDisjoint;exports.setIsSuperset=setIsSuperset;exports.setUnion=setUnion;\",\n \"node_modules/@endo/patterns/src/patterns/getGuardPayloads.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var objectMap=require('../../../common/object-map.js');var patternMatchers=require('./patternMatchers.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\ncheckKey=require('../keys/checkKey.js');/**\\n * @import {AwaitArgGuard, AwaitArgGuardPayload, InterfaceGuard, InterfaceGuardPayload, MethodGuard, MethodGuardPayload} from '../types.js'\\n */ /* The get*GuardPayload functions exist to adapt to the worlds both*/ /* before and after https://github.com/endojs/endo/pull/1712 . When*/ /* given something that would be the expected guard in either world,*/ /* it returns a *GuardPayload that is valid in the current world. Thus*/ /* it helps new consumers of these guards cope with old code that*/ /* would construct and send these guards.*/ /* Because the main use case for this legacy adaptation is in @endo/exo*/ /* or packages that depend on it, the tests for this legacy adaptation*/ /* are found in the @endo/exo `test-legacy-guard-tolerance.js`.*/ /* Unlike LegacyAwaitArgGuardShape, LegacyMethodGuardShape,*/ /* and LegacyInterfaceGuardShape, there is no need for a*/ /* LegacyRawGuardShape, because raw guards were introduced at*/ /* https://github.com/endojs/endo/pull/1831 , which was merged well after*/ /* https://github.com/endojs/endo/pull/1712 . Thus, there was never a*/ /* `klass:` form of the raw guard.*/ /* TODO At such a time that we decide we no longer need to support code*/ /* preceding https://github.com/endojs/endo/pull/1712 or guard data*/ /* generated by that code, all the adaptation complexity in this file*/ /* should be deleted.*/ /* TODO manually maintain correspondence with AwaitArgGuardPayloadShape*/ /* because this one needs to be stable and accommodate nested legacy,*/ /* when that's an issue.*/const LegacyAwaitArgGuardShape=harden({klass:'awaitArg',\\nargGuard:patternMatchers.M.pattern()});\\n\\n\\n/**\\n * By using this abstraction rather than accessing the properties directly,\\n * we smooth the transition to https://github.com/endojs/endo/pull/1712,\\n * tolerating both the legacy and current guard shapes.\\n *\\n * Note that technically, tolerating the old LegacyAwaitArgGuardShape\\n * is an exploitable bug, in that a record that matches this\\n * shape is also a valid parameter pattern that should allow\\n * an argument that matches that pattern, i.e., a copyRecord argument that\\n * at least contains a `klass: 'awaitArgGuard'` property.\\n *\\n * @param {AwaitArgGuard} awaitArgGuard\\n * @returns {AwaitArgGuardPayload}\\n */\\nconst getAwaitArgGuardPayload=(awaitArgGuard)=>{\\nif(patternMatchers.matches(awaitArgGuard,LegacyAwaitArgGuardShape)){\\n/* @ts-expect-error Legacy adaptor can be ill typed*/\\nconst{klass:_,...payload}=awaitArgGuard;\\n/* @ts-expect-error Legacy adaptor can be ill typed*/\\nreturn payload;}\\n\\npatternMatchers.assertAwaitArgGuard(awaitArgGuard);\\nreturn awaitArgGuard.payload;};\\n\\nharden(getAwaitArgGuardPayload);\\n\\n/* TODO manually maintain correspondence with SyncMethodGuardPayloadShape*/\\n/* because this one needs to be stable and accommodate nested legacy,*/\\n/* when that's an issue.*/\\nconst LegacySyncMethodGuardShape=patternMatchers.M.splitRecord(\\n{\\nklass:'methodGuard',\\ncallKind:'sync',\\nargGuards:patternMatchers.SyncValueGuardListShape,\\nreturnGuard:patternMatchers.SyncValueGuardShape},\\n\\n{\\noptionalArgGuards:patternMatchers.SyncValueGuardListShape,\\nrestArgGuard:patternMatchers.SyncValueGuardShape});\\n\\n\\n\\n/* TODO manually maintain correspondence with ArgGuardShape*/\\n/* because this one needs to be stable and accommodate nested legacy,*/\\n/* when that's an issue.*/\\nconst LegacyArgGuardShape=patternMatchers.M.or(\\npatternMatchers.RawGuardShape,\\npatternMatchers.AwaitArgGuardShape,\\nLegacyAwaitArgGuardShape,\\npatternMatchers.M.pattern());\\n\\n/* TODO manually maintain correspondence with ArgGuardListShape*/\\n/* because this one needs to be stable and accommodate nested legacy,*/\\n/* when that's an issue.*/\\nconst LegacyArgGuardListShape=patternMatchers.M.arrayOf(LegacyArgGuardShape);\\n\\n/* TODO manually maintain correspondence with AsyncMethodGuardPayloadShape*/\\n/* because this one needs to be stable and accommodate nested legacy,*/\\n/* when that's an issue.*/\\nconst LegacyAsyncMethodGuardShape=patternMatchers.M.splitRecord(\\n{\\nklass:'methodGuard',\\ncallKind:'async',\\nargGuards:LegacyArgGuardListShape,\\nreturnGuard:patternMatchers.SyncValueGuardShape},\\n\\n{\\noptionalArgGuards:patternMatchers.ArgGuardListShape,\\nrestArgGuard:patternMatchers.SyncValueGuardShape});\\n\\n\\n\\n/* TODO manually maintain correspondence with MethodGuardPayloadShape*/\\n/* because this one needs to be stable and accommodate nested legacy,*/\\n/* when that's an issue.*/\\nconst LegacyMethodGuardShape=patternMatchers.M.or(\\nLegacySyncMethodGuardShape,\\nLegacyAsyncMethodGuardShape);\\n\\n\\nconst adaptLegacyArgGuard=(argGuard)=>\\npatternMatchers.matches(argGuard,LegacyAwaitArgGuardShape)?\\npatternMatchers.M.await(getAwaitArgGuardPayload(argGuard).argGuard):\\nargGuard;\\n\\n/**\\n * By using this abstraction rather than accessing the properties directly,\\n * we smooth the transition to https://github.com/endojs/endo/pull/1712,\\n * tolerating both the legacy and current guard shapes.\\n *\\n * Unlike LegacyAwaitArgGuardShape, tolerating LegacyMethodGuardShape\\n * does not seem like a currently exploitable bug, because there is not\\n * currently any context where either a methodGuard or a copyRecord would\\n * both be meaningful.\\n *\\n * @param {MethodGuard} methodGuard\\n * @returns {MethodGuardPayload}\\n */\\nconst getMethodGuardPayload=(methodGuard)=>{\\nif(patternMatchers.matches(methodGuard,patternMatchers.MethodGuardShape)){\\nreturn methodGuard.payload;}\\n\\npatternMatchers.mustMatch(methodGuard,LegacyMethodGuardShape,'legacyMethodGuard');\\nconst{\\n/* @ts-expect-error Legacy adaptor can be ill typed*/\\nklass:_,\\n/* @ts-expect-error Legacy adaptor can be ill typed*/\\ncallKind,\\n/* @ts-expect-error Legacy adaptor can be ill typed*/\\nreturnGuard,\\n/* @ts-expect-error Legacy adaptor can be ill typed*/\\nrestArgGuard}=\\nmethodGuard;\\nlet{\\n/* @ts-expect-error Legacy adaptor can be ill typed*/\\nargGuards,\\n/* @ts-expect-error Legacy adaptor can be ill typed*/\\noptionalArgGuards}=\\nmethodGuard;\\nif(callKind==='async'){\\nargGuards=argGuards.map(adaptLegacyArgGuard);\\noptionalArgGuards=\\noptionalArgGuards&&optionalArgGuards.map(adaptLegacyArgGuard);}\\n\\nconst payload=harden({\\ncallKind,\\nargGuards,\\noptionalArgGuards,\\nrestArgGuard,\\nreturnGuard});\\n\\n/* ensure the adaptation succeeded.*/\\npatternMatchers.mustMatch(payload,patternMatchers.MethodGuardPayloadShape,'internalMethodGuardAdaptor');\\nreturn payload;};\\n\\nharden(getMethodGuardPayload);\\n\\n/* TODO manually maintain correspondence with InterfaceGuardPayloadShape*/\\n/* because this one needs to be stable and accommodate nested legacy,*/\\n/* when that's an issue.*/\\nconst LegacyInterfaceGuardShape=patternMatchers.M.splitRecord(\\n{\\nklass:'Interface',\\ninterfaceName:patternMatchers.M.string(),\\nmethodGuards:patternMatchers.M.recordOf(\\npatternMatchers.M.string(),\\npatternMatchers.M.or(patternMatchers.MethodGuardShape,LegacyMethodGuardShape))},\\n\\n\\n{\\ndefaultGuards:patternMatchers.M.or(patternMatchers.M.undefined(),'passable','raw'),\\nsloppy:patternMatchers.M.boolean(),\\n/* There is no need to accommodate LegacyMethodGuardShape in*/\\n/* this position, since `symbolMethodGuards happened*/\\n/* after https://github.com/endojs/endo/pull/1712*/\\nsymbolMethodGuards:patternMatchers.M.mapOf(patternMatchers.M.symbol(),patternMatchers.MethodGuardShape)});\\n\\n\\n\\nconst adaptMethodGuard=(methodGuard)=>{\\nif(patternMatchers.matches(methodGuard,LegacyMethodGuardShape)){\\nconst{\\ncallKind,\\nargGuards,\\noptionalArgGuards=[],\\nrestArgGuard=patternMatchers.M.any(),\\nreturnGuard}=\\ngetMethodGuardPayload(methodGuard);\\nconst mCall=callKind==='sync'?patternMatchers.M.call:patternMatchers.M.callWhen;\\nreturn mCall(...argGuards).\\noptional(...optionalArgGuards).\\nrest(restArgGuard).\\nreturns(returnGuard);}\\n\\nreturn methodGuard;};\\n\\n\\n/**\\n * By using this abstraction rather than accessing the properties directly,\\n * we smooth the transition to https://github.com/endojs/endo/pull/1712,\\n * tolerating both the legacy and current guard shapes.\\n *\\n * Unlike LegacyAwaitArgGuardShape, tolerating LegacyInterfaceGuardShape\\n * does not seem like a currently exploitable bug, because there is not\\n * currently any context where either an interfaceGuard or a copyRecord would\\n * both be meaningful.\\n *\\n * @template {Record<PropertyKey, MethodGuard>} [T=Record<PropertyKey, MethodGuard>]\\n * @param {InterfaceGuard<T>} interfaceGuard\\n * @returns {InterfaceGuardPayload<T>}\\n */\\nconst getInterfaceGuardPayload=(interfaceGuard)=>{\\nif(patternMatchers.matches(interfaceGuard,patternMatchers.InterfaceGuardShape)){\\nreturn interfaceGuard.payload;}\\n\\npatternMatchers.mustMatch(interfaceGuard,LegacyInterfaceGuardShape,'legacyInterfaceGuard');\\n/* @ts-expect-error Legacy adaptor can be ill typed*/\\n/* eslint-disable-next-line prefer-const*/\\nlet{klass:_,interfaceName,methodGuards,...rest}=interfaceGuard;\\nmethodGuards=objectMap.objectMap(methodGuards,adaptMethodGuard);\\nconst payload=harden({\\ninterfaceName,\\nmethodGuards,\\n...rest});\\n\\npatternMatchers.mustMatch(\\npayload,\\npatternMatchers.InterfaceGuardPayloadShape,\\n'internalInterfaceGuardAdaptor');\\n\\nreturn payload;};\\n\\nharden(getInterfaceGuardPayload);\\n\\nconst emptyCopyMap=checkKey.makeCopyMap([]);\\n\\n/**\\n * @param {InterfaceGuard} interfaceGuard\\n * @returns {(string | symbol)[]}\\n */\\nconst getInterfaceMethodKeys=(interfaceGuard)=>{\\nconst{methodGuards,symbolMethodGuards=emptyCopyMap}=\\ngetInterfaceGuardPayload(interfaceGuard);\\n/** @type {(string | symbol)[]} */\\n/* TODO at-ts-expect-error works locally but not from @endo/exo*/\\n/* @ts-ignore inference is too weak to see this is ok*/\\nreturn harden([\\n...Reflect.ownKeys(methodGuards),\\n...checkKey.getCopyMapKeys(symbolMethodGuards)]);};\\n\\n\\nharden(getInterfaceMethodKeys);exports.getAwaitArgGuardPayload=getAwaitArgGuardPayload;exports.getInterfaceGuardPayload=getInterfaceGuardPayload;exports.getInterfaceMethodKeys=getInterfaceMethodKeys;exports.getMethodGuardPayload=getMethodGuardPayload;\",\n \"node_modules/@endo/patterns/src/patterns/patternMatchers.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../../marshal/index.js');var identChecker=require('../../../common/ident-checker.js');var applyLabelingError=require('../../../common/apply-labeling-error.js');var fromUniqueEntries=require('../../../common/from-unique-entries.js');var listDifference=require('../../../common/list-difference.js');var index=require('../../../errors/index.js');var compareKeys=require('../keys/compareKeys.js');var checkKey=require('../keys/checkKey.js');var keycollectionOperators=require('../keys/keycollection-operators.js');var passStyleOf=require('../../../pass-style/src/passStyleOf.js');var passStyleHelpers=require('../../../pass-style/src/passStyle-helpers.js');var encodePassable=require('../../../marshal/src/encodePassable.js');var rankOrder=require('../../../marshal/src/rankOrder.js');var makeFar=require('../../../pass-style/src/make-far.js');var symbol=require('../../../pass-style/src/symbol.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nmakeTagged=require('../../../pass-style/src/makeTagged.js');/* @ts-nocheck So many errors that the suppressions hamper readability.*/ /**\\n * @import {Checker, CopyRecord, CopyTagged, Passable} from '@endo/pass-style'\\n * @import {ArgGuard, AwaitArgGuard, CheckPattern, GetRankCover, InterfaceGuard, MatcherNamespace, MethodGuard, MethodGuardMaker, Pattern, RawGuard, SyncValueGuard, Kind, Limits, AllLimits, Key, DefaultGuardType} from '../types.js'\\n * @import {MatchHelper, PatternKit} from './types.js'\\n */\\n\\nconst{entries,values}=Object;\\nconst{ownKeys}=Reflect;\\n\\n/** @type {WeakSet<Pattern>} */\\nconst patternMemo=new WeakSet();\\n\\n/* /////////////////////// Match Helpers Helpers /////////////////////////////*/\\n\\n/** For forward references to `M` */\\nlet MM;\\n\\n/**\\n * The actual default values here are, at the present time, fairly\\n * arbitrary choices and may change before they settle down. Of course\\n * at some point we'll need to stop changing them. But we should first\\n * see how our system holds up with these choices. The main criteria\\n * is that they be big enough that \\\"normal\\\" innocent programs rarely\\n * encounter these limits.\\n *\\n * Exported primarily for testing.\\n */\\nconst defaultLimits=harden({\\ndecimalDigitsLimit:100,\\nstringLengthLimit:100_000,\\nsymbolNameLengthLimit:100,\\nnumPropertiesLimit:80,\\npropertyNameLengthLimit:100,\\narrayLengthLimit:10_000,\\nnumSetElementsLimit:10_000,\\nnumUniqueBagElementsLimit:10_000,\\nnumMapEntriesLimit:5000});\\n\\n\\n/**\\n * Use the result only to get the limits you need by destructuring.\\n * Thus, the result only needs to support destructuring. The current\\n * implementation uses inheritance as a cheap hack.\\n *\\n * @param {Limits} [limits]\\n * @returns {AllLimits}\\n */\\nconst limit=(limits={})=>\\n/** @type {AllLimits} */harden({__proto__:defaultLimits,...limits});\\n\\nconst checkIsWellFormedWithLimit=(\\npayload,\\nmainPayloadShape,\\ncheck,\\nlabel)=>\\n{\\nassert(Array.isArray(mainPayloadShape));\\nif(!Array.isArray(payload)){\\nreturn check(false,index.redacted`${index.quote(label)} payload must be an array: ${payload}`);}\\n\\n\\n/* Was the following, but its overuse of patterns caused an infinite regress*/\\n/* const payloadLimitShape = harden(*/\\n/* M.split(*/\\n/* mainPayloadShape,*/\\n/* M.partial(harden([M.recordOf(M.string(), M.number())]), harden([])),*/\\n/* ),*/\\n/* );*/\\n/* return checkMatches(payload, payloadLimitShape, check, label);*/\\n\\nconst mainLength=mainPayloadShape.length;\\nif(!(payload.length===mainLength||payload.length===mainLength+1)){\\nreturn check(false,index.redacted`${index.quote(label)} payload unexpected size: ${payload}`);}\\n\\nconst limits=payload[mainLength];\\npayload=harden(payload.slice(0,mainLength));\\n/* eslint-disable-next-line no-use-before-define*/\\nif(!checkMatches(payload,mainPayloadShape,check,label)){\\nreturn false;}\\n\\nif(limits===undefined){\\nreturn true;}\\n\\nreturn(\\n(passStyleOf.passStyleOf(limits)==='copyRecord'||\\ncheck(false,index.redacted`Limits must be a record: ${index.quote(limits)}`))&&\\nentries(limits).every(\\n([key,value])=>\\npassStyleOf.passStyleOf(value)==='number'||\\ncheck(false,index.redacted`Value of limit ${index.quote(key)} but be a number: ${index.quote(value)}`)));};\\n\\n\\n\\n\\n/**\\n * @param {unknown} specimen\\n * @param {number} decimalDigitsLimit\\n * @param {Checker} check\\n */\\nconst checkDecimalDigitsLimit=(specimen,decimalDigitsLimit,check)=>{\\nif(\\nMath.floor(Math.log10(Math.abs(Number(specimen))))+1<=\\ndecimalDigitsLimit)\\n{\\nreturn true;}\\n\\nreturn check(\\nfalse,\\nindex.redacted`bigint ${specimen} must not have more than ${decimalDigitsLimit} digits`);};\\n\\n\\n\\n/**\\n * @returns {PatternKit}\\n */\\nconst makePatternKit=()=>{\\n/**\\n * If this is a recognized match tag, return the MatchHelper.\\n * Otherwise result undefined.\\n *\\n * @param {string} tag\\n * @returns {MatchHelper | undefined}\\n */\\nconst maybeMatchHelper=(tag)=>\\n/* eslint-disable-next-line no-use-before-define*/\\nHelpersByMatchTag[tag];\\n\\n/**\\n * Note that this function indicates absence by returning `undefined`,\\n * even though `undefined` is a valid pattern. To evade this confusion,\\n * to register a payload shape with that meaning, use `MM.undefined()`.\\n *\\n * @param {string} tag\\n * @returns {Pattern | undefined}\\n */\\nconst maybePayloadShape=(tag)=>\\n/* eslint-disable-next-line no-use-before-define*/\\nGuardPayloadShapes[tag];\\n\\n/** @type {Map<Kind, unknown>} */\\nconst singletonKinds=new Map([\\n['null',null],\\n['undefined',undefined]]);\\n\\n\\n/**\\n * @type {WeakMap<CopyTagged, Kind>}\\n * Only for tagged records of recognized kinds whose store-level invariants\\n * have already been checked.\\n */\\nconst tagMemo=new WeakMap();\\n\\n/**\\n * Checks only recognized tags, and only if the tagged\\n * passes the invariants associated with that recognition.\\n *\\n * @param {Passable} tagged\\n * @param {Kind} tag\\n * @param {Checker} check\\n * @returns {boolean}\\n */\\nconst checkTagged=(tagged,tag,check)=>{\\nconst matchHelper=maybeMatchHelper(tag);\\nif(matchHelper){\\n/* Buried here is the important case, where we process*/\\n/* the various patternNodes*/\\nreturn matchHelper.checkIsWellFormed(tagged.payload,check);}else\\n{\\nconst payloadShape=maybePayloadShape(tag);\\nif(payloadShape!==undefined){\\n/* eslint-disable-next-line no-use-before-define*/\\nreturn checkMatches(tagged.payload,payloadShape,check,tag);}}\\n\\n\\nswitch(tag){\\ncase'copySet':{\\nreturn checkKey.checkCopySet(tagged,check);}\\n\\ncase'copyBag':{\\nreturn checkKey.checkCopyBag(tagged,check);}\\n\\ncase'copyMap':{\\nreturn checkKey.checkCopyMap(tagged,check);}\\n\\ndefault:{\\nreturn check(\\nfalse,\\nindex.redacted`cannot check unrecognized tag ${index.quote(tag)}: ${tagged}`);}}};\\n\\n\\n\\n\\n\\n/**\\n * Returns only a recognized kind, and only if the specimen passes the\\n * invariants associated with that recognition.\\n * Otherwise, `check(false, ...)` and returns undefined\\n *\\n * @param {any} specimen\\n * @param {Checker} [check]\\n * @returns {Kind | undefined}\\n */\\nconst kindOf=(specimen,check=identChecker.identChecker)=>{\\nconst passStyle=passStyleOf.passStyleOf(specimen);\\nif(passStyle!=='tagged'){\\nreturn passStyle;}\\n\\n/* At this point we know that specimen is well formed*/\\n/* as a tagged record, which is defined at the marshal level of abstraction,*/\\n/* since `passStyleOf` checks those invariants.*/\\nif(tagMemo.has(specimen)){\\nreturn tagMemo.get(specimen);}\\n\\nconst tag=passStyleHelpers.getTag(specimen);\\nif(checkTagged(specimen,tag,check)){\\ntagMemo.set(specimen,tag);\\nreturn tag;}\\n\\nif(check!==identChecker.identChecker){\\ncheck(false,index.redacted`cannot check unrecognized tag ${index.quote(tag)}`);}\\n\\nreturn undefined;};\\n\\nharden(kindOf);\\n\\n/**\\n * Checks only recognized kinds, and only if the specimen\\n * passes the invariants associated with that recognition.\\n *\\n * @param {any} specimen\\n * @param {Kind} kind\\n * @param {Checker} check\\n * @returns {boolean}\\n */\\nconst checkKind=(specimen,kind,check)=>{\\n/* check null and undefined as Keys*/\\nif(singletonKinds.has(kind)){\\n/* eslint-disable-next-line no-use-before-define*/\\nreturn checkAsKeyPatt(specimen,singletonKinds.get(kind),check);}\\n\\n\\nconst realKind=kindOf(specimen,check);\\nif(kind===realKind){\\nreturn true;}\\n\\nif(check!==identChecker.identChecker){\\n/* `kind` and `realKind` can be embedded without quotes*/\\n/* because they are drawn from the enumerated collection of known Kinds.*/\\ncheck(false,index.redacted`${index.bare(realKind)} ${specimen} - Must be a ${index.bare(kind)}`);}\\n\\nreturn false;};\\n\\n\\n/**\\n * Checks only recognized kinds, and only if the specimen\\n * passes the invariants associated with that recognition.\\n *\\n * @param {any} specimen\\n * @param {Kind} kind\\n * @returns {boolean}\\n */\\nconst isKind=(specimen,kind)=>checkKind(specimen,kind,identChecker.identChecker);\\n\\n/**\\n * @param {any} specimen\\n * @param {Key} keyAsPattern\\n * @param {Checker} check\\n * @returns {boolean}\\n */\\nconst checkAsKeyPatt=(specimen,keyAsPattern,check)=>{\\nif(checkKey.isKey(specimen)&&compareKeys.keyEQ(specimen,keyAsPattern)){\\nreturn true;}\\n\\nreturn(\\ncheck!==identChecker.identChecker&&\\n/* When the mismatch occurs against a key used as a pattern,*/\\n/* the pattern should still be redacted.*/\\ncheck(false,index.redacted`${specimen} - Must be: ${keyAsPattern}`));};\\n\\n\\n\\n/* /////////////////////// isPattern /////////////////////////////////////////*/\\n\\n/** @type {CheckPattern} */\\nconst checkPattern=(patt,check)=>{\\nif(checkKey.isKey(patt)){\\n/* All keys are patterns. For these, the keyMemo will do.*/\\n/* All primitives that are patterns are also keys, which this*/\\n/* also takes care of without memo. The rest of our checking logic*/\\n/* is only concerned with non-key patterns.*/\\nreturn true;}\\n\\nif(patternMemo.has(patt)){\\nreturn true;}\\n\\n/* eslint-disable-next-line no-use-before-define*/\\nconst result=checkPatternInternal(patt,check);\\nif(result){\\npatternMemo.add(patt);}\\n\\nreturn result;};\\n\\n\\n/**\\n * @param {Passable} patt - known not to be a key, and therefore known\\n * not to be primitive.\\n * @param {Checker} check\\n * @returns {boolean}\\n */\\nconst checkPatternInternal=(patt,check)=>{\\n/* Purposely parallels checkKey. TODO reuse more logic between them.*/\\n/* Most of the text of the switch below not dealing with matchers is*/\\n/* essentially identical.*/\\nconst checkIt=(child)=>checkPattern(child,check);\\n\\nconst kind=kindOf(patt,check);\\nswitch(kind){\\ncase undefined:{\\nreturn false;}\\n\\ncase'copyRecord':{\\n/* A copyRecord is a pattern iff all its children are*/\\n/* patterns*/\\nreturn values(patt).every(checkIt);}\\n\\ncase'copyArray':{\\n/* A copyArray is a pattern iff all its children are*/\\n/* patterns*/\\nreturn patt.every(checkIt);}\\n\\ncase'copyMap':{\\n/* A copyMap's keys are keys and therefore already known to be*/\\n/* patterns.*/\\n/* A copyMap is a pattern if its values are patterns.*/\\nreturn checkPattern(patt.values,check);}\\n\\ncase'error':\\ncase'promise':{\\nreturn check(false,index.redacted`A ${index.quote(kind)} cannot be a pattern`);}\\n\\ndefault:{\\nif(maybeMatchHelper(kind)!==undefined){\\nreturn true;}\\n\\nreturn check(\\nfalse,\\nindex.redacted`A passable of kind ${index.quote(kind)} is not a pattern: ${patt}`);}}};\\n\\n\\n\\n\\n\\n/**\\n * @param {Passable} patt\\n * @returns {boolean}\\n */\\nconst isPattern=(patt)=>checkPattern(patt,identChecker.identChecker);\\n\\n/**\\n * @param {Pattern} patt\\n */\\nconst assertPattern=(patt)=>{\\ncheckPattern(patt,passStyleHelpers.assertChecker);};\\n\\n\\n/* /////////////////////// matches ///////////////////////////////////////////*/\\n\\n/**\\n * @param {any} specimen\\n * @param {Pattern} pattern\\n * @param {Checker} check\\n * @param {string|number} [label]\\n * @returns {boolean}\\n */\\nconst checkMatches=(specimen,pattern,check,label=undefined)=>\\n/* eslint-disable-next-line no-use-before-define*/\\napplyLabelingError.applyLabelingError(checkMatchesInternal,[specimen,pattern,check],label);\\n\\n/**\\n * @param {any} specimen\\n * @param {Pattern} patt\\n * @param {Checker} check\\n * @returns {boolean}\\n */\\nconst checkMatchesInternal=(specimen,patt,check)=>{\\n/* Worth being a bit verbose and repetitive in order to optimize*/\\nconst patternKind=kindOf(patt,check);\\nconst specimenKind=kindOf(specimen);/* may be undefined*/\\nswitch(patternKind){\\ncase undefined:{\\nreturn index.throwRedacted`pattern expected: ${patt}`;}\\n\\ncase'promise':{\\nreturn index.throwRedacted`promises cannot be patterns: ${patt}`;}\\n\\ncase'error':{\\nreturn index.throwRedacted`errors cannot be patterns: ${patt}`;}\\n\\ncase'undefined':\\ncase'null':\\ncase'boolean':\\ncase'number':\\ncase'bigint':\\ncase'string':\\ncase'symbol':\\ncase'copySet':\\ncase'copyBag':\\ncase'remotable':{\\n/* These kinds are necessarily keys*/\\nreturn checkAsKeyPatt(specimen,patt,check);}\\n\\ncase'copyArray':{\\nif(checkKey.isKey(patt)){\\n/* Takes care of patterns which are keys, so the rest of this*/\\n/* logic can assume patterns that are not keys.*/\\nreturn checkAsKeyPatt(specimen,patt,check);}\\n\\nif(specimenKind!=='copyArray'){\\nreturn check(\\nfalse,\\nindex.redacted`${specimen} - Must be a copyArray to match a copyArray pattern: ${index.quote(\\npatt)\\n}`);}\\n\\n\\nconst{length}=patt;\\nif(specimen.length!==length){\\nreturn check(\\nfalse,\\nindex.redacted`Array ${specimen} - Must be as long as copyArray pattern: ${index.quote(\\npatt)\\n}`);}\\n\\n\\nreturn patt.every((p,i)=>checkMatches(specimen[i],p,check,i));}\\n\\ncase'copyRecord':{\\nif(checkKey.isKey(patt)){\\n/* Takes care of patterns which are keys, so the rest of this*/\\n/* logic can assume patterns that are not keys.*/\\nreturn checkAsKeyPatt(specimen,patt,check);}\\n\\nif(specimenKind!=='copyRecord'){\\nreturn check(\\nfalse,\\nindex.redacted`${specimen} - Must be a copyRecord to match a copyRecord pattern: ${index.quote(\\npatt)\\n}`);}\\n\\n\\n/* TODO Detect and accumulate difference in one pass.*/\\n/* Rather than using two calls to `listDifference` to detect and*/\\n/* report if and how these lists differ, since they are already*/\\n/* in sorted order, we should instead use an algorithm like*/\\n/* `iterDisjointUnion` from merge-sort-operators.js*/\\nconst specimenNames=encodePassable.recordNames(specimen);\\nconst pattNames=encodePassable.recordNames(patt);\\nconst missing=listDifference.listDifference(pattNames,specimenNames);\\nif(missing.length>=1){\\nreturn check(\\nfalse,\\nindex.redacted`${specimen} - Must have missing properties ${index.quote(missing)}`);}\\n\\n\\nconst unexpected=listDifference.listDifference(specimenNames,pattNames);\\nif(unexpected.length>=1){\\nreturn check(\\nfalse,\\nindex.redacted`${specimen} - Must not have unexpected properties: ${index.quote(\\nunexpected)\\n}`);}\\n\\n\\nconst specimenValues=encodePassable.recordValues(specimen,specimenNames);\\nconst pattValues=encodePassable.recordValues(patt,pattNames);\\nreturn pattNames.every((label,i)=>\\ncheckMatches(specimenValues[i],pattValues[i],check,label));}\\n\\n\\ncase'copyMap':{\\nif(checkKey.isKey(patt)){\\n/* Takes care of patterns which are keys, so the rest of this*/\\n/* logic can assume patterns that are not keys.*/\\nreturn checkAsKeyPatt(specimen,patt,check);}\\n\\nif(specimenKind!=='copyMap'){\\nreturn check(\\nfalse,\\nindex.redacted`${specimen} - Must be a copyMap to match a copyMap pattern: ${index.quote(\\npatt)\\n}`);}\\n\\n\\n/* Compare keys as copySets*/\\nconst pattKeySet=checkKey.copyMapKeySet(patt);\\nconst specimenKeySet=checkKey.copyMapKeySet(specimen);\\nif(!checkMatches(specimenKeySet,pattKeySet,check)){\\nreturn false;}\\n\\n/* Compare values as copyArrays after applying a shared total order.*/\\n/* This is necessary because the antiRankOrder sorting of each map's*/\\n/* entries is a preorder that admits ties.*/\\nconst pattValues=[];\\nconst specimenValues=[];\\nconst entryPairs=keycollectionOperators.generateCollectionPairEntries(\\npatt,\\nspecimen,\\ncheckKey.getCopyMapEntryArray,\\nundefined);\\n\\nfor(const[_key,pattValue,specimenValue]of entryPairs){\\npattValues.push(pattValue);\\nspecimenValues.push(specimenValue);}\\n\\nreturn checkMatches(harden(specimenValues),harden(pattValues),check);}\\n\\ndefault:{\\nconst matchHelper=maybeMatchHelper(patternKind);\\nif(matchHelper){\\nreturn matchHelper.checkMatches(specimen,patt.payload,check);}\\n\\nthrow index.throwRedacted`internal: should have recognized ${index.quote(patternKind)} `;}}};\\n\\n\\n\\n\\n/**\\n * @param {any} specimen\\n * @param {Pattern} patt\\n * @returns {boolean}\\n */\\nconst matches=(specimen,patt)=>\\ncheckMatches(specimen,patt,identChecker.identChecker);\\n\\n/**\\n * Returning normally indicates success. Match failure is indicated by\\n * throwing.\\n *\\n * @param {any} specimen\\n * @param {Pattern} patt\\n * @param {string|number} [label]\\n */\\nconst mustMatch=(specimen,patt,label=undefined)=>{\\nlet innerError;\\ntry{\\nif(checkMatches(specimen,patt,identChecker.identChecker,undefined)){\\nreturn;}}\\n\\ncatch(er){\\ninnerError=er;}\\n\\n/* should only throw*/\\ncheckMatches(specimen,patt,passStyleHelpers.assertChecker,label);\\nconst outerError=index.makeError(\\nindex.redacted`internal: ${label}: inconsistent pattern match: ${index.quote(patt)}`);\\n\\nif(innerError!==undefined){\\nindex.note(outerError,index.redacted`caused by ${innerError}`);}\\n\\nthrow outerError;};\\n\\n\\n/* /////////////////////// getRankCover //////////////////////////////////////*/\\n\\n/** @type {GetRankCover} */\\nconst getRankCover=(patt,encodePassable)=>{\\nif(checkKey.isKey(patt)){\\nconst encoded=encodePassable(patt);\\nif(encoded!==undefined){\\nreturn[encoded,`${encoded}~`];}}\\n\\n\\nconst passStyle=passStyleOf.passStyleOf(patt);\\nswitch(passStyle){\\ncase'copyArray':{\\n/* XXX this doesn't get along with the world of cover === pair of*/\\n/* strings. In the meantime, fall through to the default which*/\\n/* returns a cover that covers all copyArrays.*/\\n/**/\\n/* const rankCovers = patt.map(p => getRankCover(p, encodePassable));*/\\n/* return harden([*/\\n/* rankCovers.map(([left, _right]) => left),*/\\n/* rankCovers.map(([_left, right]) => right),*/\\n/* ]);*/\\nbreak;}\\n\\ncase'copyRecord':{\\n/* XXX this doesn't get along with the world of cover === pair of*/\\n/* strings. In the meantime, fall through to the default which*/\\n/* returns a cover that covers all copyRecords.*/\\n/**/\\n/* const pattKeys = ownKeys(patt);*/\\n/* const pattEntries = harden(pattKeys.map(key => [key, patt[key]]));*/\\n/* const [leftEntriesLimit, rightEntriesLimit] =*/\\n/* getRankCover(pattEntries);*/\\n/* return harden([*/\\n/* fromUniqueEntries(leftEntriesLimit),*/\\n/* fromUniqueEntries(rightEntriesLimit),*/\\n/* ]);*/\\nbreak;}\\n\\ncase'tagged':{\\nconst tag=passStyleHelpers.getTag(patt);\\nconst matchHelper=maybeMatchHelper(tag);\\nif(matchHelper){\\n/* Buried here is the important case, where we process*/\\n/* the various patternNodes*/\\nreturn matchHelper.getRankCover(patt.payload,encodePassable);}\\n\\nswitch(tag){\\ncase'copySet':{\\n/* XXX this doesn't get along with the world of cover === pair of*/\\n/* strings. In the meantime, fall through to the default which*/\\n/* returns a cover that covers all copySets.*/\\n/**/\\n/* // Should already be validated by checkPattern. But because this*/\\n/* // is a check that may loosen over time, we also assert*/\\n/* // everywhere we still rely on the restriction.*/\\n/* ```js*/\\n/* patt.payload.length === 1 ||*/\\n/* Fail`Non-singleton copySets with matcher not yet implemented: ${patt}`;*/\\n/* ```*/\\n/**/\\n/* const [leftElementLimit, rightElementLimit] = getRankCover(*/\\n/* patt.payload[0],*/\\n/* );*/\\n/* return harden([*/\\n/* makeCopySet([leftElementLimit]),*/\\n/* makeCopySet([rightElementLimit]),*/\\n/* ]);*/\\nbreak;}\\n\\ncase'copyMap':{\\n/* XXX this doesn't get along with the world of cover === pair of*/\\n/* strings. In the meantime, fall through to the default which*/\\n/* returns a cover that covers all copyMaps.*/\\n/**/\\n/* // A matching copyMap must have the same keys, or at most one*/\\n/* // non-key key pattern. Thus we can assume that value positions*/\\n/* // match 1-to-1.*/\\n/* //*/\\n/* // TODO I may be overlooking that the less precise rankOrder*/\\n/* // equivalence class may cause values to be out of order,*/\\n/* // making this rankCover not actually cover. In that case, for*/\\n/* // all the values for keys at the same rank, we should union their*/\\n/* // rank covers. TODO POSSIBLE SILENT CORRECTNESS BUG*/\\n/* //*/\\n/* // If this is a bug, it probably affects the getRankCover*/\\n/* // cases of matchLTEHelper and matchGTEHelper on copyMap as*/\\n/* // well. See makeCopyMap for an idea on fixing*/\\n/* // this bug.*/\\n/* const [leftPayloadLimit, rightPayloadLimit] = getRankCover(*/\\n/* patt.payload,*/\\n/* encodePassable,*/\\n/* );*/\\n/* return harden([*/\\n/* makeTagged('copyMap', leftPayloadLimit),*/\\n/* makeTagged('copyMap', rightPayloadLimit),*/\\n/* ]);*/\\nbreak;}\\n\\ndefault:{\\nbreak;/* fall through to default*/}}\\n\\n\\nbreak;/* fall through to default*/}\\n\\ndefault:{\\nbreak;/* fall through to default*/}}\\n\\n\\nreturn rankOrder.getPassStyleCover(passStyle);};\\n\\n\\n/**\\n * @param {Passable[]} array\\n * @param {Pattern} patt\\n * @param {Checker} check\\n * @param {string} [labelPrefix]\\n * @returns {boolean}\\n */\\nconst arrayEveryMatchPattern=(array,patt,check,labelPrefix='')=>{\\nif(isKind(patt,'match:any')){\\n/* if the pattern is M.any(), we know its true*/\\nreturn true;}\\n\\nreturn array.every((el,i)=>\\ncheckMatches(el,patt,check,`${labelPrefix}[${i}]`));};\\n\\n\\n\\n/* /////////////////////// Match Helpers /////////////////////////////////////*/\\n\\n/** @type {MatchHelper} */\\nconst matchAnyHelper=makeFar.Far('match:any helper',{\\ncheckMatches:(_specimen,_matcherPayload,_check)=>true,\\n\\ncheckIsWellFormed:(matcherPayload,check)=>\\nmatcherPayload===undefined||\\ncheck(false,index.redacted`match:any payload: ${matcherPayload} - Must be undefined`),\\n\\ngetRankCover:(_matchPayload,_encodePassable)=>['','{']});\\n\\n\\n/** @type {MatchHelper} */\\nconst matchAndHelper=makeFar.Far('match:and helper',{\\ncheckMatches:(specimen,patts,check)=>{\\nreturn patts.every((patt)=>checkMatches(specimen,patt,check));},\\n\\n\\ncheckIsWellFormed:(allegedPatts,check)=>{\\nconst checkIt=(patt)=>checkPattern(patt,check);\\nreturn(\\n(passStyleOf.passStyleOf(allegedPatts)==='copyArray'||\\ncheck(false,index.redacted`Needs array of sub-patterns: ${index.quote(allegedPatts)}`))&&\\nallegedPatts.every(checkIt));},\\n\\n\\n\\ngetRankCover:(patts,encodePassable)=>\\nrankOrder.intersectRankCovers(\\nrankOrder.compareRank,\\npatts.map((p)=>getRankCover(p,encodePassable)))});\\n\\n\\n\\n/** @type {MatchHelper} */\\nconst matchOrHelper=makeFar.Far('match:or helper',{\\ncheckMatches:(specimen,patts,check)=>{\\nconst{length}=patts;\\nif(length===0){\\nreturn check(\\nfalse,\\nindex.redacted`${specimen} - no pattern disjuncts to match: ${index.quote(patts)}`);}\\n\\n\\nif(\\npatts.length===2&&\\n!matches(specimen,patts[0])&&\\nisKind(patts[0],'match:kind')&&\\npatts[0].payload==='undefined')\\n{\\n/* Worth special casing the optional pattern for*/\\n/* better error messages.*/\\nreturn checkMatches(specimen,patts[1],check);}\\n\\nif(patts.some((patt)=>matches(specimen,patt))){\\nreturn true;}\\n\\nreturn check(false,index.redacted`${specimen} - Must match one of ${index.quote(patts)}`);},\\n\\n\\ncheckIsWellFormed:matchAndHelper.checkIsWellFormed,\\n\\ngetRankCover:(patts,encodePassable)=>\\nrankOrder.unionRankCovers(\\nrankOrder.compareRank,\\npatts.map((p)=>getRankCover(p,encodePassable)))});\\n\\n\\n\\n/** @type {MatchHelper} */\\nconst matchNotHelper=makeFar.Far('match:not helper',{\\ncheckMatches:(specimen,patt,check)=>{\\nif(matches(specimen,patt)){\\nreturn check(\\nfalse,\\nindex.redacted`${specimen} - Must fail negated pattern: ${index.quote(patt)}`);}else\\n\\n{\\nreturn true;}},\\n\\n\\n\\ncheckIsWellFormed:checkPattern,\\n\\ngetRankCover:(_patt,_encodePassable)=>['','{']});\\n\\n\\n/** @type {MatchHelper} */\\nconst matchScalarHelper=makeFar.Far('match:scalar helper',{\\ncheckMatches:(specimen,_matcherPayload,check)=>\\ncheckKey.checkScalarKey(specimen,check),\\n\\ncheckIsWellFormed:matchAnyHelper.checkIsWellFormed,\\n\\ngetRankCover:(_matchPayload,_encodePassable)=>['a','z~']});\\n\\n\\n/** @type {MatchHelper} */\\nconst matchKeyHelper=makeFar.Far('match:key helper',{\\ncheckMatches:(specimen,_matcherPayload,check)=>\\ncheckKey.checkKey(specimen,check),\\n\\ncheckIsWellFormed:matchAnyHelper.checkIsWellFormed,\\n\\ngetRankCover:(_matchPayload,_encodePassable)=>['a','z~']});\\n\\n\\n/** @type {MatchHelper} */\\nconst matchPatternHelper=makeFar.Far('match:pattern helper',{\\ncheckMatches:(specimen,_matcherPayload,check)=>\\ncheckPattern(specimen,check),\\n\\ncheckIsWellFormed:matchAnyHelper.checkIsWellFormed,\\n\\ngetRankCover:(_matchPayload,_encodePassable)=>['a','z~']});\\n\\n\\n/** @type {MatchHelper} */\\nconst matchKindHelper=makeFar.Far('match:kind helper',{\\ncheckMatches:checkKind,\\n\\ncheckIsWellFormed:(allegedKeyKind,check)=>\\ntypeof allegedKeyKind==='string'||\\ncheck(\\nfalse,\\nindex.redacted`match:kind: payload: ${allegedKeyKind} - A kind name must be a string`),\\n\\n\\ngetRankCover:(kind,_encodePassable)=>{\\nlet style;\\nswitch(kind){\\ncase'copySet':\\ncase'copyMap':{\\nstyle='tagged';\\nbreak;}\\n\\ndefault:{\\nstyle=kind;\\nbreak;}}\\n\\n\\nreturn rankOrder.getPassStyleCover(style);}});\\n\\n\\n\\n/** @type {MatchHelper} */\\nconst matchTaggedHelper=makeFar.Far('match:tagged helper',{\\ncheckMatches:(specimen,[tagPatt,payloadPatt],check)=>{\\nif(passStyleOf.passStyleOf(specimen)!=='tagged'){\\nreturn check(\\nfalse,\\nindex.redacted`Expected tagged object, not ${index.quote(\\npassStyleOf.passStyleOf(specimen))\\n}: ${specimen}`);}\\n\\n\\nreturn(\\ncheckMatches(passStyleHelpers.getTag(specimen),tagPatt,check,'tag')&&\\ncheckMatches(specimen.payload,payloadPatt,check,'payload'));},\\n\\n\\n\\ncheckIsWellFormed:(payload,check)=>\\ncheckMatches(\\npayload,\\nharden([MM.pattern(),MM.pattern()]),\\ncheck,\\n'match:tagged payload'),\\n\\n\\ngetRankCover:(_kind,_encodePassable)=>rankOrder.getPassStyleCover('tagged')});\\n\\n\\n/** @type {MatchHelper} */\\nconst matchBigintHelper=makeFar.Far('match:bigint helper',{\\ncheckMatches:(specimen,[limits=undefined],check)=>{\\nconst{decimalDigitsLimit}=limit(limits);\\nreturn(\\ncheckKind(specimen,'bigint',check)&&\\ncheckDecimalDigitsLimit(specimen,decimalDigitsLimit,check));},\\n\\n\\n\\ncheckIsWellFormed:(payload,check)=>\\ncheckIsWellFormedWithLimit(\\npayload,\\nharden([]),\\ncheck,\\n'match:bigint payload'),\\n\\n\\ngetRankCover:(_matchPayload,_encodePassable)=>\\nrankOrder.getPassStyleCover('bigint')});\\n\\n\\n/** @type {MatchHelper} */\\nconst matchNatHelper=makeFar.Far('match:nat helper',{\\ncheckMatches:(specimen,[limits=undefined],check)=>{\\nconst{decimalDigitsLimit}=limit(limits);\\nreturn(\\ncheckKind(specimen,'bigint',check)&&\\ncheck(\\n/** @type {bigint} */specimen>=0n,\\nindex.redacted`${specimen} - Must be non-negative`)&&\\n\\ncheckDecimalDigitsLimit(specimen,decimalDigitsLimit,check));},\\n\\n\\n\\ncheckIsWellFormed:(payload,check)=>\\ncheckIsWellFormedWithLimit(\\npayload,\\nharden([]),\\ncheck,\\n'match:nat payload'),\\n\\n\\ngetRankCover:(_matchPayload,_encodePassable)=>\\n/* TODO Could be more precise*/\\nrankOrder.getPassStyleCover('bigint')});\\n\\n\\n/** @type {MatchHelper} */\\nconst matchStringHelper=makeFar.Far('match:string helper',{\\ncheckMatches:(specimen,[limits=undefined],check)=>{\\nconst{stringLengthLimit}=limit(limits);\\n/* prettier-ignore*/\\nreturn(\\ncheckKind(specimen,'string',check)&&(\\n/* eslint-disable-next-line @endo/restrict-comparison-operands*/\\n/** @type {string} */specimen.length<=stringLengthLimit||\\ncheck(\\nfalse,\\nindex.redacted`string ${specimen} must not be bigger than ${stringLengthLimit}`)));},\\n\\n\\n\\n\\ncheckIsWellFormed:(payload,check)=>\\ncheckIsWellFormedWithLimit(\\npayload,\\nharden([]),\\ncheck,\\n'match:string payload'),\\n\\n\\ngetRankCover:(_matchPayload,_encodePassable)=>\\nrankOrder.getPassStyleCover('string')});\\n\\n\\n/** @type {MatchHelper} */\\nconst matchSymbolHelper=makeFar.Far('match:symbol helper',{\\ncheckMatches:(specimen,[limits=undefined],check)=>{\\nconst{symbolNameLengthLimit}=limit(limits);\\nif(!checkKind(specimen,'symbol',check)){\\nreturn false;}\\n\\nconst symbolName=symbol.nameForPassableSymbol(specimen);\\n\\nif(typeof symbolName!=='string'){\\nthrow index.throwRedacted`internal: Passable symbol ${specimen} must have a passable name`;}\\n\\nreturn check(\\nsymbolName.length<=symbolNameLengthLimit,\\nindex.redacted`Symbol name ${index.quote(\\nsymbolName)\\n} must not be bigger than ${symbolNameLengthLimit}`);},\\n\\n\\n\\ncheckIsWellFormed:(payload,check)=>\\ncheckIsWellFormedWithLimit(\\npayload,\\nharden([]),\\ncheck,\\n'match:symbol payload'),\\n\\n\\ngetRankCover:(_matchPayload,_encodePassable)=>\\nrankOrder.getPassStyleCover('symbol')});\\n\\n\\n/** @type {MatchHelper} */\\nconst matchRemotableHelper=makeFar.Far('match:remotable helper',{\\ncheckMatches:(specimen,remotableDesc,check)=>{\\nif(isKind(specimen,'remotable')){\\nreturn true;}\\n\\nif(check===identChecker.identChecker){\\nreturn false;}\\n\\nconst{label}=remotableDesc;\\nconst passStyle=passStyleOf.passStyleOf(specimen);\\nconst kindDetails=\\npassStyle!=='tagged'?\\n/* Pass style can be embedded in details without quotes.*/\\nindex.bare(passStyle):\\n/* Tag must be quoted because it is potentially attacker-controlled*/\\n/* (unlike `kindOf`, this does not reject unrecognized tags).*/\\nindex.quote(passStyleHelpers.getTag(specimen));\\nreturn check(\\nfalse,\\n/* `label` can be embedded without quotes because it is provided by*/\\n/* local code like `M.remotable(\\\"...\\\")`.*/\\nindex.redacted`${specimen} - Must be a remotable ${index.bare(label)}, not ${kindDetails}`);},\\n\\n\\n\\ncheckIsWellFormed:(allegedRemotableDesc,check)=>\\ncheckMatches(\\nallegedRemotableDesc,\\nharden({label:MM.string()}),\\ncheck,\\n'match:remotable payload'),\\n\\n\\ngetRankCover:(_remotableDesc,_encodePassable)=>\\nrankOrder.getPassStyleCover('remotable')});\\n\\n\\n/** @type {MatchHelper} */\\nconst matchLTEHelper=makeFar.Far('match:lte helper',{\\ncheckMatches:(specimen,rightOperand,check)=>\\ncompareKeys.keyLTE(specimen,rightOperand)||\\ncheck(false,index.redacted`${specimen} - Must be <= ${rightOperand}`),\\n\\ncheckIsWellFormed:checkKey.checkKey,\\n\\ngetRankCover:(rightOperand,encodePassable)=>{\\nconst passStyle=passStyleOf.passStyleOf(rightOperand);\\n/* The prefer-const makes no sense when some of the variables need*/\\n/* to be `let`*/\\n/* eslint-disable-next-line prefer-const*/\\nlet[leftBound,rightBound]=rankOrder.getPassStyleCover(passStyle);\\nconst newRightBound=`${encodePassable(rightOperand)}~`;\\nif(newRightBound!==undefined){\\nrightBound=newRightBound;}\\n\\nreturn[leftBound,rightBound];}});\\n\\n\\n\\n/** @type {MatchHelper} */\\nconst matchLTHelper=makeFar.Far('match:lt helper',{\\ncheckMatches:(specimen,rightOperand,check)=>\\ncompareKeys.keyLT(specimen,rightOperand)||\\ncheck(false,index.redacted`${specimen} - Must be < ${rightOperand}`),\\n\\ncheckIsWellFormed:checkKey.checkKey,\\n\\ngetRankCover:matchLTEHelper.getRankCover});\\n\\n\\n/** @type {MatchHelper} */\\nconst matchGTEHelper=makeFar.Far('match:gte helper',{\\ncheckMatches:(specimen,rightOperand,check)=>\\ncompareKeys.keyGTE(specimen,rightOperand)||\\ncheck(false,index.redacted`${specimen} - Must be >= ${rightOperand}`),\\n\\ncheckIsWellFormed:checkKey.checkKey,\\n\\ngetRankCover:(rightOperand,encodePassable)=>{\\nconst passStyle=passStyleOf.passStyleOf(rightOperand);\\n/* The prefer-const makes no sense when some of the variables need*/\\n/* to be `let`*/\\n/* eslint-disable-next-line prefer-const*/\\nlet[leftBound,rightBound]=rankOrder.getPassStyleCover(passStyle);\\nconst newLeftBound=encodePassable(rightOperand);\\nif(newLeftBound!==undefined){\\nleftBound=newLeftBound;}\\n\\nreturn[leftBound,rightBound];}});\\n\\n\\n\\n/** @type {MatchHelper} */\\nconst matchGTHelper=makeFar.Far('match:gt helper',{\\ncheckMatches:(specimen,rightOperand,check)=>\\ncompareKeys.keyGT(specimen,rightOperand)||\\ncheck(false,index.redacted`${specimen} - Must be > ${rightOperand}`),\\n\\ncheckIsWellFormed:checkKey.checkKey,\\n\\ngetRankCover:matchGTEHelper.getRankCover});\\n\\n\\n/** @type {MatchHelper} */\\nconst matchRecordOfHelper=makeFar.Far('match:recordOf helper',{\\ncheckMatches:(\\nspecimen,\\n[keyPatt,valuePatt,limits=undefined],\\ncheck)=>\\n{\\nconst{numPropertiesLimit,propertyNameLengthLimit}=limit(limits);\\nreturn(\\ncheckKind(specimen,'copyRecord',check)&&\\ncheck(\\nownKeys(specimen).length<=numPropertiesLimit,\\nindex.redacted`Must not have more than ${index.quote(\\nnumPropertiesLimit)\\n} properties: ${specimen}`)&&\\n\\nentries(specimen).every(\\n([key,value])=>\\napplyLabelingError.applyLabelingError(\\ncheck,\\n[\\nkey.length<=propertyNameLengthLimit,\\nindex.redacted`Property name must not be longer than ${index.quote(\\npropertyNameLengthLimit)\\n}`],\\n\\nkey)&&\\n\\ncheckMatches(\\nharden([key,value]),\\nharden([keyPatt,valuePatt]),\\ncheck,\\nkey)));},\\n\\n\\n\\n\\n\\ncheckIsWellFormed:(payload,check)=>\\ncheckIsWellFormedWithLimit(\\npayload,\\nharden([MM.pattern(),MM.pattern()]),\\ncheck,\\n'match:recordOf payload'),\\n\\n\\ngetRankCover:(_entryPatt)=>rankOrder.getPassStyleCover('copyRecord')});\\n\\n\\n/** @type {MatchHelper} */\\nconst matchArrayOfHelper=makeFar.Far('match:arrayOf helper',{\\ncheckMatches:(specimen,[subPatt,limits=undefined],check)=>{\\nconst{arrayLengthLimit}=limit(limits);\\n/* prettier-ignore*/\\nreturn(\\ncheckKind(specimen,'copyArray',check)&&(\\n/** @type {Array} */specimen.length<=arrayLengthLimit||\\ncheck(\\nfalse,\\nindex.redacted`Array length ${specimen.length} must be <= limit ${arrayLengthLimit}`))&&\\n\\narrayEveryMatchPattern(specimen,subPatt,check));},\\n\\n\\n\\ncheckIsWellFormed:(payload,check)=>\\ncheckIsWellFormedWithLimit(\\npayload,\\nharden([MM.pattern()]),\\ncheck,\\n'match:arrayOf payload'),\\n\\n\\ngetRankCover:()=>rankOrder.getPassStyleCover('copyArray')});\\n\\n\\n/** @type {MatchHelper} */\\nconst matchSetOfHelper=makeFar.Far('match:setOf helper',{\\ncheckMatches:(specimen,[keyPatt,limits=undefined],check)=>{\\nconst{numSetElementsLimit}=limit(limits);\\nreturn(\\ncheckKind(specimen,'copySet',check)&&\\ncheck(\\n/** @type {Array} */specimen.payload.length<numSetElementsLimit,\\nindex.redacted`Set must not have more than ${index.quote(numSetElementsLimit)} elements: ${\\nspecimen.payload.length\\n}`)&&\\n\\narrayEveryMatchPattern(specimen.payload,keyPatt,check,'set elements'));},\\n\\n\\n\\ncheckIsWellFormed:(payload,check)=>\\ncheckIsWellFormedWithLimit(\\npayload,\\nharden([MM.pattern()]),\\ncheck,\\n'match:setOf payload'),\\n\\n\\ngetRankCover:()=>rankOrder.getPassStyleCover('tagged')});\\n\\n\\n/** @type {MatchHelper} */\\nconst matchBagOfHelper=makeFar.Far('match:bagOf helper',{\\ncheckMatches:(\\nspecimen,\\n[keyPatt,countPatt,limits=undefined],\\ncheck)=>\\n{\\nconst{numUniqueBagElementsLimit,decimalDigitsLimit}=limit(limits);\\nreturn(\\ncheckKind(specimen,'copyBag',check)&&\\ncheck(\\n/** @type {Array} */specimen.payload.length<=\\nnumUniqueBagElementsLimit,\\nindex.redacted`Bag must not have more than ${index.quote(\\nnumUniqueBagElementsLimit)\\n} unique elements: ${specimen}`)&&\\n\\nspecimen.payload.every(\\n([key,count],i)=>\\ncheckMatches(key,keyPatt,check,`bag keys[${i}]`)&&\\napplyLabelingError.applyLabelingError(\\ncheckDecimalDigitsLimit,\\n[count,decimalDigitsLimit,check],\\n`bag counts[${i}]`)&&\\n\\ncheckMatches(count,countPatt,check,`bag counts[${i}]`)));},\\n\\n\\n\\n\\ncheckIsWellFormed:(payload,check)=>\\ncheckIsWellFormedWithLimit(\\npayload,\\nharden([MM.pattern(),MM.pattern()]),\\ncheck,\\n'match:bagOf payload'),\\n\\n\\ngetRankCover:()=>rankOrder.getPassStyleCover('tagged')});\\n\\n\\n/** @type {MatchHelper} */\\nconst matchMapOfHelper=makeFar.Far('match:mapOf helper',{\\ncheckMatches:(\\nspecimen,\\n[keyPatt,valuePatt,limits=undefined],\\ncheck)=>\\n{\\nconst{numMapEntriesLimit}=limit(limits);\\nreturn(\\ncheckKind(specimen,'copyMap',check)&&\\ncheck(\\n/** @type {Array} */specimen.payload.keys.length<=\\nnumMapEntriesLimit,\\nindex.redacted`CopyMap must have no more than ${index.quote(\\nnumMapEntriesLimit)\\n} entries: ${specimen}`)&&\\n\\narrayEveryMatchPattern(\\nspecimen.payload.keys,\\nkeyPatt,\\ncheck,\\n'map keys')&&\\n\\narrayEveryMatchPattern(\\nspecimen.payload.values,\\nvaluePatt,\\ncheck,\\n'map values'));},\\n\\n\\n\\n\\ncheckIsWellFormed:(payload,check)=>\\ncheckIsWellFormedWithLimit(\\npayload,\\nharden([MM.pattern(),MM.pattern()]),\\ncheck,\\n'match:mapOf payload'),\\n\\n\\ngetRankCover:(_entryPatt)=>rankOrder.getPassStyleCover('tagged')});\\n\\n\\n/**\\n * @param {Passable[]} specimen\\n * @param {Pattern[]} requiredPatt\\n * @param {Pattern[]} optionalPatt\\n * @returns {{\\n * requiredSpecimen: Passable[],\\n * optionalSpecimen: Passable[],\\n * restSpecimen: Passable[]\\n * }}\\n */\\nconst splitArrayParts=(specimen,requiredPatt,optionalPatt)=>{\\nconst numRequired=requiredPatt.length;\\nconst numOptional=optionalPatt.length;\\nconst requiredSpecimen=specimen.slice(0,numRequired);\\nconst optionalSpecimen=specimen.slice(\\nnumRequired,\\nnumRequired+numOptional);\\n\\nconst restSpecimen=specimen.slice(numRequired+numOptional);\\nreturn harden({requiredSpecimen,optionalSpecimen,restSpecimen});};\\n\\n\\n/**\\n * Optional specimen elements which are `undefined` pass unconditionally.\\n * We encode this with the `M.or` pattern so it also produces a good\\n * compression distinguishing `undefined` from absence.\\n *\\n * @param {Pattern[]} optionalPatt\\n * @param {number} length\\n * @returns {Pattern[]} The partialPatt\\n */\\nconst adaptArrayPattern=(optionalPatt,length)=>\\nharden(optionalPatt.slice(0,length).map((patt)=>MM.opt(patt)));\\n\\n/** @type {MatchHelper} */\\nconst matchSplitArrayHelper=makeFar.Far('match:splitArray helper',{\\ncheckMatches:(\\nspecimen,\\n[requiredPatt,optionalPatt=[],restPatt=MM.any()],\\ncheck)=>\\n{\\nif(!checkKind(specimen,'copyArray',check)){\\nreturn false;}\\n\\nconst{requiredSpecimen,optionalSpecimen,restSpecimen}=\\nsplitArrayParts(specimen,requiredPatt,optionalPatt);\\nconst partialPatt=adaptArrayPattern(\\noptionalPatt,\\noptionalSpecimen.length);\\n\\nlet argNum=0;\\nreturn(\\n(requiredSpecimen.length===requiredPatt.length||\\ncheck(\\nfalse,\\nindex.redacted`Expected at least ${index.quote(\\nrequiredPatt.length)\\n} arguments: ${specimen}`))&&\\n\\nrequiredPatt.every((p,i)=>\\n/* eslint-disable-next-line no-plusplus*/\\ncheckMatches(requiredSpecimen[i],p,check,`arg ${argNum++}`))&&\\n\\npartialPatt.every((p,i)=>\\n/* eslint-disable-next-line no-plusplus*/\\ncheckMatches(optionalSpecimen[i],p,check,`arg ${argNum++}?`))&&\\n\\ncheckMatches(restSpecimen,restPatt,check,'...rest'));},\\n\\n\\n\\n/**\\n * @param {Array} splitArray\\n * @param {Checker} check\\n */\\ncheckIsWellFormed:(splitArray,check)=>{\\nif(\\npassStyleOf.passStyleOf(splitArray)==='copyArray'&&(\\nsplitArray.length>=1||splitArray.length<=3))\\n{\\nconst[requiredPatt,optionalPatt=undefined,restPatt=undefined]=\\nsplitArray;\\nif(\\nisPattern(requiredPatt)&&\\npassStyleOf.passStyleOf(requiredPatt)==='copyArray'&&(\\noptionalPatt===undefined||\\nisPattern(optionalPatt)&&\\npassStyleOf.passStyleOf(optionalPatt)==='copyArray')&&(\\nrestPatt===undefined||isPattern(restPatt)))\\n{\\nreturn true;}}\\n\\n\\nreturn check(\\nfalse,\\nindex.redacted`Must be an array of a requiredPatt array, an optional optionalPatt array, and an optional restPatt: ${index.quote(\\nsplitArray)\\n}`);},\\n\\n\\n\\ngetRankCover:([\\n_requiredPatt,\\n_optionalPatt=undefined,\\n_restPatt=undefined])=>\\nrankOrder.getPassStyleCover('copyArray')});\\n\\n\\n/**\\n * @param {CopyRecord<Passable>} specimen\\n * @param {CopyRecord<Pattern>} requiredPatt\\n * @param {CopyRecord<Pattern>} optionalPatt\\n * @returns {{\\n * requiredSpecimen: CopyRecord<Passable>,\\n * optionalSpecimen: CopyRecord<Passable>,\\n * restSpecimen: CopyRecord<Passable>\\n * }}\\n */\\nconst splitRecordParts=(specimen,requiredPatt,optionalPatt)=>{\\n/* Not frozen! Mutated in place*/\\n/** @type {[string, Passable][]} */\\nconst requiredEntries=[];\\n/** @type {[string, Passable][]} */\\nconst optionalEntries=[];\\n/** @type {[string, Passable][]} */\\nconst restEntries=[];\\nfor(const[name,value]of entries(specimen)){\\nif(passStyleHelpers.hasOwnPropertyOf(requiredPatt,name)){\\nrequiredEntries.push([name,value]);}else\\nif(passStyleHelpers.hasOwnPropertyOf(optionalPatt,name)){\\noptionalEntries.push([name,value]);}else\\n{\\nrestEntries.push([name,value]);}}\\n\\n\\nreturn harden({\\nrequiredSpecimen:fromUniqueEntries.fromUniqueEntries(requiredEntries),\\noptionalSpecimen:fromUniqueEntries.fromUniqueEntries(optionalEntries),\\nrestSpecimen:fromUniqueEntries.fromUniqueEntries(restEntries)});};\\n\\n\\n\\n/**\\n * Optional specimen values which are `undefined` pass unconditionally.\\n * We encode this with the `M.or` pattern so it also produces a good\\n * compression distinguishing `undefined` from absence.\\n *\\n * @param {CopyRecord<Pattern>} optionalPatt\\n * @param {string[]} names\\n * @returns {CopyRecord<Pattern>} The partialPatt\\n */\\nconst adaptRecordPattern=(optionalPatt,names)=>\\nfromUniqueEntries.fromUniqueEntries(names.map((name)=>[name,MM.opt(optionalPatt[name])]));\\n\\n/** @type {MatchHelper} */\\nconst matchSplitRecordHelper=makeFar.Far('match:splitRecord helper',{\\ncheckMatches:(\\nspecimen,\\n[requiredPatt,optionalPatt={},restPatt=MM.any()],\\ncheck)=>\\n{\\nif(!checkKind(specimen,'copyRecord',check)){\\nreturn false;}\\n\\nconst{requiredSpecimen,optionalSpecimen,restSpecimen}=\\nsplitRecordParts(specimen,requiredPatt,optionalPatt);\\n\\nconst partialNames=/** @type {string[]} */ownKeys(optionalSpecimen);\\nconst partialPatt=adaptRecordPattern(optionalPatt,partialNames);\\nreturn(\\ncheckMatches(requiredSpecimen,requiredPatt,check)&&\\npartialNames.every((name)=>\\ncheckMatches(\\noptionalSpecimen[name],\\npartialPatt[name],\\ncheck,\\n`${name}?`))&&\\n\\n\\ncheckMatches(restSpecimen,restPatt,check,'...rest'));},\\n\\n\\n\\n/**\\n * @param {Array} splitArray\\n * @param {Checker} check\\n */\\ncheckIsWellFormed:(splitArray,check)=>{\\nif(\\npassStyleOf.passStyleOf(splitArray)==='copyArray'&&(\\nsplitArray.length>=1||splitArray.length<=3))\\n{\\nconst[requiredPatt,optionalPatt=undefined,restPatt=undefined]=\\nsplitArray;\\nif(\\nisPattern(requiredPatt)&&\\npassStyleOf.passStyleOf(requiredPatt)==='copyRecord'&&(\\noptionalPatt===undefined||\\nisPattern(optionalPatt)&&\\npassStyleOf.passStyleOf(optionalPatt)==='copyRecord')&&(\\nrestPatt===undefined||isPattern(restPatt)))\\n{\\nreturn true;}}\\n\\n\\nreturn check(\\nfalse,\\nindex.redacted`Must be an array of a requiredPatt record, an optional optionalPatt record, and an optional restPatt: ${index.quote(\\nsplitArray)\\n}`);},\\n\\n\\n\\ngetRankCover:([\\nrequiredPatt,\\n_optionalPatt=undefined,\\n_restPatt=undefined])=>\\nrankOrder.getPassStyleCover(passStyleOf.passStyleOf(requiredPatt))});\\n\\n\\n/** @type {Record<string, MatchHelper>} */\\nconst HelpersByMatchTag=harden({\\n'match:any':matchAnyHelper,\\n'match:and':matchAndHelper,\\n'match:or':matchOrHelper,\\n'match:not':matchNotHelper,\\n\\n'match:scalar':matchScalarHelper,\\n'match:key':matchKeyHelper,\\n'match:pattern':matchPatternHelper,\\n'match:kind':matchKindHelper,\\n'match:tagged':matchTaggedHelper,\\n'match:bigint':matchBigintHelper,\\n'match:nat':matchNatHelper,\\n'match:string':matchStringHelper,\\n'match:symbol':matchSymbolHelper,\\n'match:remotable':matchRemotableHelper,\\n\\n'match:lt':matchLTHelper,\\n'match:lte':matchLTEHelper,\\n'match:gte':matchGTEHelper,\\n'match:gt':matchGTHelper,\\n\\n'match:arrayOf':matchArrayOfHelper,\\n'match:recordOf':matchRecordOfHelper,\\n'match:setOf':matchSetOfHelper,\\n'match:bagOf':matchBagOfHelper,\\n'match:mapOf':matchMapOfHelper,\\n'match:splitArray':matchSplitArrayHelper,\\n'match:splitRecord':matchSplitRecordHelper});\\n\\n\\nconst makeMatcher=(tag,payload)=>{\\nconst matcher=makeTagged.makeTagged(tag,payload);\\nassertPattern(matcher);\\nreturn matcher;};\\n\\n\\nconst makeKindMatcher=(kind)=>makeMatcher('match:kind',kind);\\n\\nconst AnyShape=makeMatcher('match:any',undefined);\\nconst ScalarShape=makeMatcher('match:scalar',undefined);\\nconst KeyShape=makeMatcher('match:key',undefined);\\nconst PatternShape=makeMatcher('match:pattern',undefined);\\nconst BooleanShape=makeKindMatcher('boolean');\\nconst NumberShape=makeKindMatcher('number');\\nconst BigIntShape=makeTagged.makeTagged('match:bigint',[]);\\nconst NatShape=makeTagged.makeTagged('match:nat',[]);\\nconst StringShape=makeTagged.makeTagged('match:string',[]);\\nconst SymbolShape=makeTagged.makeTagged('match:symbol',[]);\\nconst RecordShape=makeTagged.makeTagged('match:recordOf',[AnyShape,AnyShape]);\\nconst ArrayShape=makeTagged.makeTagged('match:arrayOf',[AnyShape]);\\nconst SetShape=makeTagged.makeTagged('match:setOf',[AnyShape]);\\nconst BagShape=makeTagged.makeTagged('match:bagOf',[AnyShape,AnyShape]);\\nconst MapShape=makeTagged.makeTagged('match:mapOf',[AnyShape,AnyShape]);\\nconst RemotableShape=makeKindMatcher('remotable');\\nconst ErrorShape=makeKindMatcher('error');\\nconst PromiseShape=makeKindMatcher('promise');\\nconst UndefinedShape=makeKindMatcher('undefined');\\n\\n/**\\n * For when the last element of the payload is the optional limits,\\n * so that when it is `undefined` it is dropped from the end of the\\n * payloads array.\\n *\\n * @param {string} tag\\n * @param {Passable[]} payload\\n */\\nconst makeLimitsMatcher=(tag,payload)=>{\\nif(payload[payload.length-1]===undefined){\\npayload=harden(payload.slice(0,payload.length-1));}\\n\\nreturn makeMatcher(tag,payload);};\\n\\n\\nconst makeRemotableMatcher=(label=undefined)=>\\nlabel===undefined?\\nRemotableShape:\\nmakeMatcher('match:remotable',harden({label}));\\n\\n/**\\n * @template T\\n * @param {T} empty\\n * @param {T} base\\n * @param {T} [optional]\\n * @param {T} [rest]\\n * @returns {T[]}\\n */\\nconst makeSplitPayload=(\\nempty,\\nbase,\\noptional=undefined,\\nrest=undefined)=>\\n{\\nif(rest){\\nreturn[base,optional||empty,rest];}\\n\\nif(optional){\\nreturn[base,optional];}\\n\\nreturn[base];};\\n\\n\\n/* //////////////////*/\\n\\n/** @type {MatcherNamespace} */\\nconst M=harden({\\nany:()=>AnyShape,\\nand:(...patts)=>makeMatcher('match:and',patts),\\nor:(...patts)=>makeMatcher('match:or',patts),\\nnot:(subPatt)=>makeMatcher('match:not',subPatt),\\n\\nscalar:()=>ScalarShape,\\nkey:()=>KeyShape,\\npattern:()=>PatternShape,\\nkind:makeKindMatcher,\\ntagged:(tagPatt=M.string(),payloadPatt=M.any())=>\\nmakeMatcher('match:tagged',harden([tagPatt,payloadPatt])),\\nboolean:()=>BooleanShape,\\nnumber:()=>NumberShape,\\nbigint:(limits=undefined)=>\\nlimits?makeLimitsMatcher('match:bigint',[limits]):BigIntShape,\\nnat:(limits=undefined)=>\\nlimits?makeLimitsMatcher('match:nat',[limits]):NatShape,\\nstring:(limits=undefined)=>\\nlimits?makeLimitsMatcher('match:string',[limits]):StringShape,\\nsymbol:(limits=undefined)=>\\nlimits?makeLimitsMatcher('match:symbol',[limits]):SymbolShape,\\nrecord:(limits=undefined)=>\\nlimits?M.recordOf(M.any(),M.any(),limits):RecordShape,\\n/* struct: A pattern that matches CopyRecords with a fixed quantity of*/\\n/* entries where the values match patterns for corresponding keys is merely*/\\n/* a hardened object with patterns in the places of values for*/\\n/* corresponding keys.*/\\n/* For example, a pattern that matches CopyRecords that have a string value*/\\n/* for the key 'x' and a number for the key 'y' is:*/\\n/* harden({ x: M.string(), y: M.number() }).*/\\narray:(limits=undefined)=>\\nlimits?M.arrayOf(M.any(),limits):ArrayShape,\\n/* tuple: A pattern that matches CopyArrays with a fixed quantity of values*/\\n/* that match a heterogeneous array of patterns is merely a hardened array*/\\n/* of the respective patterns.*/\\n/* For example, a pattern that matches CopyArrays of length 2 that have a*/\\n/* string at index 0 and a number at index 1 is:*/\\n/* harden([ M.string(), M.number() ]).*/\\nset:(limits=undefined)=>limits?M.setOf(M.any(),limits):SetShape,\\nbag:(limits=undefined)=>\\nlimits?M.bagOf(M.any(),M.any(),limits):BagShape,\\nmap:(limits=undefined)=>\\nlimits?M.mapOf(M.any(),M.any(),limits):MapShape,\\n/* heterogeneous map: A pattern that matches CopyMaps with a fixed quantity*/\\n/* of entries where the value for each key matches a corresponding pattern*/\\n/* is merely a (hardened) CopyMap with patterns instead of values for the*/\\n/* corresponding keys.*/\\n/* For example, a pattern that matches CopyMaps where the value for the key*/\\n/* 'x' is a number and the value for the key 'y' is a string is:*/\\n/* makeCopyMap([['x', M.number()], ['y', M.string()]]).*/\\nremotable:makeRemotableMatcher,\\nerror:()=>ErrorShape,\\npromise:()=>PromiseShape,\\nundefined:()=>UndefinedShape,\\nnull:()=>null,\\n\\nlt:(rightOperand)=>makeMatcher('match:lt',rightOperand),\\nlte:(rightOperand)=>makeMatcher('match:lte',rightOperand),\\neq:(key)=>{\\ncheckKey.assertKey(key);\\nreturn key===undefined?M.undefined():key;},\\n\\nneq:(key)=>M.not(M.eq(key)),\\ngte:(rightOperand)=>makeMatcher('match:gte',rightOperand),\\ngt:(rightOperand)=>makeMatcher('match:gt',rightOperand),\\n\\nrecordOf:(keyPatt=M.any(),valuePatt=M.any(),limits=undefined)=>\\nmakeLimitsMatcher('match:recordOf',[keyPatt,valuePatt,limits]),\\narrayOf:(subPatt=M.any(),limits=undefined)=>\\nmakeLimitsMatcher('match:arrayOf',[subPatt,limits]),\\nsetOf:(keyPatt=M.any(),limits=undefined)=>\\nmakeLimitsMatcher('match:setOf',[keyPatt,limits]),\\nbagOf:(keyPatt=M.any(),countPatt=M.any(),limits=undefined)=>\\nmakeLimitsMatcher('match:bagOf',[keyPatt,countPatt,limits]),\\nmapOf:(keyPatt=M.any(),valuePatt=M.any(),limits=undefined)=>\\nmakeLimitsMatcher('match:mapOf',[keyPatt,valuePatt,limits]),\\nsplitArray:(base,optional=undefined,rest=undefined)=>\\nmakeMatcher(\\n'match:splitArray',\\nmakeSplitPayload([],base,optional,rest)),\\n\\nsplitRecord:(base,optional=undefined,rest=undefined)=>\\nmakeMatcher(\\n'match:splitRecord',\\nmakeSplitPayload({},base,optional,rest)),\\n\\nsplit:(base,rest=undefined)=>{\\nif(passStyleOf.passStyleOf(harden(base))==='copyArray'){\\n/* TODO at-ts-expect-error works locally but not from @endo/exo*/\\n/* @ts-expect-error We know it should be an array*/\\nreturn M.splitArray(base,rest&&[],rest);}else\\n{\\nreturn M.splitRecord(base,rest&&{},rest);}},\\n\\n\\npartial:(base,rest=undefined)=>{\\nif(passStyleOf.passStyleOf(harden(base))==='copyArray'){\\n/* TODO at-ts-expect-error works locally but not from @endo/exo*/\\n/* @ts-expect-error We know it should be an array*/\\nreturn M.splitArray([],base,rest);}else\\n{\\nreturn M.splitRecord({},base,rest);}},\\n\\n\\n\\neref:(t)=>M.or(t,M.promise()),\\nopt:(t)=>M.or(M.undefined(),t),\\n\\ninterface:(interfaceName,methodGuards,options)=>\\n/* eslint-disable-next-line no-use-before-define*/\\nmakeInterfaceGuard(interfaceName,methodGuards,options),\\ncall:(...argPatterns)=>\\n/* eslint-disable-next-line no-use-before-define*/\\nmakeMethodGuardMaker('sync',argPatterns),\\ncallWhen:(...argGuards)=>\\n/* eslint-disable-next-line no-use-before-define*/\\nmakeMethodGuardMaker('async',argGuards),\\n\\nawait:(argPattern)=>\\n/* eslint-disable-next-line no-use-before-define*/\\nmakeAwaitArgGuard(argPattern),\\nraw:()=>\\n/* eslint-disable-next-line no-use-before-define*/\\nmakeRawGuard()});\\n\\n\\nreturn harden({\\ncheckMatches,\\nmatches,\\nmustMatch,\\nassertPattern,\\nisPattern,\\ngetRankCover,\\nM,\\nkindOf});};\\n\\n\\n\\n/* Only include those whose meaning is independent of an imputed sort order*/\\n/* of remotables, or of encoding of passable as sortable strings. Thus,*/\\n/* getRankCover is omitted. To get one, you'd need to instantiate*/\\n/* `makePatternKit()` yourself. Since there are currently no external*/\\n/* uses of `getRankCover`, for clarity during development, `makePatternKit`*/\\n/* is not currently exported.*/\\nconst{\\ncheckMatches,\\nmatches,\\nmustMatch,\\nassertPattern,\\nisPattern,\\ngetRankCover,\\nM,\\nkindOf}=\\nmakePatternKit();\\n\\nMM=M;\\n\\n/* //////////////////////////// Guards ///////////////////////////////////////*/\\n\\n/* M.await(...)*/\\nconst AwaitArgGuardPayloadShape=harden({\\nargGuard:M.pattern()});\\n\\n\\nconst AwaitArgGuardShape=M.kind('guard:awaitArgGuard');\\n\\n/**\\n * @param {any} specimen\\n * @returns {specimen is AwaitArgGuard}\\n */\\nconst isAwaitArgGuard=(specimen)=>\\nmatches(specimen,AwaitArgGuardShape);\\nharden(isAwaitArgGuard);\\n\\n/**\\n * @param {any} specimen\\n * @returns {asserts specimen is AwaitArgGuard}\\n */\\nconst assertAwaitArgGuard=(specimen)=>{\\nmustMatch(specimen,AwaitArgGuardShape,'awaitArgGuard');};\\n\\nharden(assertAwaitArgGuard);\\n\\n/**\\n * @param {Pattern} argPattern\\n * @returns {AwaitArgGuard}\\n */\\nconst makeAwaitArgGuard=(argPattern)=>{\\n/** @type {AwaitArgGuard} */\\nconst result=makeTagged.makeTagged('guard:awaitArgGuard',{\\nargGuard:argPattern});\\n\\nassertAwaitArgGuard(result);\\nreturn result;};\\n\\n\\n/* M.raw()*/\\n\\nconst RawGuardPayloadShape=M.record();\\n\\nconst RawGuardShape=M.kind('guard:rawGuard');\\n\\nconst isRawGuard=(specimen)=>matches(specimen,RawGuardShape);\\n\\nconst assertRawGuard=(specimen)=>\\nmustMatch(specimen,RawGuardShape,'rawGuard');\\n\\n/**\\n * @returns {RawGuard}\\n */\\nconst makeRawGuard=()=>makeTagged.makeTagged('guard:rawGuard',{});\\n\\n/* M.call(...)*/\\n/* M.callWhen(...)*/\\n\\nconst SyncValueGuardShape=M.or(RawGuardShape,M.pattern());\\n\\nconst SyncValueGuardListShape=M.arrayOf(SyncValueGuardShape);\\n\\nconst ArgGuardShape=M.or(RawGuardShape,AwaitArgGuardShape,M.pattern());\\nconst ArgGuardListShape=M.arrayOf(ArgGuardShape);\\n\\nconst SyncMethodGuardPayloadShape=harden({\\ncallKind:'sync',\\nargGuards:SyncValueGuardListShape,\\noptionalArgGuards:M.opt(SyncValueGuardListShape),\\nrestArgGuard:M.opt(SyncValueGuardShape),\\nreturnGuard:SyncValueGuardShape});\\n\\n\\nconst AsyncMethodGuardPayloadShape=harden({\\ncallKind:'async',\\nargGuards:ArgGuardListShape,\\noptionalArgGuards:M.opt(ArgGuardListShape),\\nrestArgGuard:M.opt(SyncValueGuardShape),\\nreturnGuard:SyncValueGuardShape});\\n\\n\\nconst MethodGuardPayloadShape=M.or(\\nSyncMethodGuardPayloadShape,\\nAsyncMethodGuardPayloadShape);\\n\\n\\nconst MethodGuardShape=M.kind('guard:methodGuard');\\n\\n/**\\n * @param {any} specimen\\n * @returns {asserts specimen is MethodGuard}\\n */\\nconst assertMethodGuard=(specimen)=>{\\nmustMatch(specimen,MethodGuardShape,'methodGuard');};\\n\\nharden(assertMethodGuard);\\n\\n/**\\n * @param {'sync'|'async'} callKind\\n * @param {ArgGuard[]} argGuards\\n * @param {ArgGuard[]} [optionalArgGuards]\\n * @param {SyncValueGuard} [restArgGuard]\\n * @returns {MethodGuardMaker}\\n */\\nconst makeMethodGuardMaker=(\\ncallKind,\\nargGuards,\\noptionalArgGuards=undefined,\\nrestArgGuard=undefined)=>\\n\\nharden({\\noptional:(...optArgGuards)=>{\\noptionalArgGuards===undefined||\\nindex.throwRedacted`Can only have one set of optional guards`;\\nrestArgGuard===undefined||\\nindex.throwRedacted`optional arg guards must come before rest arg`;\\nreturn makeMethodGuardMaker(callKind,argGuards,optArgGuards);},\\n\\nrest:(rArgGuard)=>{\\nrestArgGuard===undefined||index.throwRedacted`Can only have one rest arg`;\\nreturn makeMethodGuardMaker(\\ncallKind,\\nargGuards,\\noptionalArgGuards,\\nrArgGuard);},\\n\\n\\nreturns:(returnGuard=M.undefined())=>{\\n/** @type {MethodGuard} */\\nconst result=makeTagged.makeTagged('guard:methodGuard',{\\ncallKind,\\nargGuards,\\noptionalArgGuards,\\nrestArgGuard,\\nreturnGuard});\\n\\nassertMethodGuard(result);\\nreturn result;}});\\n\\n\\n\\nconst InterfaceGuardPayloadShape=M.splitRecord(\\n{\\ninterfaceName:M.string(),\\nmethodGuards:M.recordOf(M.string(),MethodGuardShape)},\\n\\n{\\ndefaultGuards:M.or(M.undefined(),'passable','raw'),\\nsloppy:M.boolean(),\\nsymbolMethodGuards:M.mapOf(M.symbol(),MethodGuardShape)});\\n\\n\\n\\nconst InterfaceGuardShape=M.kind('guard:interfaceGuard');\\n\\n/**\\n * @param {any} specimen\\n * @returns {asserts specimen is InterfaceGuard}\\n */\\nconst assertInterfaceGuard=(specimen)=>{\\nmustMatch(specimen,InterfaceGuardShape,'interfaceGuard');};\\n\\nharden(assertInterfaceGuard);\\n\\n/**\\n * @template {Record<PropertyKey, MethodGuard>} [M = Record<PropertyKey, MethodGuard>]\\n * @param {string} interfaceName\\n * @param {M} methodGuards\\n * @param {{ sloppy?: boolean, defaultGuards?: DefaultGuardType }} [options]\\n * @returns {InterfaceGuard<M>}\\n */\\nconst makeInterfaceGuard=(interfaceName,methodGuards,options={})=>{\\nconst{sloppy=false,defaultGuards=sloppy?'passable':undefined}=\\noptions;\\n/* For backwards compatibility, string-keyed method guards are represented in*/\\n/* a CopyRecord. But symbol-keyed methods cannot be, so we put those in a*/\\n/* CopyMap when present.*/\\n/** @type {Record<string, MethodGuard>} */\\nconst stringMethodGuards={};\\n/** @type {Array<[symbol, MethodGuard]>} */\\nconst symbolMethodGuardsEntries=[];\\nfor(const key of ownKeys(methodGuards)){\\nconst value=methodGuards[/** @type {string} */key];\\nif(typeof key==='symbol'){\\nsymbolMethodGuardsEntries.push([key,value]);}else\\n{\\nstringMethodGuards[key]=value;}}\\n\\n\\n/** @type {InterfaceGuard} */\\nconst result=makeTagged.makeTagged('guard:interfaceGuard',{\\ninterfaceName,\\nmethodGuards:stringMethodGuards,\\n...(symbolMethodGuardsEntries.length?\\n{symbolMethodGuards:checkKey.makeCopyMap(symbolMethodGuardsEntries)}:\\n{}),\\ndefaultGuards});\\n\\nassertInterfaceGuard(result);\\nreturn(/** @type {InterfaceGuard<M>} */result);};\\n\\n\\nconst GuardPayloadShapes=harden({\\n'guard:awaitArgGuard':AwaitArgGuardPayloadShape,\\n'guard:rawGuard':RawGuardPayloadShape,\\n'guard:methodGuard':MethodGuardPayloadShape,\\n'guard:interfaceGuard':InterfaceGuardPayloadShape});exports.ArgGuardListShape=ArgGuardListShape;exports.AwaitArgGuardShape=AwaitArgGuardShape;exports.InterfaceGuardPayloadShape=InterfaceGuardPayloadShape;exports.InterfaceGuardShape=InterfaceGuardShape;exports.M=M;exports.MethodGuardPayloadShape=MethodGuardPayloadShape;exports.MethodGuardShape=MethodGuardShape;exports.RawGuardShape=RawGuardShape;exports.SyncValueGuardListShape=SyncValueGuardListShape;exports.SyncValueGuardShape=SyncValueGuardShape;exports.assertAwaitArgGuard=assertAwaitArgGuard;exports.assertInterfaceGuard=assertInterfaceGuard;exports.assertMethodGuard=assertMethodGuard;exports.assertPattern=assertPattern;exports.assertRawGuard=assertRawGuard;exports.checkMatches=checkMatches;exports.defaultLimits=defaultLimits;exports.getRankCover=getRankCover;exports.isAwaitArgGuard=isAwaitArgGuard;exports.isPattern=isPattern;exports.isRawGuard=isRawGuard;exports.kindOf=kindOf;exports.matches=matches;exports.mustMatch=mustMatch;\",\n \"node_modules/@endo/patterns/src/types.js\": \"\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n'use strict';/*/ <reference types=\\\"ses\\\"/>*/ /* NB: as of TS 5.5 nightly, TS thinks RankCover and Checker \\\"is declared but never read\\\" but they are*/ /**\\n * @import {Checker, CopyArray, CopyRecord, CopyTagged, Passable, PassStyle, Primitive, RemotableObject} from '@endo/pass-style';\\n * @import {RankCompare, RankCover} from '@endo/marshal';\\n */ /**\\n * @typedef {Exclude<Passable<RemotableObject, never>, Error | Promise>} Key\\n *\\n * Keys are Passable arbitrarily-nested pass-by-copy containers\\n * (CopyArray, CopyRecord, CopySet, CopyBag, CopyMap) in which every\\n * non-container leaf is either a Passable primitive value or a Remotable (a\\n * remotely-accessible object or presence for a remote object), or such leaves\\n * in isolation with no container.\\n *\\n * Keys are so named because they can be used as keys in CopyMaps and\\n * [agoric-sdk Stores](https://github.com/Agoric/agoric-sdk/blob/master/packages/store/docs/store-taxonomy.md),\\n * and as elements in CopySets and CopyBags.\\n *\\n * Keys cannot contain promises or errors, as these do not have useful\\n * distributed equality semantics. Keys also cannot contain any CopyTagged\\n * except for those recognized as CopySets, CopyBags, and CopyMaps.\\n *\\n * Be aware that we may recognize more CopyTaggeds over time, including\\n * CopyTaggeds recognized as Keys.\\n *\\n * Distributed equality is location independent.\\n * The same two Keys, passed to another location, will be `keyEQ` there iff\\n * they are `keyEQ` here. (`keyEQ` tests equality according to the\\n * key distributed equality semantics.)\\n */ /**\\n * @typedef {Primitive | RemotableObject} ScalarKey\\n */ /**\\n * @callback GetRankCover\\n * @param {Passable} payload\\n * @param {KeyToDBKey} encodePassable\\n * @returns {RankCover}\\n */ /**\\n * @callback KeyToDBKey\\n * @param {Key} key\\n * @returns {string}\\n */ /**\\n * @typedef {Exclude<Passable, Error | Promise>} Pattern\\n *\\n * Patterns are Passable arbitrarily-nested pass-by-copy containers\\n * (CopyArray, CopyRecord, CopySet, CopyBag, CopyMap) in which every\\n * non-container leaf is either a Key or a Matcher, or such leaves in isolation\\n * with no container.\\n *\\n * A Pattern acts as a declarative total predicate over Passables, where each\\n * Passable is either matched or not matched by it. Every Key is also a Pattern\\n * that matches only \\\"itself\\\", i.e., Keys that are `keyEQ` to it according to\\n * the key distributed equality semantics.\\n *\\n * Patterns cannot contain promises or errors, as these do\\n * not have useful distributed equality or matching semantics. Likewise,\\n * no Pattern can distinguish among promises, or distinguish among errors.\\n * Patterns also cannot contain any CopyTaggeds except for those recognized as\\n * CopySets, CopyBags, CopyMaps, or Matchers.\\n *\\n * Be aware that we may recognize more CopyTaggeds over time, including\\n * CopyTaggeds recognized as Patterns.\\n *\\n * Whether a Passable is matched by a given Pattern is location independent.\\n * If a given Passable and Pattern are passed to another location,\\n * the Passable will be matched by the Pattern there iff the Passable is matched\\n * by the Pattern here.\\n *\\n * Patterns are often used in a type-like manner, to represent the category\\n * of Passables that the Pattern is intended* to match. To keep this\\n * distinction clear, we often use the suffix \\\"Shape\\\" rather than \\\"Pattern\\\"\\n * to avoid confusion when the Pattern itself represents\\n * some category of Pattern. For example, an \\\"AmountShape\\\" represents the\\n * category of Amounts. And \\\"AmountPatternShape\\\" represents the\\n * category of Patterns over Amounts.\\n *\\n * * We say \\\"intended\\\" above because Patterns, in order to be declarative\\n * and Passable, cannot have the generality of predicates written in a\\n * Turing-universal programming language. Rather, to represent the category of\\n * things intended to be a Foo, a FooShape should reliably\\n * accept all Foos and reject only non-Foos. However, a FooShape may also accept\\n * non-Foos that \\\"look like\\\" or \\\"have the same shape as\\\" genuine Foos.\\n * An accurate predicate for e.g. input validation would need to supplement the\\n * Pattern check with code to detect the residual cases.\\n * We hope the \\\"Shape\\\" metaphor helps remind us of this type-like imprecision\\n * of Patterns.\\n */ /* TODO parameterize CopyTagged to support these refinements*/ /**\\n * @template {Key} [K=Key]\\n * @typedef {CopyTagged<'copySet', K[]>} CopySet\\n *\\n * A Passable collection of Keys that are all mutually distinguishable\\n * according to the key distributed equality semantics exposed by `keyEQ`.\\n */ /**\\n * @template {Key} [K=Key]\\n * @typedef {CopyTagged<'copyBag', [K, bigint][]>} CopyBag\\n *\\n * A Passable collection of entries with Keys that are all mutually distinguishable\\n * according to the key distributed equality semantics exposed by `keyEQ`,\\n * each with a corresponding positive cardinality.\\n */ /**\\n * @template {Key} [K=Key]\\n * @template {Passable} [V=Passable]\\n * @typedef {CopyTagged<'copyMap', { keys: K[], values: V[] }>} CopyMap\\n *\\n * A Passable collection of entries with Keys that are all mutually distinguishable\\n * according to the key distributed equality semantics exposed by `keyEQ`,\\n * each with a corresponding Passable value.\\n */ /**\\n * @typedef {CopySet | CopyBag | CopyMap} KeyCollection\\n *\\n * CopySet, CopyBag, and CopyMap all store Keys in reverse rankOrder,\\n * which supports generalized utilities.\\n */ /* TODO: enumerate Matcher tag values?*/ /**\\n * @typedef {CopyTagged<`match:${string}`, Passable>} Matcher\\n *\\n * A Pattern representing the predicate characterizing a category of Passables,\\n * such as strings or 8-bit unsigned integer numbers or CopyArrays of Remotables.\\n */ /**\\n * @typedef {RankCompare} FullCompare\\n * A `FullCompare` function satisfies all the invariants stated below for\\n * `RankCompare`'s relation with KeyCompare.\\n * In addition, its equality is as precise as the `KeyCompare`\\n * comparison defined below, in that, for all Keys `x` and `y`,\\n * `FullCompare(x, y) === 0` iff `KeyCompare(x, y) === 0`.\\n *\\n * For non-Key inputs, a `FullCompare` should be exactly as imprecise as\\n * `RankCompare`. For example, both will treat all errors as in the same\\n * equivalence class. Both will treat all promises as in the same\\n * equivalence class. Both will order tagged records the same way, which is\\n * admittedly weird because some (such as CopySets, CopyBags, and CopyMaps)\\n * will be considered Keys while others will be considered non-Keys.\\n */ /**\\n * @typedef {object} RankComparatorKit\\n * @property {RankCompare} comparator\\n * @property {RankCompare} antiComparator\\n */ /**\\n * @typedef {object} FullComparatorKit\\n * @property {FullCompare} comparator\\n * @property {FullCompare} antiComparator\\n */ /**\\n * @typedef {-1 | 0 | 1 | NaN} KeyComparison\\n * The result of a `KeyCompare` function that defines a meaningful\\n * and meaningfully precise partial order of Key values. See `KeyCompare`.\\n */ /**\\n * @callback KeyCompare\\n * `compareKeys` implements a partial order over Keys --- it defines relative\\n * position between two Keys but leaves some pairs incomparable (for example,\\n * subsets over sets is a partial order in which {} precedes {x} and {y}, which\\n * are mutually incomparable but both precede {x, y}). As with the rank ordering\\n * produced by `compareRank`, -1, 0, and 1 respectively mean \\\"less than\\\",\\n * \\\"equivalent to\\\", and \\\"greater than\\\". NaN means \\\"incomparable\\\" --- the first\\n * key is not less, equivalent, or greater than the second.\\n *\\n * By using NaN for \\\"incomparable\\\", the normal equivalence for using\\n * the return value in a comparison is preserved.\\n * `compareKeys(left, right) >= 0` iff `left` is greater than or\\n * equivalent to `right` in the partial ordering.\\n *\\n * Key order (a partial order) and rank order (a total preorder) are\\n * co-designed to support efficient range search for Key-based queries\\n * (@see {@link ../README.md#rank-order-and-key-order}).\\n *\\n * @param {Key} left\\n * @param {Key} right\\n * @returns {KeyComparison}\\n */ /**\\n * @callback CheckPattern\\n * @param {Passable} allegedPattern\\n * @param {Checker} check\\n * @returns {boolean}\\n */ /**\\n * @typedef {object} AllLimits\\n * @property {number} decimalDigitsLimit\\n * @property {number} stringLengthLimit\\n * @property {number} symbolNameLengthLimit\\n * @property {number} numPropertiesLimit\\n * @property {number} propertyNameLengthLimit\\n * @property {number} arrayLengthLimit\\n * @property {number} numSetElementsLimit\\n * @property {number} numUniqueBagElementsLimit\\n * @property {number} numMapEntriesLimit\\n */ /**\\n * @typedef {Partial<AllLimits>} Limits\\n */ /**\\n * @typedef {Exclude<PassStyle, 'tagged'> |\\n * 'copySet' | 'copyBag' | 'copyMap' |\\n * `match:${any}` | `guard:${any}`\\n * } Kind\\n * It is either a PassStyle other than 'tagged', or, if the underlying\\n * PassStyle is 'tagged', then the `getTag` value for tags that are\\n * recognized at the @endo/patterns level of abstraction. For each of those\\n * tags, a tagged record only has that kind if it satisfies the invariants\\n * that the @endo/patterns level associates with that kind.\\n */ /**\\n * @typedef {object} PatternMatchers\\n *\\n * @property {() => Matcher} any\\n * Matches any Passable.\\n *\\n * @property {(...subPatts: Pattern[]) => Matcher} and\\n * Matches against the intersection of all sub-Patterns.\\n *\\n * @property {(...subPatts: Pattern[]) => Matcher} or\\n * Matches against the union of all sub-Patterns\\n * (requiring a successful match against at least one).\\n *\\n * @property {(subPatt: Pattern) => Matcher} not\\n * Matches against the negation of the sub-Pattern.\\n *\\n * @property {() => Matcher} scalar\\n * Matches any Passable primitive value or Remotable.\\n * All matched values are Keys.\\n *\\n * @property {() => Matcher} key\\n * Matches any value that can be a key in a CopyMap\\n * or an element in a CopySet or CopyBag.\\n * All matched values are also valid Patterns that match only themselves.\\n *\\n * @property {() => Matcher} pattern\\n * Matches any Pattern that can be used to characterize Passables.\\n * A Pattern cannot contain promises or errors,\\n * as these are not stable enough to usefully match.\\n *\\n * @property {(kind: PassStyle | string) => Matcher} kind\\n * When `kind` specifies a PassStyle other than \\\"tagged\\\",\\n * matches any value having that PassStyle.\\n * Otherwise, when `kind` specifies a known tagged record tag\\n * (such as 'copySet', 'copyBag', 'copyMap', or 'match:scalar'),\\n * matches any CopyTagged with that tag and a valid tag-specific payload.\\n * Otherwise, does not match any value.\\n * TODO: Reject attempts to create a kind matcher with unknown `kind`?\\n *\\n * @property {(tagPatt?: Pattern, payloadPatt?: Pattern) => Matcher} tagged\\n * For matching an arbitrary Passable Tagged object, whether it has a\\n * recognized kind or not. If `tagPatt` is omitted, it defaults to\\n * `M.string()`. If `payloadPatt` is omitted, it defaults to\\n * `M.any()`.\\n *\\n * @property {() => Matcher} boolean\\n * Matches `true` or `false`.\\n *\\n * @property {() => Matcher} number\\n * Matches any floating point number,\\n * including `NaN` and either signed Infinity.\\n *\\n * @property {(limits?: Limits) => Matcher} bigint\\n * Matches any bigint, subject to limits.\\n *\\n * @property {(limits?: Limits) => Matcher} nat\\n * Matches any non-negative bigint, subject to limits.\\n *\\n * @property {(limits?: Limits) => Matcher} string\\n * Matches any string, subject to limits.\\n *\\n * @property {(limits?: Limits) => Matcher} symbol\\n * Matches any registered or well-known symbol,\\n * subject to limits.\\n *\\n * @property {(limits?: Limits) => Matcher} record\\n * Matches any CopyRecord, subject to limits.\\n *\\n * @property {(limits?: Limits) => Matcher} array\\n * Matches any CopyArray, subject to limits.\\n *\\n * @property {(limits?: Limits) => Matcher} set\\n * Matches any CopySet, subject to limits.\\n *\\n * @property {(limits?: Limits) => Matcher} bag\\n * Matches any CopyBag, subject to limits.\\n *\\n * @property {(limits?: Limits) => Matcher} map\\n * Matches any CopyMap, subject to limits.\\n *\\n * @property {(label?: string) => Matcher} remotable\\n * Matches a far object or its remote presence.\\n * The optional `label` is purely for diagnostic purposes and does not\\n * add any constraints.\\n *\\n * @property {() => Matcher} error\\n * Matches any error object.\\n * Error objects are Passable, but are neither Keys nor Patterns.\\n * They do not have a useful identity.\\n *\\n * @property {() => Matcher} promise\\n * Matches any promise object.\\n * Promises are Passable, but are neither Keys nor Patterns.\\n * They do not have a useful identity.\\n *\\n * @property {() => Matcher} undefined\\n * Matches the exact value `undefined`.\\n * All keys including `undefined` are already valid Patterns and\\n * so can validly represent themselves.\\n * But optional Pattern arguments `(patt = undefined) => ...`\\n * treat explicit `undefined` as omission of the argument.\\n * Thus, when a passed Pattern does not also need to be a Key,\\n * we recommend passing `M.undefined()` rather than `undefined`.\\n *\\n * @property {() => null} null\\n * Returns `null`, which matches only itself.\\n *\\n * @property {(rightOperand :Key) => Matcher} lt\\n * Matches any value that compareKeys reports as less than rightOperand.\\n *\\n * @property {(rightOperand :Key) => Matcher} lte\\n * Matches any value that compareKeys reports as less than or equal to\\n * rightOperand.\\n *\\n * @property {(key :Key) => Matcher} eq\\n * Matches any value that is equal to key.\\n *\\n * @property {(key :Key) => Matcher} neq\\n * Matches any value that is not equal to key.\\n *\\n * @property {(rightOperand :Key) => Matcher} gte\\n * Matches any value that compareKeys reports as greater than or equal\\n * to rightOperand.\\n *\\n * @property {(rightOperand :Key) => Matcher} gt\\n * Matches any value that compareKeys reports as greater than\\n * rightOperand.\\n *\\n * @property {(subPatt?: Pattern, limits?: Limits) => Matcher} arrayOf\\n * Matches any CopyArray whose elements are all matched by `subPatt`\\n * if defined, subject to limits.\\n *\\n * @property {(keyPatt?: Pattern,\\n * valuePatt?: Pattern,\\n * limits?: Limits\\n * ) => Matcher} recordOf\\n * Matches any CopyRecord whose keys are all matched by `keyPatt`\\n * if defined and values are all matched by `valuePatt` if defined,\\n * subject to limits.\\n *\\n * @property {(keyPatt?: Pattern, limits?: Limits) => Matcher} setOf\\n * Matches any CopySet whose elements are all matched by `keyPatt`\\n * if defined, subject to limits.\\n *\\n * @property {(keyPatt?: Pattern,\\n * countPatt?: Pattern,\\n * limits?: Limits\\n * ) => Matcher} bagOf\\n * Matches any CopyBag whose elements are all matched by `keyPatt`\\n * if defined and the cardinality of each is matched by `countPatt`\\n * if defined, subject to limits.\\n * `countPatt` is expected to rarely be useful,\\n * but is provided to minimize surprise.\\n *\\n * @property {(keyPatt?: Pattern,\\n * valuePatt?: Pattern,\\n * limits?: Limits\\n * ) => Matcher} mapOf\\n * Matches any CopyMap whose keys are all matched by `keyPatt` if defined\\n * and values are all matched by `valuePatt` if defined,\\n * subject to limits.\\n *\\n * @property {(required: Pattern[],\\n * optional?: Pattern[],\\n * rest?: Pattern,\\n * ) => Matcher} splitArray\\n * Matches any array --- typically an arguments list --- consisting of\\n * - an initial portion matched by `required`, and\\n * - a middle portion of length up to the length of `optional` that is\\n * matched by the equal-length prefix of `optional` if `optional` is\\n * defined, and\\n * - a remainder that is matched by `rest` if `rest` is defined.\\n * The array must be at least as long as `required`\\n * but its remainder can be arbitrarily short.\\n * Any array elements beyond the summed length of `required` and `optional`\\n * are collected and matched against `rest`.\\n *\\n * @property {(required: CopyRecord<Pattern>,\\n * optional?: CopyRecord<Pattern>,\\n * rest?: Pattern,\\n * ) => Matcher} splitRecord\\n * Matches any CopyRecord that can be split into component CopyRecords\\n * as follows:\\n * - all properties corresponding with a property of `required`\\n * - all properties corresponding with a property of `optional`\\n * but not corresponding with a property of `required`\\n * - all other properties\\n * where the first component is matched by `required`,\\n * the second component is matched by the subset of `optional`\\n * corresponding with its properties if `optional` is defined, and\\n * the third component is matched by `rest` if defined.\\n * The CopyRecord must have all properties that appear on `required`,\\n * but may omit properties that appear on `optional`.\\n *\\n * @property {(basePatt: CopyRecord<any> | CopyArray<any>,\\n * rest?: Pattern,\\n * ) => Matcher} split\\n * Deprecated. Use `M.splitArray` or `M.splitRecord` instead.\\n * An array or record is split into the first part that is matched by\\n * `basePatt`, and the remainder, which is matched against `rest` if present.\\n *\\n * @property {(basePatt: CopyRecord<any> | CopyArray<any>,\\n * rest?: Pattern,\\n * ) => Matcher} partial\\n * Deprecated. Use `M.splitArray` or `M.splitRecord` instead.\\n * An array or record is split into the first part that is matched by\\n * `basePatt`, and the remainder, which is matched against `rest` if present.\\n * `M.partial` differs from `M.split` in the handling of data that is\\n * described in `basePatt` but absent in a provided specimen:\\n * - For a CopyRecord, `M.partial` ignores properties of `basePatt`\\n * that are not present on the specimen.\\n * - For a CopyArray, `M.partial` ignores elements of `basePatt`\\n * at indices beyond the maximum index of the specimen.\\n *\\n * @property {(subPatt: Pattern) => Pattern} eref\\n * Matches any Passable that is either matched by `subPatt` or is a promise object.\\n * Note that validation is immediate, so (unlike the TypeScript `ERef<T>`\\n * type) `M.eref` matches a promise object whose fulfillment value is\\n * _not_ matched by `subPatt`.\\n * For describing a top-level parameter,\\n * `M.callWhen(..., M.await(p), ...)` is preferred over `M.call(..., M.eref(p), ...)`\\n * because the former always checks against the sub-Pattern (awaiting fulfillment\\n * if necessary) while the latter bypasses such checks when the relevant argument\\n * is a promise.\\n *\\n * @property {(subPatt: Pattern) => Pattern} opt\\n * Matches any Passable that is matched by `subPatt` or is the exact value `undefined`.\\n */ /**\\n * @typedef {undefined | 'passable' | 'raw'} DefaultGuardType\\n */ /**\\n * @typedef {<M extends Record<PropertyKey, MethodGuard>>(\\n * interfaceName: string,\\n * methodGuards: M,\\n * options: {defaultGuards?: undefined, sloppy?: false }) => InterfaceGuard<M>\\n * } MakeInterfaceGuardStrict\\n */ /**\\n * @typedef {(\\n * interfaceName: string,\\n * methodGuards: any,\\n * options: {defaultGuards?: 'passable' | 'raw', sloppy?: true }) => InterfaceGuard<any>\\n * } MakeInterfaceGuardSloppy\\n */ /**\\n * @typedef {<M extends Record<PropertyKey, MethodGuard>>(\\n * interfaceName: string,\\n * methodGuards: M,\\n * options?: {defaultGuards?: DefaultGuardType, sloppy?: boolean}) => InterfaceGuard<M>\\n * } MakeInterfaceGuardGeneral\\n */ /** @typedef {MakeInterfaceGuardStrict & MakeInterfaceGuardSloppy & MakeInterfaceGuardGeneral} MakeInterfaceGuard */ /**\\n * @typedef {object} GuardMakers\\n *\\n * @property {MakeInterfaceGuard} interface\\n * Guard the interface of an exo object\\n *\\n * @property {(...argPatterns: SyncValueGuard[]) => MethodGuardMaker} call\\n * Guard a synchronous call. Arguments not guarded by `M.raw()` are\\n * automatically hardened and must be at least Passable.\\n *\\n * @property {(...argGuards: ArgGuard[]) => MethodGuardMaker} callWhen\\n * Guard an async call. Arguments not guarded by `M.raw()` are automatically\\n * hardened and must be at least Passable.\\n *\\n * @property {(argPattern: Pattern) => AwaitArgGuard} await\\n * Guard a positional parameter in `M.callWhen`, awaiting it and matching its\\n * fulfillment against the provided pattern.\\n * For example, `M.callWhen(M.await(M.nat())).returns()` will await the first\\n * argument, check that its fulfillment satisfies `M.nat()`, and only then call\\n * the guarded method with that fulfillment. If the argument is a non-promise\\n * value that already satisfies `M.nat()`, then the result of `await`ing it will\\n * still pass, and `M.callWhen` will still delay the guarded method call to a\\n * future turn.\\n * If the argument is a promise that rejects rather than fulfills, or if its\\n * fulfillment does not satisfy the nested pattern, then the call is rejected\\n * without ever invoking the guarded method.\\n *\\n * Any `AwaitArgGuard` may not appear as a rest pattern or a result pattern,\\n * only a top-level single parameter pattern.\\n *\\n * @property {() => RawGuard} raw\\n * In parameter position, pass this argument through without any hardening or checking.\\n * In rest position, pass the rest of the arguments through without any hardening or checking.\\n * In return position, return the result without any hardening or checking.\\n */ /**\\n * @typedef {PatternMatchers & GuardMakers} MatcherNamespace\\n */ /** @typedef {(...args: any[]) => any} Method */ /**\\n * @template {Record<PropertyKey, MethodGuard>} [T=Record<PropertyKey, MethodGuard>]\\n * @typedef {{\\n * interfaceName: string,\\n * methodGuards:\\n * Omit<T, symbol> & Partial<{ [K in Extract<keyof T, symbol>]: never }>,\\n * symbolMethodGuards?:\\n * CopyMap<Extract<keyof T, symbol>, T[Extract<keyof T, symbol>]>,\\n * defaultGuards?: DefaultGuardType,\\n * sloppy?: boolean,\\n * }} InterfaceGuardPayload\\n */ /**\\n * @template {Record<PropertyKey, MethodGuard>} [T=Record<PropertyKey, MethodGuard>]\\n * @typedef {CopyTagged<'guard:interfaceGuard', InterfaceGuardPayload<T>>} InterfaceGuard\\n */ /**\\n * @typedef {MethodGuardOptional & MethodGuardRestReturns} MethodGuardMaker\\n * A method name and parameter/return signature like:\\n * ```js\\n * foo(a, b, c = d, ...e) => f\\n * ```\\n * should be guarded by something like:\\n * ```js\\n * {\\n * ...otherMethodGuards,\\n * foo: M.call(AShape, BShape).optional(CShape).rest(EShape).returns(FShape),\\n * }\\n * ```\\n/**\\n * @typedef {object} MethodGuardReturns\\n * @property {(returnGuard?: SyncValueGuard) => MethodGuard} returns\\n * Arguments have been specified, now finish by creating a `MethodGuard`.\\n * If the return guard is not `M.raw()`, the return value is automatically\\n * hardened and must be Passable.\\n */ /**\\n * @typedef {object} MethodGuardRest\\n * @property {(restArgGuard: SyncValueGuard) => MethodGuardReturns} rest\\n * If the rest argument guard is not `M.raw()`, all rest arguments are\\n * automatically hardened and must be Passable.\\n */ /**\\n * @typedef {MethodGuardRest & MethodGuardReturns} MethodGuardRestReturns\\n * Mandatory and optional arguments have been specified, now specify `rest`, or\\n * finish with `returns`.\\n */ /**\\n * @typedef {object} MethodGuardOptional\\n * @property {(...optArgGuards: ArgGuard[]) => MethodGuardRestReturns} optional\\n * Optional arguments not guarded with `M.raw()` are automatically hardened and\\n * must be Passable.\\n */ /**\\n * @typedef {{\\n * callKind: 'sync' | 'async',\\n * argGuards: ArgGuard[],\\n * optionalArgGuards?: ArgGuard[],\\n * restArgGuard?: SyncValueGuard,\\n * returnGuard: SyncValueGuard,\\n * }} MethodGuardPayload\\n */ /**\\n * @typedef {CopyTagged<'guard:methodGuard', MethodGuardPayload>} MethodGuard\\n */ /**\\n * @typedef {{\\n * argGuard: Pattern\\n * }} AwaitArgGuardPayload\\n */ /**\\n * @typedef {CopyTagged<'guard:awaitArgGuard', AwaitArgGuardPayload>} AwaitArgGuard\\n */ /**\\n * @typedef {{}} RawGuardPayload\\n */ /**\\n * @typedef {CopyTagged<'guard:rawGuard', RawGuardPayload>} RawGuard\\n */ /** @typedef {RawGuard | Pattern} SyncValueGuard */ /** @typedef {AwaitArgGuard | RawGuard | Pattern} ArgGuard */\",\n \"node_modules/@endo/promise-kit/index.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var promiseExecutorKit=require('./src/promise-executor-kit.js');var memoRace=require('./src/memo-race.js');var isPromise=require('./src/is-promise.js');\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nrequire('./src/types.js');/* global globalThis */ /** @type {PromiseConstructor} */\\nconst BestPipelinablePromise=globalThis.HandledPromise||Promise;\\n\\n/**\\n * makePromiseKit() builds a Promise object, and returns a record\\n * containing the promise itself, as well as separate facets for resolving\\n * and rejecting it.\\n *\\n * @template T\\n * @returns {IMPORT('./src/types.js').PromiseKit<T>}\\n */\\nfunction makePromiseKit(){\\nconst{resolve,reject,executor}=promiseExecutorKit.makeReleasingExecutorKit();\\n\\nconst promise=new BestPipelinablePromise(executor);\\n\\nreturn harden({promise,resolve,reject});}\\n\\nharden(makePromiseKit);\\n\\n/* NB: Another implementation for Promise.race would be to use the releasing executor,*/\\n/* However while it would no longer leak the raced promise objects themselves, it would*/\\n/* still leak reactions on the non-resolved promises contending for the race.*/\\n\\n/**\\n * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved\\n * or rejected.\\n *\\n * Unlike `Promise.race` it cleans up after itself so a non-resolved value doesn't hold onto\\n * the result promise.\\n *\\n * @template {readonly unknown[] | []} T\\n * @param {T} values An iterable of Promises.\\n * @returns {Promise<Awaited<T[number]>>} A new Promise.\\n */\\nfunction racePromises(values){\\nreturn harden(memoRace.memoRace.call(BestPipelinablePromise,values));}\\n\\nharden(racePromises);exports.isPromise=isPromise.isPromise;exports.makePromiseKit=makePromiseKit;exports.racePromises=racePromises;\",\n \"node_modules/@endo/promise-kit/src/is-promise.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});/**\\n * Determine if the argument is a Promise.\\n *\\n * @param {unknown} maybePromise The value to examine\\n * @returns {maybePromise is Promise} Whether it is a promise\\n */\\nfunction isPromise(maybePromise){\\nreturn Promise.resolve(maybePromise)===maybePromise;}\\n\\nharden(isPromise);exports.isPromise=isPromise;\",\n \"node_modules/@endo/promise-kit/src/memo-race.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});/* Initial version authored by Brian Kim:\\nhttps://github.com/nodejs/node/issues/17469#issuecomment-685216777\\n This is free and unencumbered software released into the public domain.\\n Anyone is free to copy, modify, publish, use, compile, sell, or\\ndistribute this software, either in source code form or as a compiled\\nbinary, for any purpose, commercial or non-commercial, and by any\\nmeans.\\n In jurisdictions that recognize copyright laws, the author or authors\\nof this software dedicate any and all copyright interest in the\\nsoftware to the public domain. We make this dedication for the benefit\\nof the public at large and to the detriment of our heirs and\\nsuccessors. We intend this dedication to be an overt act of\\nrelinquishment in perpetuity of all present and future rights to this\\nsoftware under copyright law.\\n THE SOFTWARE IS PROVIDED \\\"AS IS\\\", WITHOUT WARRANTY OF ANY KIND,\\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\\nIN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\\nOTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\\nARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\\nOTHER DEALINGS IN THE SOFTWARE.\\n For more information, please refer to <http://unlicense.org/>\\n*/\\n\\n\\n\\n\\n\\n\\n\\nconst isObject=(value)=>Object(value)===value;\\n\\n/**\\n * @template [T=any]\\n * @typedef {object} Deferred\\n * @property {(value?: IMPORT(\\\"./types.js\\\").ERef<T> ) => void} resolve\\n * @property {(err?: any ) => void} reject\\n */\\n\\n/**\\n * @typedef { never\\n * | {settled: false, deferreds: Set<Deferred>}\\n * | {settled: true, deferreds?: undefined}\\n * } PromiseMemoRecord\\n */\\n\\n/* Keys are the values passed to race, values are a record of data containing a*/\\n/* set of deferreds and whether the value has settled.*/\\n/** @type {WeakMap<object, PromiseMemoRecord>} */\\nconst knownPromises=new WeakMap();\\n\\n/**\\n * @param {PromiseMemoRecord | undefined} record\\n * @returns {Set<Deferred>}\\n */\\nconst markSettled=(record)=>{\\nif(!record||record.settled){\\nreturn new Set();}\\n\\n\\nconst{deferreds}=record;\\nObject.assign(record,{\\ndeferreds:undefined,\\nsettled:true});\\n\\nObject.freeze(record);\\nreturn deferreds;};\\n\\n\\n/**\\n *\\n * @param {any} value\\n * @returns {PromiseMemoRecord}\\n */\\nconst getMemoRecord=(value)=>{\\nif(!isObject(value)){\\n/* If the contender is a primitive, attempting to use it as a key in the*/\\n/* weakmap would throw an error. Luckily, it is safe to call*/\\n/* `Promise.resolve(contender).then` on a primitive value multiple times*/\\n/* because the promise fulfills immediately. So we fake a settled record.*/\\nreturn harden({settled:true});}\\n\\n\\nlet record=knownPromises.get(value);\\n\\nif(!record){\\nrecord={deferreds:new Set(),settled:false};\\nknownPromises.set(value,record);\\n/* This call to `then` happens once for the lifetime of the value.*/\\nPromise.resolve(value).then(\\n(val)=>{\\nfor(const{resolve}of markSettled(record)){\\nresolve(val);}},\\n\\n\\n(err)=>{\\nfor(const{reject}of markSettled(record)){\\nreject(err);}});}\\n\\n\\n\\n\\nreturn record;};\\n\\n\\nconst{race}={\\n/**\\n * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved\\n * or rejected.\\n *\\n * Unlike `Promise.race` it cleans up after itself so a non-resolved value doesn't hold onto\\n * the result promise.\\n *\\n * @template {readonly unknown[] | []} T\\n * @template {PromiseConstructor} [P=PromiseConstructor]\\n * @this {P}\\n * @param {T} values An iterable of Promises.\\n * @returns {Promise<Awaited<T[number]>>} A new Promise.\\n */\\nrace(values){\\nlet deferred;\\n/** @type {[...T]} */\\n/* @ts-expect-error filled by the loop*/\\nconst cachedValues=[];\\nconst C=this;\\nconst result=new C((resolve,reject)=>{\\ndeferred={resolve,reject};\\nfor(const value of values){\\ncachedValues.push(value);\\nconst{settled,deferreds}=getMemoRecord(value);\\nif(settled){\\n/* If the contender is settled (including primitives), it is safe*/\\n/* to call `Promise.resolve(value).then` on it.*/\\nC.resolve(value).then(resolve,reject);}else\\n{\\ndeferreds.add(deferred);}}});\\n\\n\\n\\n\\n/* The finally callback executes when any value settles, preventing any of*/\\n/* the unresolved values from retaining a reference to the resolved value.*/\\nreturn result.finally(()=>{\\nfor(const value of cachedValues){\\nconst{deferreds}=getMemoRecord(value);\\nif(deferreds){\\ndeferreds.delete(deferred);}}});}};exports.memoRace=race;\",\n \"node_modules/@endo/promise-kit/src/promise-executor-kit.js\": \"'use strict';\\n\\n\\n\\n\\n\\n\\n\\n\\nObject.defineProperty(exports,'__esModule',{value:true});/*/ <reference types=\\\"ses\\\"/>*/ /**\\n * @template T\\n * @callback PromiseExecutor The promise executor\\n * @param {(value: IMPORT('./types.js').ERef<T>) => void} resolve\\n * @param {(reason: any) => void} reject\\n */ /**\\n * makeReleasingExecutorKit() builds resolve/reject functions which drop references\\n * to the resolve/reject functions gathered from an executor to be used with a\\n * promise constructor.\\n *\\n * @template T\\n * @returns {Pick<IMPORT('./types.js').PromiseKit<T>, 'resolve' | 'reject'> & { executor: PromiseExecutor<T>}}\\n */const makeReleasingExecutorKit=()=>{/** @type {null | undefined | ((value: IMPORT('./types.js').ERef<T>) => void)} */let internalResolve;/** @type {null | undefined | ((reason: unknown) => void)} */let internalReject;\\n\\n/** @param {IMPORT('./types.js').ERef<T>} value */\\nconst resolve=(value)=>{\\nif(internalResolve){\\ninternalResolve(value);\\ninternalResolve=null;\\ninternalReject=null;}else\\n{\\nassert(internalResolve===null);}};\\n\\n\\n\\n/** @param {unknown} reason */\\nconst reject=(reason)=>{\\nif(internalReject){\\ninternalReject(reason);\\ninternalResolve=null;\\ninternalReject=null;}else\\n{\\nassert(internalReject===null);}};\\n\\n\\n\\nconst executor=(res,rej)=>{\\nassert(internalResolve===undefined&&internalReject===undefined);\\ninternalResolve=res;\\ninternalReject=rej;};\\n\\n\\nreturn harden({resolve,reject,executor});};\\n\\nharden(makeReleasingExecutorKit);exports.makeReleasingExecutorKit=makeReleasingExecutorKit;\",\n \"node_modules/@endo/promise-kit/src/types.js\": \"'use strict';/**\\n * @template T\\n * @typedef {object} PromiseKit A reified Promise\\n * @property {(value: ERef<T>) => void} resolve\\n * @property {(reason: any) => void} reject\\n * @property {Promise<T>} promise\\n */\",\n \"node_modules/@endo/zip/index.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('./src/types.js');var reader=require('./src/reader.js');var writer=require('./src/writer.js');/* eslint-disable-next-line import/export*/exports.ZipReader=reader.ZipReader;exports.readZip=reader.readZip;exports.ZipWriter=writer.ZipWriter;exports.writeZip=writer.writeZip;\",\n \"node_modules/@endo/zip/src/buffer-reader.js\": \"'use strict';\\nObject.defineProperty(exports,'__esModule',{value:true});/* @ts-check*/ /* eslint no-bitwise: [\\\"off\\\"] */\\n\\nconst q=JSON.stringify;\\n\\n/**\\n * @typedef {object} BufferReaderState\\n * @property {Uint8Array} bytes\\n * @property {DataView} data\\n * @property {number} length\\n * @property {number} index\\n * @property {number} offset\\n */\\n\\n/** @type {WeakMap<BufferReader, BufferReaderState>} */\\nconst privateFields=new WeakMap();\\n\\n/** @type {(bufferReader: BufferReader) => BufferReaderState} */\\nconst privateFieldsGet=privateFields.get.bind(privateFields);\\n\\nclass BufferReader{\\n/**\\n * @param {ArrayBuffer} buffer\\n */\\nconstructor(buffer){\\nconst bytes=new Uint8Array(buffer);\\nconst data=new DataView(bytes.buffer);\\nprivateFields.set(this,{\\nbytes,\\ndata,\\nlength:bytes.length,\\nindex:0,\\noffset:0});}\\n\\n\\n\\n/**\\n * @returns {number}\\n */\\nget length(){\\nreturn privateFieldsGet(this).length;}\\n\\n\\n/**\\n * @returns {number}\\n */\\nget index(){\\nreturn privateFieldsGet(this).index;}\\n\\n\\n/**\\n * @param {number} index\\n */\\nset index(index){\\nthis.seek(index);}\\n\\n\\n/**\\n * @param {number} offset\\n */\\nset offset(offset){\\nconst fields=privateFieldsGet(this);\\nif(offset>fields.data.byteLength){\\nthrow Error('Cannot set offset beyond length of underlying data');}\\n\\nif(offset<0){\\nthrow Error('Cannot set negative offset');}\\n\\nfields.offset=offset;\\nfields.length=fields.data.byteLength-fields.offset;}\\n\\n\\n/**\\n * @param {number} index\\n * @returns {boolean} whether the read head can move to the given absolute\\n * index.\\n */\\ncanSeek(index){\\nconst fields=privateFieldsGet(this);\\nreturn index>=0&&fields.offset+index<=fields.length;}\\n\\n\\n/**\\n * @param {number} index the index to check.\\n * @throws {Error} an Error if the index is out of bounds.\\n */\\nassertCanSeek(index){\\nconst fields=privateFieldsGet(this);\\nif(!this.canSeek(index)){\\nthrow Error(\\n`End of data reached (data length = ${fields.length}, asked index ${index}`);}}\\n\\n\\n\\n\\n/**\\n * @param {number} index\\n * @returns {number} prior index\\n */\\nseek(index){\\nconst fields=privateFieldsGet(this);\\nconst restore=fields.index;\\nthis.assertCanSeek(index);\\nfields.index=index;\\nreturn restore;}\\n\\n\\n/**\\n * @param {number} size\\n * @returns {Uint8Array}\\n */\\npeek(size){\\nconst fields=privateFieldsGet(this);\\n/* Clamp size.*/\\nsize=Math.max(0,Math.min(fields.length-fields.index,size));\\nif(size===0){\\n/* in IE10, when using subarray(idx, idx), we get the array [0x00] instead of [].*/\\nreturn new Uint8Array(0);}\\n\\nconst result=fields.bytes.subarray(\\nfields.offset+fields.index,\\nfields.offset+fields.index+size);\\n\\nreturn result;}\\n\\n\\n/**\\n * @param {number} offset\\n */\\ncanRead(offset){\\nconst fields=privateFieldsGet(this);\\nreturn this.canSeek(fields.index+offset);}\\n\\n\\n/**\\n * Check that the offset will not go too far.\\n *\\n * @param {number} offset the additional offset to check.\\n * @throws {Error} an Error if the offset is out of bounds.\\n */\\nassertCanRead(offset){\\nconst fields=privateFieldsGet(this);\\nthis.assertCanSeek(fields.index+offset);}\\n\\n\\n/**\\n * Get raw data without conversion, <size> bytes.\\n *\\n * @param {number} size the number of bytes to read.\\n * @returns {Uint8Array} the raw data.\\n */\\nread(size){\\nconst fields=privateFieldsGet(this);\\nthis.assertCanRead(size);\\nconst result=this.peek(size);\\nfields.index+=size;\\nreturn result;}\\n\\n\\n/**\\n * @returns {number}\\n */\\nreadUint8(){\\nconst fields=privateFieldsGet(this);\\nthis.assertCanRead(1);\\nconst index=fields.offset+fields.index;\\nconst value=fields.data.getUint8(index);\\nfields.index+=1;\\nreturn value;}\\n\\n\\n/**\\n * @returns {number}\\n * @param {boolean=} littleEndian\\n */\\nreadUint16(littleEndian){\\nconst fields=privateFieldsGet(this);\\nthis.assertCanRead(2);\\nconst index=fields.offset+fields.index;\\nconst value=fields.data.getUint16(index,littleEndian);\\nfields.index+=2;\\nreturn value;}\\n\\n\\n/**\\n * @returns {number}\\n * @param {boolean=} littleEndian\\n */\\nreadUint32(littleEndian){\\nconst fields=privateFieldsGet(this);\\nthis.assertCanRead(4);\\nconst index=fields.offset+fields.index;\\nconst value=fields.data.getUint32(index,littleEndian);\\nfields.index+=4;\\nreturn value;}\\n\\n\\n/**\\n * @param {number} index\\n * @returns {number}\\n */\\nbyteAt(index){\\nconst fields=privateFieldsGet(this);\\nreturn fields.bytes[fields.offset+index];}\\n\\n\\n/**\\n * @param {number} offset\\n */\\nskip(offset){\\nconst fields=privateFieldsGet(this);\\nthis.seek(fields.index+offset);}\\n\\n\\n/**\\n * @param {Uint8Array} expected\\n * @returns {boolean}\\n */\\nexpect(expected){\\nconst fields=privateFieldsGet(this);\\nif(!this.matchAt(fields.index,expected)){\\nreturn false;}\\n\\nfields.index+=expected.length;\\nreturn true;}\\n\\n\\n/**\\n * @param {number} index\\n * @param {Uint8Array} expected\\n * @returns {boolean}\\n */\\nmatchAt(index,expected){\\nconst fields=privateFieldsGet(this);\\nif(index+expected.length>fields.length||index<0){\\nreturn false;}\\n\\nfor(let i=0;i<expected.length;i+=1){\\nif(expected[i]!==this.byteAt(index+i)){\\nreturn false;}}\\n\\n\\nreturn true;}\\n\\n\\n/**\\n * @param {Uint8Array} expected\\n */\\nassert(expected){\\nconst fields=privateFieldsGet(this);\\nif(!this.expect(expected)){\\nthrow Error(\\n`Expected ${q(expected)} at ${fields.index}, got ${this.peek(\\nexpected.length)\\n}`);}}\\n\\n\\n\\n\\n/**\\n * @param {Uint8Array} expected\\n * @returns {number}\\n */\\nfindLast(expected){\\nconst fields=privateFieldsGet(this);\\nlet index=fields.length-expected.length;\\nwhile(index>=0&&!this.matchAt(index,expected)){\\nindex-=1;}\\n\\nreturn index;}}exports.BufferReader=BufferReader;\",\n \"node_modules/@endo/zip/src/buffer-writer.js\": \"'use strict';\\n\\n\\nObject.defineProperty(exports,'__esModule',{value:true});/* @ts-check*/ /* eslint no-bitwise: [\\\"off\\\"] */ /**\\n * @type {WeakMap<BufferWriter, {\\n * length: number,\\n * index: number,\\n * bytes: Uint8Array,\\n * data: DataView,\\n * capacity: number,\\n * }>}\\n */\\nconst privateFields=new WeakMap();\\n\\n/**\\n * @param {BufferWriter} self\\n */\\nconst getPrivateFields=(self)=>{\\nconst fields=privateFields.get(self);\\nif(!fields){\\nthrow Error('BufferWriter fields are not initialized');}\\n\\nreturn fields;};\\n\\n\\nconst assertNatNumber=(n)=>{\\nif(Number.isSafeInteger(n)&&/** @type {number} */n>=0){\\nreturn;}\\n\\nthrow TypeError(`must be a non-negative integer, got ${n}`);};\\n\\n\\nclass BufferWriter{\\n/**\\n * @returns {number}\\n */\\nget length(){\\nreturn getPrivateFields(this).length;}\\n\\n\\n/**\\n * @returns {number}\\n */\\nget index(){\\nreturn getPrivateFields(this).index;}\\n\\n\\n/**\\n * @param {number} index\\n */\\nset index(index){\\nthis.seek(index);}\\n\\n\\n/**\\n * @param {number=} capacity\\n */\\nconstructor(capacity=16){\\nconst bytes=new Uint8Array(capacity);\\nconst data=new DataView(bytes.buffer);\\nprivateFields.set(this,{\\nbytes,\\ndata,\\nindex:0,\\nlength:0,\\ncapacity});}\\n\\n\\n\\n/**\\n * @param {number} required\\n */\\nensureCanSeek(required){\\nassertNatNumber(required);\\nconst fields=getPrivateFields(this);\\nlet capacity=fields.capacity;\\nwhile(capacity<required){\\ncapacity*=2;}\\n\\nconst bytes=new Uint8Array(capacity);\\nconst data=new DataView(bytes.buffer);\\nbytes.set(fields.bytes.subarray(0,fields.length));\\nfields.bytes=bytes;\\nfields.data=data;\\nfields.capacity=capacity;}\\n\\n\\n/**\\n * @param {number} index\\n */\\nseek(index){\\nconst fields=getPrivateFields(this);\\nthis.ensureCanSeek(index);\\nfields.index=index;\\nfields.length=Math.max(fields.index,fields.length);}\\n\\n\\n/**\\n * @param {number} size\\n */\\nensureCanWrite(size){\\nassertNatNumber(size);\\nconst fields=getPrivateFields(this);\\nthis.ensureCanSeek(fields.index+size);}\\n\\n\\n/**\\n * @param {Uint8Array} bytes\\n */\\nwrite(bytes){\\nconst fields=getPrivateFields(this);\\nthis.ensureCanWrite(bytes.byteLength);\\nfields.bytes.set(bytes,fields.index);\\nfields.index+=bytes.byteLength;\\nfields.length=Math.max(fields.index,fields.length);}\\n\\n\\n/**\\n * @param {number} start\\n * @param {number} end\\n */\\nwriteCopy(start,end){\\nassertNatNumber(start);\\nassertNatNumber(end);\\nconst fields=getPrivateFields(this);\\nconst size=end-start;\\nthis.ensureCanWrite(size);\\nfields.bytes.copyWithin(fields.index,start,end);\\nfields.index+=size;\\nfields.length=Math.max(fields.index,fields.length);}\\n\\n\\n/**\\n * @param {number} value\\n */\\nwriteUint8(value){\\nconst fields=getPrivateFields(this);\\nthis.ensureCanWrite(1);\\nfields.data.setUint8(fields.index,value);\\nfields.index+=1;\\nfields.length=Math.max(fields.index,fields.length);}\\n\\n\\n/**\\n * @param {number} value\\n * @param {boolean=} littleEndian\\n */\\nwriteUint16(value,littleEndian){\\nconst fields=getPrivateFields(this);\\nthis.ensureCanWrite(2);\\nconst index=fields.index;\\nfields.data.setUint16(index,value,littleEndian);\\nfields.index+=2;\\nfields.length=Math.max(fields.index,fields.length);}\\n\\n\\n/**\\n * @param {number} value\\n * @param {boolean=} littleEndian\\n */\\nwriteUint32(value,littleEndian){\\nconst fields=getPrivateFields(this);\\nthis.ensureCanWrite(4);\\nconst index=fields.index;\\nfields.data.setUint32(index,value,littleEndian);\\nfields.index+=4;\\nfields.length=Math.max(fields.index,fields.length);}\\n\\n\\n/**\\n * @param {number=} begin\\n * @param {number=} end\\n * @returns {Uint8Array}\\n */\\nsubarray(begin,end){\\nconst fields=getPrivateFields(this);\\nreturn fields.bytes.subarray(0,fields.length).subarray(begin,end);}\\n\\n\\n/**\\n * @param {number=} begin\\n * @param {number=} end\\n * @returns {Uint8Array}\\n */\\nslice(begin,end){\\nreturn this.subarray(begin,end).slice();}}exports.BufferWriter=BufferWriter;\",\n \"node_modules/@endo/zip/src/compression.js\": \"'use strict';\\n\\nObject.defineProperty(exports,'__esModule',{value:true});/* @ts-check*/ /* STORE is the magic number for \\\"not compressed\\\".*/\\nconst STORE=0;exports.STORE=STORE;\",\n \"node_modules/@endo/zip/src/crc32.js\": \"'use strict';\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nObject.defineProperty(exports,'__esModule',{value:true});/* @ts-check*/ /* eslint no-bitwise: [\\\"off\\\"] */ /**\\n * The following functions `makeTable` and `crc32` come from `pako`, from\\n * pako/lib/zlib/crc32.js released under the MIT license, see pako\\n * https://github.com/nodeca/pako/\\n */ /* Use ordinary array, since untyped makes no boost here*/ /**\\n * @returns {Array<number>}\\n */function makeTable(){let c;const table=[];\\nfor(let n=0;n<256;n+=1){\\nc=n;\\nfor(let k=0;k<8;k+=1){\\nc=c&1?0xedb88320^c>>>1:c>>>1;}\\n\\ntable[n]=c;}\\n\\n\\nreturn table;}\\n\\n\\n/* Initialize a table of 256 signed 32 bit integers.*/\\nconst table=makeTable();\\n\\n/**\\n * @param {Uint8Array} bytes\\n * @param {number} length\\n * @param {number} index\\n * @param {number} crc\\n */\\nfunction crc32(bytes,length=bytes.length,index=0,crc=0){\\nconst end=index+length;\\n\\ncrc^=-1;\\n\\nfor(let i=index;i<end;i+=1){\\ncrc=crc>>>8^table[(crc^bytes[i])&0xff];}\\n\\n\\nreturn(crc^-1)>>>0;}exports.crc32=crc32;\",\n \"node_modules/@endo/zip/src/format-reader.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('./types.js');var crc32=require('./crc32.js');var signature=require('./signature.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\ncompression=require('./compression.js');/* @ts-check*/ /* q, as in quote, for quoting strings in errors*/\\nconst q=JSON.stringify;\\n\\nconst MAX_VALUE_16BITS=65535;\\nconst MAX_VALUE_32BITS=4294967295;\\n\\nconst textDecoder=new TextDecoder();\\n\\n/**\\n * @param {number} bitFlag\\n * @returns {boolean}\\n */\\nfunction isEncrypted(bitFlag){\\nreturn(bitFlag&0x0001)===0x0001;}\\n\\n\\n/**\\n * @param {BufferReader} reader\\n * @returns {Date}\\n * @see http://www.delorie.com/djgpp/doc/rbinter/it/65/16.html\\n * @see http://www.delorie.com/djgpp/doc/rbinter/it/66/16.html\\n */\\nfunction readDosDateTime(reader){\\nconst dosTime=reader.readUint32(true);\\nreturn new Date(\\nDate.UTC(\\n(dosTime>>25&0x7f)+1980,/* year*/\\n(dosTime>>21&0x0f)-1,/* month*/\\ndosTime>>16&0x1f,/* day*/\\ndosTime>>11&0x1f,/* hour*/\\ndosTime>>5&0x3f,/* minute*/\\n(dosTime&0x1f)<<1/* second*/));}\\n\\n\\n\\n\\n/**\\n * @param {BufferReader} reader\\n * @returns {ArchiveHeaders}\\n */\\nfunction readHeaders(reader){\\nreturn{\\nversionNeeded:reader.readUint16(true),\\nbitFlag:reader.readUint16(true),\\ncompressionMethod:reader.readUint16(true),\\ndate:readDosDateTime(reader),\\ncrc32:reader.readUint32(true),\\ncompressedLength:reader.readUint32(true),\\nuncompressedLength:reader.readUint32(true)};}\\n\\n\\n\\n/**\\n * @param {BufferReader} reader\\n * @returns {CentralFileRecord}\\n */\\nfunction readCentralFileHeader(reader){\\nconst version=reader.readUint8();\\nconst madeBy=reader.readUint8();\\nconst headers=readHeaders(reader);\\nconst nameLength=reader.readUint16(true);\\nconst extraFieldsLength=reader.readUint16(true);\\nconst commentLength=reader.readUint16(true);\\nconst diskNumberStart=reader.readUint16(true);\\nconst internalFileAttributes=reader.readUint16(true);\\nconst externalFileAttributes=reader.readUint32(true);\\nconst fileStart=reader.readUint32(true);\\n\\nconst name=reader.read(nameLength);\\n/* TODO read extra fields, particularly Zip64*/\\nreader.skip(extraFieldsLength);\\n\\nif(headers.uncompressedLength===MAX_VALUE_32BITS){\\nthrow Error('Cannot read Zip64');}\\n\\nif(headers.compressedLength===MAX_VALUE_32BITS){\\nthrow Error('Cannot read Zip64');}\\n\\nif(fileStart===MAX_VALUE_32BITS){\\nthrow Error('Cannot read Zip64');}\\n\\nif(diskNumberStart===MAX_VALUE_32BITS){\\nthrow Error('Cannot read Zip64');}\\n\\n\\nconst comment=reader.read(commentLength);\\n\\nreturn{\\nname,\\nversion,\\nmadeBy,\\n...headers,\\ndiskNumberStart,\\ninternalFileAttributes,\\nexternalFileAttributes,\\nfileStart,\\ncomment};}\\n\\n\\n\\n/**\\n * @param {BufferReader} reader\\n * @param {CentralDirectoryLocator} locator\\n * @returns {Array<CentralFileRecord>}\\n */\\nfunction readCentralDirectory(reader,locator){\\nconst{centralDirectoryOffset,centralDirectoryRecords}=locator;\\nreader.seek(centralDirectoryOffset);\\n\\nconst entries=[];\\nwhile(reader.expect(signature.CENTRAL_FILE_HEADER)){\\nconst entry=readCentralFileHeader(reader);\\nentries.push(entry);}\\n\\n\\nif(centralDirectoryRecords!==entries.length){\\n/* We expected some records but couldn't find ANY.*/\\n/* This is really suspicious, as if something went wrong.*/\\nthrow Error(\\n`Corrupted zip or bug: expected ${centralDirectoryRecords} records in central dir, got ${entries.length}`);}\\n\\n\\n\\nreturn entries;}\\n\\n\\n/**\\n * @param {BufferReader} reader\\n * @returns {LocalFileRecord}\\n */\\nfunction readFile(reader){\\nreader.expect(signature.LOCAL_FILE_HEADER);\\nconst headers=readHeaders(reader);\\nconst nameLength=reader.readUint16(true);\\nconst extraFieldsLength=reader.readUint16(true);\\nconst name=reader.read(nameLength);\\nreader.skip(extraFieldsLength);\\nconst content=reader.read(headers.compressedLength);\\nreturn{name,...headers,content};}\\n\\n\\n/**\\n * @param {BufferReader} reader\\n * @param {Array<CentralFileRecord>} records\\n * @returns {Array<LocalFileRecord>}\\n */\\nfunction readLocalFiles(reader,records){\\nconst files=[];\\nfor(const record of records){\\nreader.seek(record.fileStart);\\nconst file=readFile(reader);\\nfiles.push(file);}\\n\\nreturn files;}\\n\\n\\n/**\\n * @param {BufferReader} reader\\n * @returns {CentralDirectoryLocator}\\n */\\nfunction readBlockEndOfCentral(reader){\\nif(!reader.expect(signature.CENTRAL_DIRECTORY_END)){\\nthrow Error(\\n'Corrupt zip file, or zip file containing an unsupported variable-width end-of-archive comment, or an unsupported zip file with 64 bit sizes');}\\n\\n\\nconst diskNumber=reader.readUint16(true);\\nconst diskWithCentralDirStart=reader.readUint16(true);\\nconst centralDirectoryRecordsOnThisDisk=reader.readUint16(true);\\nconst centralDirectoryRecords=reader.readUint16(true);\\nconst centralDirectorySize=reader.readUint32(true);\\nconst centralDirectoryOffset=reader.readUint32(true);\\nconst commentLength=reader.readUint16(true);\\n/* Warning: the encoding depends of the system locale.*/\\n/* On a Linux machine with LANG=en_US.utf8, this field is utf8 encoded.*/\\n/* On a Windows machine, this field is encoded with the localized Windows*/\\n/* code page.*/\\nconst comment=textDecoder.decode(reader.read(commentLength));\\nreturn{\\ndiskNumber,\\ndiskWithCentralDirStart,\\ncentralDirectoryRecordsOnThisDisk,\\ncentralDirectoryRecords,\\ncentralDirectorySize,\\ncentralDirectoryOffset,\\ncomment};}\\n\\n\\n\\n/**\\n * @param {BufferReader} reader\\n * @returns {CentralDirectoryLocator}\\n */\\nfunction readEndOfCentralDirectoryRecord(reader){\\n/* Zip files are permitted to have a variable-width comment at the end of the*/\\n/* \\\"end of central directory record\\\" and may have subsequent Zip64 headers.*/\\n/* The prescribed method of finding the beginning of the \\\"end of central*/\\n/* directory record\\\" is to seek the magic number:*/\\n/**/\\n/* reader.findLast(signature.CENTRAL_DIRECTORY_END);*/\\n/**/\\n/* This introduces a number of undesirable, attackable ambiguities*/\\n/* Agoric is not comfortable supporting, so we forbid the comment*/\\n/* and 64 bit zip support so we can seek a predictable length*/\\n/* from the end.*/\\nconst centralDirectoryEnd=reader.length-22;\\nif(centralDirectoryEnd<0){\\nthrow Error('Corrupted zip: not enough content');}\\n\\nreader.seek(centralDirectoryEnd);\\nconst locator=readBlockEndOfCentral(reader);\\n\\n/* Excerpt from the zip spec:*/\\n/* 4) If one of the fields in the end of central directory*/\\n/* record is too small to hold required data, the field*/\\n/* should be set to -1 (0xFFFF or 0xFFFFFFFF) and the*/\\n/* ZIP64 format record should be created.*/\\n/* 5) The end of central directory record and the*/\\n/* Zip64 end of central directory locator record must*/\\n/* reside on the same disk when splitting or spanning*/\\n/* an archive.*/\\nconst zip64=\\nlocator.diskNumber===MAX_VALUE_16BITS||\\nlocator.diskWithCentralDirStart===MAX_VALUE_16BITS||\\nlocator.centralDirectoryRecordsOnThisDisk===MAX_VALUE_16BITS||\\nlocator.centralDirectoryRecords===MAX_VALUE_16BITS||\\nlocator.centralDirectorySize===MAX_VALUE_32BITS||\\nlocator.centralDirectoryOffset===MAX_VALUE_32BITS;\\n\\nif(zip64){\\nthrow Error('Cannot read Zip64');}\\n\\n\\nconst{\\ncentralDirectoryOffset,\\ncentralDirectorySize\\n/* zip64EndOfCentralSize*/}=\\nlocator;\\n\\nconst expectedCentralDirectoryEnd=\\ncentralDirectoryOffset+centralDirectorySize;\\nconst extraBytes=centralDirectoryEnd-expectedCentralDirectoryEnd;\\n\\nreader.offset=extraBytes;\\n\\nreturn locator;}\\n\\n\\n/**\\n * @param {CentralFileRecord} centralRecord\\n * @param {LocalFileRecord} localRecord\\n * @param {string} archiveName\\n */\\nfunction checkRecords(centralRecord,localRecord,archiveName){\\nconst centralName=textDecoder.decode(centralRecord.name);\\nconst localName=textDecoder.decode(localRecord.name);\\n\\n/* In some zip files created on Windows, the filename stored in the central*/\\n/* dir contains \\\"\\\\\\\" instead of \\\"/\\\". Strangely, the file name in the local*/\\n/* directory uses \\\"/\\\" as specified:*/\\n/* http://www.info-zip.org/FAQ.html#backslashes or APPNOTE#4.4.17.1, \\\"All*/\\n/* slashes MUST be forward slashes '/'\\\") but there are a lot of bad zip*/\\n/* generators... Search \\\"unzip mismatching \\\"local\\\" filename continuing with*/\\n/* \\\"central\\\" filename version\\\".*/\\n/**/\\n/* The reasoning appears to be that the central directory is for*/\\n/* user display and may differ, though this opens the possibility*/\\n/* for spoofing attacks.*/\\n/* http://seclists.org/fulldisclosure/2009/Sep/394*/\\n/**/\\n/* We strike a compromise: the central directory name may vary from the local*/\\n/* name exactly and only by different slashes.*/\\nif(centralName.replace(/\\\\\\\\/g,'/')!==localName){\\nthrow Error(\\n`Zip integrity error: central record file name ${q(\\ncentralName)\\n} must match local file name ${q(localName)} in archive ${q(\\narchiveName)\\n}`);}\\n\\n\\n\\n/**\\n * @param {boolean} value\\n * @param {string} message\\n */\\nfunction check(value,message){\\nif(!value){\\nthrow Error(\\n`Zip integrity error: ${message} for file ${q(\\nlocalName)\\n} in archive ${q(archiveName)}`);}}\\n\\n\\n\\n\\ncheck(\\ncentralRecord.bitFlag===localRecord.bitFlag,\\n`Central record bit flag ${centralRecord.bitFlag.toString(\\n16)\\n} must match local record bit flag ${localRecord.bitFlag.toString(16)}`);\\n\\ncheck(\\ncentralRecord.compressionMethod===localRecord.compressionMethod,\\n`Central record compression method ${q(\\ncentralRecord.compressionMethod)\\n} must match local compression method ${q(localRecord.compressionMethod)}`);\\n\\n/* TODO Date integrity check would be easier on the original bytes.*/\\n/* Perhaps defer decoding the underlying bytes.*/\\ncheck(\\ncentralRecord.crc32===localRecord.crc32,\\n`Central record CRC-32 checksum ${centralRecord.crc32} must match local checksum ${localRecord.crc32}`);\\n\\ncheck(\\ncentralRecord.compressedLength===localRecord.compressedLength,\\n`Central record compressed size ${centralRecord.compressedLength} must match local ${localRecord.compressedLength}`);\\n\\ncheck(\\ncentralRecord.uncompressedLength===localRecord.uncompressedLength,\\n`Central record uncompressed size ${centralRecord.uncompressedLength} must match local ${localRecord.uncompressedLength}`);\\n\\n\\nconst checksum=crc32.crc32(localRecord.content);\\ncheck(\\nchecksum===localRecord.crc32,\\n`CRC-32 checksum mismatch, wanted ${localRecord.crc32} but actual content is ${checksum}`);}\\n\\n\\n\\n/**\\n * @param {number} externalFileAttributes\\n */\\nfunction modeForExternalAttributes(externalFileAttributes){\\nreturn externalFileAttributes>>16&0xffff;}\\n\\n\\n/**\\n * @param {CentralFileRecord} centralRecord\\n * @param {LocalFileRecord} localRecord\\n * @returns {CompressedFile}\\n */\\nfunction recordToFile(centralRecord,localRecord){\\nconst mode=modeForExternalAttributes(centralRecord.externalFileAttributes);\\nreturn{\\nname:centralRecord.name,\\nmode,\\ndate:centralRecord.date,\\ncrc32:centralRecord.crc32,\\ncompressionMethod:centralRecord.compressionMethod,\\ncompressedLength:centralRecord.compressedLength,\\nuncompressedLength:centralRecord.uncompressedLength,\\ncontent:localRecord.content,\\ncomment:centralRecord.comment};}\\n\\n\\n\\n/**\\n * @param {CompressedFile} file\\n * @returns {UncompressedFile}\\n */\\nfunction decompressFile(file){\\nif(file.compressionMethod!==compression.STORE){\\nthrow Error(\\n`Cannot find decompressor for compression method ${q(\\nfile.compressionMethod)\\n} for file ${file.name}`);}\\n\\n\\nreturn{\\nname:file.name,\\nmode:file.mode,\\ndate:file.date,\\ncontent:file.content,\\ncomment:file.comment};}\\n\\n\\n\\n/**\\n * @param {UncompressedFile} file\\n * @returns {ArchivedFile}\\n */\\nfunction decodeFile(file){\\nconst name=textDecoder.decode(file.name);\\nconst comment=textDecoder.decode(file.comment);\\nreturn{\\nname,\\ntype:'file',\\nmode:file.mode&0o777,\\ndate:file.date,\\ncontent:file.content,\\ncomment};}\\n\\n\\n\\n/**\\n * @param {BufferReader} reader\\n * @param {string} name\\n */\\nfunction readZip(reader,name='<unknown>'){\\nconst locator=readEndOfCentralDirectoryRecord(reader);\\nconst centralRecords=readCentralDirectory(reader,locator);\\nconst localRecords=readLocalFiles(reader,centralRecords);\\nconst files=new Map();\\n\\nfor(let i=0;i<centralRecords.length;i+=1){\\nconst centralRecord=centralRecords[i];\\nconst localRecord=localRecords[i];\\n\\ncheckRecords(centralRecord,localRecord,name);\\n\\nif(isEncrypted(centralRecord.bitFlag)){\\nthrow Error('Encrypted zip are not supported');}\\n\\n\\nconst isDir=(centralRecord.externalFileAttributes&0x0010)!==0;\\nif(!isDir){\\nconst compressedFile=recordToFile(centralRecord,localRecord);\\nconst decompressedFile=decompressFile(compressedFile);\\nconst decodedFile=decodeFile(decompressedFile);\\nfiles.set(decodedFile.name,decodedFile);}\\n\\n/* TODO handle explicit directory entries*/}\\n\\nreturn files;}exports.readZip=readZip;\",\n \"node_modules/@endo/zip/src/format-writer.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var crc32=require('./crc32.js');var signature=require('./signature.js');var compression=require('./compression.js');/* @ts-check*/\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nconst UNIX=3;\\nconst UNIX_VERSION=30;\\n\\nconst textEncoder=new TextEncoder();\\n\\n/**\\n * @param {BufferWriter} writer\\n * @param {Date?} date\\n * @see http://www.delorie.com/djgpp/doc/rbinter/it/65/16.html\\n * @see http://www.delorie.com/djgpp/doc/rbinter/it/66/16.html\\n */\\nfunction writeDosDateTime(writer,date){\\nconst dosTime=\\ndate!==undefined&&date!==null?\\n(date.getUTCFullYear()-1980&0x7f)<<25|/* year*/\\ndate.getUTCMonth()+1<<21|/* month*/\\ndate.getUTCDate()<<16|/* day*/\\ndate.getUTCHours()<<11|/* hour*/\\ndate.getUTCMinutes()<<5|/* minute*/\\ndate.getUTCSeconds()>>1/* second*/:\\n0;/* Epoch origin by default.*/\\nwriter.writeUint32(dosTime,true);}\\n\\n\\n/**\\n * @param {BufferWriter} writer\\n * @param {FileRecord} file\\n * @returns {LocalFileLocator}\\n */\\nfunction writeFile(writer,file){\\n/* Header*/\\nconst fileStart=writer.index;\\nwriter.write(signature.LOCAL_FILE_HEADER);\\nconst headerStart=writer.index;\\n/* Version needed to extract*/\\nwriter.writeUint16(10,true);\\nwriter.writeUint16(file.bitFlag,true);\\nwriter.writeUint16(file.compressionMethod,true);\\nwriteDosDateTime(writer,file.date);\\nwriter.writeUint32(file.crc32,true);\\nwriter.writeUint32(file.compressedLength,true);\\nwriter.writeUint32(file.uncompressedLength,true);\\nwriter.writeUint16(file.name.length,true);\\nconst headerEnd=writer.length;\\n\\n/* TODO count of extra fields length*/\\nwriter.writeUint16(0,true);\\nwriter.write(file.name);\\n/* TODO write extra fields*/\\nwriter.write(file.content);\\n\\nreturn{\\nfileStart,\\nheaderStart,\\nheaderEnd};}\\n\\n\\n\\n/**\\n * @param {BufferWriter} writer\\n * @param {FileRecord} file\\n * @param {LocalFileLocator} locator\\n */\\nfunction writeCentralFileHeader(writer,file,locator){\\nwriter.write(signature.CENTRAL_FILE_HEADER);\\nwriter.writeUint8(file.version);\\nwriter.writeUint8(file.madeBy);\\nwriter.writeCopy(locator.headerStart,locator.headerEnd);\\n/* TODO extra fields length*/\\nwriter.writeUint16(0,true);\\nwriter.writeUint16(file.comment.length,true);\\nwriter.writeUint16(file.diskNumberStart,true);\\nwriter.writeUint16(file.internalFileAttributes,true);\\nwriter.writeUint32(file.externalFileAttributes,true);\\nwriter.writeUint32(locator.fileStart,true);\\nwriter.write(file.centralName);\\n/* TODO extra fields*/\\nwriter.write(file.comment);}\\n\\n\\n/**\\n * @param {BufferWriter} writer\\n * @param {number} entriesCount\\n * @param {number} centralDirectoryStart\\n * @param {number} centralDirectoryLength\\n * @param {Uint8Array} commentBytes\\n */\\nfunction writeEndOfCentralDirectoryRecord(\\nwriter,\\nentriesCount,\\ncentralDirectoryStart,\\ncentralDirectoryLength,\\ncommentBytes)\\n{\\nwriter.write(signature.CENTRAL_DIRECTORY_END);\\nwriter.writeUint16(0,true);\\nwriter.writeUint16(0,true);\\nwriter.writeUint16(entriesCount,true);\\nwriter.writeUint16(entriesCount,true);\\nwriter.writeUint32(centralDirectoryLength,true);\\nwriter.writeUint32(centralDirectoryStart,true);\\nwriter.writeUint16(commentBytes.length,true);\\nwriter.write(commentBytes);}\\n\\n\\n/**\\n * @param {BufferWriter} writer\\n * @param {Array<FileRecord>} records\\n * @param {string} comment\\n */\\nfunction writeZipRecords(writer,records,comment=''){\\n/* Write records with local headers.*/\\nconst locators=[];\\nfor(let i=0;i<records.length;i+=1){\\nlocators.push(writeFile(writer,records[i]));}\\n\\n\\n/* writeCentralDirectory*/\\nconst centralDirectoryStart=writer.index;\\nfor(let i=0;i<locators.length;i+=1){\\nwriteCentralFileHeader(writer,records[i],locators[i]);}\\n\\nconst centralDirectoryLength=writer.index-centralDirectoryStart;\\n\\nconst commentBytes=textEncoder.encode(comment);\\n\\n/* Write central directory end.*/\\nwriteEndOfCentralDirectoryRecord(\\nwriter,\\nrecords.length,\\ncentralDirectoryStart,\\ncentralDirectoryLength,\\ncommentBytes);}\\n\\n\\n\\n/**\\n * @param {IMPORT('./types.js').ArchivedFile} file\\n * @returns {IMPORT('./types.js').UncompressedFile}\\n */\\nfunction encodeFile(file){\\nconst name=textEncoder.encode(file.name.replace(/\\\\\\\\/g,'/'));\\nconst comment=textEncoder.encode(file.comment);\\nreturn{\\nname,\\nmode:file.mode,\\ndate:file.date,\\ncontent:file.content,\\ncomment};}\\n\\n\\n\\n/**\\n * @param {IMPORT('./types.js').UncompressedFile} file\\n * @returns {IMPORT('./types.js').CompressedFile}\\n */\\nfunction compressFileWithStore(file){\\nreturn{\\nname:file.name,\\nmode:file.mode,\\ndate:file.date,\\ncrc32:crc32.crc32(file.content),\\ncompressionMethod:compression.STORE,\\ncompressedLength:file.content.length,\\nuncompressedLength:file.content.length,\\ncontent:file.content,\\ncomment:file.comment};}\\n\\n\\n\\n/**\\n * Computes Zip external file attributes field from a UNIX mode for a file.\\n *\\n * @param {number} mode\\n * @returns {number}\\n */\\nfunction externalFileAttributes(mode){\\nreturn(mode&0o777|0o100000)<<16;}\\n\\n\\n/* TODO Add support for directory records.*/\\n/* /***/\\n/* * @param {number} mode*/\\n/* * @return {number}*/\\n/* *X/*/\\n/* function externalDirectoryAttributes(mode) {*/\\n/* // The 0x10 is the DOS directory attribute, which is set regardless of platform.*/\\n/* return ((mode & 0o777) | 0o40000) << 16 | 0x10;*/\\n/* }*/\\n\\n/**\\n * @param {IMPORT('./types.js').CompressedFile} file\\n * @returns {FileRecord}\\n */\\nfunction makeFileRecord(file){\\nreturn{\\nname:file.name,\\ncentralName:file.name,\\nmadeBy:UNIX,\\nversion:UNIX_VERSION,\\nversionNeeded:0,/* TODO this is probably too lax.*/\\nbitFlag:0,\\ncompressionMethod:compression.STORE,\\ndate:file.date,\\ncrc32:file.crc32,\\ncompressedLength:file.compressedLength,\\nuncompressedLength:file.uncompressedLength,\\ndiskNumberStart:0,\\ninternalFileAttributes:0,\\nexternalFileAttributes:externalFileAttributes(file.mode),\\ncomment:file.comment,\\ncontent:file.content};}\\n\\n\\n\\n/**\\n * @param {BufferWriter} writer\\n * @param {Array<IMPORT('./types.js').ArchivedFile>} files\\n * @param {string} comment\\n */\\nfunction writeZip(writer,files,comment=''){\\nconst encodedFiles=files.map(encodeFile);\\nconst compressedFiles=encodedFiles.map(compressFileWithStore);\\n/* TODO collate directoryRecords from file bases.*/\\nconst fileRecords=compressedFiles.map(makeFileRecord);\\nwriteZipRecords(writer,fileRecords,comment);}exports.writeZip=writeZip;exports.writeZipRecords=writeZipRecords;\",\n \"node_modules/@endo/zip/src/reader.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var bufferReader=require('./buffer-reader.js');var formatReader=require('./format-reader.js');/* @ts-check*/\\n\\n\\n\\n\\nclass ZipReader{\\n/**\\n * @param {Uint8Array} data\\n * @param {object} [options]\\n * @param {string} [options.name]\\n */\\nconstructor(data,options={}){\\nconst{name='<unknown>'}=options;\\nconst reader=new bufferReader.BufferReader(data);\\nthis.files=formatReader.readZip(reader);\\nthis.name=name;}\\n\\n\\n/**\\n * @param {string} name\\n * @returns {Uint8Array}\\n */\\nread(name){\\nconst file=this.files.get(name);\\nif(file===undefined){\\nthrow Error(`Cannot find file ${name} in Zip file ${this.name}`);}\\n\\nreturn file.content;}\\n\\n\\n/**\\n * @param {string} name\\n * @returns {IMPORT('./types.js').ArchivedStat=}\\n */\\nstat(name){\\nconst file=this.files.get(name);\\nif(file===undefined){\\nreturn undefined;}\\n\\nreturn{\\ntype:file.type,\\nmode:file.mode,\\ndate:file.date,\\ncomment:file.comment};}}\\n\\n\\n\\n\\n/**\\n * @param {Uint8Array} data\\n * @param {string} location\\n * @returns {Promise<IMPORT('./types.js').ArchiveReader>}\\n */\\nconst readZip=async(data,location)=>{\\nconst reader=new ZipReader(data,{name:location});\\n/** @type {IMPORT('./types.js').ReadFn} */\\nconst read=async(path)=>reader.read(path);\\nreturn{read};};exports.ZipReader=ZipReader;exports.readZip=readZip;\",\n \"node_modules/@endo/zip/src/signature.js\": \"'use strict';\\n\\n\\nObject.defineProperty(exports,'__esModule',{value:true});/* @ts-check*/ /* eslint no-bitwise: [\\\"off\\\"] */ /**\\n * @param {string} string\\n * @returns {Uint8Array}\\n */\\nfunction u(string){\\nconst array=new Uint8Array(string.length);\\nfor(let i=0;i<string.length;i+=1){\\narray[i]=string.charCodeAt(i)&0xff;}\\n\\nreturn array;}\\n\\n\\nconst LOCAL_FILE_HEADER=u('PK\\\\x03\\\\x04');\\nconst CENTRAL_FILE_HEADER=u('PK\\\\x01\\\\x02');\\nconst CENTRAL_DIRECTORY_END=u('PK\\\\x05\\\\x06');\\nconst ZIP64_CENTRAL_DIRECTORY_LOCATOR=u('PK\\\\x06\\\\x07');\\nconst ZIP64_CENTRAL_DIRECTORY_END=u('PK\\\\x06\\\\x06');\\nconst DATA_DESCRIPTOR=u('PK\\\\x07\\\\x08');exports.CENTRAL_DIRECTORY_END=CENTRAL_DIRECTORY_END;exports.CENTRAL_FILE_HEADER=CENTRAL_FILE_HEADER;exports.DATA_DESCRIPTOR=DATA_DESCRIPTOR;exports.LOCAL_FILE_HEADER=LOCAL_FILE_HEADER;exports.ZIP64_CENTRAL_DIRECTORY_END=ZIP64_CENTRAL_DIRECTORY_END;exports.ZIP64_CENTRAL_DIRECTORY_LOCATOR=ZIP64_CENTRAL_DIRECTORY_LOCATOR;\",\n \"node_modules/@endo/zip/src/types.js\": \"\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n'use strict';/* @ts-check*/ /**\\n * @typedef {{\\n * mode: number,\\n * date: Date?,\\n * comment: string,\\n * type: \\\"file\\\" | \\\"directory\\\"\\n * }} ArchivedStat\\n *\\n * @typedef {{\\n * name: string,\\n * content: Uint8Array,\\n * } & ArchivedStat} ArchivedFile\\n *\\n * @typedef {{\\n * name: Uint8Array,\\n * mode: number,\\n * date: Date?,\\n * content: Uint8Array,\\n * comment: Uint8Array,\\n * }} UncompressedFile\\n *\\n * @typedef {{\\n * name: Uint8Array,\\n * mode: number,\\n * date: Date?,\\n * crc32: number,\\n * compressionMethod: number,\\n * compressedLength: number,\\n * uncompressedLength: number,\\n * content: Uint8Array,\\n * comment: Uint8Array,\\n * }} CompressedFile\\n *\\n * @typedef {{\\n * versionNeeded: number,\\n * bitFlag: number,\\n * compressionMethod: number,\\n * date: Date?,\\n * crc32: number,\\n * compressedLength: number,\\n * uncompressedLength: number,\\n * }} ArchiveHeaders\\n */ /**\\n * @typedef {object} ArchiveReader\\n * @property {ReadFn} read\\n */ /**\\n * @callback ReadFn\\n * @param {string} name\\n * @returns {Promise<Uint8Array>} bytes\\n */ /**\\n * @typedef {object} ArchiveWriter\\n * @property {WriteFn} write\\n * @property {SnapshotFn} snapshot\\n */ /**\\n * @callback WriteFn\\n * @param {string} name\\n * @param {Uint8Array} bytes\\n * @returns {Promise<void>}\\n */ /**\\n * @callback SnapshotFn\\n * @returns {Promise<Uint8Array>}\\n */\",\n \"node_modules/@endo/zip/src/writer.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var bufferWriter=require('./buffer-writer.js');var formatWriter=require('./format-writer.js');/* @ts-check*/\\n\\n\\n\\n\\nclass ZipWriter{\\n/**\\n * @param {{\\n * date: Date,\\n * }} options\\n */\\nconstructor(options={date:new Date()}){\\nconst{date}=options;\\n/** type {Map<string, ZFile>} */\\nthis.files=new Map();\\nthis.date=date;}\\n\\n\\n/**\\n * @param {string} name\\n * @param {Uint8Array} content\\n * @param {{\\n * mode?: number,\\n * date?: Date,\\n * comment?: string,\\n * }} [options]\\n */\\nwrite(name,content,options={}){\\nconst{mode=0o644,date=undefined,comment=''}=options;\\nif(!content){\\nthrow Error(`ZipWriter write requires content for ${name}`);}\\n\\nthis.files.set(name,{\\nname,\\nmode,\\ndate,\\ncontent,\\ncomment});}\\n\\n\\n\\n/**\\n * @returns {Uint8Array}\\n */\\nsnapshot(){\\nconst writer=new bufferWriter.BufferWriter();\\nformatWriter.writeZip(writer,Array.from(this.files.values()));\\nreturn writer.subarray();}}\\n\\n\\n\\n/**\\n * @returns {IMPORT('./types.js').ArchiveWriter}\\n */\\nconst writeZip=()=>{\\nconst writer=new ZipWriter();\\n/** @type {IMPORT('./types.js').WriteFn} */\\nconst write=async(path,data)=>{\\nwriter.write(path,data);};\\n\\n/** @type {IMPORT('./types.js').SnapshotFn} */\\nconst snapshot=async()=>writer.snapshot();\\nreturn{write,snapshot};};exports.ZipWriter=ZipWriter;exports.writeZip=writeZip;\",\n \"packages/store/src/index.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../../node_modules/@endo/patterns/index.js');var scalarWeakSetStore=require('./stores/scalarWeakSetStore.js');var scalarSetStore=require('./stores/scalarSetStore.js');var scalarWeakMapStore=require('./stores/scalarWeakMapStore.js');var scalarMapStore=require('./stores/scalarMapStore.js');var storeUtils=require('./stores/store-utils.js');require('../../../node_modules/@endo/exo/index.js');var legacyMap=require('./legacy/legacyMap.js');var legacyWeakMap=require('./legacy/legacyWeakMap.js');require('./types.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\npatternMatchers=require('../../../node_modules/@endo/patterns/src/patterns/patternMatchers.js');/**\\n * @import {MustMatch} from '@agoric/internal';\\n */ /* XXX @agoric/store should not depend on @agoric/internal*/ /* TODO move to Endo*/ /** @type {MustMatch} */const mustMatch=patternMatchers.mustMatch;exports.makeScalarWeakSetStore=scalarWeakSetStore.makeScalarWeakSetStore;exports.makeScalarSetStore=scalarSetStore.makeScalarSetStore;exports.makeScalarWeakMapStore=scalarWeakMapStore.makeScalarWeakMapStore;exports.makeScalarMapStore=scalarMapStore.makeScalarMapStore;exports.provideLazy=storeUtils.provideLazy;exports.makeLegacyMap=legacyMap.makeLegacyMap;exports.makeLegacyWeakMap=legacyWeakMap.makeLegacyWeakMap;exports.M=patternMatchers.M;exports.assertPattern=patternMatchers.assertPattern;exports.getRankCover=patternMatchers.getRankCover;exports.isPattern=patternMatchers.isPattern;exports.matches=patternMatchers.matches;exports.mustMatch=mustMatch;\",\n \"packages/store/src/legacy/legacyMap.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var\\n\\n\\n\\n\\nindex=require('../../../../node_modules/@endo/errors/index.js');/** @import {LegacyMap, LegacyWeakMap} from '../types.js'; */ /**\\n * This module and its fraternal sibling legacyWeakMap exist only to ease a\\n * transition to the modern `store` system, are deprecated, and will eventually\\n * disappear. They are needed for now to support some of the uses of the old\\n * behavior that are not compatible with the new. The constraint imposed by the\\n * new is that only passables can be used as values, and only keys (roughly,\\n * structures, aka comparables) can be used as values.\\n *\\n * See https://github.com/Agoric/agoric-sdk/pull/3567\\n *\\n * TODO Once that PR is merged, link to the documents rather than the PRs.\\n *\\n * Each of these non-conforming uses should be marked with a\\n *\\n * ```js\\n * // Legacy because...\\n * ```\\n *\\n * comment explaining the problem inhibiting conversion to the new system. Some\\n * of these problems as of this writing:\\n *\\n * - A promiseKit used as a value, even though a promiseKit is not a passable.\\n * Solutions are to make it a passable, or to convert the container back to a\\n * conventional JavaScript Map.\\n * - A mutable array used as a value, that is subsequently mutated. Freezing the\\n * array wouldn't work of course because it would break the subsequent\\n * mutation. Using a far object wrapping an array would likely work fine.\\n *\\n * @deprecated switch to ScalarMap if possible, Map otherwise\\n * @template K,V\\n * @param {string} [tag] - tag for debugging\\n * @returns {LegacyMap<K, V>}\\n */\\nconst makeLegacyMap=(tag='key')=>{\\nconst m=new Map();\\nconst assertKeyDoesNotExist=(key)=>\\n!m.has(key)||index.throwRedacted`${index.quote(tag)} already registered: ${key}`;\\nconst assertKeyExists=(key)=>\\nm.has(key)||index.throwRedacted`${index.quote(tag)} not found: ${key}`;\\nreturn harden({\\nhas:(key)=>{\\n/* Check if a key exists. The key can be any JavaScript value,*/\\n/* though the answer will always be false for keys that cannot be found*/\\n/* in this map.*/\\nreturn m.has(key);},\\n\\ninit:(key,value)=>{\\nassertKeyDoesNotExist(key);\\nm.set(key,value);},\\n\\nget:(key)=>{\\nassertKeyExists(key);\\nreturn m.get(key);},\\n\\nset:(key,value)=>{\\nassertKeyExists(key);\\nm.set(key,value);},\\n\\ndelete:(key)=>{\\nassertKeyExists(key);\\nm.delete(key);},\\n\\nkeys:()=>m.keys(),\\nvalues:()=>m.values(),\\nentries:()=>m.entries(),\\ngetSize:()=>m.size,\\nclear:()=>m.clear()});};\\n\\n\\nharden(makeLegacyMap);exports.makeLegacyMap=makeLegacyMap;\",\n \"packages/store/src/legacy/legacyWeakMap.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var\\n\\n\\n\\n\\nindex=require('../../../../node_modules/@endo/errors/index.js');/** @import {LegacyWeakMap} from '../types.js'; */ /**\\n * See doccomment in the closely related `legacyMap.js` module.\\n *\\n * @deprecated switch to ScalarWeakMap if possible, WeakMap otherwise\\n * @template K,V\\n * @param {string} [tag] - tag for debugging\\n * @returns {LegacyWeakMap<K, V>}\\n */\\nconst makeLegacyWeakMap=(tag='key')=>{\\n/** @type {WeakMap<K & object, V>} */\\nconst wm=new WeakMap();\\nconst assertKeyDoesNotExist=(key)=>\\n!wm.has(key)||index.throwRedacted`${index.quote(tag)} already registered: ${key}`;\\nconst assertKeyExists=(key)=>\\nwm.has(key)||index.throwRedacted`${index.quote(tag)} not found: ${key}`;\\nreturn harden({\\nhas:(key)=>{\\n/* Check if a key exists. The key can be any JavaScript value,*/\\n/* though the answer will always be false for keys that cannot be found*/\\n/* in this map.*/\\nreturn wm.has(key);},\\n\\ninit:(key,value)=>{\\nassertKeyDoesNotExist(key);\\nwm.set(key,value);},\\n\\nget:(key)=>{\\nassertKeyExists(key);\\n/* How to tell typescript I believe the `get` will succeed.*/\\nreturn(/** @type {V} */wm.get(key));},\\n\\nset:(key,value)=>{\\nassertKeyExists(key);\\nwm.set(key,value);},\\n\\ndelete:(key)=>{\\nassertKeyExists(key);\\nwm.delete(key);}});};\\n\\n\\n\\nharden(makeLegacyWeakMap);exports.makeLegacyWeakMap=makeLegacyWeakMap;\",\n \"packages/store/src/stores/scalarMapStore.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var index=require('../../../../node_modules/@endo/errors/index.js');require('../../../../node_modules/@endo/pass-style/index.js');require('../../../../node_modules/@endo/marshal/index.js');require('../../../../node_modules/@endo/patterns/index.js');var scalarWeakMapStore=require('./scalarWeakMapStore.js');var storeUtils=require('./store-utils.js');var rankOrder=require('../../../../node_modules/@endo/marshal/src/rankOrder.js');var patternMatchers=require('../../../../node_modules/@endo/patterns/src/patterns/patternMatchers.js');var iterHelpers=require('../../../../node_modules/@endo/pass-style/src/iter-helpers.js');var checkKey=require('../../../../node_modules/@endo/patterns/src/keys/checkKey.js');var passStyleOf=require('../../../../node_modules/@endo/pass-style/src/passStyleOf.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nmakeFar=require('../../../../node_modules/@endo/pass-style/src/make-far.js');/**\\n * @import {Passable} from '@endo/pass-style';\\n * @import {Key, Pattern} from '@endo/patterns';\\n * @import {MapStore, MapStoreMethods, StoreOptions} from '../types.js';\\n */ /**\\n * @template {Key} K\\n * @template {Passable} V\\n * @param {Map<K, V>} jsmap\\n * @param {(k: K, v: V) => void} assertKVOkToAdd\\n * @param {(k: K, v: V) => void} assertKVOkToSet\\n * @param {(k: K) => void} [assertKeyOkToDelete]\\n * @param {string} [tag]\\n * @returns {MapStoreMethods<K, V>}\\n */const makeMapStoreMethods=(jsmap,assertKVOkToAdd,assertKVOkToSet,\\nassertKeyOkToDelete=undefined,\\ntag='key')=>\\n{\\nconst{assertUpdateOnAdd,assertUpdateOnDelete,iterableKeys}=\\nstoreUtils.makeCurrentKeysKit(\\n()=>jsmap.keys(),\\n(k)=>jsmap.has(k),\\nrankOrder.compareRank,\\nassertKVOkToAdd,\\nassertKeyOkToDelete,\\ntag);\\n\\n\\n/**\\n * @param {Pattern} [keyPatt]\\n * @param {Pattern} [valuePatt]\\n * @returns {Iterable<K>}\\n */\\nconst keys=(keyPatt=undefined,valuePatt=undefined)=>{\\nif(keyPatt===undefined&&valuePatt===undefined){\\nreturn iterableKeys;}\\n\\nconst filter=(k)=>{\\nif(keyPatt!==undefined&&!patternMatchers.matches(k,keyPatt)){\\nreturn false;}\\n\\n/* Uses the current jsmap value, since the iteratator survives `.set`*/\\nif(valuePatt!==undefined&&!patternMatchers.matches(jsmap.get(k),valuePatt)){\\nreturn false;}\\n\\nreturn true;};\\n\\nreturn iterHelpers.filterIterable(iterableKeys,filter);};\\n\\n\\n/**\\n * @param {Pattern} [keyPatt]\\n * @param {Pattern} [valuePatt]\\n * @returns {Iterable<V>}\\n */\\nconst values=(keyPatt=undefined,valuePatt=undefined)=>\\niterHelpers.mapIterable(keys(keyPatt,valuePatt),(k)=>/** @type {V} */jsmap.get(k));\\n\\n/**\\n * @param {Pattern} [keyPatt]\\n * @param {Pattern} [valuePatt]\\n * @returns {Iterable<[K, V]>}\\n */\\nconst entries=(keyPatt=undefined,valuePatt=undefined)=>\\niterHelpers.mapIterable(keys(keyPatt,valuePatt),(k)=>[\\nk,\\n/** @type {V} */jsmap.get(k)]);\\n\\n\\nreturn harden({\\n...scalarWeakMapStore.makeWeakMapStoreMethods(\\njsmap,\\n/** @type {(k: K, v: V) => void} */assertUpdateOnAdd,\\nassertKVOkToSet,\\nassertUpdateOnDelete,\\ntag),\\n\\nkeys,\\nvalues,\\nentries,\\n\\nsnapshot:(keyPatt=undefined,valuePatt=undefined)=>\\ncheckKey.makeCopyMap(entries(keyPatt,valuePatt)),\\n\\ngetSize:(keyPatt=undefined,valuePatt=undefined)=>\\nkeyPatt===undefined&&valuePatt===undefined?\\njsmap.size:\\n[...keys(keyPatt,valuePatt)].length,\\n\\nclear:(keyPatt=undefined,valuePatt=undefined)=>{\\nif(keyPatt===undefined&&valuePatt===undefined){\\njsmap.clear();}\\n\\nfor(const key of keys(keyPatt,valuePatt)){\\njsmap.delete(key);}}});};\\n\\n\\n\\n\\n\\n/**\\n * Distinguishes between adding a new key (init) and updating or referencing a\\n * key (get, set, delete).\\n *\\n * `init` is only allowed if the key does not already exist. `Get`, `set` and\\n * `delete` are only allowed if the key does already exist.\\n *\\n * This is a _scalar_ map in that the keys can only be atomic values, primitives\\n * or remotables. Other storeMaps will accept, for example, copyArrays and\\n * copyRecords, as keys and look them up based on equality of their contents.\\n *\\n * @param {string} [tag] - the column name for the key\\n * @param {StoreOptions} [options]\\n * @returns {MapStore<any, any>}\\n */\\nconst makeScalarMapStore=(\\ntag='key',\\n{keyShape=undefined,valueShape=undefined}={})=>\\n{\\nconst jsmap=new Map();\\nif(keyShape!==undefined){\\npatternMatchers.assertPattern(keyShape);}\\n\\nif(valueShape!==undefined){\\npatternMatchers.assertPattern(valueShape);}\\n\\n\\nconst assertKVOkToSet=(_key,value)=>{\\n/* TODO: Just a transition kludge. Remove when possible.*/\\n/* See https://github.com/Agoric/agoric-sdk/issues/3606*/\\nharden(value);\\n\\npassStyleOf.assertPassable(value);\\nif(valueShape!==undefined){\\npatternMatchers.mustMatch(value,valueShape,'mapStore value');}};\\n\\n\\n\\nconst assertKVOkToAdd=(key,value)=>{\\n/* TODO: Just a transition kludge. Remove when possible.*/\\n/* See https://github.com/Agoric/agoric-sdk/issues/3606*/\\nharden(key);\\n\\ncheckKey.assertScalarKey(key);\\nif(keyShape!==undefined){\\npatternMatchers.mustMatch(key,keyShape,'mapStore key');}\\n\\nassertKVOkToSet(key,value);};\\n\\n\\nreturn makeFar.Far(`scalar MapStore of ${index.quote(tag)}`,{\\n...makeMapStoreMethods(\\njsmap,\\nassertKVOkToAdd,\\nassertKVOkToSet,\\nundefined,\\ntag)});};\\n\\n\\n\\nharden(makeScalarMapStore);exports.makeMapStoreMethods=makeMapStoreMethods;exports.makeScalarMapStore=makeScalarMapStore;\",\n \"packages/store/src/stores/scalarSetStore.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var index=require('../../../../node_modules/@endo/errors/index.js');require('../../../../node_modules/@endo/pass-style/index.js');require('../../../../node_modules/@endo/marshal/index.js');require('../../../../node_modules/@endo/patterns/index.js');var scalarWeakSetStore=require('./scalarWeakSetStore.js');var storeUtils=require('./store-utils.js');var rankOrder=require('../../../../node_modules/@endo/marshal/src/rankOrder.js');var iterHelpers=require('../../../../node_modules/@endo/pass-style/src/iter-helpers.js');var patternMatchers=require('../../../../node_modules/@endo/patterns/src/patterns/patternMatchers.js');var checkKey=require('../../../../node_modules/@endo/patterns/src/keys/checkKey.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nmakeFar=require('../../../../node_modules/@endo/pass-style/src/make-far.js');/**\\n * @import {Key, Pattern} from '@endo/patterns';\\n * @import {SetStore, SetStoreMethods, StoreOptions} from '../types.js';\\n */ /**\\n * @template {Key} K\\n * @param {Set<K>} jsset\\n * @param {(k: K) => void} assertKeyOkToAdd\\n * @param {(k: K) => void} [assertKeyOkToDelete]\\n * @param {string} [keyName]\\n * @returns {SetStoreMethods<K>}\\n */const makeSetStoreMethods=(jsset,assertKeyOkToAdd,\\nassertKeyOkToDelete=undefined,\\nkeyName='key')=>\\n{\\nconst{assertUpdateOnAdd,assertUpdateOnDelete,iterableKeys}=\\nstoreUtils.makeCurrentKeysKit(\\n()=>jsset.keys(),\\n(k)=>jsset.has(k),\\nrankOrder.compareRank,\\nassertKeyOkToAdd,\\nassertKeyOkToDelete,\\nkeyName);\\n\\n\\n/**\\n * @param {Pattern} [keyPatt]\\n * @returns {Iterable<K>}\\n */\\nconst keys=(keyPatt=undefined)=>\\nkeyPatt===undefined?\\niterableKeys:\\niterHelpers.filterIterable(iterableKeys,(k)=>patternMatchers.matches(k,keyPatt));\\n\\nreturn harden({\\n...scalarWeakSetStore.makeWeakSetStoreMethods(\\njsset,\\nassertUpdateOnAdd,\\nassertUpdateOnDelete,\\nkeyName),\\n\\n\\nkeys,\\n\\nvalues:keys,\\n\\nsnapshot:(keyPatt=undefined)=>checkKey.makeCopySet(keys(keyPatt)),\\n\\ngetSize:(keyPatt=undefined)=>\\nkeyPatt===undefined?jsset.size:[...keys(keyPatt)].length,\\n\\nclear:(keyPatt=undefined)=>{\\nif(keyPatt===undefined){\\njsset.clear();}\\n\\nfor(const key of keys(keyPatt)){\\njsset.delete(key);}}});};\\n\\n\\n\\n\\n\\n/**\\n * Distinguishes between adding a new key (init) and updating or referencing a\\n * key (get, set, delete).\\n *\\n * `init` is only allowed if the key does not already exist. `Get`, `set` and\\n * `delete` are only allowed if the key does already exist.\\n *\\n * This is a _scalar_ set in that the keys can only be atomic values, primitives\\n * or remotables. Other storeSets will accept, for example, copyArrays and\\n * copyRecords, as keys and look them up based on equality of their contents.\\n *\\n * @template K\\n * @param {string} [tag] - tag for debugging\\n * @param {StoreOptions} [options]\\n * @returns {SetStore<K>}\\n */\\nconst makeScalarSetStore=(\\ntag='key',\\n{keyShape=undefined}={})=>\\n{\\nconst jsset=new Set();\\nif(keyShape!==undefined){\\npatternMatchers.assertPattern(keyShape);}\\n\\n\\nconst assertKeyOkToAdd=(key)=>{\\n/* TODO: Just a transition kludge. Remove when possible.*/\\n/* See https://github.com/Agoric/agoric-sdk/issues/3606*/\\nharden(key);\\n\\ncheckKey.assertScalarKey(key);\\nif(keyShape!==undefined){\\npatternMatchers.mustMatch(key,keyShape,'setStore key');}};\\n\\n\\n\\nreturn makeFar.Far(`scalar SetStore of ${index.quote(tag)}`,{\\n...makeSetStoreMethods(jsset,assertKeyOkToAdd,undefined,tag)});};\\n\\n\\nharden(makeScalarSetStore);exports.makeScalarSetStore=makeScalarSetStore;exports.makeSetStoreMethods=makeSetStoreMethods;\",\n \"packages/store/src/stores/scalarWeakMapStore.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var index=require('../../../../node_modules/@endo/errors/index.js');require('../../../../node_modules/@endo/pass-style/index.js');require('../../../../node_modules/@endo/patterns/index.js');var checkKey=require('../../../../node_modules/@endo/patterns/src/keys/checkKey.js');var patternMatchers=require('../../../../node_modules/@endo/patterns/src/patterns/patternMatchers.js');var passStyleOf=require('../../../../node_modules/@endo/pass-style/src/passStyleOf.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nmakeFar=require('../../../../node_modules/@endo/pass-style/src/make-far.js');/**\\n * @import {Key} from '@endo/patterns';\\n * @import {Passable, RemotableObject} from '@endo/pass-style';\\n * @import {WeakMapStore, StoreOptions} from '../types.js';\\n */ /**\\n * @template {Key} K\\n * @template {Passable} V\\n * @param {WeakMap<K & object, V>} jsmap\\n * @param {(k: K, v: V) => void} assertKVOkToAdd\\n * @param {(k: K, v: V) => void} assertKVOkToSet\\n * @param {(k: K) => void} [assertKeyOkToDelete]\\n * @param {string} [keyName]\\n * @returns {WeakMapStore<K, V>}\\n */const makeWeakMapStoreMethods=(jsmap,assertKVOkToAdd,assertKVOkToSet,\\nassertKeyOkToDelete=undefined,\\nkeyName='key')=>\\n{\\nconst assertKeyDoesNotExist=(key)=>\\n!jsmap.has(key)||index.throwRedacted`${index.quote(keyName)} already registered: ${key}`;\\n\\nconst assertKeyExists=(key)=>\\njsmap.has(key)||index.throwRedacted`${index.quote(keyName)} not found: ${key}`;\\n\\nreturn harden({\\nhas:(key)=>{\\n/* Check if a key exists. The key can be any JavaScript value,*/\\n/* though the answer will always be false for keys that cannot be found*/\\n/* in this map.*/\\nreturn jsmap.has(key);},\\n\\nget:(key)=>{\\nassertKeyExists(key);\\n/* How to tell typescript I believe the `get` will succeed.*/\\nreturn(/** @type {V} */jsmap.get(key));},\\n\\n\\ninit:(key,value)=>{\\nassertKeyDoesNotExist(key);\\nassertKVOkToAdd(key,value);\\njsmap.set(key,value);},\\n\\nset:(key,value)=>{\\nassertKeyExists(key);\\nassertKVOkToSet(key,value);\\njsmap.set(key,value);},\\n\\ndelete:(key)=>{\\nassertKeyExists(key);\\nif(assertKeyOkToDelete!==undefined){\\nassertKeyOkToDelete(key);}\\n\\njsmap.delete(key);},\\n\\n\\naddAll:(entries)=>{\\nif(typeof entries[Symbol.iterator]!=='function'){\\nif(Object.isFrozen(entries)&&checkKey.isCopyMap(entries)){\\n/* @ts-expect-error XXX*/\\nentries=checkKey.getCopyMapEntries(entries);}else\\n{\\nindex.throwRedacted`provided data source is not iterable: ${entries}`;}}\\n\\n\\nfor(const[key,value]of/** @type {Iterable<[K, V]>} */entries){\\n/* Don't assert that the key either does or does not exist.*/\\nassertKVOkToAdd(key,value);\\njsmap.set(key,value);}}});};\\n\\n\\n\\n\\n\\n/**\\n * This is a _scalar_ mapStore in that the keys can only be atomic values:\\n * primitives or remotables. Other mapStores will accept, for example,\\n * copyArrays and copyRecords as keys and look them up based on equality of\\n * their contents.\\n *\\n * TODO For now, this scalarWeakMap accepts only remotables, reflecting the\\n * constraints of the underlying JavaScript WeakMap it uses internally. But it\\n * should accept the primitives as well, storing them in a separate internal\\n * map. What makes it \\\"weak\\\" is that it provides no API for enumerating what's\\n * there. Though note that this would only enables collection of the remotables,\\n * since the other primitives may always reappear.\\n *\\n * @template K,V\\n * @param {string} [tag] - tag for debugging\\n * @param {StoreOptions} [options]\\n * @returns {RemotableObject & WeakMapStore<K, V>}\\n */\\nconst makeScalarWeakMapStore=(\\ntag='key',\\n{longLived=true,keyShape=undefined,valueShape=undefined}={})=>\\n{\\nconst jsmap=new(longLived?WeakMap:Map)();\\nif(keyShape!==undefined){\\npatternMatchers.assertPattern(keyShape);}\\n\\nif(valueShape!==undefined){\\npatternMatchers.assertPattern(valueShape);}\\n\\n\\nconst assertKVOkToSet=(_key,value)=>{\\n/* TODO: Just a transition kludge. Remove when possible.*/\\n/* See https://github.com/Agoric/agoric-sdk/issues/3606*/\\nharden(value);\\n\\npassStyleOf.assertPassable(value);\\nif(valueShape!==undefined){\\npatternMatchers.mustMatch(value,valueShape,'weakMapStore value');}};\\n\\n\\n\\nconst assertKVOkToAdd=(key,value)=>{\\n/* TODO: Just a transition kludge. Remove when possible.*/\\n/* See https://github.com/Agoric/agoric-sdk/issues/3606*/\\nharden(key);\\npassStyleOf.passStyleOf(key)==='remotable'||\\nindex.throwRedacted`Only remotables can be keys of scalar WeakMapStores: ${key}`;\\nif(keyShape!==undefined){\\npatternMatchers.mustMatch(key,keyShape,'weakMapStore key');}\\n\\nassertKVOkToSet(key,value);};\\n\\n\\nreturn makeFar.Far(`scalar WeakMapStore of ${index.quote(tag)}`,{\\n...makeWeakMapStoreMethods(\\njsmap,\\nassertKVOkToAdd,\\nassertKVOkToSet,\\nundefined,\\ntag)});};\\n\\n\\n\\nharden(makeScalarWeakMapStore);exports.makeScalarWeakMapStore=makeScalarWeakMapStore;exports.makeWeakMapStoreMethods=makeWeakMapStoreMethods;\",\n \"packages/store/src/stores/scalarWeakSetStore.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var index=require('../../../../node_modules/@endo/errors/index.js');require('../../../../node_modules/@endo/pass-style/index.js');require('../../../../node_modules/@endo/patterns/index.js');var checkKey=require('../../../../node_modules/@endo/patterns/src/keys/checkKey.js');var patternMatchers=require('../../../../node_modules/@endo/patterns/src/patterns/patternMatchers.js');var passStyleOf=require('../../../../node_modules/@endo/pass-style/src/passStyleOf.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nmakeFar=require('../../../../node_modules/@endo/pass-style/src/make-far.js');/**\\n * @import {Key} from '@endo/patterns';\\n * @import {StoreOptions, WeakSetStore, WeakSetStoreMethods} from '@agoric/store';\\n */ /**\\n * @template {Key} K\\n * @param {WeakSet<K & object>} jsset\\n * @param {(k: K) => void} assertKeyOkToAdd\\n * @param {(k: K) => void} [assertKeyOkToDelete]\\n * @param {string} [keyName]\\n * @returns {WeakSetStoreMethods<K>}\\n */const makeWeakSetStoreMethods=(jsset,assertKeyOkToAdd,\\nassertKeyOkToDelete=undefined,\\nkeyName='key')=>\\n{\\nconst assertKeyExists=(key)=>\\njsset.has(key)||index.throwRedacted`${index.quote(keyName)} not found: ${key}`;\\n\\nreturn harden({\\nhas:(key)=>{\\n/* Check if a key exists. The key can be any JavaScript value,*/\\n/* though the answer will always be false for keys that cannot be found*/\\n/* in this set.*/\\nreturn jsset.has(key);},\\n\\n\\nadd:(key)=>{\\nassertKeyOkToAdd(key);\\njsset.add(key);},\\n\\ndelete:(key)=>{\\nassertKeyExists(key);\\nif(assertKeyOkToDelete!==undefined){\\nassertKeyOkToDelete(key);}\\n\\njsset.delete(key);},\\n\\n\\naddAll:(keys)=>{\\nif(typeof keys[Symbol.iterator]!=='function'){\\nif(Object.isFrozen(keys)&&checkKey.isCopySet(keys)){\\n/* @ts-expect-error XXX*/\\nkeys=checkKey.getCopySetKeys(keys);}else\\n{\\nindex.throwRedacted`provided data source is not iterable: ${keys}`;}}\\n\\n\\nfor(const key of/** @type {Iterable<K>} */keys){\\nassertKeyOkToAdd(key);\\njsset.add(key);}}});};\\n\\n\\n\\n\\n\\n/**\\n * This is a _scalar_ set in that the keys can only be atomic values, primitives\\n * or remotables. Other storeSets will accept, for example, copyArrays and\\n * copyRecords, as keys and look them up based on equality of their contents.\\n *\\n * TODO For now, this scalarWeakSet accepts only remotables, reflecting the\\n * constraints of the underlying JavaScript WeakSet it uses internally. But it\\n * should accept the primitives as well, storing them in a separate internal\\n * set. What makes it \\\"weak\\\" is that it provides no API for enumerating what's\\n * there. Though note that this would only enables collection of the remotables,\\n * since the other primitives may always appear.\\n *\\n * @template K\\n * @param {string} [tag] - tag for debugging\\n * @param {StoreOptions} [options]\\n * @returns {WeakSetStore<K>}\\n */\\nconst makeScalarWeakSetStore=(\\ntag='key',\\n{longLived=true,keyShape=undefined}={})=>\\n{\\nconst jsset=new(longLived?WeakSet:Set)();\\nif(keyShape!==undefined){\\npatternMatchers.assertPattern(keyShape);}\\n\\n\\nconst assertKeyOkToAdd=(key)=>{\\n/* TODO: Just a transition kludge. Remove when possible.*/\\n/* See https://github.com/Agoric/agoric-sdk/issues/3606*/\\nharden(key);\\npassStyleOf.passStyleOf(key)==='remotable'||\\nindex.throwRedacted`Only remotables can be keys of scalar WeakStores: ${key}`;\\nif(keyShape!==undefined){\\npatternMatchers.mustMatch(key,keyShape,'weakSetStore key');}};\\n\\n\\n\\nreturn makeFar.Far(`scalar WeakSetStore of ${index.quote(tag)}`,{\\n...makeWeakSetStoreMethods(jsset,assertKeyOkToAdd,undefined,tag)});};\\n\\n\\nharden(makeScalarWeakSetStore);exports.makeScalarWeakSetStore=makeScalarWeakSetStore;exports.makeWeakSetStoreMethods=makeWeakSetStoreMethods;\",\n \"packages/store/src/stores/store-utils.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var index=require('../../../../node_modules/@endo/errors/index.js');require('../../../../node_modules/@endo/marshal/index.js');require('../../../../node_modules/@endo/patterns/index.js');var patternMatchers=require('../../../../node_modules/@endo/patterns/src/patterns/patternMatchers.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nmakeFar=require('../../../../node_modules/@endo/pass-style/src/make-far.js');/**\\n * @import {RankCompare} from '@endo/marshal';\\n * @import {MapStore, WeakMapStore} from '../types.js';\\n * @import {Passable} from '@endo/pass-style';\\n * @import {Key} from '@endo/patterns';\\n */ /* TODO: Undate `@endo/patterns` to export the original, and delete the*/ /* reimplementation here.*/ /**\\n * Should behave identically to the one in `@endo/patterns`, but reimplemented\\n * for now because `@endo/patterns` forgot to export this one. This one is\\n * simple enough that I prefer a reimplementation to a deep import.\\n *\\n * @param {unknown} s\\n * @returns {s is CopySet}\\n */const isCopySet=(s)=>patternMatchers.matches(s,patternMatchers.M.set());/* TODO: Undate `@endo/patterns` to export the original, and delete the*/ /* reimplementation here.*/ /**\\n * Should behave identically to the one in `@endo/patterns`, but reimplemented\\n * for now because `@endo/patterns` forgot to export this one. This one is\\n * simple enough that I prefer a reimplementation to a deep import.\\n *\\n * @param {unknown} m\\n * @returns {m is CopyMap}\\n */\\nconst isCopyMap=(m)=>patternMatchers.matches(m,patternMatchers.M.map());\\n\\n/**\\n * @template {Key} K\\n * @template {Passable} V\\n * @typedef {object} CurrentKeysKit\\n * @property {(k: K, v?: V) => void} assertUpdateOnAdd\\n * @property {(k: K) => void} assertUpdateOnDelete\\n * @property {Iterable<K>} iterableKeys\\n */\\n\\n/**\\n * @template {Key} K\\n * @template {Passable} V\\n * @param {() => Iterable<K>} getRawKeys\\n * @param {(k: K) => boolean} checkHas\\n * @param {RankCompare} compare\\n * @param {(k: K, v?: V) => void} assertOkToAdd\\n * @param {(k: K) => void} [assertOkToDelete]\\n * @param {string} [keyName]\\n * @returns {CurrentKeysKit<K, V>}\\n */\\nconst makeCurrentKeysKit=(\\ngetRawKeys,\\ncheckHas,\\ncompare,\\nassertOkToAdd,\\nassertOkToDelete=undefined,\\nkeyName='key')=>\\n{\\nlet updateCount=0;\\nlet sortedKeysMemo;\\n\\nconst assertUpdateOnAdd=(k,v=undefined)=>{\\nassertOkToAdd(k,v);\\nupdateCount+=1;\\nsortedKeysMemo=undefined;};\\n\\n\\nconst assertUpdateOnDelete=(k)=>assertOkToDelete&&assertOkToDelete(k);\\n\\nconst getSortedKeys=()=>{\\nif(sortedKeysMemo===undefined){\\nsortedKeysMemo=harden([...getRawKeys()].sort(compare));}\\n\\nreturn sortedKeysMemo;};\\n\\n\\nconst iterableKeys=makeFar.Far('Iterable of keys',{\\n[Symbol.iterator]:()=>{\\nconst generation=updateCount;\\ngetSortedKeys();\\nconst len=sortedKeysMemo.length;\\nlet i=0;\\nreturn makeFar.Far('Iterator of keys',{\\nnext:()=>{\\ngeneration===updateCount||index.throwRedacted`Store ${index.quote(keyName)} cursor stale`;\\n/* If they're equal, then the sortedKeyMemo is the same one*/\\n/* we started with.*/\\nfor(;;){\\nif(i<len){\\nconst value=sortedKeysMemo[i];\\ni+=1;\\nif(checkHas(value)){\\nreturn harden({done:false,value});}}else\\n\\n{\\nreturn harden({done:true,value:undefined});}}}});}});\\n\\n\\n\\n\\n\\n\\n\\nreturn harden({\\nassertUpdateOnAdd,\\nassertUpdateOnDelete,\\niterableKeys});};\\n\\n\\nharden(makeCurrentKeysKit);\\n\\n/**\\n * Call `provideLazy` to get or make the value associated with the key. If there\\n * already is one, return that. Otherwise, call `makeValue(key)`, remember it as\\n * the value for that key, and return it.\\n *\\n * @template {Key} K\\n * @template {Passable} V\\n * @param {WeakMapStore<K, V>} mapStore\\n * @param {K} key\\n * @param {(key: K) => V} makeValue\\n * @returns {V}\\n */\\nconst provideLazy=(mapStore,key,makeValue)=>{\\nif(!mapStore.has(key)){\\nmapStore.init(key,makeValue(key));}\\n\\nreturn mapStore.get(key);};\\n\\nharden(provideLazy);\\n\\n/**\\n * Helper for use cases in which the maker function is async. For two\\n * provideLazy calls with the same key, one may be making when the other call\\n * starts and it would make again. (Then there'd be a collision when the second\\n * tries to store the key.) This prevents that race condition by immediately\\n * storing a Promise for the maker in an ephemeral store.\\n *\\n * When the `store` argument is durable storage, note that it's possible for\\n * termination to happen after the make completes and before it reaches durable\\n * storage.\\n *\\n * @template {Key} K\\n * @template {Passable} V\\n * @param {WeakMapStore<K, V>} store\\n */\\nconst makeAtomicProvider=(store)=>{\\n/** @type {Map<K, Promise<V>>} */\\nconst pending=new Map();\\n\\n/**\\n * Call `provideAsync` to get or make the value associated with the key, when\\n * the maker is asynchronous. If there already is one, return that. Otherwise,\\n * call `makeValue(key)`, remember it as the value for that key, and return\\n * it.\\n *\\n * @param {K} key\\n * @param {(key: K) => Promise<V>} makeValue make the value for the store if\\n * it hasn't been made yet or the last make failed\\n * @param {(key: K, value: V) => Promise<void>} [finishValue] runs exactly\\n * once after a new value is added to the store\\n * @returns {Promise<V>}\\n */\\nconst provideAsync=(key,makeValue,finishValue)=>{\\nif(store.has(key)){\\nreturn Promise.resolve(store.get(key));}\\n\\nif(!pending.has(key)){\\nconst valP=makeValue(key).\\nthen((v)=>{\\nstore.init(key,v);\\nreturn v;}).\\n\\nthen((v)=>{\\nif(finishValue){\\nreturn finishValue(key,v).then(()=>v);}\\n\\nreturn v;}).\\n\\nfinally(()=>{\\npending.delete(key);});\\n\\npending.set(key,valP);}\\n\\nconst valP=pending.get(key);\\nassert(valP);\\nreturn valP;};\\n\\n\\nreturn harden({provideAsync});};\\n\\nharden(makeAtomicProvider);\\n/**\\n * @template {Key} K\\n * @template {Passable} V\\n * @typedef {ReturnType<typeof makeAtomicProvider<K, V>>} AtomicProvider<K, V>\\n */\\n\\n/**\\n * @template {Key} K\\n * @template {Passable} V\\n * @param {MapStore<K, V[]>} mapStore\\n * @param {K} key\\n * @param {V} item\\n */\\nconst appendToStoredArray=(mapStore,key,item)=>{\\nif(mapStore.has(key)){\\nconst extant=mapStore.get(key);\\nmapStore.set(key,harden([...extant,item]));}else\\n{\\nmapStore.init(key,harden([item]));}};\\n\\n\\nharden(appendToStoredArray);exports.appendToStoredArray=appendToStoredArray;exports.isCopyMap=isCopyMap;exports.isCopySet=isCopySet;exports.makeAtomicProvider=makeAtomicProvider;exports.makeCurrentKeysKit=makeCurrentKeysKit;exports.provideLazy=provideLazy;\",\n \"packages/store/src/types.js\": \"\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n'use strict';/*/ <reference types=\\\"ses\\\" />*/ /**\\n * Note TODO https://github.com/endojs/endo/issues/1488\\n *\\n * @import {Passable, RemotableObject} from '@endo/pass-style'\\n * @import {CopySet, CopyMap, Pattern} from '@endo/patterns'\\n * @import {Key} from '@endo/patterns'\\n */ /**\\n * @typedef {object} StoreOptions Of the dimensions on which KeyedStores can\\n * differ, we only represent a few of them as standard options. A given store\\n * maker should document which options it supports, as well as its positions\\n * on dimensions for which it does not support options.\\n * @property {boolean} [longLived] Which way to optimize a weak store. True\\n * means that we expect this weak store to outlive most of its keys, in which\\n * case we internally may use a JavaScript `WeakMap`. Otherwise we internally\\n * may use a JavaScript `Map`. Defaults to true, so please mark short lived\\n * stores explicitly.\\n * @property {boolean} [durable] The contents of this store survive termination\\n * of its containing process, allowing for restart or upgrade but at the cost\\n * of forbidding storage of references to ephemeral data. Defaults to false.\\n * @property {boolean} [fakeDurable] This store pretends to be a durable store\\n * but does not enforce that the things stored in it actually be themselves\\n * durable (whereas an actual durable store would forbid storage of such\\n * items). This is in service of allowing incremental transition to use of\\n * durable stores, to enable normal operation and testing when some stuff\\n * intended to eventually be durable has not yet been made durable. A store\\n * marked as fakeDurable will appear to operate normally but any attempt to\\n * upgrade its containing vat will fail with an error. Defaults to false.\\n * @property {Pattern} [keyShape]\\n * @property {Pattern} [valueShape]\\n */ /**\\n * Most store methods are in one of three categories\\n *\\n * - lookup methods (`has`,`get`)\\n * - update methods (`add`,`init`,`set`,`delete`,`addAll`)\\n * - query methods (`snapshot`,`keys`,`values`,`entries`,`getSize`)\\n * - query-update methods (`clear`)\\n *\\n * WeakStores have the lookup and update methods but not the query or\\n * query-update methods. Non-weak Stores are like their corresponding\\n * WeakStores, but with the additional query and query-update methods.\\n */ /* TODO use Key for K*/ /**\\n * @template K\\n * @typedef {object} WeakSetStoreMethods\\n * @property {(key: K) => boolean} has Check if a key exists. The key can be any\\n * JavaScript value, though the answer will always be false for keys that\\n * cannot be found in this store.\\n * @property {(key: K) => void} add Add the key to the set if it is not already\\n * there. Do nothing silently if already there. The key must be one allowed by\\n * this store. For example a scalar store only allows primitives and\\n * remotables.\\n * @property {(key: K) => void} delete Remove the key. Throws if not found.\\n * @property {(keys: CopySet<any> | Iterable<K>) => void} addAll\\n */ /**\\n * @template K\\n * @typedef {RemotableObject & WeakSetStoreMethods<K>} WeakSetStore\\n */ /* TODO use Key for K*/ /**\\n * @template K\\n * @typedef {object} SetStoreMethods\\n * @property {(key: K) => boolean} has Check if a key exists. The key can be any\\n * JavaScript value, though the answer will always be false for keys that\\n * cannot be found in this store.\\n * @property {(key: K) => void} add Add the key to the set if it is not already\\n * there. Do nothing silently if already there. The key must be one allowed by\\n * this store. For example a scalar store only allows primitives and\\n * remotables.\\n * @property {(key: K) => void} delete Remove the key. Throws if not found.\\n * @property {(keys: CopySet<any> | Iterable<K>) => void} addAll\\n * @property {(keyPatt?: Pattern) => Iterable<K>} keys\\n * @property {(keyPatt?: Pattern) => Iterable<K>} values\\n * @property {(keyPatt?: Pattern) => CopySet<any>} snapshot\\n * @property {(keyPatt?: Pattern) => number} getSize\\n * @property {(keyPatt?: Pattern) => void} clear\\n */ /**\\n * @template K\\n * @typedef {RemotableObject & SetStoreMethods<K>} SetStore\\n */ /* TODO use Key for K*/ /* TODO use Passable for V*/ /**\\n * @template K\\n * @template V\\n * @typedef {object} WeakMapStore\\n * @property {(key: K) => boolean} has Check if a key exists. The key can be any\\n * JavaScript value, though the answer will always be false for keys that\\n * cannot be found in this store.\\n * @property {(key: K) => V} get Return a value for the key. Throws if not\\n * found.\\n * @property {(key: K, value: V) => void} init Initialize the key only if it\\n * doesn't already exist. The key must be one allowed by this store. For\\n * example a scalar store only allows primitives and remotables.\\n * @property {(key: K, value: V) => void} set Set the key. Throws if not found.\\n * @property {(key: K) => void} delete Remove the key. Throws if not found.\\n * @property {(entries: CopyMap<any, any> | Iterable<[K, V]>) => void} addAll\\n */ /* TODO use Key for K*/ /* TODO use Passable for V*/ /**\\n * @template K\\n * @template V\\n * @typedef {object} MapStoreMethods\\n * @property {(key: K) => boolean} has Check if a key exists. The key can be any\\n * JavaScript value, though the answer will always be false for keys that\\n * cannot be found in this map\\n * @property {(key: K) => V} get Return a value for the key. Throws if not\\n * found.\\n * @property {(key: K, value: V) => void} init Initialize the key only if it\\n * doesn't already exist. The key must be one allowed by this store. For\\n * example a scalar store only allows primitives and remotables.\\n * @property {(key: K, value: V) => void} set Set the key. Throws if not found.\\n * @property {(key: K) => void} delete Remove the key. Throws if not found.\\n * @property {(entries: CopyMap<any, Passable> | Iterable<[K, V]>) => void} addAll\\n * @property {(keyPatt?: Pattern, valuePatt?: Pattern) => Iterable<K>} keys\\n * @property {(keyPatt?: Pattern, valuePatt?: Pattern) => Iterable<V>} values\\n * @property {(keyPatt?: Pattern, valuePatt?: Pattern) => Iterable<[K, V]>} entries\\n * @property {(\\n * keyPatt?: Pattern,\\n * valuePatt?: Pattern,\\n * ) => CopyMap<any, Passable>} snapshot\\n * @property {(keyPatt?: Pattern, valuePatt?: Pattern) => number} getSize\\n * @property {(keyPatt?: Pattern, valuePatt?: Pattern) => void} clear\\n */ /**\\n * @template [K=any]\\n * @template [V=any]\\n * @typedef {RemotableObject & MapStoreMethods<K, V>} MapStore\\n */ /* ///////////////////////// Deprecated Legacy /////////////////////////////////*/ /**\\n * @template K\\n * @template V\\n * @typedef {object} LegacyWeakMap LegacyWeakMap is deprecated. Use WeakMapStore\\n * instead if possible.\\n * @property {(key: K) => boolean} has Check if a key exists\\n * @property {(key: K) => V} get Return a value for the key. Throws if not\\n * found.\\n * @property {(key: K, value: V) => void} init Initialize the key only if it\\n * doesn't already exist\\n * @property {(key: K, value: V) => void} set Set the key. Throws if not found.\\n * @property {(key: K) => void} delete Remove the key. Throws if not found.\\n */ /**\\n * @template K\\n * @template V\\n * @typedef {object} LegacyMap LegacyMap is deprecated. Use MapStore instead if\\n * possible.\\n * @property {(key: K) => boolean} has Check if a key exists\\n * @property {(key: K) => V} get Return a value for the key. Throws if not\\n * found.\\n * @property {(key: K, value: V) => void} init Initialize the key only if it\\n * doesn't already exist\\n * @property {(key: K, value: V) => void} set Set the key. Throws if not found.\\n * @property {(key: K) => void} delete Remove the key. Throws if not found.\\n * @property {() => Iterable<K>} keys\\n * @property {() => Iterable<V>} values\\n * @property {() => Iterable<[K, V]>} entries\\n * @property {() => number} getSize\\n * @property {() => void} clear\\n */\",\n \"packages/swingset-liveslots/src/boyd-gc.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nparseVatSlots=require('./parseVatSlots.js');/* Theory of Operation (vref logical objects)\\n Liveslots coordinates access to \\\"logical objects\\\", sometimes known\\n as \\\"vref objects\\\" because each one is named with a distinct vref\\n identifier (o+1, o-2, o+d3/4, etc). The SwingSet kernel coordinates\\n access to the objects between vats, using a kref identifier (ko56),\\n but vats never see krefs.\\n When vat code (written in JavaScript) needs to interact with a\\n logical object, it needs some JS `Object` to pass in arguments, or\\n to invoke methods upon, or to receive in the arguments of a method\\n call. We use Presence objects for imported vrefs, Remotable/heap\\n objects for locally-created (potentially-exported) ephemeral\\n objects, and Representatives for virtual/durable objects initially\\n created by calling the Kind's maker function. Liveslots is\\n responsible for recognizing these `Object` objects when they appear\\n at its doorstep (e.g. in a remote method send, or when assigned to\\n the `state` of a virtual object), and knowing which vref is being\\n referenced. Liveslots is also the one to create all Presences and\\n Representatives (vat code creates the Remotable/heap objects, by\\n calling `Far()`).\\n For garbage-collection purposes, liveslots tracks the \\\"reachable\\\"\\n and \\\"recognizable\\\" status for these logical objects. A logical\\n object is either VREF-REACHABLE, VREF-RECOGNIZABLE, or\\n nothing. Strong references from a VREF-REACHABLE object makes the\\n target also VREF-REACHABLE. Weak references from a VREF-REACHABLE\\n makes the target at least VREF-RECOGNIZABLE, although it might be\\n VREF-REACHABLE if there is also a strong reference to it.\\n Weak collections provide weak access to their keys, and strong\\n access to their values. Strong collections provide strong access to\\n both keys and values. Virtual/durable objects provide strong access\\n to their `state`. The \\\"reachable set\\\" is the transitive closure of\\n strong edges, given a set of anchors. There will also be a\\n \\\"recognizable set\\\", with weak edges from some members of the\\n reachable set.\\n Liveslots needs to keep track of the reachable or recognizable\\n status of logical objects to limit storage consumption. It must\\n preserve all reachable data, but it can delete data that can no\\n longer be reached. Liveslots also needs to coordinate status updates\\n with the kernel, to enable the kernel to do the same.\\n The logical object for an imported vref (known as a \\\"Presence-style\\n vref\\\", o-NN) can be kept alive by either the existence of an actual\\n Presence `Object`, or by a (strong) virtual/durable collection that\\n uses the vref as its key or inside its value, or by a (weak)\\n collection that uses the vref inside its value, or by a\\n virtual/durable object that uses the vref inside its `state`. We\\n call the Presence the \\\"RAM pillar\\\", and the virtual/durable\\n references the \\\"vdata pillar\\\". The \\\"vdata pillar\\\" is tracked as a\\n record in the vatstore DB. We say the logical object is\\n VREF-REACHABLE if either pillar is up, and it becomes\\n VREF-UNREACHABLE if all pillars are down.\\n The logical object for a virtual/durable object (known as\\n \\\"Representative-style\\\", o+vKK/II or o+dKK/II) can be kept alive by\\n any of three pillars: the Representative (RAM pillar), a\\n virtual/durable collection or object state (vdata pillar), or by\\n virtue of being exported to the kernel (export pillar). Sending a\\n Representative in a message to some other vat will cause the vref to\\n be exported, and the kernel will tell us if/when that other vat ever\\n drops their strong reference, which will then drop the export\\n pillar. The \\\"export status\\\" for a vref is one of EXPORT-REACHABLE,\\n EXPORT-RECOGNIZABLE, or nothing.\\n The third category of vrefs (o+NN) are for locally-created ephmeral\\n objects, created by calling `Far()`. Liveslots frequently calls\\n these \\\"Remotable-style vrefs\\\", although \\\"heap\\\" might be a less\\n ambiguous term. They have only the RAM pillar: the lifetime of the\\n logical object is the same as that of the \\\"Remotable\\\" heap value.\\n Once all pillars for a logical object have dropped, liveslots needs\\n to delete the logical object. For virtual/durable objects, this\\n means deleting the `state` data, and since the state can hold\\n references to other objects, it means decrementing refcounts and\\n dropping vdata pillars, which might trigger more deletions. For\\n logical objects that have been imported from the kernel, it must\\n also notify the kernel of the transition from \\\"reachable\\\" status to\\n \\\"unreachable\\\", so the kernel can propagate the event outwards to the\\n upstream vat that exported the object, deleting table entries all\\n the way.\\n Objects which are unreachable by our vat might still be reachable by\\n others, or by something in the exporting vat, so becoming\\n unreachable is not the end of the story. The logical object might\\n still be *recognizable* by our vat, as a key in one or more weak\\n collections. While in this VREF-RECOGNIZABLE state, three things\\n might happen:\\n * The owner, or someone who still has access, may send it to us in a\\n message. The vat code receives a newly-minted Presence or\\n Representative object, and now the logical object is\\n VREF-REACHABLE once more.\\n * The owner may declare the object \\\"retired\\\", meaning they've\\n deleted it. We should drop our matching WeakMap entries, and free\\n their data (which might make other objects become\\n unreachable). This is triggered by \\\"dispatch.retireImports\\\".\\n * We might delete our last WeakMap that recognized the vref,\\n allowing us to tell the kernel that we don't care about the vref\\n anymore, so it can remove the bookkeeping records. This uses\\n \\\"possiblyRetiredSet\\\", and may invoke \\\"syscall.retireImports\\\".\\n We track recognizability status using \\\"recognizer records\\\". When the\\n recognizer is a virtual/durable collection or object, the record is\\n stored in the vatstore DB.\\n The kernel tracks the vat's imported vrefs with an \\\"import status\\\",\\n one of IMPORT-REACHABLE, IMPORT-RECOGNIZABLE, or nothing. This\\n status is stored in the c-list entry, and is not visible to the\\n vat. It changes when the vat receives a vref in a delivery, or\\n performs syscall.dropImports or syscall.retireImports, or receives a\\n dispatch.retireImports.\\n /*\\n Theory of Operation (imports/Presences)\\n This describes the states that a Presence `Object` might be in, and\\n how we track changes in that status. The Presence forms the \\\"RAM\\n pillar\\\" that may support the logical object (vref).\\n A Presence object is in one of 5 states: UNKNOWN, REACHABLE,\\n UNREACHABLE, COLLECTED, FINALIZED. Note that there's no actual state\\n machine with those values, and we can't observe all of the\\n transitions from JavaScript, but we can describe what operations\\n could cause a transition, and what our observations allow us to\\n deduce about the state:\\n * UNKNOWN moves to REACHABLE when a crank introduces a new import\\n * userspace holds a reference only in REACHABLE\\n * REACHABLE moves to UNREACHABLE only during a userspace crank\\n * UNREACHABLE moves to COLLECTED when engine GC runs, which queues the finalizer\\n * COLLECTED moves to FINALIZED when a new turn runs the finalizer\\n * FINALIZED moves to UNKNOWN when liveslots sends a dropImports syscall\\n convertSlotToVal either imports a vref for the first time, or\\n re-introduces a previously-seen vref. It transitions from:\\n * UNKNOWN to REACHABLE by creating a new Presence\\n * UNREACHABLE to REACHABLE by re-using the old Presence that userspace\\n forgot about\\n * COLLECTED/FINALIZED to REACHABLE by creating a new Presence\\n Our tracking tables hold data that depends on the current state:\\n * slotToVal holds a WeakRef only in [REACHABLE, UNREACHABLE, COLLECTED]\\n * that WeakRef .deref()s into something only in [REACHABLE, UNREACHABLE]\\n * possiblyDeadSet holds the vref only in FINALIZED\\n * (TODO) re-introduction could remove the vref from possiblyDeadSet\\n Each state thus has a set of perhaps-measurable properties:\\n * UNKNOWN: slotToVal[baseRef] is missing, baseRef not in possiblyDeadSet\\n * REACHABLE: slotToVal[baseRef] has live weakref, userspace can reach\\n * UNREACHABLE: slotToVal[baseRef] has live weakref, userspace cannot reach\\n * COLLECTED: slotToVal[baseRef] has dead weakref\\n * FINALIZED: slotToVal[baseRef] is missing, baseRef is in possiblyDeadSet\\n Our finalizer callback is queued by the engine's transition from\\n UNREACHABLE to COLLECTED, but the baseRef might be re-introduced\\n before the callback has a chance to run. There might even be\\n multiple copies of the finalizer callback queued. So the callback\\n must deduce the current state and only perform cleanup (i.e. delete\\n the slotToVal entry and add the baseRef to possiblyDeadSet) in the\\n COLLECTED state.\\n Our general rule is \\\"trust the finalizer\\\". The GC code below\\n considers a Presence to be reachable (the vref's \\\"RAM pillar\\\"\\n remains \\\"up\\\") until it moves to the FINALIZED state. We do this to\\n avoid race conditions between some other pillar dropping (and a BOYD\\n sampling the WeakRef) while it is in the COLLECTED state. If we\\n treated COLLECTED as the RAM pillar being \\\"down\\\"), then the\\n subsequent finalizer callback would examine the vref a second time,\\n potentially causing a vat-fatal double syscall.dropImports. This\\n rule may change if/when we use FinalizationRegistry better, by\\n explicitly de-registering the vref when we drop it, which JS\\n guarantees will remove and pending callback from the queue. This may\\n help us avoid probing the WeakRef during BOYD (instead relying upon\\n the fired/not-fired state of the FR), since that probing can cause\\n engines to retain objects longer than necessary.\\n */ /* Additional notes:\\n There are three categories of vrefs:\\n * Presence-style (o-NN, imports, durable)\\n * Remotable-style (o+NN, exportable, ephemeral)\\n * Representative-style (o+vKK/II or o+dKK/II, exportable, virtual/durable)\\n We don't necessarily have a Presence for every o-NN vref that the\\n vat can reach, because the vref might be held in virtual/durable\\n data (\\\"vdata\\\") while the in-RAM `Presence` object was\\n dropped. Likewise the in-RAM `Representative` can be dropped while\\n the o+dKK/II vref is kept VREF-REACHABLE by either vdata or an\\n export to the kernel. We *do* always have a Remotable for every o+NN\\n vref that the vat knows about, because Remotables are ephemeral.\\n The vat does not record any information about the kernel-facing\\n import status (c-list state) for Presence-style vrefs (o-NN), and\\n cannot ask the kernel for it, so we rely upon the invariant that you\\n only add a vref to possiblyDeadSet if it was VREF-REACHABLE\\n first. That way, possiblyDeadSet.has(vref) means that the c-list\\n import status was IMPORT-REACHABLE. Likewise, code should only add\\n to possiblyRetiredSet if the vref was at least VREF-RECOGNIZABLE\\n beforehand, meaning the c-list status was at least\\n IMPORT-RECOGNIZABLE. This helps us avoid a vat-fatal duplicate\\n dropImports or retireImports syscall.\\n For imports, the lifetime is controlled by the upstream vat: we\\n might drop VREF-REACHABLE today and maintain VREF-RECOGNIZABLE for\\n days until the object is finally retired. For exports *we* control\\n the lifetime, so when we determine an export is no longer\\n VREF-REACHABLE, we delete it and retire the vref immediately, and it\\n does not observably linger in the VREF-RECOGNIZABLE state. This\\n simplifies our tracking, and allows the deletion of Remotables and\\n Representative-type vrefs to be idempotent.\\n Each vref's reachability status is determined by a set of\\n \\\"pillars\\\". For Presence-style vrefs, there are two: the RAM pillar\\n (the `Presence` object), and the vdata pillar. The vdata pillar is\\n tracked in a vatstore key named `vom.rc.${vref}`, which stores the\\n reachable/recognizable refcounts.\\n For Representative-style vrefs, we add the export-status pillar,\\n because anything that we've exported to the kernel must be kept\\n alive until the kernel issues a dispatch.dropExports. That gives us\\n three pillars:\\n * the RAM pillar is the `Representative` object\\n * the vdata pillar is stored in `vom.rc.${vref}`\\n * the export-status pillar is stored in `vom.es.${vref}`\\n Remotables have only the RAM pillar. When a Remotable-style vref is\\n exported to the kernel, the Remotable is added to the\\n `exportedRemotables` set. And when it is stored in vdata, it appears\\n as a key of the `remotableRefCounts` map. That keeps the Remotable\\n itself alive until the other reachability pathways have gone\\n away. We don't do this for Representatives because it would violate\\n our \\\"don't use RAM for inactive virtual objects\\\" rule.\\n When an imported Presence becomes VREF-UNREACHABLE, it might still\\n be VREF-RECOGNIZABLE, by virtue of being the key of one or more weak\\n collections. If not, it might transit from VREF-REACHABLE directly\\n to NONE. The code that reacts to the VREF-UNREACHABLE transition\\n must check for recognizers, and do a retireImports right away if\\n there are none. Otherwise, recognizer will remain until either the\\n kernel retires the object (dispatch.retireImports), or the weak\\n collection is deleted, in which case possiblyRetiredSet will be\\n updated with the vref that might no longer be recognized. There will\\n be a race between us ceasing to recognize the vref (which should\\n trigger a syscall.retireImports), and the kernel telling us the\\n object has been deleted (via dispatch.retireImports). Either one\\n must inhibit the other.\\n possiblyRetiredSet only cares about Presence-style vrefs, because\\n they represent imports, whose lifetime is not under our control. The\\n collection-deletion code will add Remotable- and Representative-\\n style vrefs in possiblyRetiredSet, but we can remove and ignore\\n them.\\n We use slotToVal.has(vref) everywhere for our \\\"is it still\\n reachable\\\" check, which returns true for the Presence's REACHABLE /\\n UNREACHABLE / COLLECTED states, and false for the FINALIZED\\n state. In contrast, getValForSlot(vref) returns false for both\\n COLLECTED and FINALIZED. We want COLLECTED to qualify as \\\"still\\n reachable\\\" because it means there's still a finalizer callback\\n queued, which will be run eventually, and we need that callback to\\n not trigger a duplicate drop. We use slotToVal.has() in the\\n possiblyRetiredSet loop (to inhibit retirement of imported vrefs\\n whose Presences are in the COLLECTED state, and which just lost a\\n recognizer), because getValForSlot would allow such COLLECTED vrefs\\n to be retired, even before the finalizer had fired and could do a\\n dropImports.\\n When we decide to delete a virtual object, we will delete its\\n `state`, decrementing the refcounts of any objects therein, which\\n might shake loose more data. So we keep looping until we've stopped\\n adding things to possiblyDeadSet. The same can happen when we use\\n vrm.ceaseRecognition() to delete any weak collection values keyed by\\n it. We also call ceaseRecognition when we realize that a Remotable\\n has been deleted. But the possiblyDeadSet processing loop cannot\\n make the decision to retire a Presence-style vref: those are deleted\\n outside our vat, and the kernel notifies us of the vref's retirement\\n with dispatch.retireImports (which also calls ceaseRecognition). The\\n only thing possiblyDeadSet can tell us about Presences is that our\\n vat can no longer *reach* the vref, which means we need to do a\\n syscall.dropImports, which cannot immediately release more data.\\n When the kernel sends us a dispatch.bringOutYourDead (or \\\"BOYD\\\" for\\n short), this scanForDeadObjects() will be called. This is the only\\n appropriate time for the syscall behavior to depend upon engine GC\\n behavior: during all other deliveries, we want the syscalls to be a\\n deterministic function of delivery contents, userspace behavior, and\\n vatstore data.\\n During BOYD, we still try to minimize the variation of behavior as\\n much as possible. The first step is to ask the engine to perform a\\n full GC sweep, to collect any remaining UNREACHABLE objects, and\\n allow the finalizer callbacks to run before looking at the\\n results. We also sort the vrefs before processing them, to remove\\n sensitivity to the exact order of finalizer invocation.\\n That makes BOYD a safe time to look inside WeakRefs and make\\n syscalls based on the contents, or to read the sets that are\\n modified during FinalizationRegistry callbacks and make syscalls to\\n query their state further. This this is the only time we examine and\\n clear possiblyDeadSet and possiblyRetiredSet, or probe\\n slotToVal. Outside of BOYD, in convertSlotToVal, we must probe the\\n WeakRefs to see whether we must build a new Presence or\\n Representative, or not, but we have carefully designed that code to\\n avoid making syscalls during the unmarshalling process, so the only\\n consequence of GC differences should be differences in metering and\\n memory allocation patterns.\\n Our general strategy is to look at the baseRefs/vrefs whose state\\n might have changed, determine their new reachability /\\n recognizability status, and then resolve any discrepancies between\\n that status and that of other parties who need to match.\\n The kernel is one such party. If the kernel thinks we can reach an\\n imported o-NN vref, but we've now determined that we cannot, we must\\n send a syscall.dropImports to resolve the difference. Once sent, the\\n kernel will update our c-list entry to reflect the unreachable (but\\n still recognizable) status. Likewise, if the kernel thinks *it* can\\n recognize an exported o+NN vref, but we've just retired it, we need\\n to update the kernel with a syscall.retireExports, so it can notify\\n downstream vats that have weak collections with our vref as a key.\\n The DB-backed `state` of a virtual object is another such party. If\\n the object is unreachable, but still has state data, we must delete\\n that state, and decrement refcounts it might have held.\\n Our plan is summarized as:\\n * outer loop\\n * gcAndFinalize\\n * sort possiblyDeadSet, examine each by type\\n * all: remove from possiblyDeadSet\\n * presence (vref):\\n * if unreachable:\\n * dropImports\\n * add to possiblyRetiredSet\\n * remotable (vref):\\n * if unreachable:\\n * retireExports if kernelRecognizableRemotables\\n * vrm.ceaseRecognition\\n * VOM (baseRef)\\n * if unreachable:\\n * deleteVirtualObject (and retireExports retirees)\\n * repeat loop if gcAgain or possiblyDeadSet.size > 0\\n * now sort and process possiblyRetiredSet. for each:\\n * ignore unless presence\\n * if unreachable and unrecognizable: retireImport\\n (that's a duplicate reachability check, but note the answer might\\n be different now)\\n*/ /* BaseRef vs vref\\n For multi-faceted virtual/durable objects (eg `defineKind()` with\\n faceted `behavior` argument), each time userspace create a new\\n instance, we create a full \\\"cohort\\\" of facets, passing a record of\\n Representative objects (one per facet) back to the caller. Each\\n facet gets its own vref, but they all share a common prefix, known\\n as the \\\"baseRef\\\". For example, `o+d44/2` is a BaseRef for a cohort,\\n the second instance created of the `o+d44` Kind, whose individual\\n facets would have vrefs of `o+d44/2:0` and `o+d44/2:1`.\\n We use a WeakMap to ensure that holding any facet will keep all the\\n others alive, so the cohort lives and dies as a group. The GC\\n tracking code needs to track the whole cohort at once, not the\\n individual facets, and any data structure which refers to cohorts\\n will use the BaseRef instead of a single vref. So `slotToVal` is\\n keyed by a BaseRef, and its values are a cohort of facets. But\\n `valToSlot` is keyed by the facets, and its values are the\\n individual facet's vref.\\n For Presence- and Remotable- style objects, the baseRef is just the\\n vref (i.e., every baseRef is either a cohort-identifying prefix or\\n an isolated-object vref, and every vref either has a baseRef prefix\\n and identifies one facet of a cohort or has no such prefix and\\n identifies an isolated object).\\n Most of the GC-related APIs that appear here take vrefs, but the\\n exceptions are:\\n * slotToVal is keyed by BaseRef\\n * possiblyDeadSet holds BaseRefs, that's what our WeakRefs track\\n * vrm.isVirtualObjectReachable takes baseRef\\n * vrm.deleteVirtualObject takes baseRef, returns [bool, retireees=vrefs]\\n * vrm.ceaseRecognition takes either baseRef or vref\\n (if given a baseRef, it will process all the facets)\\n */const makeBOYDKit=({gcTools,slotToVal,vrm,kernelRecognizableRemotables,syscall,possiblyDeadSet,possiblyRetiredSet})=>{/* Representative (o+dNN/II or o+vNN/II) lifetimes are also*/ /* controlled by us. We allow the Representative object to go away*/ /* without deleting the vref, so we must track all three pillars:*/ /* Representative (RAM), export, and vdata. When we decide the vref*/ /* is unreachable, we must delete the virtual object's state, as*/ /* well as retiring the object (by telling the kernel it has been*/ /* retired, if the kernel cares, and removing any local recognition*/ /* records).*/const checkExportRepresentative=(baseRef)=>{/* RAM pillar || (vdata pillar || export pillar)*/const isReachable=slotToVal.has(baseRef)||vrm.isVirtualObjectReachable(baseRef);let gcAgain=false;let exportsToRetire=[];if(!isReachable){/* again, we own the object, so we retire it immediately*/[gcAgain,exportsToRetire]=vrm.deleteVirtualObject(baseRef);}return{gcAgain,exportsToRetire};};/* Remotable (o+NN) lifetimes are controlled by us: we delete/retire*/ /* the object as soon as it becomes unreachable. We only track the*/ /* Remotable/Far object (the RAM pillar) directly: exports retain*/ /* the Remotable in the exportedRemotables set, and vdata retains it*/ /* as keys of the remotableRefCounts map. So when we decide the vref*/ /* is unreachable, the Remotable is already gone, and it had no*/ /* other data we need to delete, so our task is to remove any local*/ /* recognition records, and to inform the kernel with a*/ /* retireExports if kernelRecognizableRemotables says that the*/ /* kernel still cares.*/ /**/ /* note: we track export status for remotables in the*/ /* kernelRecognizableRemotables set, not vom.es.VREF records. We*/ /* don't currently track recognition records with*/ /* vom.ir.VREF|COLLECTION, but we should, see #9956*/const checkExportRemotable=(vref)=>{let gcAgain=false;let exportsToRetire=[];/* Remotables have only the RAM pillar*/const isReachable=slotToVal.has(vref);if(!isReachable){/* We own the object, so retire it immediately. If the kernel*/ /* was recognizing it, we tell them it is now retired*/if(kernelRecognizableRemotables.has(vref)){kernelRecognizableRemotables.delete(vref);exportsToRetire=[vref];/* the kernel must not have been able to reach the object,*/ /* else it would still be pinned by exportedRemotables*/}/* and remove it from any local weak collections*/gcAgain=vrm.ceaseRecognition(vref);}return{gcAgain,exportsToRetire};};/* Presence (o-NN) lifetimes are controlled by the upstream vat, or*/ /* the kernel. If the vref was in possiblyDeadSet, then it *was**/ /* reachable before, so we can safely presume the kernel to think we*/ /* can reach it.*/const checkImportPresence=(vref)=>{/* RAM pillar || vdata pillar*/ /* use slotToVal.has, not getSlotForVal(), to avoid duplicate drop*/const isReachable=slotToVal.has(vref)||vrm.isPresenceReachable(vref);let dropImport;if(!isReachable){dropImport=vref;}return{dropImport};};const scanForDeadObjects=async()=>{await null;/* `possiblyDeadSet` holds vrefs which have lost a supporting*/ /* pillar (in-memory, export, or virtualized data refcount) since*/ /* the last call to scanForDeadObjects. The vref might still be*/ /* supported by a remaining pillar, or the pillar which was*/ /* dropped might have been restored (e.g., re-exported after a*/ /* drop, or given a new in-memory manifestation).*/const importsToDrop=new Set();const importsToRetire=new Set();const exportsToRetire=new Set();let gcAgain=false;do{gcAgain=false;await gcTools.gcAndFinalize();/* process a sorted list of vref/baseRefs we need to check for*/ /* reachability, one at a time*/for(const vrefOrBaseRef of[...possiblyDeadSet].sort()){/* remove the vref now, but some deleteVirtualObject might*/ /* shake it loose again for a future pass to investigate*/possiblyDeadSet.delete(vrefOrBaseRef);const parsed=parseVatSlots.parseVatSlot(vrefOrBaseRef);assert.equal(parsed.type,'object',vrefOrBaseRef);let res={};if(parsed.virtual||parsed.durable){const baseRef=vrefOrBaseRef;res=checkExportRepresentative(baseRef);}else if(parsed.allocatedByVat){const vref=vrefOrBaseRef;res=checkExportRemotable(vref);}else{const vref=vrefOrBaseRef;res=checkImportPresence(vref);}/* prepare our end-of-crank syscalls*/if(res.dropImport){importsToDrop.add(res.dropImport);possiblyRetiredSet.add(res.dropImport);}for(const facetVref of res.exportsToRetire||[]){exportsToRetire.add(facetVref);}gcAgain||=!!res.gcAgain;}/* Deleting virtual object state, or freeing weak-keyed*/ /* collection entries, might shake loose more*/ /* objects. possiblyDeadSet and possiblyRetiredSet are added*/ /* when a vdata vref decrefs to zero, and gcAgain means that*/ /* something in RAM might now be free. In both cases we should*/ /* do another pass, including gcAndFinalize(), until we've*/ /* cleared everything we can.*/}while(possiblyDeadSet.size>0||gcAgain);/* Now we process potential retirements, by which we really mean*/ /* de-recognitions, where this vat has ceased to even recognize a*/ /* previously unreachable-yet-recognizable*/ /* vref. addToPossiblyRetiredSet() is called from*/ /* ceaseRecognition() when a recognizer goes away, such when a*/ /* weak collection being deleted and it no longer recognizes all*/ /* its former keys. ceaseRecognition() can be called from the loop*/ /* above (when a Remotable-style object is deleted, or from within*/ /* deleteVirtualObject), or in response to a retireImport()*/ /* delivery. We assume possiblyRetiredSet is given vrefs of all*/ /* sorts, but we only care about Presence-type, because we must do*/ /* retireImports for them: the kernel doesn't care if/when we stop*/ /* recognizing our own (maybe-exported) Remotable- and*/ /* Representative- type vrefs.*/for(const vref of[...possiblyRetiredSet].sort()){possiblyRetiredSet.delete(vref);const parsed=parseVatSlots.parseVatSlot(vref);assert.equal(parsed.type,'object',vref);/* ignore non-Presences*/if(parsed.allocatedByVat)continue;/* if we're dropping the vref, checkImportPresence() already*/ /* did our isReachable check, so we can safely skip it (and*/ /* save a vatstore syscall)*/const isReachable=!importsToDrop.has(vref)&&(/* Use slotToVal.has, not getValForSlot(), to avoid retirement*/ /* before the finalizer fires and does dropImport*/slotToVal.has(vref)||vrm.isPresenceReachable(vref));const isRecognizable=isReachable||vrm.isVrefRecognizable(vref);if(!isRecognizable){importsToRetire.add(vref);}}/* note that retiring Presence-type vrefs cannot shake loose any*/ /* local data, so we don't need to loop back around*/if(importsToDrop.size){syscall.dropImports([...importsToDrop].sort());}if(importsToRetire.size){syscall.retireImports([...importsToRetire].sort());}if(exportsToRetire.size){syscall.retireExports([...exportsToRetire].sort());}};return{scanForDeadObjects};};harden(makeBOYDKit);exports.makeBOYDKit=makeBOYDKit;\",\n \"packages/swingset-liveslots/src/cache.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nindex=require('../../../node_modules/@endo/errors/index.js');/**\\n * @template V\\n * @callback CacheGet\\n * @param {string} key\\n * @returns {V | undefined}\\n */ /**\\n * @template V\\n * @callback CacheSet\\n * @param {string} key\\n * @param {V} value\\n * @returns {void}\\n */ /**\\n * @callback CacheDelete\\n * @param {string} key\\n * @returns {void}\\n *\\n * @callback CacheFlush\\n * @returns {void}\\n *\\n * @callback CacheInsistClear\\n * @returns {void}\\n */ /**\\n * @template V\\n * @typedef {object} Cache\\n * @property {CacheGet<V>} get\\n * @property {CacheSet<V>} set\\n * @property {CacheDelete} delete\\n * @property {CacheFlush} flush\\n * @property {CacheInsistClear} insistClear\\n */ /**\\n * Cache of virtual object/collection state\\n *\\n * This cache is empty between deliveries. Within a delivery, the\\n * first access to some data will cause vatstore reads to populate the\\n * cache, then the data is retained until end-of-delivery. Writes to\\n * data will update the cache entry and mark it as dirty. At\\n * end-of-delivery, we flush the cache, writing out any dirty entries,\\n * and deleting all entries.\\n *\\n * This needs RAM for everything read during a delivery (rather than\\n * having a fixed maximum size), but yields a simple (easy to debug)\\n * deterministic relationship between data access and reads/writes to\\n * the backing store.\\n *\\n * @template V\\n * @param {(key: string) => V} readBacking\\n * @param {(key: string, value: V) => void} writeBacking\\n * @param {(key: string) => void} deleteBacking\\n * @returns {Cache<V>}\\n *\\n * This cache is part of the virtual object manager and is not intended to be\\n * used independently; it is exported only for the benefit of test code.\\n */function makeCache(readBacking,writeBacking,deleteBacking){const stash=new Map();const dirtyKeys=new Set();/** @type {Cache<V>} */const cache={get:(key)=>{assert.typeof(key,'string');if(stash.has(key)){return stash.get(key);}else if(dirtyKeys.has(key)){/* Respect a pending deletion.*/return undefined;}const value=readBacking(key);stash.set(key,value);return value;},set:(key,value)=>{assert.typeof(key,'string');stash.set(key,value);dirtyKeys.add(key);},delete:(key)=>{assert.typeof(key,'string');stash.delete(key);dirtyKeys.add(key);},flush:()=>{const keys=[...dirtyKeys.keys()];\\nfor(const key of keys.sort()){\\nif(stash.has(key)){\\nwriteBacking(key,stash.get(key));}else\\n{\\ndeleteBacking(key);}}\\n\\n\\nstash.clear();\\ndirtyKeys.clear();},\\n\\ninsistClear:()=>{\\ndirtyKeys.size===0||index.throwRedacted`cache still has dirtyKeys`;\\nstash.size===0||index.throwRedacted`cache still has stash`;}};\\n\\n\\nreturn harden(cache);}exports.makeCache=makeCache;\",\n \"packages/swingset-liveslots/src/capdata.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var\\n\\nindex=require('../../../node_modules/@endo/errors/index.js');/**\\n * Assert function to ensure that something expected to be a capdata object\\n * actually is. A capdata object should have a .body property that's a string\\n * and a .slots property that's an array of strings.\\n *\\n * @param {any} capdata The object to be tested\\n * @throws {Error} if, upon inspection, the parameter does not satisfy the above\\n * criteria.\\n * @returns {asserts capdata is IMPORT('./types.js').SwingSetCapData}\\n */\\nfunction insistCapData(capdata){\\ntypeof capdata.body==='string'||\\nindex.throwRedacted`capdata has non-string .body ${capdata.body}`;\\nArray.isArray(capdata.slots)||\\nindex.throwRedacted`capdata has non-Array slots ${capdata.slots}`;\\n/* TODO check that the .slots array elements are actually strings*/}exports.insistCapData=insistCapData;\",\n \"packages/swingset-liveslots/src/collectionManager.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var index=require('../../../node_modules/@endo/errors/index.js');require('../../../node_modules/@endo/far/src/index.js');require('../../../node_modules/@endo/marshal/index.js');require('../../../node_modules/@endo/patterns/index.js');require('../../store/src/index.js');var parseVatSlots=require('./parseVatSlots.js');var vatstoreIterators=require('./vatstore-iterators.js');var cache=require('./cache.js');var rankOrder=require('../../../node_modules/@endo/marshal/src/rankOrder.js');var patternMatchers=require('../../../node_modules/@endo/patterns/src/patterns/patternMatchers.js');var encodePassable=require('../../../node_modules/@endo/marshal/src/encodePassable.js');var passStyleOf=require('../../../node_modules/@endo/pass-style/src/passStyleOf.js');var checkKey=require('../../../node_modules/@endo/patterns/src/keys/checkKey.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nmakeFar=require('../../../node_modules/@endo/pass-style/src/make-far.js');/**\\n * @import {ToCapData, FromCapData} from '@endo/marshal';\\n */ /* XXX TODO: The following key length limit was put in place due to limitations*/ /* in LMDB. With the move away from LMDB, it is no longer relevant, but I'm*/ /* leaving it in place for the time being as a general defensive measure against*/ /* various kind of resource exhaustion mischief. Although the switch to a*/ /* database without the limitation that motivated this would enable this max*/ /* length value to be made larger, current code is already engineered with this*/ /* max in mind, so leaving it in place for the time being it should not pose any*/ /* new challenges. Later, when we have time to examine this more deeply, we*/ /* should consider relaxing or removing this cap.*/const MAX_DBKEY_LENGTH=220;\\nfunction pattEq(p1,p2){\\nreturn rankOrder.compareRank(p1,p2)===0;}\\n\\n\\nfunction matchAny(patt){\\nreturn patt===undefined||pattEq(patt,patternMatchers.M.any());}\\n\\n\\nfunction throwNotDurable(value,slotIndex,serializedValue){\\n/* prettier-ignore*/\\nindex.throwRedacted`value is not durable: ${value} at slot ${index.quote(slotIndex)} of ${serializedValue.body}`;}\\n\\n\\nfunction failNotFound(key,label){\\nindex.throwRedacted`key ${key} not found in collection ${index.quote(label)}`;}\\n\\n\\nfunction failNotIterable(value){\\nindex.throwRedacted`provided data source is not iterable: ${value}`;}\\n\\n\\nfunction prefixc(collectionID,dbEntryKey){\\nreturn`vc.${collectionID}.${dbEntryKey}`;}\\n\\n\\nconst collectionMetaKeys=new Set([\\n'|entryCount',\\n'|nextOrdinal',\\n'|schemata']);\\n\\n\\n/**\\n * @typedef {object} SchemaCacheValue\\n * @property {Pattern} keyShape\\n * @property {Pattern} valueShape\\n * @property {string} label\\n * @property {object} schemataCapData\\n */\\n\\n/* * Build a cache that holds the schema for each collection.\\n *\\n * The cache maps collectionID to { keyShape, valueShape, label,\\n * schemataCapData }. These are initialized when the collection is\\n * first constructed, and never modified afterwards. The values live\\n * in the vatstore, inside two keys, one for the [keyShape,\\n * valueShape] schemata, another for the label.\\n */\\n\\nfunction makeSchemaCache(syscall,unserialize){\\n/** @type {(collectionID: string) => SchemaCacheValue} */\\nconst readBacking=(collectionID)=>{\\n/* this is only called once per crank*/\\nconst schemataKey=prefixc(collectionID,'|schemata');\\nconst schemataValue=syscall.vatstoreGet(schemataKey);\\nconst schemataCapData=JSON.parse(schemataValue);\\nconst{label,keyShape,valueShape}=unserialize(schemataCapData);\\nreturn harden({keyShape,valueShape,label,schemataCapData});};\\n\\n/** @type {(collectionID: string, value: SchemaCacheValue) => void } */\\nconst writeBacking=(collectionID,value)=>{\\nconst{schemataCapData}=value;\\nconst schemataKey=prefixc(collectionID,'|schemata');\\nconst schemataValue=JSON.stringify(schemataCapData);\\nsyscall.vatstoreSet(schemataKey,schemataValue);};\\n\\n/** @type {(collectionID: string) => void} */\\nconst deleteBacking=(collectionID)=>{\\nconst schemataKey=prefixc(collectionID,'|schemata');\\nsyscall.vatstoreDelete(schemataKey);};\\n\\nreturn cache.makeCache(readBacking,writeBacking,deleteBacking);}\\n\\n\\n/**\\n * @param {*} syscall\\n * @param {IMPORT('./virtualReferences.js').VirtualReferenceManager} vrm\\n * @param {() => number} allocateExportID\\n * @param {() => number} allocateCollectionID\\n * @param {(val: any) => string | undefined} convertValToSlot\\n * @param {*} convertSlotToVal\\n * @param {*} registerValue\\n * @param {ToCapData<string>} serialize\\n * @param {FromCapData<string>} unserialize\\n * @param {(capDatas: any) => void} assertAcceptableSyscallCapdataSize\\n */\\nfunction makeCollectionManager(\\nsyscall,\\nvrm,\\nallocateExportID,\\nallocateCollectionID,\\nconvertValToSlot,\\nconvertSlotToVal,\\nregisterValue,\\nserialize,\\nunserialize,\\nassertAcceptableSyscallCapdataSize)\\n{\\nconst storeKindIDToName=new Map();\\n\\n/** @type { IMPORT('./cache.js').Cache<SchemaCacheValue>} */\\nconst schemaCache=makeSchemaCache(syscall,unserialize);\\n\\nconst storeKindInfo={\\nscalarMapStore:{\\nhasWeakKeys:false,\\nkindID:0,\\n/* eslint-disable-next-line no-use-before-define*/\\nreanimator:reanimateMapStore,\\ndurable:false},\\n\\nscalarWeakMapStore:{\\nhasWeakKeys:true,\\nkindID:0,\\n/* eslint-disable-next-line no-use-before-define*/\\nreanimator:reanimateWeakMapStore,\\ndurable:false},\\n\\nscalarSetStore:{\\nhasWeakKeys:false,\\nkindID:0,\\n/* eslint-disable-next-line no-use-before-define*/\\nreanimator:reanimateSetStore,\\ndurable:false},\\n\\nscalarWeakSetStore:{\\nhasWeakKeys:true,\\nkindID:0,\\n/* eslint-disable-next-line no-use-before-define*/\\nreanimator:reanimateWeakSetStore,\\ndurable:false},\\n\\nscalarDurableMapStore:{\\nhasWeakKeys:false,\\nkindID:0,\\n/* eslint-disable-next-line no-use-before-define*/\\nreanimator:reanimateMapStore,\\ndurable:true},\\n\\nscalarDurableWeakMapStore:{\\nhasWeakKeys:true,\\nkindID:0,\\n/* eslint-disable-next-line no-use-before-define*/\\nreanimator:reanimateWeakMapStore,\\ndurable:true},\\n\\nscalarDurableSetStore:{\\nhasWeakKeys:false,\\nkindID:0,\\n/* eslint-disable-next-line no-use-before-define*/\\nreanimator:reanimateSetStore,\\ndurable:true},\\n\\nscalarDurableWeakSetStore:{\\nhasWeakKeys:true,\\nkindID:0,\\n/* eslint-disable-next-line no-use-before-define*/\\nreanimator:reanimateWeakSetStore,\\ndurable:true}};\\n\\n\\n\\nfunction initializeStoreKindInfo(){\\nlet storeKindIDs={};\\nconst rawTable=syscall.vatstoreGet('storeKindIDTable');\\nif(rawTable){\\nstoreKindIDs=JSON.parse(rawTable);}\\n\\nfor(const kind of Object.getOwnPropertyNames(storeKindInfo)){\\nlet kindID=storeKindIDs[kind];\\nif(!kindID){\\nkindID=allocateExportID();\\nstoreKindIDs[kind]=kindID;}\\n\\nstoreKindInfo[kind].kindID=kindID;\\nstoreKindIDToName.set(`${kindID}`,kind);\\nvrm.registerKind(\\nkindID,\\nstoreKindInfo[kind].reanimator,\\n/* eslint-disable-next-line no-use-before-define*/\\ndeleteCollection,\\nstoreKindInfo[kind].durable);}\\n\\n\\nsyscall.vatstoreSet('storeKindIDTable',JSON.stringify(storeKindIDs));}\\n\\n\\nfunction obtainStoreKindID(kindName){\\nreturn storeKindInfo[kindName].kindID;}\\n\\n\\n/* Now that it's only used for this purpose, what should it be called?*/\\n/* TODO Should we be using the new encodeBigInt scheme instead, anyway?*/\\nconst BIGINT_TAG_LEN=10;\\n\\n/**\\n * Delete an entry from a collection as part of garbage collecting the entry's key.\\n *\\n * @param {string} collectionID - the collection from which the entry is to be deleted\\n * @param {string} vobjID - the entry key being removed\\n *\\n * @returns {boolean} true if this removal possibly introduces a further GC opportunity\\n */\\nfunction deleteCollectionEntry(collectionID,vobjID){\\nconst ordinalKey=prefixc(collectionID,`|${vobjID}`);\\nconst ordinalString=syscall.vatstoreGet(ordinalKey);\\nsyscall.vatstoreDelete(ordinalKey);\\nconst ordinalTag=encodePassable.zeroPad(ordinalString,BIGINT_TAG_LEN);\\nconst recordKey=prefixc(collectionID,`r${ordinalTag}:${vobjID}`);\\nconst rawValue=syscall.vatstoreGet(recordKey);\\nlet doMoreGC=false;\\nif(rawValue!==undefined){\\nconst value=JSON.parse(rawValue);\\ndoMoreGC=value.slots.map(vrm.removeReachableVref).some((b)=>b);\\nsyscall.vatstoreDelete(recordKey);}\\n\\nreturn doMoreGC;}\\n\\nvrm.setDeleteCollectionEntry(deleteCollectionEntry);\\n\\nfunction summonCollectionInternal(_initial,collectionID,kindName){\\nindex.assert.typeof(kindName,'string');\\nconst kindInfo=storeKindInfo[kindName];\\nkindInfo||index.throwRedacted`unknown collection kind ${kindName}`;\\nconst{hasWeakKeys,durable}=kindInfo;\\nconst getSchema=()=>{\\nconst result=schemaCache.get(collectionID);\\nindex.assert(result!==undefined);\\nreturn result;};\\n\\nconst dbKeyPrefix=`vc.${collectionID}.`;\\nlet currentGenerationNumber=0;\\n\\nconst makeInvalidKeyTypeMsg=(label)=>\\n`invalid key type for collection ${index.quote(label)}`;\\nconst makeInvalidValueTypeMsg=(label)=>\\n`invalid value type for collection ${index.quote(label)}`;\\n\\nconst serializeValue=(value)=>{\\nconst{valueShape,label}=getSchema();\\nif(valueShape!==undefined){\\npatternMatchers.mustMatch(value,valueShape,makeInvalidValueTypeMsg(label));}\\n\\nreturn serialize(value);};\\n\\n\\nconst unserializeValue=(data)=>{\\nconst{valueShape,label}=getSchema();\\nconst value=unserialize(data);\\nif(valueShape!==undefined){\\npatternMatchers.mustMatch(value,valueShape,makeInvalidValueTypeMsg(label));}\\n\\nreturn value;};\\n\\n\\nfunction prefix(dbEntryKey){\\nreturn`${dbKeyPrefix}${dbEntryKey}`;}\\n\\n\\n/* A \\\"vref\\\" is a string like \\\"o-4\\\" or \\\"o+d44/2:0\\\"*/\\n/* An \\\"EncodedKey\\\" is the output of encode-passable:*/\\n/* * strings become `s${string}`, like \\\"foo\\\" -> \\\"sfoo\\\"*/\\n/* * small positive BigInts become `p${len}:${digits}`, like 47n -> \\\"p2:47\\\"*/\\n/* * refs are assigned an \\\"ordinal\\\" and use `r${fixedLengthOrdinal}:${vref}`*/\\n/* * e.g. vref(o-4) becomes \\\"r0000000001:o-4\\\"*/\\n/* A \\\"DBKey\\\" is used to index the vatstore. DBKeys for collection*/\\n/* entries join a collection prefix and an EncodedKey. Some*/\\n/* possible DBKeys for entries of collection \\\"5\\\", using collection*/\\n/* prefix \\\"vc.5.\\\", are:*/\\n/* * \\\"foo\\\" -> \\\"vc.5.sfoo\\\"*/\\n/* * 47n -> \\\"vc.5.p2:47\\\"*/\\n/* * vref(o-4) -> \\\"vc.5.r0000000001:o-4\\\"*/\\n\\nconst encodeRemotable=(remotable)=>{\\n/* eslint-disable-next-line no-use-before-define*/\\nconst ordinal=getOrdinal(remotable);\\nordinal!==undefined||index.throwRedacted`no ordinal for ${remotable}`;\\nconst ordinalTag=encodePassable.zeroPad(ordinal,BIGINT_TAG_LEN);\\nreturn`r${ordinalTag}:${convertValToSlot(remotable)}`;};\\n\\n\\n/* `makeEncodePassable` has three named options:*/\\n/* `encodeRemotable`, `encodeError`, and `encodePromise`.*/\\n/* Those which are omitted default to a function that always throws.*/\\n/* So by omitting `encodeError` and `encodePromise`, we know that*/\\n/* the resulting function will encode only `Key` arguments.*/\\nconst encodeKey=encodePassable.makeEncodePassable({encodeRemotable});\\n\\nconst vrefFromEncodedKey=(encodedKey)=>\\nencodedKey.substring(1+BIGINT_TAG_LEN+1);\\n\\nconst decodeRemotable=(encodedKey)=>\\nconvertSlotToVal(vrefFromEncodedKey(encodedKey));\\n\\n/* `makeDecodePassable` has three named options:*/\\n/* `decodeRemotable`, `decodeError`, and `decodePromise`.*/\\n/* Those which are omitted default to a function that always throws.*/\\n/* So by omitting `decodeError` and `decodePromise`, we know that*/\\n/* the resulting function will decode only to `Key` results.*/\\nconst decodeKey=encodePassable.makeDecodePassable({decodeRemotable});\\n\\nfunction generateOrdinal(remotable){\\nconst nextOrdinal=Number.parseInt(\\nsyscall.vatstoreGet(prefix('|nextOrdinal')),\\n10);\\n\\nsyscall.vatstoreSet(\\nprefix(`|${convertValToSlot(remotable)}`),\\n`${nextOrdinal}`);\\n\\nsyscall.vatstoreSet(prefix('|nextOrdinal'),`${nextOrdinal+1}`);}\\n\\n\\nfunction getOrdinal(remotable){\\nreturn syscall.vatstoreGet(prefix(`|${convertValToSlot(remotable)}`));}\\n\\n\\nfunction deleteOrdinal(remotable){\\nsyscall.vatstoreDelete(prefix(`|${convertValToSlot(remotable)}`));}\\n\\n\\nfunction keyToDBKey(key){\\nconst encodedKey=encodeKey(key);\\nindex.assert(encodedKey.length<MAX_DBKEY_LENGTH,'key too large');\\nreturn prefix(encodedKey);}\\n\\n\\nfunction dbKeyToKey(dbKey){\\n/* convert e.g. vc.5.r0000000001:o+v10/1 to r0000000001:o+v10/1*/\\nconst dbEntryKey=dbKey.substring(dbKeyPrefix.length);\\nreturn decodeKey(dbEntryKey);}\\n\\n\\nfunction dbKeyToEncodedKey(dbKey){\\nindex.assert(dbKey.startsWith(dbKeyPrefix),dbKey);\\nreturn dbKey.substring(dbKeyPrefix.length);}\\n\\n\\nfunction has(key){\\nconst{keyShape}=getSchema();\\nif(!patternMatchers.matches(key,keyShape)){\\nreturn false;}else\\nif(passStyleOf.passStyleOf(key)==='remotable'){\\nreturn getOrdinal(key)!==undefined;}else\\n{\\nreturn syscall.vatstoreGet(keyToDBKey(key))!==undefined;}}\\n\\n\\n\\nfunction mustGet(key,label){\\nif(passStyleOf.passStyleOf(key)==='remotable'&&getOrdinal(key)===undefined){\\nfailNotFound(key,label);}\\n\\nconst dbKey=keyToDBKey(key);\\nconst result=syscall.vatstoreGet(dbKey)||failNotFound(key,label);\\nreturn{dbKey,result};}\\n\\n\\nfunction get(key){\\nconst{keyShape,label}=getSchema();\\npatternMatchers.mustMatch(key,keyShape,makeInvalidKeyTypeMsg(label));\\nconst{result}=mustGet(key,label);\\nreturn unserializeValue(JSON.parse(result));}\\n\\n\\nfunction updateEntryCount(delta){\\nif(!hasWeakKeys){\\nconst entryCount=Number.parseInt(\\nsyscall.vatstoreGet(prefix('|entryCount')),\\n10);\\n\\nsyscall.vatstoreSet(prefix('|entryCount'),`${entryCount+delta}`);}}\\n\\n\\n\\nconst doInit=(key,value,precheckedHas)=>{\\nconst{keyShape,label}=getSchema();\\npatternMatchers.mustMatch(key,keyShape,makeInvalidKeyTypeMsg(label));\\nprecheckedHas||\\n!has(key)||\\nindex.throwRedacted`key ${key} already registered in collection ${index.quote(label)}`;\\nconst serializedValue=serializeValue(value);\\ncurrentGenerationNumber+=1;\\nassertAcceptableSyscallCapdataSize([serializedValue]);\\nif(durable){\\nfor(const[slotIndex,vref]of serializedValue.slots.entries()){\\nif(!vrm.isDurable(vref)){\\nthrowNotDurable(value,slotIndex,serializedValue);}}}\\n\\n\\n\\nif(passStyleOf.passStyleOf(key)==='remotable'){\\n/** @type {string} */\\n/* @ts-expect-error not undefined b/c of has() check*/\\nconst vref=convertValToSlot(key);\\nif(durable){\\nvrm.isDurable(vref)||index.throwRedacted`key (${key}) is not durable in ${value}`;}\\n\\ngenerateOrdinal(key);\\nif(hasWeakKeys){\\nvrm.addRecognizableValue(key,`${collectionID}`,true);}else\\n{\\nvrm.addReachableVref(vref);}}\\n\\n\\nfor(const vref of serializedValue.slots){\\nvrm.addReachableVref(vref);}\\n\\nsyscall.vatstoreSet(keyToDBKey(key),JSON.stringify(serializedValue));\\nupdateEntryCount(1);};\\n\\n\\nconst init=(key,value)=>doInit(key,value,false);\\n\\nconst addToSet=(key)=>{\\nif(!has(key)){\\ndoInit(key,null,true);}};\\n\\n\\n\\nfunction set(key,value){\\nconst{keyShape,label}=getSchema();\\npatternMatchers.mustMatch(key,keyShape,makeInvalidKeyTypeMsg(label));\\nconst after=serializeValue(harden(value));\\nassertAcceptableSyscallCapdataSize([after]);\\nif(durable){\\nfor(const[i,vref]of after.slots.entries()){\\nif(!vrm.isDurable(vref)){\\nthrowNotDurable(value,i,after);}}}\\n\\n\\n\\nconst{dbKey,result:rawBefore}=mustGet(key,label);\\nconst before=JSON.parse(rawBefore);\\nvrm.updateReferenceCounts(before.slots,after.slots);\\nsyscall.vatstoreSet(dbKey,JSON.stringify(after));}\\n\\n\\nfunction deleteInternal(key){\\nconst{keyShape,label}=getSchema();\\npatternMatchers.mustMatch(key,keyShape,makeInvalidKeyTypeMsg(label));\\nconst{dbKey,result:rawValue}=mustGet(key,label);\\nconst value=JSON.parse(rawValue);\\nconst doMoreGC1=value.slots.map(vrm.removeReachableVref).some((b)=>b);\\nsyscall.vatstoreDelete(dbKey);\\nlet doMoreGC2=false;\\nif(passStyleOf.passStyleOf(key)==='remotable'){\\ndeleteOrdinal(key);\\nif(hasWeakKeys){\\nvrm.removeRecognizableValue(key,`${collectionID}`,true);}else\\n{\\ndoMoreGC2=vrm.removeReachableVref(convertValToSlot(key));}}\\n\\n\\nreturn doMoreGC1||doMoreGC2;}\\n\\n\\nfunction del(key){\\ndeleteInternal(key);\\nupdateEntryCount(-1);}\\n\\n\\nfunction entriesInternal(\\nyieldKeys,\\nyieldValues,\\nkeyPatt=patternMatchers.M.any(),\\nvaluePatt=patternMatchers.M.any())\\n{\\nindex.assert(yieldKeys||yieldValues,'useless entries()');\\npatternMatchers.assertPattern(keyPatt);\\npatternMatchers.assertPattern(valuePatt);\\n\\nconst[coverStart,coverEnd]=patternMatchers.getRankCover(keyPatt,encodeKey);\\nconst start=prefix(coverStart);/* inclusive*/\\nconst end=prefix(coverEnd);/* exclusive*/\\n\\nconst generationAtStart=currentGenerationNumber;\\nconst checkGen=()=>\\ncurrentGenerationNumber===generationAtStart||\\nindex.throwRedacted`keys in store cannot be added to during iteration`;\\n\\nconst needToMatchKey=!matchAny(keyPatt);\\nconst needToMatchValue=!matchAny(valuePatt);\\n\\n/* we might not need to unserialize the dbKey or get the dbValue*/\\nconst needKeys=yieldKeys||needToMatchKey;\\nconst needValues=yieldValues||needToMatchValue;\\n\\n/**\\n * @yields {[any, any]}\\n * @returns {Generator<[any, any], void, unknown>}\\n */\\nfunction*iter(){\\n/* the inner iterator yields all keys for which (start <= key < end)*/\\nconst iterKeys=vatstoreIterators.enumerateKeysStartEnd(syscall,start,end,checkGen);\\n\\n/* and the outer iterator filters by keyPatt/valuePatt and*/\\n/* yields the right [key,value] tuples*/\\nfor(const dbKey of iterKeys){\\nconst key=needKeys?dbKeyToKey(dbKey):undefined;\\n/* safe because needToMatchKey implies needKeys*/\\nif(needToMatchKey&&!patternMatchers.matches(key,keyPatt)){\\ncontinue;}\\n\\nconst value=needValues?\\nunserializeValue(JSON.parse(syscall.vatstoreGet(dbKey))):\\nundefined;\\nif(needToMatchValue&&!patternMatchers.matches(value,valuePatt)){\\ncontinue;}\\n\\nyield[yieldKeys?key:undefined,yieldValues?value:undefined];}}\\n\\n\\nharden(iter);\\nreturn iter();}\\n\\n\\nfunction keys(keyPatt,valuePatt){\\nfunction*iter(){\\nfor(const entry of entriesInternal(true,false,keyPatt,valuePatt)){\\nyield entry[0];}}\\n\\n\\nharden(iter);\\nreturn iter();}\\n\\n\\n/**\\n * Clear the entire contents of a collection non-selectively. Since we are\\n * being unconditional, we don't need to inspect any of the keys to decide\\n * what to do and therefore can avoid deserializing the keys. In particular,\\n * this avoids swapping in any virtual objects that were used as keys, which\\n * can needlessly thrash the virtual object cache when an entire collection\\n * is being deleted.\\n *\\n * @returns {boolean} true if this operation introduces a potential\\n * opportunity to do further GC.\\n */\\nfunction clearInternalFull(){\\nlet doMoreGC=false;\\n\\n/* visit every DB entry associated with the collection, which*/\\n/* (due to sorting) will be collection entries first, and then a*/\\n/* mixture of ordinal-assignment mappings and size-independent*/\\n/* metadata (both of which start with \\\"|\\\").*/\\nfor(const dbKey of vatstoreIterators.enumerateKeysWithPrefix(syscall,dbKeyPrefix)){\\nconst encodedKey=dbKeyToEncodedKey(dbKey);\\n\\n/* preserve general metadata (\\\"|entryCount\\\" and friends are*/\\n/* cleared by our caller)*/\\nif(collectionMetaKeys.has(encodedKey))continue;\\n\\nif(encodedKey.startsWith('|')){\\n/* ordinal assignment; decref or de-recognize its vref*/\\nconst keyVref=encodedKey.substring(1);\\nparseVatSlots.parseVatSlot(keyVref);\\nif(hasWeakKeys){\\nvrm.removeRecognizableVref(keyVref,`${collectionID}`,true);}else\\n{\\ndoMoreGC=vrm.removeReachableVref(keyVref)||doMoreGC;}}else\\n\\n{\\n/* a collection entry; decref slots from its value*/\\nconst value=JSON.parse(syscall.vatstoreGet(dbKey));\\ndoMoreGC=\\nvalue.slots.map(vrm.removeReachableVref).some((b)=>b)||doMoreGC;}\\n\\n\\n/* in either case, delete the DB entry*/\\nsyscall.vatstoreDelete(dbKey);}\\n\\n\\nreturn doMoreGC;}\\n\\n\\nfunction clearInternal(isDeleting,keyPatt,valuePatt){\\nlet doMoreGC=false;\\nif(isDeleting){\\ndoMoreGC=clearInternalFull();\\n/* |entryCount will be deleted along with metadata keys*/}else\\nif(matchAny(keyPatt)&&matchAny(valuePatt)){\\ndoMoreGC=clearInternalFull();\\nif(!hasWeakKeys){\\nsyscall.vatstoreSet(prefix('|entryCount'),'0');}}else\\n\\n{\\nlet numDeleted=0;\\nfor(const k of keys(keyPatt,valuePatt)){\\nnumDeleted+=1;\\ndoMoreGC=deleteInternal(k)||doMoreGC;}\\n\\nupdateEntryCount(-numDeleted);}\\n\\nreturn doMoreGC;}\\n\\n\\nfunction clear(keyPatt,valuePatt){\\nclearInternal(false,keyPatt,valuePatt);}\\n\\n\\nfunction values(keyPatt,valuePatt){\\nfunction*iter(){\\nfor(const entry of entriesInternal(false,true,keyPatt,valuePatt)){\\nyield entry[1];}}\\n\\n\\nharden(iter);\\nreturn iter();}\\n\\n\\nfunction entries(keyPatt,valuePatt){\\nfunction*iter(){\\nfor(const entry of entriesInternal(true,true,keyPatt,valuePatt)){\\nyield entry;}}\\n\\n\\nharden(iter);\\nreturn iter();}\\n\\n\\nfunction countEntries(keyPatt,valuePatt){\\nlet count=0;\\n/* eslint-disable-next-line no-unused-vars*/\\nfor(const k of keys(keyPatt,valuePatt)){\\ncount+=1;}\\n\\nreturn count;}\\n\\n\\nfunction getSize(keyPatt,valuePatt){\\nif(matchAny(keyPatt)&&matchAny(valuePatt)){\\nreturn Number.parseInt(syscall.vatstoreGet(prefix('|entryCount')),10);}\\n\\nreturn countEntries(keyPatt,valuePatt);}\\n\\n\\nfunction sizeInternal(){\\nreturn countEntries();}\\n\\n\\nconst snapshotSet=(keyPatt)=>checkKey.makeCopySet(keys(keyPatt));\\n\\nconst snapshotMap=(keyPatt,valuePatt)=>\\ncheckKey.makeCopyMap(entries(keyPatt,valuePatt));\\n\\nconst addAllToSet=(elems)=>{\\nif(typeof elems[Symbol.iterator]!=='function'){\\nelems=\\nObject.isFrozen(elems)&&checkKey.isCopySet(elems)?\\ncheckKey.getCopySetKeys(elems):\\nfailNotIterable(elems);}\\n\\nfor(const elem of elems){\\naddToSet(elem);}};\\n\\n\\n\\nconst addAllToMap=(mapEntries)=>{\\nif(typeof mapEntries[Symbol.iterator]!=='function'){\\nmapEntries=\\nObject.isFrozen(mapEntries)&&checkKey.isCopyMap(mapEntries)?\\ncheckKey.getCopyMapEntries(mapEntries):\\nfailNotIterable(mapEntries);}\\n\\nfor(const[key,value]of mapEntries){\\nif(has(key)){\\nset(key,value);}else\\n{\\ndoInit(key,value,true);}}};\\n\\n\\n\\n\\nreturn{\\nhas,\\nget,\\ngetSize,\\ninit,\\naddToSet,\\nset,\\ndelete:del,\\nkeys,\\nvalues,\\nentries,\\naddAllToSet,\\naddAllToMap,\\nsnapshotSet,\\nsnapshotMap,\\nsizeInternal,\\nclear,\\nclearInternal};}\\n\\n\\n\\nfunction summonCollection(initial,collectionID,kindName){\\nconst hasWeakKeys=storeKindInfo[kindName].hasWeakKeys;\\nconst raw=summonCollectionInternal(initial,collectionID,kindName);\\n\\nconst{\\nhas,\\nget,\\ninit,\\naddToSet,\\naddAllToMap,\\naddAllToSet,\\nset,\\ndelete:del}=\\nraw;\\nconst weakMethods={\\nhas,\\nget,\\ninit,\\naddToSet,\\naddAllToSet,\\naddAllToMap,\\nset,\\ndelete:del};\\n\\n\\nlet collection;\\nif(hasWeakKeys){\\ncollection=weakMethods;}else\\n{\\nconst{\\nkeys,\\nvalues,\\nentries,\\ngetSize,\\nsnapshotSet,\\nsnapshotMap,\\nclear}=\\nraw;\\ncollection={\\n...weakMethods,\\nkeys,\\nvalues,\\nentries,\\ngetSize,\\nsnapshotSet,\\nsnapshotMap,\\nclear};}\\n\\n\\nreturn collection;}\\n\\n\\nfunction storeSizeInternal(vobjID){\\nconst{id,subid}=parseVatSlots.parseVatSlot(vobjID);\\nconst kindName=storeKindIDToName.get(`${id}`);\\nkindName||index.throwRedacted`unknown kind ID ${id}`;\\nconst collectionID=`${subid}`;\\nconst collection=summonCollectionInternal(false,collectionID,kindName);\\nreturn collection.sizeInternal();}\\n\\n\\nfunction deleteCollection(vobjID){\\nconst{id,subid}=parseVatSlots.parseVatSlot(vobjID);\\nconst kindName=storeKindIDToName.get(`${id}`);\\nconst collectionID=`${subid}`;\\nconst collection=summonCollectionInternal(false,collectionID,kindName);\\n\\nlet doMoreGC=collection.clearInternal(true);\\nconst record=schemaCache.get(collectionID);\\nindex.assert(record!==undefined);\\nconst{schemataCapData}=record;\\ndoMoreGC=\\nschemataCapData.slots.map(vrm.removeReachableVref).some((b)=>b)||\\ndoMoreGC;\\nfor(const dbKey of vatstoreIterators.enumerateKeysWithPrefix(\\nsyscall,\\nprefixc(collectionID,'|')))\\n{\\n/* this key is owned by schemaCache, and will be deleted when*/\\n/* schemaCache is flushed*/\\nif(dbKey.endsWith('|schemata')){\\ncontinue;}\\n\\n/* but we must still delete the other keys (|nextOrdinal and*/\\n/* |entryCount)*/\\nsyscall.vatstoreDelete(dbKey);}\\n\\nschemaCache.delete(collectionID);\\nreturn doMoreGC;}\\n\\n\\nfunction makeCollection(label,kindName,isDurable,keyShape,valueShape){\\nindex.assert.typeof(label,'string');\\nindex.assert(storeKindInfo[kindName]);\\npatternMatchers.assertPattern(keyShape);\\nif(valueShape){\\npatternMatchers.assertPattern(valueShape);}\\n\\nconst collectionID=`${allocateCollectionID()}`;\\nconst kindID=obtainStoreKindID(kindName);\\nconst vobjID=parseVatSlots.makeBaseRef(kindID,collectionID,isDurable);\\n\\nsyscall.vatstoreSet(prefixc(collectionID,'|nextOrdinal'),'1');\\nconst{hasWeakKeys}=storeKindInfo[kindName];\\nif(!hasWeakKeys){\\nsyscall.vatstoreSet(prefixc(collectionID,'|entryCount'),'0');}\\n\\n\\nconst schemata={label};/* don't populate 'undefined', keep it small*/\\nif(keyShape!==undefined){\\nschemata.keyShape=keyShape;}\\n\\nif(valueShape!==undefined){\\nschemata.valueShape=valueShape;}\\n\\nconst schemataCapData=serialize(harden(schemata));\\nif(isDurable){\\nfor(const[slotIndex,vref]of schemataCapData.slots.entries()){\\nif(!vrm.isDurable(vref)){\\nthrowNotDurable(vref,slotIndex,schemataCapData);}}}\\n\\n\\n\\nfor(const vref of schemataCapData.slots){\\nvrm.addReachableVref(vref);}\\n\\n\\nschemaCache.set(\\ncollectionID,\\nharden({keyShape,valueShape,label,schemataCapData}));\\n\\n\\nreturn[vobjID,summonCollection(true,collectionID,kindName)];}\\n\\n\\nfunction collectionToMapStore(collection){\\nconst{\\nhas,\\nget,\\ninit,\\nset,\\ndelete:del,\\naddAllToMap,\\nkeys,\\nvalues,\\nentries,\\nsnapshotMap,\\ngetSize,\\nclear}=\\ncollection;\\nconst mapStore={\\nhas,\\nget,\\ninit,\\nset,\\ndelete:del,\\naddAll:addAllToMap,\\nkeys,\\nvalues,\\nentries,\\nsnapshot:snapshotMap,\\ngetSize,\\nclear};\\n\\nreturn makeFar.Far('mapStore',mapStore);}\\n\\n\\nfunction collectionToWeakMapStore(collection){\\nconst{has,get,init,set,delete:del,addAllToMap}=collection;\\nconst weakMapStore={\\nhas,\\nget,\\ninit,\\nset,\\ndelete:del,\\naddAll:addAllToMap};\\n\\nreturn makeFar.Far('weakMapStore',weakMapStore);}\\n\\n\\nfunction collectionToSetStore(collection){\\nconst{\\nhas,\\naddToSet,\\ndelete:del,\\naddAllToSet,\\nkeys,\\nsnapshotSet,\\ngetSize,\\nclear}=\\ncollection;\\n\\nconst setStore={\\nhas,\\nadd:addToSet,\\ndelete:del,\\naddAll:addAllToSet,\\nkeys:(patt)=>keys(patt),\\nvalues:(patt)=>keys(patt),\\nsnapshot:snapshotSet,\\ngetSize:(patt)=>getSize(patt),\\nclear};\\n\\nreturn makeFar.Far('setStore',setStore);}\\n\\n\\nfunction collectionToWeakSetStore(collection){\\nconst{has,addToSet,delete:del,addAllToSet}=collection;\\n\\nconst weakSetStore={\\nhas,\\nadd:addToSet,\\ndelete:del,\\naddAll:addAllToSet};\\n\\nreturn makeFar.Far('weakSetStore',weakSetStore);}\\n\\n\\n/**\\n * Produce a big map.\\n *\\n * @template K,V\\n * @param {string} [label] - diagnostic label for the store\\n * @param {StoreOptions} [options]\\n * @returns {MapStore<K,V>}\\n */\\nfunction makeBigMapStore(label='map',options={}){\\nconst{\\nkeyShape=patternMatchers.M.any(),\\nvalueShape=undefined,\\ndurable=false}=\\noptions;\\nconst kindName=durable?'scalarDurableMapStore':'scalarMapStore';\\nconst[vobjID,collection]=makeCollection(\\nlabel,\\nkindName,\\ndurable,\\nkeyShape,\\nvalueShape);\\n\\nconst store=collectionToMapStore(collection);\\nregisterValue(vobjID,store,false);\\nreturn store;}\\n\\n\\nfunction provideBaggage(){\\nlet baggageID=syscall.vatstoreGet('baggageID');\\nif(baggageID){\\nreturn convertSlotToVal(baggageID);}else\\n{\\nconst baggage=makeBigMapStore('baggage',{\\nkeyShape:patternMatchers.M.string(),\\ndurable:true});\\n\\nbaggageID=convertValToSlot(baggage);\\nsyscall.vatstoreSet('baggageID',baggageID);\\n/* artificially increment the baggage's refcount so it never gets GC'd*/\\nvrm.addReachableVref(baggageID);\\nreturn baggage;}}\\n\\n\\n\\n/**\\n * Produce a weak big map.\\n *\\n * @template K,V\\n * @param {string} [label] - diagnostic label for the store\\n * @param {StoreOptions} [options]\\n * @returns {WeakMapStore<K,V>}\\n */\\nfunction makeBigWeakMapStore(label='weakMap',options={}){\\nconst{\\nkeyShape=patternMatchers.M.any(),\\nvalueShape=undefined,\\ndurable=false}=\\noptions;\\nconst kindName=durable?\\n'scalarDurableWeakMapStore':\\n'scalarWeakMapStore';\\nconst[vobjID,collection]=makeCollection(\\nlabel,\\nkindName,\\ndurable,\\nkeyShape,\\nvalueShape);\\n\\nconst store=collectionToWeakMapStore(collection);\\nregisterValue(vobjID,store,false);\\nreturn store;}\\n\\n\\n/**\\n * Produce a big set.\\n *\\n * @template K\\n * @param {string} [label] - diagnostic label for the store\\n * @param {StoreOptions} [options]\\n * @returns {SetStore<K>}\\n */\\nfunction makeBigSetStore(label='set',options={}){\\nconst{\\nkeyShape=patternMatchers.M.scalar(),\\nvalueShape=undefined,\\ndurable=false}=\\noptions;\\nconst kindName=durable?'scalarDurableSetStore':'scalarSetStore';\\nconst[vobjID,collection]=makeCollection(\\nlabel,\\nkindName,\\ndurable,\\nkeyShape,\\nvalueShape);\\n\\nconst store=collectionToSetStore(collection);\\nregisterValue(vobjID,store,false);\\nreturn store;}\\n\\n\\n/**\\n * Produce a weak big set.\\n *\\n * @template K\\n * @param {string} [label] - diagnostic label for the store\\n * @param {StoreOptions} [options]\\n * @returns {WeakSetStore<K>}\\n */\\nfunction makeBigWeakSetStore(label='weakSet',options={}){\\nconst{\\nkeyShape=patternMatchers.M.scalar(),\\nvalueShape=undefined,\\ndurable=false}=\\noptions;\\nconst kindName=durable?\\n'scalarDurableWeakSetStore':\\n'scalarWeakSetStore';\\nconst[vobjID,collection]=makeCollection(\\nlabel,\\nkindName,\\ndurable,\\nkeyShape,\\nvalueShape);\\n\\nconst store=collectionToWeakSetStore(collection);\\nregisterValue(vobjID,store,false);\\nreturn store;}\\n\\n\\nfunction reanimateCollection(vobjID){\\nconst{id,subid}=parseVatSlots.parseVatSlot(vobjID);\\nconst collectionID=`${subid}`;\\nconst kindName=storeKindIDToName.get(`${id}`);\\nreturn summonCollection(false,collectionID,kindName);}\\n\\n\\nfunction reanimateMapStore(vobjID){\\nreturn collectionToMapStore(reanimateCollection(vobjID));}\\n\\n\\nfunction reanimateWeakMapStore(vobjID){\\nreturn collectionToWeakMapStore(reanimateCollection(vobjID));}\\n\\n\\nfunction reanimateSetStore(vobjID){\\nreturn collectionToSetStore(reanimateCollection(vobjID));}\\n\\n\\nfunction reanimateWeakSetStore(vobjID){\\nreturn collectionToWeakSetStore(reanimateCollection(vobjID));}\\n\\n\\nconst testHooks={\\nobtainStoreKindID,\\nstoreSizeInternal,\\nmakeCollection};\\n\\n\\n/**\\n * @param {Pattern} baseKeyShape\\n * @param {StoreOptions} options\\n * @returns {StoreOptions}\\n */\\nconst narrowKeyShapeOption=(baseKeyShape,options)=>{\\nconst{keyShape:keyShapeRestriction}=options;\\n/* To prepare for pattern-based compression*/\\n/* https://github.com/Agoric/agoric-sdk/pull/6432*/\\n/* put the substantive pattern, if any, last in the `M.and` since*/\\n/* an `M.and` pattern compresses only according to its last conjunct.*/\\nconst keyShape=\\nkeyShapeRestriction===undefined?\\nbaseKeyShape:\\npatternMatchers.M.and(baseKeyShape,keyShapeRestriction);\\nreturn harden({...options,keyShape});};\\n\\n\\n/**\\n * Produce a *scalar* big map: keys can only be atomic values, primitives, or\\n * remotables.\\n *\\n * @template K,V\\n * @param {string} [label] - diagnostic label for the store\\n * @param {StoreOptions} [options]\\n * @returns {MapStore<K,V>}\\n */\\nconst makeScalarBigMapStore=(label='map',options={})=>\\nmakeBigMapStore(label,narrowKeyShapeOption(patternMatchers.M.scalar(),options));\\n\\n/**\\n * Produce a *scalar* weak big map: keys can only be atomic values,\\n * primitives, or remotables.\\n *\\n * @template K,V\\n * @param {string} [label] - diagnostic label for the store\\n * @param {StoreOptions} [options]\\n * @returns {WeakMapStore<K,V>}\\n */\\nconst makeScalarBigWeakMapStore=(label='weakMap',options={})=>\\nmakeBigWeakMapStore(label,narrowKeyShapeOption(patternMatchers.M.scalar(),options));\\n\\n/**\\n * Produce a *scalar* big set: keys can only be atomic values, primitives, or\\n * remotables.\\n *\\n * @template K\\n * @param {string} [label] - diagnostic label for the store\\n * @param {StoreOptions} [options]\\n * @returns {SetStore<K>}\\n */\\nconst makeScalarBigSetStore=(label='set',options={})=>\\nmakeBigSetStore(label,narrowKeyShapeOption(patternMatchers.M.scalar(),options));\\n\\n/**\\n * Produce a *scalar* weak big set: keys can only be atomic values,\\n * primitives, or remotables.\\n *\\n * @template K\\n * @param {string} [label] - diagnostic label for the store\\n * @param {StoreOptions} [options]\\n * @returns {WeakSetStore<K>}\\n */\\nconst makeScalarBigWeakSetStore=(label='weakSet',options={})=>\\nmakeBigWeakSetStore(label,narrowKeyShapeOption(patternMatchers.M.scalar(),options));\\n\\nconst flushSchemaCache=()=>schemaCache.flush();\\n\\nfunction getRetentionStats(){\\nreturn{};}\\n\\n\\nreturn harden({\\ninitializeStoreKindInfo,\\nmakeScalarBigMapStore,\\nmakeScalarBigWeakMapStore,\\nmakeScalarBigSetStore,\\nmakeScalarBigWeakSetStore,\\nprovideBaggage,\\nflushSchemaCache,\\ngetRetentionStats,\\ntestHooks});}exports.collectionMetaKeys=collectionMetaKeys;exports.makeCollectionManager=makeCollectionManager;\",\n \"packages/swingset-liveslots/src/facetiousness.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var\\n\\nindex=require('../../../node_modules/@endo/errors/index.js');/**\\n * Assess the facetiousness of a value. If the value is an object containing\\n * only named properties and each such property's value is a function, `obj`\\n * represents a single facet and 'one' is returned. If each property's value\\n * is instead an object of facetiousness 'one', `obj` represents multiple\\n * facets and 'many' is returned. In all other cases `obj` does not represent\\n * any kind of facet abstraction and 'not' is returned.\\n *\\n * @typedef {'one'|'many'|'not'} Facetiousness\\n *\\n * @param {*} obj The (alleged) object to be assessed\\n * @returns {Facetiousness} an assessment of the facetiousness of `obj`\\n */\\nfunction assessFacetiousness(obj){\\nif(typeof obj!=='object'){\\nreturn'not';}\\n\\nlet result;\\nfor(const prop of Reflect.ownKeys(obj)){\\nconst value=obj[prop];\\nlet resultFromProp;\\nif(typeof value==='function'){\\nresultFromProp='one';}else\\nif(\\n/* symbols are not permitted as facet names*/\\ntypeof prop!=='symbol'&&\\nassessFacetiousness(value)==='one')\\n{\\nresultFromProp='many';}else\\n{\\nreturn'not';}\\n\\nif(!result){\\n/* capture the result of inspecting the first property*/\\nresult=resultFromProp;}else\\nif(resultFromProp!==result){\\n/* and bail out upon encountering any deviation*/\\nreturn'not';}}\\n\\n\\n/* empty objects are methodless Far objects*/\\nreturn(/** @type {Facetiousness} */result||'one');}\\n\\n\\n/* note: mutates 'desc' in-place*/\\nconst checkAndUpdateFacetiousness=(tag,desc,proposedFacetNames)=>{\\n/* The first time a durable kind gets a definition, the saved*/\\n/* descriptor will have neither \\\".unfaceted\\\" nor \\\".facets\\\", and we*/\\n/* must update the details in the descriptor. When a later*/\\n/* incarnation redefines the behavior, we must check for*/\\n/* compatibility (all old facets must still be defined). We*/\\n/* re-assign .facets/.unfaceted each time, even if we're not*/\\n/* changing anything.*/\\n\\nif(desc.unfaceted&&proposedFacetNames){\\nindex.throwRedacted`defineDurableKindMulti called for unfaceted KindHandle ${tag}`;}\\n\\nif(desc.facets&&!proposedFacetNames){\\nindex.throwRedacted`defineDurableKind called for faceted KindHandle ${tag}`;}\\n\\nlet newFacetNames;\\nif(proposedFacetNames){\\nconst oldFacetNames=desc.facets?[...desc.facets]:[];\\nconst proposal=[...proposedFacetNames];\\nnewFacetNames=[];\\n/* all old facets must be present in the proposal*/\\nfor(const facet of oldFacetNames){\\nconst proposedIdx=proposal.indexOf(facet);\\nif(proposedIdx===-1){\\nconst orig=oldFacetNames.join(',');\\nconst newer=proposedFacetNames.join(',');\\nindex.throwRedacted`durable kind \\\"${tag}\\\" facets (${newer}) is missing ${facet} from original definition (${orig})`;}\\n\\nproposal.splice(proposedIdx,1);/* remove from proposal*/\\nnewFacetNames.push(facet);}\\n\\n\\n/* new facets are appended in alphabetic order*/\\nproposal.sort();\\ndesc.facets=newFacetNames.concat(proposal);}else\\n{\\ndesc.unfaceted=true;}\\n\\nreturn desc.facets;/* 'undefined' for unfaceted*/\\n/* caller will saveDurableKindDescriptor()*/};exports.assessFacetiousness=assessFacetiousness;exports.checkAndUpdateFacetiousness=checkAndUpdateFacetiousness;\",\n \"packages/swingset-liveslots/src/index.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var liveslots=require('./liveslots.js');var message=require('./message.js');require('./types.js');require('./vatDataTypes.js');/*/ <reference types=\\\"@agoric/store/exported.js\\\" />*/exports.makeLiveSlots=liveslots.makeLiveSlots;exports.makeMarshaller=liveslots.makeMarshaller;exports.insistMessage=message.insistMessage;exports.insistVatDeliveryObject=message.insistVatDeliveryObject;exports.insistVatDeliveryResult=message.insistVatDeliveryResult;exports.insistVatSyscallObject=message.insistVatSyscallObject;exports.insistVatSyscallResult=message.insistVatSyscallResult;\",\n \"packages/swingset-liveslots/src/kdebug.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});let enableKDebug=false;\\n\\nfunction kdebugEnable(flag){\\nenableKDebug=!!flag;}\\n\\n\\nfunction kdebug(...args){\\nif(enableKDebug){\\nconsole.log(...args);}}\\n\\n\\n\\nfunction legibilizeValue(val,slots,smallcaps){\\ntry{\\nif(Array.isArray(val)){\\nlet result='[';\\nfor(const elem of val){\\nif(result.length!==1){\\nresult+=', ';}\\n\\nresult+=legibilizeValue(elem,slots,smallcaps);}\\n\\nresult+=']';\\nreturn result;}else\\nif(val&&typeof val==='object'&&val.constructor===Object){\\nconst qClass=val['@qclass'];\\nif(qClass&&!smallcaps){\\nswitch(qClass){\\ncase'undefined':\\ncase'NaN':\\ncase'Infinity':\\ncase'-Infinity':\\nreturn qClass;\\ncase'bigint':\\nreturn val.digits;\\ncase'slot':\\nreturn`@${slots[val.index]}`;\\ncase'symbol':\\nreturn`[${val.name}]`;\\ncase'@@asyncIterator':\\nreturn`[Symbol.asyncIterator]`;\\ncase'error':\\nreturn`new ${val.name}('${val.message}')`;\\ndefault:\\n/* unknown qClass, treat it like any other object literal*/\\nbreak;}}\\n\\n\\nlet result='{';\\nfor(const prop of Object.getOwnPropertyNames(val)){\\nif(result.length!==1){\\nresult+=', ';}\\n\\n/* prettier-ignore*/\\nresult+=`${String(prop)}: ${legibilizeValue(val[prop],slots,smallcaps)}`;}\\n\\nresult+='}';\\nreturn result;}else\\nif(val&&typeof val==='string'&&smallcaps){\\nconst prefix=val.charAt(0);\\nconst rest=val.substring(1);\\nswitch(prefix){\\ncase'!':\\nreturn`\\\"${rest}\\\"`;\\ncase'%':\\nreturn`[${rest}]`;\\ncase'#':\\ncase'+':\\ncase'-':\\nreturn rest;\\ncase'$':\\ncase'&':{\\nconst idx=Number(rest.slice(0,rest.indexOf('.')));\\nreturn`@${slots[idx]}`;}\\n\\ndefault:\\nreturn JSON.stringify(val)||'<unintelligible value>';}}else\\n\\n{\\nreturn JSON.stringify(val)||'<unintelligible value>';}}\\n\\ncatch{\\nreturn'<unintelligible value>';}}\\n\\n\\n\\nfunction legibilizeMethod(method,smallcaps){\\ntry{\\nif(typeof method==='string'){\\nif(!smallcaps){\\nreturn method;}\\n\\nconst prefix=method.charAt(0);\\nconst rest=method.substring(1);\\nswitch(prefix){\\ncase'%':\\nreturn`[${rest}]`;\\ncase'#':\\nif(rest==='undefined'){\\nreturn'<funcall>';}else\\n{\\nreturn'<unintelligible method>';}\\n\\ncase'!':\\nreturn rest;\\ncase'+':\\ncase'-':\\ncase'$':\\ncase'&':\\nreturn'<unintelligible method>';\\ndefault:\\nreturn method;}}else\\n\\nif(typeof method==='symbol'){\\nreturn`[${method.toString()}]`;}else\\nif(method===undefined){\\nreturn'<funcall>';}else\\nif(typeof method==='object'){\\nif(smallcaps){\\nreturn'<unintelligible method>';}\\n\\nconst qclass=method['@qclass'];\\nif(qclass==='undefined'){\\nreturn'<funcall>';}else\\nif(qclass==='symbol'){\\nreturn`[${method.name}]`;}else\\nif(qclass==='@@asyncIterator'){\\nreturn`[Symbol.asyncIterator]`;}else\\n{\\nreturn'<invalid method type>';}}else\\n\\n{\\nreturn'<unintelligible method>';}}\\n\\ncatch{\\nreturn'<unintelligible method>';}}\\n\\n\\n\\nfunction extractMethod(methargsCapdata){\\ntry{\\nlet smallcaps=false;\\nlet bodyString=methargsCapdata.body;\\nif(bodyString.charAt(0)==='#'){\\nsmallcaps=true;\\nbodyString=bodyString.substring(1);}\\n\\nconst methargs=JSON.parse(bodyString);\\nreturn legibilizeMethod(methargs[0],smallcaps);}\\ncatch{\\nreturn'<unknown>';}}\\n\\n\\n\\nfunction legibilizeMessageArgs(methargsCapdata){\\ntry{\\nlet smallcaps=false;\\nlet bodyString=methargsCapdata.body;\\nif(bodyString.charAt(0)==='#'){\\nsmallcaps=true;\\nbodyString=bodyString.substring(1);}\\n\\nconst methargs=JSON.parse(bodyString);\\nconst[method,args]=methargs;\\nconst methodStr=legibilizeMethod(method,smallcaps);\\nconst argsStrs=args.map((arg)=>\\nlegibilizeValue(arg,methargsCapdata.slots,smallcaps));\\n\\nreturn[methodStr,argsStrs.join(', ')];}\\ncatch{\\nreturn'<unintelligible message args>';}}exports.extractMethod=extractMethod;exports.kdebug=kdebug;exports.kdebugEnable=kdebugEnable;exports.legibilizeMessageArgs=legibilizeMessageArgs;exports.legibilizeMethod=legibilizeMethod;exports.legibilizeValue=legibilizeValue;\",\n \"packages/swingset-liveslots/src/liveslots.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var index=require('../../../node_modules/@endo/errors/index.js');require('../../../node_modules/@endo/pass-style/index.js');require('../../../node_modules/@endo/pass-style/endow.js');require('../../../node_modules/@endo/marshal/index.js');require('../../../node_modules/@endo/promise-kit/index.js');var noShim=require('../../../node_modules/@endo/eventual-send/src/no-shim.js');var parseVatSlots=require('./parseVatSlots.js');var capdata=require('./capdata.js');var kdebug=require('./kdebug.js');var message=require('./message.js');var virtualReferences=require('./virtualReferences.js');var virtualObjectManager=require('./virtualObjectManager.js');var collectionManager=require('./collectionManager.js');var watchedPromises=require('./watchedPromises.js');var boydGc=require('./boyd-gc.js');var makeFar=require('../../../node_modules/@endo/pass-style/src/make-far.js');var marshal=require('../../../node_modules/@endo/marshal/src/marshal.js');var isPromise=require('../../../node_modules/@endo/promise-kit/src/is-promise.js');var passStyleOf=require('../../../node_modules/@endo/pass-style/src/passStyleOf.js');var remotable=require('../../../node_modules/@endo/pass-style/src/remotable.js');\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nconst SYSCALL_CAPDATA_BODY_SIZE_LIMIT=10_000_000;\\nconst SYSCALL_CAPDATA_SLOTS_LENGTH_LIMIT=10_000;\\n\\n/* 'makeLiveSlots' is a dispatcher which uses javascript Maps to keep track*/\\n/* of local objects which have been exported. These cannot be persisted*/\\n/* beyond the runtime of the javascript environment, so this mechanism is not*/\\n/* going to work for our in-chain hosts.*/\\n\\n/**\\n * Instantiate the liveslots layer for a new vat and then populate the vat with\\n * a new root object and its initial associated object graph, if any.\\n *\\n * @param {*} syscall Kernel syscall interface that the vat will have access to\\n * @param {*} forVatID Vat ID label, for use in debug diagnostics\\n * @param {*} vatPowers\\n * @param {IMPORT('./types.js').LiveSlotsOptions} liveSlotsOptions\\n * @param {*} gcTools { WeakRef, FinalizationRegistry, waitUntilQuiescent, gcAndFinalize,\\n * meterControl }\\n * @param {Pick<Console, 'debug' | 'log' | 'info' | 'warn' | 'error'>} console\\n * @param {*} buildVatNamespace\\n *\\n * @returns {*} { dispatch }\\n */\\nfunction build(\\nsyscall,\\nforVatID,\\nvatPowers,\\nliveSlotsOptions={},\\ngcTools,\\nconsole,\\nbuildVatNamespace)\\n{\\nconst{enableDisavow=false,relaxDurabilityRules=false}=\\nliveSlotsOptions;\\nconst{WeakRef,FinalizationRegistry,meterControl}=gcTools;\\nconst enableLSDebug=false;\\nfunction lsdebug(...args){\\nif(enableLSDebug){\\nconsole.log(...args);}}\\n\\n\\n\\nlet didStartVat=false;\\nconst didStopVat=false;\\n\\nconst outstandingProxies=new WeakSet();\\n\\nlet syscallCapdataBodySizeLimit=SYSCALL_CAPDATA_BODY_SIZE_LIMIT;\\nlet syscallCapdataSlotsLengthLimit=SYSCALL_CAPDATA_SLOTS_LENGTH_LIMIT;\\n\\nfunction setSyscallCapdataLimits(\\nbodySizeLimit=SYSCALL_CAPDATA_BODY_SIZE_LIMIT,\\nslotsLengthLimit=SYSCALL_CAPDATA_SLOTS_LENGTH_LIMIT)\\n{\\nsyscallCapdataBodySizeLimit=bodySizeLimit;\\nsyscallCapdataSlotsLengthLimit=slotsLengthLimit;}\\n\\n\\nfunction isAcceptableSyscallCapdataSize(capdatas){\\nlet bodySizeTotal=0;\\nlet slotsLengthTotal=0;\\nfor(const capdata of capdatas){\\nbodySizeTotal+=capdata.body.length;\\nslotsLengthTotal+=capdata.slots.length;}\\n\\nreturn(\\nbodySizeTotal<=syscallCapdataBodySizeLimit&&\\nslotsLengthTotal<=syscallCapdataSlotsLengthLimit);}\\n\\n\\n\\nfunction assertAcceptableSyscallCapdataSize(capdatas){\\nindex.assert(\\nisAcceptableSyscallCapdataSize(capdatas),\\n'syscall capdata too large');}\\n\\n\\n\\n/**\\n * Translation and tracking tables to map in-vat object/promise references\\n * to/from vat-format slot strings.\\n *\\n * Exports: pass-by-presence objects (Remotables) in the vat are exported as\\n * o+NN slots, as are \\\"virtual object\\\" exports. Promises are exported as p+NN\\n * slots. We retain a strong reference to all exports via the\\n * `exportedRemotables` Set until the kernel tells us all external references\\n * have been dropped via dispatch.dropExports, or by some unilateral\\n * revoke-object operation executed by our user-level code.\\n *\\n * Imports: o-NN slots are represented as a Presence. p-NN slots are\\n * represented as an imported Promise, with the resolver held in an\\n * additional table (importedPromisesByPromiseID) to handle a future\\n * incoming resolution message. We retain a weak reference to the Presence,\\n * and use a FinalizationRegistry to learn when the vat has dropped it, so\\n * we can notify the kernel. We retain strong references to unresolved\\n * Promises. When an import is added, the finalizer is added to\\n * `vreffedObjectRegistry`.\\n *\\n * slotToVal is a Map whose keys are slots (strings) and the values are\\n * WeakRefs. If the entry is present but wr.deref()===undefined (the\\n * weakref is dead), treat that as if the entry was not present. The same\\n * slotToVal table is used for both imports and returning exports. The\\n * subset of those which need to be held strongly (exported objects and\\n * promises, imported promises) are kept alive by `exportedRemotables`.\\n *\\n * valToSlot is a WeakMap whose keys are Remotable/Presence/Promise\\n * objects, and the keys are (string) slot identifiers. This is used\\n * for both exports and returned imports.\\n *\\n * We use two weak maps plus the strong `exportedRemotables` set, because\\n * it seems simpler than using four separate maps (import-vs-export times\\n * strong-vs-weak).\\n */\\n\\n/** @type {WeakMap<object, string>} */\\nconst valToSlot=new WeakMap();/* object -> vref*/\\nconst slotToVal=new Map();/* baseRef -> WeakRef(object)*/\\nconst exportedRemotables=new Set();/* objects*/\\nconst kernelRecognizableRemotables=new Set();/* vrefs*/\\nconst importedDevices=new Set();/* device nodes*/\\nconst possiblyDeadSet=new Set();/* baseRefs that need to be checked for being dead*/\\nconst possiblyRetiredSet=new Set();/* vrefs that might need to be rechecked for being retired*/\\n\\n/* importedVPIDs and exportedVPIDs track all promises which the*/\\n/* kernel knows about: the kernel is the decider for importedVPIDs,*/\\n/* and we are the decider for exportedVPIDs*/\\n\\n/* We do not need to include the ancillary promises that*/\\n/* resolutionCollector() creates: those are resolved immediately*/\\n/* after export. However we remove those during resolution just in*/\\n/* case they overlap with non-ancillary ones.*/\\n\\nconst exportedVPIDs=new Map();/* VPID -> Promise, kernel-known, vat-decided*/\\nconst importedVPIDs=new Map();/* VPID -> { promise, resolve, reject }, kernel-known+decided*/\\n\\nfunction retainExportedVref(vref){\\n/* if the vref corresponds to a Remotable, keep a strong reference to it*/\\n/* until the kernel tells us to release it*/\\nconst{type,allocatedByVat,virtual,durable}=parseVatSlots.parseVatSlot(vref);\\nif(type==='object'&&allocatedByVat){\\nif(virtual||durable){\\n/* eslint-disable-next-line no-use-before-define*/\\nvrm.setExportStatus(vref,'reachable');}else\\n{\\n/* eslint-disable-next-line no-use-before-define*/\\nconst remotable=requiredValForSlot(vref);\\nexportedRemotables.add(remotable);\\nkernelRecognizableRemotables.add(vref);}}}\\n\\n\\n\\n\\nfunction finalizeDroppedObject(baseRef){\\n/* TODO: Ideally this function should assert that it is not metered. This*/\\n/* appears to be fine in practice, but it breaks a number of unit tests in*/\\n/* ways that are not obvious how to fix.*/\\n/* meterControl.assertNotMetered();*/\\nconst wr=slotToVal.get(baseRef);\\n/* The finalizer for a given Presence might run in any state:*/\\n/* * COLLECTED: most common. Action: move to FINALIZED*/\\n/* * REACHABLE/UNREACHABLE: after re-introduction. Action: ignore*/\\n/* * FINALIZED: after re-introduction and subsequent finalizer invocation*/\\n/* (second finalizer executed for the same baseRef). Action: be idempotent*/\\n/* * UNKNOWN: after re-introduction, multiple finalizer invocation,*/\\n/* and post-crank cleanup does dropImports and deletes baseRef from*/\\n/* deadSet. Action: ignore*/\\n\\nif(wr&&!wr.deref()){\\n/* we're in the COLLECTED state, or FINALIZED after a re-introduction*/\\n/* eslint-disable-next-line no-use-before-define*/\\naddToPossiblyDeadSet(baseRef);\\nslotToVal.delete(baseRef);}}\\n\\n\\nconst vreffedObjectRegistry=new FinalizationRegistry(finalizeDroppedObject);\\n\\n/**\\n * Remember disavowed Presences which will kill the vat if you try to talk\\n * to them\\n */\\nconst disavowedPresences=new WeakSet();\\nconst disavowalError=harden(Error(`this Presence has been disavowed`));\\n\\nfunction makeImportedPresence(slot,iface=`Alleged: presence ${slot}`){\\n/* Called by convertSlotToVal for type=object (an `o-NN` reference). We*/\\n/* build a Presence for application-level code to receive. This Presence*/\\n/* is associated with 'slot' so that all handled messages get sent to*/\\n/* that slot: pres~.foo() causes a syscall.send(target=slot, msg=foo).*/\\n\\nlsdebug(`makeImportedPresence(${slot})`);\\nconst fulfilledHandler={\\napplyMethod(o,prop,args,returnedP){\\n/* Support: o~.[prop](...args) remote method invocation*/\\nlsdebug(`makeImportedPresence handler.applyMethod (${slot})`);\\nif(disavowedPresences.has(o)){\\n/* eslint-disable-next-line no-use-before-define*/\\nexitVatWithFailure(disavowalError);\\nthrow disavowalError;}\\n\\n/* eslint-disable-next-line no-use-before-define*/\\nreturn queueMessage(slot,prop,args,returnedP);},\\n\\napplyFunction(o,args,returnedP){\\nreturn fulfilledHandler.applyMethod(o,undefined,args,returnedP);},\\n\\nget(o,prop){\\nlsdebug(`makeImportedPresence handler.get (${slot})`);\\nif(disavowedPresences.has(o)){\\n/* eslint-disable-next-line no-use-before-define*/\\nexitVatWithFailure(disavowalError);\\nthrow disavowalError;}\\n\\n/* FIXME: Actually use remote property lookup*/\\nreturn o[prop];}};\\n\\n\\n\\nlet remotePresence;\\nconst p=new noShim.HandledPromise((_res,_rej,resolveWithPresence)=>{\\n/* Use Remotable rather than Far to make a remote from a presence*/\\nremotePresence=makeFar.Remotable(\\niface,\\nundefined,\\nresolveWithPresence(fulfilledHandler));\\n\\n/* remote === presence, actually*/\\n\\n/* todo: mfig says resolveWithPresence*/\\n/* gives us a Presence, Remotable gives us a Remote. I think that*/\\n/* implies we have a lot of renaming to do, 'makeRemote' instead of*/\\n/* 'makeImportedPresence', etc. I'd like to defer that for a later*/\\n/* cleanup/renaming pass.*/});\\n/* no unfulfilledHandler*/\\n\\n/* The call to resolveWithPresence performs the forwarding logic*/\\n/* immediately, so by the time we reach here, E(presence).foo() will use*/\\n/* our fulfilledHandler, and nobody can observe the fact that we failed*/\\n/* to provide an unfulfilledHandler.*/\\n\\n/* We throw 'p' away, but it is retained by the internal tables of*/\\n/* HandledPromise, and will be returned to anyone who calls*/\\n/* `HandledPromise.resolve(presence)`. So we must harden it now, for*/\\n/* safety, to prevent it from being used as a communication channel*/\\n/* between isolated objects that share a reference to the Presence.*/\\nvoid harden(p);\\n\\n/* Up at the application level, presence~.foo(args) starts by doing*/\\n/* HandledPromise.resolve(presence), which retrieves it, and then does*/\\n/* p.eventualSend('foo', [args]), which uses the fulfilledHandler.*/\\n\\n/* We harden the presence for the same safety reasons.*/\\nreturn harden(remotePresence);}\\n\\n\\nfunction makePipelinablePromise(vpid){\\n/* Called by convertSlotToVal(type=promise) for incoming promises (a*/\\n/* `p-NN` reference), and by queueMessage() for the result of an outbound*/\\n/* message (a `p+NN` reference). We build a Promise for application-level*/\\n/* code, to which messages can be pipelined, and we prepare for the*/\\n/* kernel to tell us that it has been resolved in various ways.*/\\nparseVatSlots.insistVatType('promise',vpid);\\nlsdebug(`makePipelinablePromise(${vpid})`);\\n\\n/* The Promise will we associated with a handler that converts p~.foo() into*/\\n/* a syscall.send() that targets the vpid. When the Promise is resolved*/\\n/* (during receipt of a dispatch.notify), this Promise's handler will be*/\\n/* replaced by the handler of the resolution, which might be a Presence or a*/\\n/* local object.*/\\n\\n/* for safety as we shake out bugs in HandledPromise, we guard against*/\\n/* this handler being used after it was supposed to be resolved*/\\nlet handlerActive=true;\\nconst unfulfilledHandler={\\napplyMethod(_p,prop,args,returnedP){\\n/* Support: p~.[prop](...args) remote method invocation*/\\nlsdebug(`makePipelinablePromise handler.applyMethod (${vpid})`);\\nif(!handlerActive){\\nconsole.error(`mIPromise handler called after resolution`);\\nindex.throwRedacted`mIPromise handler called after resolution`;}\\n\\n/* eslint-disable-next-line no-use-before-define*/\\nreturn queueMessage(vpid,prop,args,returnedP);},\\n\\nget(p,prop){\\n/* Support: p~.[prop]*/\\nlsdebug(`makePipelinablePromise handler.get (${vpid})`);\\nif(!handlerActive){\\nconsole.error(`mIPromise handler called after resolution`);\\nindex.throwRedacted`mIPromise handler called after resolution`;}\\n\\n/* FIXME: Actually pipeline.*/\\nreturn noShim.E.when(p,(o)=>o[prop]);}};\\n\\n\\n\\nlet resolve;\\nlet reject;\\nconst p=new noShim.HandledPromise((res,rej,_resPres)=>{\\nresolve=res;\\nreject=rej;},\\nunfulfilledHandler);\\n\\n/* Prepare for the kernel to tell us about resolution. Both ensure the*/\\n/* old handler should never be called again. TODO: once we're confident*/\\n/* about how we interact with HandledPromise, just use harden({ resolve,*/\\n/* reject }).*/\\nconst pRec=harden({\\npromise:p,\\nresolve(resolution){\\nhandlerActive=false;\\nresolve(resolution);},\\n\\n\\nreject(rejection){\\nhandlerActive=false;\\nreject(rejection);}});\\n\\n\\nreturn pRec;}\\n\\n\\nfunction makeDeviceNode(id,iface=`Alleged: device ${id}`){\\nreturn makeFar.Remotable(iface);}\\n\\n\\n/* TODO: fix awkward non-orthogonality: allocateExportID() returns a number,*/\\n/* allocatePromiseID() returns a slot, registerPromise() uses the slot from*/\\n/* allocatePromiseID(), exportPassByPresence() generates a slot itself using*/\\n/* the number from allocateExportID(). Both allocateX fns should return a*/\\n/* number or return a slot; both exportY fns should either create a slot or*/\\n/* use a slot from the corresponding allocateX*/\\n\\nfunction allocateExportID(){\\n/* eslint-disable-next-line no-use-before-define*/\\nreturn vrm.allocateNextID('exportID');}\\n\\n\\nfunction allocateCollectionID(){\\n/* eslint-disable-next-line no-use-before-define*/\\nreturn vrm.allocateNextID('collectionID');}\\n\\n\\nfunction allocatePromiseID(){\\n/* eslint-disable-next-line no-use-before-define*/\\nconst promiseID=vrm.allocateNextID('promiseID');\\nreturn parseVatSlots.makeVatSlot('promise',true,promiseID);}\\n\\n\\nconst knownResolutions=new WeakMap();\\n\\n/**\\n * Determines if a vref from a watched promise or outbound argument\\n * identifies a promise that should be exported, and if so then\\n * adds it to exportedVPIDs and sets up handlers.\\n *\\n * @param {any} vref\\n * @returns {boolean} whether the vref was added to exportedVPIDs\\n */\\nfunction maybeExportPromise(vref){\\n/* we only care about new vpids*/\\nif(\\nparseVatSlots.parseVatSlot(vref).type==='promise'&&\\n!exportedVPIDs.has(vref)&&\\n!importedVPIDs.has(vref))\\n{\\nconst vpid=vref;\\n/* The kernel is about to learn about this promise (syscall.send*/\\n/* arguments or syscall.resolve resolution data), so prepare to*/\\n/* do a syscall.resolve when it fires. The caller must finish*/\\n/* doing their syscall before this turn finishes, to ensure the*/\\n/* kernel isn't surprised by a spurious resolution.*/\\n/* eslint-disable-next-line no-use-before-define*/\\nconst p=requiredValForSlot(vpid);\\n/* if (!knownResolutions.has(p)) { // TODO really?*/\\n/* eslint-disable-next-line no-use-before-define*/\\nfollowForKernel(vpid,p);\\nreturn true;}\\n\\nreturn false;}\\n\\n\\nfunction exportPassByPresence(){\\nconst exportID=allocateExportID();\\nreturn parseVatSlots.makeVatSlot('object',true,exportID);}\\n\\n\\n/* eslint-disable-next-line no-use-before-define*/\\nconst m=marshal.makeMarshal(convertValToSlot,convertSlotToVal,{\\nmarshalName:`liveSlots:${forVatID}`,\\nserializeBodyFormat:'smallcaps',\\n/* TODO Temporary hack.*/\\n/* See https://github.com/Agoric/agoric-sdk/issues/2780*/\\nerrorIdNum:70_000,\\nmarshalSaveError:(err)=>\\n/* By sending this to `console.warn`, under cosmic-swingset this is*/\\n/* controlled by the `console` option given to makeLiveSlots.*/\\nconsole.warn('Logging sent error stack',err)});\\n\\nconst unmeteredUnserialize=meterControl.unmetered(m.unserialize);\\n/* eslint-disable-next-line no-use-before-define*/\\nconst unmeteredConvertSlotToVal=meterControl.unmetered(convertSlotToVal);\\n\\nfunction getSlotForVal(val){\\nreturn valToSlot.get(val);}\\n\\n\\nfunction getValForSlot(baseRef){\\nmeterControl.assertNotMetered();\\nconst wr=slotToVal.get(baseRef);\\nreturn wr&&wr.deref();}\\n\\n\\nfunction requiredValForSlot(baseRef){\\nconst wr=slotToVal.get(baseRef);\\nconst result=wr&&wr.deref();\\nresult||index.throwRedacted`no value for ${baseRef}`;\\nreturn result;}\\n\\n\\nfunction addToPossiblyDeadSet(baseRef){\\npossiblyDeadSet.add(baseRef);}\\n\\n\\nfunction addToPossiblyRetiredSet(vref){\\npossiblyRetiredSet.add(vref);}\\n\\n\\nconst vrm=virtualReferences.makeVirtualReferenceManager(\\nsyscall,\\ngetSlotForVal,\\nrequiredValForSlot,\\nFinalizationRegistry,\\nWeakRef,\\naddToPossiblyDeadSet,\\naddToPossiblyRetiredSet,\\nrelaxDurabilityRules);\\n\\n\\nconst vom=virtualObjectManager.makeVirtualObjectManager(\\nsyscall,\\nvrm,\\nallocateExportID,\\ngetSlotForVal,\\nrequiredValForSlot,\\n/* eslint-disable-next-line no-use-before-define*/\\nregisterValue,\\nm.serialize,\\nunmeteredUnserialize,\\nassertAcceptableSyscallCapdataSize,\\nliveSlotsOptions);\\n\\n\\nconst collectionManager$1=collectionManager.makeCollectionManager(\\nsyscall,\\nvrm,\\nallocateExportID,\\nallocateCollectionID,\\n/* eslint-disable-next-line no-use-before-define*/\\nconvertValToSlot,\\nunmeteredConvertSlotToVal,\\n/* eslint-disable-next-line no-use-before-define*/\\nregisterValue,\\nm.serialize,\\nunmeteredUnserialize,\\nassertAcceptableSyscallCapdataSize);\\n\\n\\nconst watchedPromiseManager=watchedPromises.makeWatchedPromiseManager({\\nsyscall,\\nvrm,\\nvom,\\ncollectionManager:collectionManager$1,\\n/* eslint-disable-next-line no-use-before-define*/\\nconvertValToSlot,\\nconvertSlotToVal:unmeteredConvertSlotToVal,\\nmaybeExportPromise});\\n\\n\\nfunction convertValToSlot(val){\\n/* lsdebug(`serializeToSlot`, val, Object.isFrozen(val));*/\\n/* This is either a Presence (in presenceToImportID), a*/\\n/* previously-serialized local pass-by-presence object or*/\\n/* previously-serialized local Promise (in valToSlot), a new local*/\\n/* pass-by-presence object, or a new local Promise.*/\\n\\n/* If we've already assigned it an importID or exportID, it might be in*/\\n/* slots/slotMap for this particular act of serialization. If it's new,*/\\n/* it certainly will not be in slotMap. If we've already serialized it in*/\\n/* this particular act, it will definitely be in slotMap.*/\\n\\nif(!valToSlot.has(val)){\\nlet slot;\\n/* must be a new export/store*/\\n/* lsdebug('must be a new export', JSON.stringify(val));*/\\nif(isPromise.isPromise(val)){\\n/* the promise either appeared in outbound arguments, or in a*/\\n/* virtual-object store operation, so immediately after*/\\n/* serialization we'll either add it to exportedVPIDs or*/\\n/* increment a vdata refcount*/\\nslot=allocatePromiseID();}else\\n{\\nif(disavowedPresences.has(val)){\\n/* eslint-disable-next-line no-use-before-define*/\\nexitVatWithFailure(disavowalError);\\nthrow disavowalError;/* cannot reference a disavowed object*/}\\n\\nindex.assert.equal(passStyleOf.passStyleOf(val),'remotable');\\nslot=exportPassByPresence();}\\n\\nconst{type,baseRef}=parseVatSlots.parseVatSlot(slot);/* also used as assertion*/\\nvalToSlot.set(val,slot);\\nslotToVal.set(baseRef,new WeakRef(val));\\nif(type==='object'){\\n/* Set.delete() metering seems unaffected by presence/absence, but it*/\\n/* doesn't matter anyway because deadSet.add only happens when*/\\n/* finializers run, and we wrote xsnap.c to ensure they only run*/\\n/* deterministically (during gcAndFinalize)*/\\nvreffedObjectRegistry.register(val,baseRef,val);}}\\n\\n\\nreturn valToSlot.get(val);}\\n\\n\\nlet importedPromises=null;\\nfunction beginCollectingPromiseImports(){\\nimportedPromises=new Set();}\\n\\nfunction finishCollectingPromiseImports(){\\nconst result=importedPromises;\\nimportedPromises=null;\\nreturn result;}\\n\\n\\nfunction registerValue(baseRef,val,valIsCohort){\\nconst{type,id,facet}=parseVatSlots.parseVatSlot(baseRef);\\n!facet||\\nindex.throwRedacted`registerValue(${baseRef} should not receive individual facets`;\\nslotToVal.set(baseRef,new WeakRef(val));\\nif(valIsCohort){\\nfor(const[index,name]of vrm.getFacetNames(id).entries()){\\nvalToSlot.set(val[name],`${baseRef}:${index}`);}}else\\n\\n{\\nvalToSlot.set(val,baseRef);}\\n\\n/* we don't dropImports on promises, to avoid interaction with retire*/\\nif(type==='object'){\\nvreffedObjectRegistry.register(val,baseRef,val);}}\\n\\n\\n\\n/* The meter usage of convertSlotToVal is strongly affected by GC, because*/\\n/* it only creates a new Presence if one does not already exist. Userspace*/\\n/* moves from REACHABLE to UNREACHABLE, but the JS engine then moves to*/\\n/* COLLECTED (and maybe FINALIZED) on its own, and we must not allow the*/\\n/* latter changes to affect metering. So every call to convertSlotToVal (or*/\\n/* m.unserialize) must be wrapped by unmetered().*/\\nfunction convertSlotToVal(slot,iface=undefined){\\nmeterControl.assertNotMetered();\\nconst{type,allocatedByVat,id,virtual,durable,facet,baseRef}=\\nparseVatSlots.parseVatSlot(slot);\\nlet val=getValForSlot(baseRef);\\nif(val){\\nif(virtual||durable){\\nif(facet!==undefined){\\nreturn vrm.getFacet(id,val,facet);}}\\n\\n\\nreturn val;}\\n\\nlet result;\\nif(virtual||durable){\\nindex.assert.equal(type,'object');\\ntry{\\nval=vrm.reanimate(baseRef);}\\ncatch(err){\\nconst wrappedError=index.makeError(index.redacted`failed to reanimate ${iface}`);\\nindex.note(wrappedError,index.redacted`Original error: ${err}`);\\nthrow wrappedError;}\\n\\nif(facet!==undefined){\\nresult=vrm.getFacet(id,val,facet);}}else\\n\\nif(type==='object'){\\n/* Note: an abandonned (e.g. by an upgrade) exported ephemeral or virtual*/\\n/* object would appear as an import if re-introduced. In the future we*/\\n/* may need to change that if we want to keep recognizing such references*/\\n/* In that case we'd need to create an imported presence for these*/\\n/* unknown vrefs allocated by the vat.*/\\n/* See https://github.com/Agoric/agoric-sdk/issues/9746*/\\n!allocatedByVat||index.throwRedacted`I don't remember allocating ${slot}`;\\n/* this is a new import value*/\\nval=makeImportedPresence(slot,iface);}else\\nif(type==='promise'){\\n/* We unconditionally create a promise record, even if the promise looks*/\\n/* like it was allocated by us. This can happen when re-importing a*/\\n/* promise created by the previous incarnation. We may or may not have*/\\n/* been the decider of the promise. If we were, the kernel will be*/\\n/* rejecting the promise on our behalf. We may have previously been*/\\n/* subscribed to that promise, but subscription is idempotent.*/\\nconst pRec=makePipelinablePromise(slot);\\nimportedVPIDs.set(slot,pRec);\\nval=pRec.promise;\\n/* ideally we'd wait until .then is called on p before subscribing,*/\\n/* but the current Promise API doesn't give us a way to discover*/\\n/* this, so we must subscribe right away. If we were using Vows or*/\\n/* some other then-able, we could just hook then() to notify us.*/\\nif(importedPromises){\\n/* leave the subscribe() up to dispatch.notify()*/\\nimportedPromises.add(slot);}else\\n{\\n/* probably in dispatch.deliver(), so subscribe now*/\\nsyscall.subscribe(slot);}}else\\n\\nif(type==='device'){\\n!allocatedByVat||index.throwRedacted`unexpected device ${slot} allocated by vat`;\\nval=makeDeviceNode(slot,iface);\\nimportedDevices.add(val);}else\\n{\\nindex.throwRedacted`unrecognized slot type '${type}'`;}\\n\\nregisterValue(baseRef,val,facet!==undefined);\\nif(!result){\\nresult=val;}\\n\\nreturn result;}\\n\\n\\nfunction revivePromise(slot){\\nmeterControl.assertNotMetered();\\nconst{type}=parseVatSlots.parseVatSlot(slot);\\ntype==='promise'||index.throwRedacted`revivePromise called on non-promise ${slot}`;\\nconst val=getValForSlot(slot);\\nif(val){\\n/* revivePromise is only called by loadWatchedPromiseTable, which runs*/\\n/* after buildRootObject(), which is given the deserialized vatParameters.*/\\n/* The only way revivePromise() might encounter a pre-existing vpid is if*/\\n/* these vatParameters include a promise that the previous incarnation*/\\n/* watched, but that `buildRootObject` in the new incarnation didn't*/\\n/* explicitly watch again. This can be either a previously imported*/\\n/* promise, or a promise the previous incarnation exported, regardless of*/\\n/* who the decider now is.*/\\n/**/\\n/* In that case convertSlotToVal() has already deserialized the vpid, but*/\\n/* since `buildRootObject` didn't explicitely call watchPromise on it, no*/\\n/* registration exists so loadWatchedPromiseTable attempts to revive the*/\\n/* promise.*/\\nreturn val;}\\n\\n/* NOTE: it is important that this code not do anything *more**/\\n/* than what convertSlotToVal(vpid) would do*/\\nconst pRec=makePipelinablePromise(slot);\\nimportedVPIDs.set(slot,pRec);\\nconst p=pRec.promise;\\nregisterValue(slot,p);\\nreturn p;}\\n\\nconst unmeteredRevivePromise=meterControl.unmetered(revivePromise);\\n\\nfunction resolutionCollector(){\\nconst resolutions=[];\\nconst doneResolutions=new Set();\\n\\nfunction scanSlots(slots){\\nfor(const slot of slots){\\nconst{type}=parseVatSlots.parseVatSlot(slot);\\nif(type==='promise'){\\n/* this can run metered because it's supposed to always be present*/\\nconst p=requiredValForSlot(slot);\\nconst priorResolution=knownResolutions.get(p);\\nif(priorResolution&&!doneResolutions.has(slot)){\\nconst[priorRejected,priorRes]=priorResolution;\\n/* eslint-disable-next-line no-use-before-define*/\\ncollect(slot,priorRejected,priorRes);}}}}\\n\\n\\n\\n\\n\\nfunction collect(promiseID,rejected,value){\\ndoneResolutions.add(promiseID);\\nmeterControl.assertIsMetered();/* else userspace getters could escape*/\\nlet valueSer;\\ntry{\\nvalueSer=m.serialize(value);}\\ncatch(e){\\n/* Serialization failure.*/\\nvalueSer=m.serialize(e);\\nrejected=true;}\\n\\nvalueSer.slots.map(retainExportedVref);\\n/* do maybeExportPromise() next to the syscall, not here*/\\nresolutions.push([promiseID,rejected,valueSer]);\\nscanSlots(valueSer.slots);}\\n\\n\\nfunction forPromise(promiseID,rejected,value){\\ncollect(promiseID,rejected,value);\\nreturn resolutions;}\\n\\n\\nfunction forSlots(slots){\\nscanSlots(slots);\\nreturn resolutions;}\\n\\n\\nreturn{\\nforPromise,\\nforSlots};}\\n\\n\\n\\nfunction queueMessage(targetSlot,prop,args,returnedP){\\nconst methargs=[prop,args];\\n\\nmeterControl.assertIsMetered();/* else userspace getters could escape*/\\nconst serMethargs=m.serialize(harden(methargs));\\nassertAcceptableSyscallCapdataSize([serMethargs]);\\nserMethargs.slots.map(retainExportedVref);\\n\\nconst resultVPID=allocatePromiseID();\\nlsdebug(`Promise allocation ${forVatID}:${resultVPID} in queueMessage`);\\n/* create a Promise which callers follow for the result, give it a*/\\n/* handler so we can pipeline messages to it, and prepare for the kernel*/\\n/* to notify us of its resolution*/\\nconst pRec=makePipelinablePromise(resultVPID);\\n\\n/* userspace sees `returnedP` (so that's what we need to register*/\\n/* in slotToVal, and what's what we need to retain with a strong*/\\n/* reference via importedVPIDs), but when dispatch.notify arrives,*/\\n/* we need to fire `pRec.promise` because that's what we've got*/\\n/* the firing controls for*/\\nimportedVPIDs.set(resultVPID,harden({...pRec,promise:returnedP}));\\nvalToSlot.set(returnedP,resultVPID);\\nslotToVal.set(resultVPID,new WeakRef(returnedP));\\n\\n/* prettier-ignore*/\\nlsdebug(\\n`ls.qm send(${JSON.stringify(targetSlot)}, ${kdebug.legibilizeMethod(prop)}) -> ${resultVPID}`);\\n\\nsyscall.send(targetSlot,serMethargs,resultVPID);\\n\\n/* The vpids in the syscall.send might be in A:exportedVPIDs,*/\\n/* B:importedVPIDs, or C:neither. Just after the send(), we are*/\\n/* newly on the hook for following the ones in C:neither. One*/\\n/* option would be to feed all the syscall.send slots to*/\\n/* maybeExportPromise(), which will sort them into A/B/C, then*/\\n/* take everything in C:neither and do a .then on it and add it to*/\\n/* exportedVPIDs. Then we call it a day, and allow all the*/\\n/* resolutions to be delivered in a later turn.*/\\n/**/\\n/* But instead, we choose the option that says \\\"but many of those*/\\n/* promises might already be resolved\\\", and if there's more than*/\\n/* one, we could amortize some syscall overhead by emitting all*/\\n/* the known resolutions in a 2-or-larger batch, and in this*/\\n/* moment (in this turn) we have a whole list of them that we can*/\\n/* check synchronously.*/\\n/**/\\n/* To implement this option, the sequence is:*/\\n/* * use W to name the vpids in syscall.send*/\\n/* * feed W into resolutionCollector(), to get 'resolutions'*/\\n/* * that provides the resolution of any promise in W that is*/\\n/* known to be resolved, plus any known-resolved promises*/\\n/* transitively referenced through their resolution data*/\\n/* * all these resolutions will use the original vpid, which the*/\\n/* kernel does not currently know about, because the vpid was*/\\n/* retired earlier, the previous time that promise was*/\\n/* resolved*/\\n/* * name X the set of vpids resolved in 'resolutions'*/\\n/* * assert that X vpids are not in exportedVPIDs or importedVPIDs*/\\n/* * they can only be in X if we remembered the Promise's*/\\n/* resolution, which means we observed the vpid resolve*/\\n/* * at that moment of observation, we would have removed it*/\\n/* from exportedVPIDs, as we did a syscall.resolve on it*/\\n/* * name Y the set of vpids *referenced* by 'resolutions'*/\\n/* * emit syscall.resolve(resolutions)*/\\n/* * Z = (W+Y)-X: the set of vpids we told the kernel but didn't resolve*/\\n/* * feed Z into maybeExportPromise()*/\\n\\nconst maybeNewVPIDs=new Set(serMethargs.slots);\\nconst resolutions=resolutionCollector().forSlots(serMethargs.slots);\\nif(resolutions.length>0){\\ntry{\\nconst resolutionCDs=resolutions.map(\\n([_xvpid,_isReject,resolutionCD])=>resolutionCD);\\n\\nassertAcceptableSyscallCapdataSize(resolutionCDs);}\\ncatch(e){\\nsyscall.exit(true,m.serialize(e));\\nreturn null;}\\n\\nsyscall.resolve(resolutions);\\nfor(const resolution of resolutions){\\nconst[_xvpid,_isReject,resolutionCD]=resolution;\\nfor(const vref of resolutionCD.slots){\\nmaybeNewVPIDs.add(vref);}}\\n\\n\\nfor(const resolution of resolutions){\\nconst[xvpid]=resolution;\\nmaybeNewVPIDs.delete(xvpid);}}\\n\\n\\nfor(const newVPID of Array.from(maybeNewVPIDs).sort()){\\nmaybeExportPromise(newVPID);}\\n\\n\\n/* ideally we'd wait until .then is called on p before subscribing, but*/\\n/* the current Promise API doesn't give us a way to discover this, so we*/\\n/* must subscribe right away. If we were using Vows or some other*/\\n/* then-able, we could just hook then() to notify us.*/\\nsyscall.subscribe(resultVPID);\\n\\n/* We return our new 'pRec.promise' to the handler, and when we*/\\n/* resolve it (during dispatch.notify) its resolution will be used*/\\n/* to resolve the caller's 'returnedP' Promise, but the caller*/\\n/* never sees pRec.promise itself. The caller got back their*/\\n/* 'returnedP' Promise before the handler even got invoked, and*/\\n/* thus before this queueMessage() was called.. If that caller*/\\n/* passes the 'returnedP' Promise they received as argument or*/\\n/* return value, we want it to serialize as resultVPID. And if*/\\n/* someone passes resultVPID to them, we want the user-level code*/\\n/* to get back that Promise, not 'pRec.promise'. As a result, we*/\\n/* do not retain or track 'pRec.promise'. Only 'returnedP' is*/\\n/* registered and retained by importedVPIDs.*/\\n\\nreturn pRec.promise;}\\n\\n\\nfunction forbidPromises(serArgs){\\nfor(const slot of serArgs.slots){\\nparseVatSlots.parseVatSlot(slot).type!=='promise'||\\nindex.throwRedacted`D() arguments cannot include a Promise`;}}\\n\\n\\n\\nfunction DeviceHandler(slot){\\nreturn{\\nget(target,prop){\\nif(typeof prop!=='string'&&typeof prop!=='symbol'){\\nreturn undefined;}\\n\\nreturn(...args)=>{\\nmeterControl.assertIsMetered();/* userspace getters shouldn't escape*/\\nconst serArgs=m.serialize(harden(args));\\nassertAcceptableSyscallCapdataSize([serArgs]);\\nserArgs.slots.map(retainExportedVref);\\n/* if we didn't forbid promises, we'd need to*/\\n/* maybeExportPromise() here*/\\nforbidPromises(serArgs);\\nconst ret=syscall.callNow(slot,prop,serArgs);\\ncapdata.insistCapData(ret);\\nforbidPromises(ret);\\n/* but the unserialize must be unmetered, to prevent divergence*/\\nconst retval=unmeteredUnserialize(ret);\\nreturn retval;};}};}\\n\\n\\n\\n\\n\\nfunction D(x){\\n/* results = D(devicenode).name(args)*/\\nif(outstandingProxies.has(x)){\\nthrow Error('D(D(x)) is invalid');}\\n\\nconst slot=valToSlot.get(x);\\nif(!slot||parseVatSlots.parseVatSlot(slot).type!=='device'){\\nthrow Error('D() must be given a device node');}\\n\\nconst handler=DeviceHandler(slot);\\nconst pr=harden(new Proxy({},handler));\\noutstandingProxies.add(pr);\\nreturn pr;}\\n\\n\\nfunction deliver(target,methargsdata,resultVPID){\\nindex.assert(didStartVat);\\nindex.assert(!didStopVat);\\ncapdata.insistCapData(methargsdata);\\n\\n/* prettier-ignore*/\\nlsdebug(\\n`ls[${forVatID}].dispatch.deliver ${target}.${kdebug.extractMethod(methargsdata)} -> ${resultVPID}`);\\n\\nconst t=convertSlotToVal(target);\\nt||index.throwRedacted`no target ${target}`;\\n/* TODO: if we acquire new decision-making authority over a promise that*/\\n/* we already knew about ('resultVPID' is already in slotToVal), we should no*/\\n/* longer accept dispatch.notify from the kernel. We currently use*/\\n/* importedPromisesByPromiseID to track a combination of \\\"we care about*/\\n/* when this promise resolves\\\" and \\\"we are listening for the kernel to*/\\n/* resolve it\\\". We should split that into two tables or something. And we*/\\n/* should error-check cases that the kernel shouldn't do, like getting*/\\n/* the same vpid as a result= twice, or getting a result= for an exported*/\\n/* promise (for which we were already the decider).*/\\n\\nmeterControl.assertNotMetered();\\nconst methargs=m.unserialize(methargsdata);\\nconst[method,args]=methargs;\\n\\n/* If the method is missing, or is not a Function, or the method throws a*/\\n/* synchronous exception, we notify the caller (by rejecting the result*/\\n/* promise, if any). If the method returns an eventually-rejected*/\\n/* Promise, we notify them when it resolves.*/\\n\\n/* If the method returns a synchronous value, we notify the caller right*/\\n/* away. If it returns an eventually-fulfilled Promise, we notify the*/\\n/* caller when it resolves.*/\\n\\n/* Both situations are the business of this vat and the calling vat, not*/\\n/* the kernel. deliver() does not report such exceptions to the kernel.*/\\n\\n/* We have a presence, so forward to it.*/\\nlet res;\\nif(args){\\n/* It has arguments, must be a method or function application.*/\\nif(method===undefined){\\nres=noShim.HandledPromise.applyFunction(t,args);}else\\n{\\nres=noShim.HandledPromise.applyMethod(t,method,args);}}else\\n\\n{\\n/* Just a getter.*/\\n/* TODO: untested, but in principle sound.*/\\nres=noShim.HandledPromise.get(t,method);}\\n\\n\\nlet p=res;/* the promise tied to resultVPID*/\\nif(resultVPID){\\nif(importedVPIDs.has(resultVPID)){\\n/* This vpid was imported earlier, and we just now became the*/\\n/* decider, so we already have a local Promise object for*/\\n/* it. We keep using that object.*/\\n/* , but forward it to 'res', and*/\\n/* move it from importedVPIDs to exportedVPIDs.*/\\nconst pRec=importedVPIDs.get(resultVPID);\\n/* remove it from importedVPIDs: the kernel will no longer be*/\\n/* telling us about its resolution*/\\nimportedVPIDs.delete(resultVPID);\\n/* forward it to the userspace-fired result promise (despite*/\\n/* using resolve(), this could either fulfill or reject)*/\\npRec.resolve(res);\\n/* exportedVPIDs will hold a strong reference to the pRec*/\\n/* promise that everyone is already using, and when it fires*/\\n/* we'll notify the kernel*/\\np=pRec.promise;\\n/* note: the kernel does not unsubscribe vats that acquire*/\\n/* decider status (but it probably should), so after we do our*/\\n/* syscall.resolve, the kernel will give us a*/\\n/* dispatch.notify. But we'll ignore the stale vpid by*/\\n/* checking importedVPIDs in notifyOnePromise()*/}else\\n{\\n/* new vpid*/\\nregisterValue(resultVPID,res,false);}\\n\\n/* in both cases, we are now the decider, so treat it like an*/\\n/* exported promise*/\\n/* eslint-disable-next-line no-use-before-define*/\\nfollowForKernel(resultVPID,p);}}\\n\\n\\n\\nfunction unregisterUnreferencedVPID(vpid){\\nlsdebug(`unregisterUnreferencedVPID ${forVatID}:${vpid}`);\\nindex.assert.equal(parseVatSlots.parseVatSlot(vpid).type,'promise');\\n/* we are only called with vpids that are in exportedVPIDs or*/\\n/* importedVPIDs, so the WeakRef should still be populated, making*/\\n/* this safe to call from metered code*/\\nconst p=requiredValForSlot(vpid);\\nif(vrm.getReachablePromiseRefCount(p)===0){\\n/* unregister*/\\nvalToSlot.delete(p);\\nslotToVal.delete(vpid);\\n/* the caller will remove the vpid from*/\\n/* exportedVPIDs/importedVPIDs in a moment*/}}\\n\\n\\n\\n/**\\n *\\n * @param {string} vpid\\n * @param {Promise<unknown>} p\\n */\\nfunction followForKernel(vpid,p){\\nparseVatSlots.insistVatType('promise',vpid);\\nexportedVPIDs.set(vpid,p);\\n\\nfunction handle(isReject,value){\\nknownResolutions.set(p,harden([isReject,value]));\\nlsdebug(`ls.thenHandler fired`,value);\\nindex.assert(exportedVPIDs.has(vpid),vpid);\\nconst rc=resolutionCollector();\\nconst resolutions=rc.forPromise(vpid,isReject,value);\\ntry{\\nconst resolutionCDs=resolutions.map(\\n([_xvpid,_isReject,resolutionCD])=>resolutionCD);\\n\\nassertAcceptableSyscallCapdataSize(resolutionCDs);}\\ncatch(e){\\nsyscall.exit(true,m.serialize(e));\\nreturn;}\\n\\nsyscall.resolve(resolutions);\\n\\nconst maybeNewVPIDs=new Set();\\n/* if we mention a vpid, we might need to track it*/\\nfor(const resolution of resolutions){\\nconst[_xvpid,_isReject,resolutionCD]=resolution;\\nfor(const vref of resolutionCD.slots){\\nmaybeNewVPIDs.add(vref);}}\\n\\n\\n/* but not if we just resolved it (including the primary)*/\\nfor(const resolution of resolutions){\\nconst[xvpid]=resolution;\\nmaybeNewVPIDs.delete(xvpid);}\\n\\n/* track everything that's left*/\\nfor(const newVPID of Array.from(maybeNewVPIDs).sort()){\\nmaybeExportPromise(newVPID);}\\n\\n\\n/* only the primary can possibly be newly resolved*/\\nunregisterUnreferencedVPID(vpid);\\nexportedVPIDs.delete(vpid);}\\n\\n\\nvoid noShim.E.when(\\np,\\n(value)=>handle(false,value),\\n(value)=>handle(true,value));}\\n\\n\\n\\nfunction notifyOnePromise(promiseID,rejected,data){\\ncapdata.insistCapData(data);\\nlsdebug(\\n`ls.dispatch.notify(${promiseID}, ${rejected}, ${data.body}, [${data.slots}])`);\\n\\nparseVatSlots.insistVatType('promise',promiseID);\\nconst pRec=importedVPIDs.get(promiseID);\\n/* we check pRec to ignore stale notifies, either from before an*/\\n/* upgrade, or if we acquire decider authority for a*/\\n/* previously-imported promise*/\\nif(pRec){\\nmeterControl.assertNotMetered();\\nconst val=m.unserialize(data);\\nif(rejected){\\npRec.reject(val);}else\\n{\\npRec.resolve(val);}\\n\\nreturn true;/* caller will remove from importedVPIDs*/}\\n\\n/* else ignore: our predecessor version might have subscribed*/\\nreturn false;}\\n\\n\\nfunction notify(resolutions){\\nindex.assert(didStartVat);\\nindex.assert(!didStopVat);\\n/* notifyOnePromise() will tell us whether each vpid in the batch*/\\n/* was retired or stale*/\\nconst retiredVPIDs=[];\\n/* Deserializing the batch of resolutions may import new promises,*/\\n/* some of which are resolved later in the batch. We'll need to*/\\n/* subscribe to the remaining (new+unresolved) ones.*/\\nbeginCollectingPromiseImports();\\nfor(const resolution of resolutions){\\nconst[vpid,rejected,data]=resolution;\\nconst retired=notifyOnePromise(vpid,rejected,data);\\nif(retired){\\nretiredVPIDs.push(vpid);/* not stale*/}}\\n\\n\\n/* 'imports' is an exclusively-owned Set that holds all new*/\\n/* promise vpids, both resolved and unresolved*/\\nconst imports=finishCollectingPromiseImports();\\nfor(const vpid of retiredVPIDs){\\nunregisterUnreferencedVPID(vpid);/* unregisters if not in vdata*/\\nimportedVPIDs.delete(vpid);\\nimports.delete(vpid);/* resolved, so don't subscribe()*/}\\n\\nfor(const vpid of Array.from(imports).sort()){\\nsyscall.subscribe(vpid);}}\\n\\n\\n\\nfunction dropExports(vrefs){\\nindex.assert(Array.isArray(vrefs));\\nvrefs.map((vref)=>parseVatSlots.insistVatType('object',vref));\\nvrefs.map((vref)=>index.assert(parseVatSlots.parseVatSlot(vref).allocatedByVat));\\n/* console.log(`-- liveslots acting upon dropExports ${vrefs.join(',')}`);*/\\nmeterControl.assertNotMetered();\\nfor(const vref of vrefs){\\nconst o=getValForSlot(vref);\\nif(o){\\nexportedRemotables.delete(o);}\\n\\nconst{virtual,durable}=parseVatSlots.parseVatSlot(vref);\\nif(virtual||durable){\\nvrm.setExportStatus(vref,'recognizable');}}}\\n\\n\\n\\n\\nfunction retireOneExport(vref){\\nparseVatSlots.insistVatType('object',vref);\\nconst{virtual,durable,allocatedByVat,type}=parseVatSlots.parseVatSlot(vref);\\nindex.assert(allocatedByVat);\\nindex.assert.equal(type,'object');\\n/* console.log(`-- liveslots acting on retireExports ${vref}`);*/\\nif(virtual||durable){\\nvrm.setExportStatus(vref,'none');}else\\n{\\n/* Remotable*/\\nkernelRecognizableRemotables.delete(vref);}}\\n\\n\\n\\nfunction retireExports(vrefs){\\nindex.assert(Array.isArray(vrefs));\\nfor(const vref of vrefs){\\nretireOneExport(vref);}}\\n\\n\\n\\nfunction retireImports(vrefs){\\nindex.assert(Array.isArray(vrefs));\\nvrefs.map((vref)=>parseVatSlots.insistVatType('object',vref));\\nvrefs.map((vref)=>index.assert(!parseVatSlots.parseVatSlot(vref).allocatedByVat));\\nfor(const vref of vrefs){\\nvrm.ceaseRecognition(vref);}}\\n\\n\\n\\n/* TODO: when we add notifyForward, guard against cycles*/\\n\\nfunction exitVat(completion){\\nmeterControl.assertIsMetered();/* else userspace getters could escape*/\\nconst args=m.serialize(harden(completion));\\nif(isAcceptableSyscallCapdataSize([args])){\\nargs.slots.map(retainExportedVref);\\nsyscall.exit(false,args);}else\\n{\\nsyscall.exit(true,m.serialize(Error('syscall capdata too large')));}}\\n\\n\\n\\nfunction exitVatWithFailure(reason){\\nmeterControl.assertIsMetered();/* else userspace getters could escape*/\\nconst args=m.serialize(harden(reason));\\nif(isAcceptableSyscallCapdataSize([args])){\\nargs.slots.map(retainExportedVref);\\nsyscall.exit(true,args);}else\\n{\\nsyscall.exit(true,m.serialize(Error('syscall capdata too large')));}}\\n\\n\\n\\nfunction disavow(presence){\\nif(!valToSlot.has(presence)){\\nindex.throwRedacted`attempt to disavow unknown ${presence}`;}\\n\\nconst slot=valToSlot.get(presence);\\n/* @ts-expect-error not undefined b/c of has() check*/\\nconst{type,allocatedByVat}=parseVatSlots.parseVatSlot(slot);\\ntype==='object'||index.throwRedacted`attempt to disavow non-object ${presence}`;\\n/* disavow() is only for imports: we'll use a different API to revoke*/\\n/* exports, one which accepts an Error object*/\\n!allocatedByVat||index.throwRedacted`attempt to disavow an export`;\\nvalToSlot.delete(presence);\\nslotToVal.delete(slot);\\ndisavowedPresences.add(presence);\\n\\nsyscall.dropImports([slot]);}\\n\\n\\nconst vatGlobals=harden({\\nVatData:{\\ndefineKind:vom.defineKind,\\ndefineKindMulti:vom.defineKindMulti,\\ndefineDurableKind:vom.defineDurableKind,\\ndefineDurableKindMulti:vom.defineDurableKindMulti,\\nmakeKindHandle:vom.makeKindHandle,\\ncanBeDurable:vom.canBeDurable,\\nprovidePromiseWatcher:watchedPromiseManager.providePromiseWatcher,\\nwatchPromise:watchedPromiseManager.watchPromise,\\nmakeScalarBigMapStore:collectionManager$1.makeScalarBigMapStore,\\nmakeScalarBigWeakMapStore:collectionManager$1.makeScalarBigWeakMapStore,\\nmakeScalarBigSetStore:collectionManager$1.makeScalarBigSetStore,\\nmakeScalarBigWeakSetStore:collectionManager$1.makeScalarBigWeakSetStore}});\\n\\n\\n\\nconst inescapableGlobalProperties=harden({\\nWeakMap:vom.VirtualObjectAwareWeakMap,\\nWeakSet:vom.VirtualObjectAwareWeakSet,\\n[passStyleOf.PassStyleOfEndowmentSymbol]:passStyleOf.passStyleOf});\\n\\n\\nfunction getRetentionStats(){\\nreturn{\\n...collectionManager$1.getRetentionStats(),\\n...vrm.getRetentionStats(),\\n...vom.getRetentionStats(),\\nexportedRemotables:exportedRemotables.size,\\nimportedDevices:importedDevices.size,\\nkernelRecognizableRemotables:kernelRecognizableRemotables.size,\\nexportedVPIDs:exportedVPIDs.size,\\nimportedVPIDs:importedVPIDs.size,\\npossiblyDeadSet:possiblyDeadSet.size,\\npossiblyRetiredSet:possiblyRetiredSet.size,\\nslotToVal:slotToVal.size};}\\n\\n\\n\\nconst testHooks=harden({\\n...vom.testHooks,\\n...vrm.testHooks,\\n...collectionManager$1.testHooks,\\nsetSyscallCapdataLimits,\\nvatGlobals,\\n\\ngetRetentionStats,\\nexportedRemotables,\\nimportedDevices,\\nkernelRecognizableRemotables,\\nexportedVPIDs,\\nimportedVPIDs,\\npossiblyDeadSet,\\npossiblyRetiredSet,\\nslotToVal,\\nvalToSlot,\\n/* eslint-disable-next-line no-use-before-define*/\\nafterDispatchActions});\\n\\n\\nfunction setVatOption(option,_value){\\n/* note: we removed the only settable option in #7138, but we'll*/\\n/* retain dispatch.changeVatOptions to make it easier to add a new*/\\n/* one in the future*/\\nswitch(option){\\ndefault:\\nconsole.warn(`WARNING setVatOption unknown option ${option}`);}}\\n\\n\\n\\nfunction changeVatOptions(options){\\nfor(const option of Object.getOwnPropertyNames(options)){\\nsetVatOption(option,options[option]);}}\\n\\n\\n\\nlet baggage;\\nasync function startVat(vatParametersCapData){\\ncapdata.insistCapData(vatParametersCapData);\\nindex.assert(!didStartVat);\\ndidStartVat=true;\\nindex.assert(!didStopVat);\\n\\n/* Build the `vatPowers` provided to `buildRootObject`. We include*/\\n/* vatGlobals and inescapableGlobalProperties to make it easier to write*/\\n/* unit tests that share their vatPowers with the test program, for*/\\n/* direct manipulation). 'D' is used by only a few vats: (bootstrap,*/\\n/* bridge, vat-http).*/\\nconst vpow={\\nD,\\nexitVat,\\nexitVatWithFailure,\\n...vatGlobals,\\n...inescapableGlobalProperties,\\n...vatPowers};\\n\\nif(enableDisavow){\\nvpow.disavow=disavow;}\\n\\nharden(vpow);\\n\\nvrm.initializeIDCounters();\\nvom.initializeKindHandleKind();\\ncollectionManager$1.initializeStoreKindInfo();\\n\\nconst vatParameters=m.unserialize(vatParametersCapData);\\nbaggage=collectionManager$1.provideBaggage();\\nwatchedPromiseManager.preparePromiseWatcherTables();\\n\\n/* Below this point, user-provided code might crash or overrun a meter, so*/\\n/* any prior-to-user-code setup that can be done without reference to the*/\\n/* content of the user-provided code should be above this point.*/\\nawait Promise.resolve();\\n\\n/* syscalls/VatData/makeKind must be enabled before invoking buildVatNamespace*/\\nconst vatNS=await buildVatNamespace(\\nvatGlobals,\\ninescapableGlobalProperties);\\n\\nconst buildRootObject=vatNS.buildRootObject;\\ntypeof buildRootObject==='function'||\\nindex.throwRedacted`vat source bundle lacks buildRootObject() function`;\\n\\n/* here we finally invoke the vat code, and get back the root object*/\\nconst rootObject=await buildRootObject(vpow,vatParameters,baggage);\\npassStyleOf.passStyleOf(rootObject)==='remotable'||\\nindex.throwRedacted`buildRootObject() for vat ${forVatID} returned ${rootObject}, which is not Far`;\\nremotable.getInterfaceOf(rootObject)!==undefined||\\nindex.throwRedacted`buildRootObject() for vat ${forVatID} returned ${rootObject} with no interface`;\\nif(valToSlot.has(rootObject)){\\nindex.throwRedacted`buildRootObject() must return ephemeral, not virtual/durable object`;}\\n\\n\\n/* Need to load watched promises *after* buildRootObject() so that handler kindIDs*/\\n/* have a chance to be reassociated with their handlers.*/\\nwatchedPromiseManager.loadWatchedPromiseTable(unmeteredRevivePromise);\\n\\nconst rootSlot=parseVatSlots.makeVatSlot('object',true,BigInt(0));\\nvalToSlot.set(rootObject,rootSlot);\\nslotToVal.set(rootSlot,new WeakRef(rootObject));\\nretainExportedVref(rootSlot);\\n/* we do not use vreffedObjectRegistry for root objects*/\\n\\nvom.insistAllDurableKindsReconnected();}\\n\\n\\n/**\\n * @param {IMPORT('./types.js').VatDeliveryObject} delivery\\n * @returns {void | Promise<void>}\\n */\\nfunction dispatchToUserspace(delivery){\\nlet result;\\nconst[type,...args]=delivery;\\nswitch(type){\\ncase'message':{\\nconst[targetSlot,msg]=args;\\nmessage.insistMessage(msg);\\ndeliver(targetSlot,msg.methargs,msg.result);\\nbreak;}\\n\\ncase'notify':{\\nconst[resolutions]=args;\\nnotify(resolutions);\\nbreak;}\\n\\ncase'dropExports':{\\nconst[vrefs]=args;\\ndropExports(vrefs);\\nbreak;}\\n\\ncase'retireExports':{\\nconst[vrefs]=args;\\nretireExports(vrefs);\\nbreak;}\\n\\ncase'retireImports':{\\nconst[vrefs]=args;\\nretireImports(vrefs);\\nbreak;}\\n\\ncase'changeVatOptions':{\\nconst[options]=args;\\nchangeVatOptions(options);\\nbreak;}\\n\\ncase'startVat':{\\nconst[vpCapData]=args;\\nresult=startVat(vpCapData);\\nbreak;}\\n\\ndefault:\\nindex.throwRedacted`unknown delivery type ${type}`;}\\n\\nreturn result;}\\n\\n\\n/* the first turn of each dispatch is spent in liveslots, and is not*/\\n/* metered*/\\nconst unmeteredDispatch=meterControl.unmetered(dispatchToUserspace);\\n\\nconst{scanForDeadObjects}=boydGc.makeBOYDKit({\\ngcTools,\\nslotToVal,\\nvrm,\\nkernelRecognizableRemotables,\\nsyscall,\\npossiblyDeadSet,\\npossiblyRetiredSet});\\n\\n\\n/**\\n * @param { IMPORT('./types.js').SwingSetCapData } _disconnectObjectCapData\\n * @returns {Promise<void>}\\n */\\nasync function stopVat(_disconnectObjectCapData){\\nconsole.warn('stopVat is a no-op as of #6650');}\\n\\n\\n/**\\n * Do things that should be done (such as flushing caches to disk) after a\\n * dispatch has completed and user code has relinquished agency.\\n */\\nfunction afterDispatchActions(){\\nvrm.flushIDCounters();\\ncollectionManager$1.flushSchemaCache();\\nvom.flushStateCache();}\\n\\n\\nconst bringOutYourDead=async()=>{\\nawait scanForDeadObjects();\\n/* Now flush all the vatstore changes (deletions and refcounts) we*/\\n/* made. dispatch() calls afterDispatchActions() automatically for*/\\n/* most methods, but not bringOutYourDead().*/\\nafterDispatchActions();\\n/* XXX TODO: make this conditional on a config setting*/\\nreturn getRetentionStats();};\\n\\n\\n/**\\n * This 'dispatch' function is the entry point for the vat as a whole: the\\n * vat-worker supervisor gives us VatDeliveryObjects (like\\n * dispatch.deliver) to execute. Here in liveslots, we invoke user-provided\\n * code during this time, which might cause us to make some syscalls. This\\n * userspace code might use Promises to add more turns to the ready promise\\n * queue, but we never give it direct access to the timer or IO queues\\n * (setImmediate, setInterval, setTimeout), so once the promise queue is\\n * empty, the vat userspace loses \\\"agency\\\" (the ability to initiate further\\n * execution), and waitUntilQuiescent fires. At that point we return\\n * control to the supervisor by resolving our return promise.\\n *\\n * Liveslots specifically guards against userspace reacquiring agency after\\n * our return promise is fired: vats are idle between cranks. Metering of\\n * the worker guards against userspace performing a synchronous infinite\\n * loop (`for (;;) {}`, the dreaded cthulu operator) or an async one\\n * (`function again() { return Promise.resolve().then(again); }`), by\\n * killing the vat after too much work. Userspace errors during delivery\\n * are expressed by calling syscall.resolve to reject the\\n * dispatch.deliver(result=) promise ID, which is unrelated to the Promise\\n * that `dispatch` returns.\\n *\\n * Liveslots does the authority to stall a crank indefinitely, by virtue of\\n * having access to `waitUntilQuiescent` and `FinalizationRegistry` (to\\n * retain agency), and the ability to disable metering (to disable worker\\n * termination), but only a buggy liveslots would do this. The kernel is\\n * vulnerable to a buggy liveslots never finishing a crank.\\n *\\n * This `dispatch` function always returns a Promise. It resolves (with\\n * nothing) when the crank completes successfully. If it rejects, that\\n * indicates the delivery has failed, and the worker should send an\\n * [\\\"error\\\", ..] `VatDeliveryResult` back to the kernel (which may elect to\\n * terminate the vat). Userspace should not be able to cause the delivery\\n * to fail: only a bug in liveslots should trigger a failure.\\n *\\n * @param {IMPORT('./types.js').VatDeliveryObject} delivery\\n * @returns {Promise<void>}\\n */\\nasync function dispatch(delivery){\\n/* We must short-circuit dispatch to bringOutYourDead here because it has to*/\\n/* be async, same for stopVat*/\\nif(delivery[0]==='bringOutYourDead'){\\nreturn meterControl.runWithoutMeteringAsync(bringOutYourDead);}else\\nif(delivery[0]==='stopVat'){\\nreturn meterControl.runWithoutMeteringAsync(()=>stopVat(delivery[1]));}else\\n{\\n/* Start user code running, record any internal liveslots errors. We do*/\\n/* *not* directly wait for the userspace function to complete, nor for*/\\n/* any promise it returns to fire.*/\\nconst p=Promise.resolve(delivery).then(unmeteredDispatch);\\n\\n/* Instead, we wait for userspace to become idle by draining the*/\\n/* promise queue. We clean up and then examine/return 'p' so any*/\\n/* bugs in liveslots that cause an error during*/\\n/* unmeteredDispatch (or a 'buildRootObject' that fails to*/\\n/* complete in time) will be reported to the supervisor (but*/\\n/* only after userspace is idle).*/\\nreturn gcTools.waitUntilQuiescent().then(()=>{\\nafterDispatchActions();\\n/* eslint-disable-next-line prefer-promise-reject-errors*/\\nreturn Promise.race([p,Promise.reject('buildRootObject unresolved')]);\\n/* the only delivery that pays attention to a user-provided*/\\n/* Promise is startVat, so the error message is specialized to*/\\n/* the only user problem that could cause the promise to not be*/\\n/* settled.*/});}}\\n\\n\\n\\nharden(dispatch);\\n\\n/* we return 'possiblyDeadSet' for unit tests*/\\nreturn harden({\\ndispatch,\\nm,\\ntestHooks});}\\n\\n\\n\\n/**\\n * Instantiate the liveslots layer for a new vat and then populate the vat with\\n * a new root object and its initial associated object graph, if any.\\n *\\n * @param {*} syscall Kernel syscall interface that the vat will have access to\\n * @param {*} forVatID Vat ID label, for use in debug diagostics\\n * @param {*} vatPowers\\n * @param {IMPORT('./types.js').LiveSlotsOptions} liveSlotsOptions\\n * @param {*} gcTools { WeakRef, FinalizationRegistry, waitUntilQuiescent }\\n * @param {Pick<Console, 'debug' | 'log' | 'info' | 'warn' | 'error'>} [liveSlotsConsole]\\n * @param {*} [buildVatNamespace]\\n *\\n * @returns {*} { dispatch }\\n *\\n * setBuildRootObject should be called, once, with a function that will\\n * create a root object for the new vat The caller provided buildRootObject\\n * function produces and returns the new vat's root object:\\n *\\n * buildRootObject(vatPowers, vatParameters)\\n *\\n * Within the vat, `import { E } from '@endo/eventual-send'` will\\n * provide the E wrapper. For any object x, E(x) returns a proxy object\\n * that converts any method invocation into a corresponding eventual send\\n * to x. That is, E(x).foo(arg1, arg2) is equivalent to x~.foo(arg1,\\n * arg2)\\n *\\n * If x is the presence in this vat of a remote object (that is, an object\\n * outside the vat), this will result in a message send out of the vat via\\n * the kernel syscall interface.\\n *\\n * In the same vein, if x is the presence in this vat of a kernel device,\\n * vatPowers.D(x) returns a proxy such that a method invocation on it is\\n * translated into the corresponding immediate invocation of the device\\n * (using, once again, the kernel syscall interface). D(x).foo(args) will\\n * perform an immediate syscall.callNow on the device node.\\n */\\nfunction makeLiveSlots(\\nsyscall,\\nforVatID='unknown',\\nvatPowers=harden({}),\\nliveSlotsOptions,\\ngcTools,\\nliveSlotsConsole=console,\\nbuildVatNamespace)\\n{\\nconst r=build(\\nsyscall,\\nforVatID,\\nvatPowers,\\nliveSlotsOptions,\\ngcTools,\\nliveSlotsConsole,\\nbuildVatNamespace);\\n\\nconst{dispatch,possiblyDeadSet,testHooks}=r;/* omit 'm'*/\\nreturn harden({\\ndispatch,\\npossiblyDeadSet,\\ntestHooks});}\\n\\n\\n\\n/* for tests*/\\nfunction makeMarshaller(syscall,gcTools,vatID='forVatID'){\\n/* @ts-expect-error missing buildVatNamespace param*/\\nconst{m}=build(syscall,vatID,{},{},gcTools,console);\\nreturn{m};}exports.makeLiveSlots=makeLiveSlots;exports.makeMarshaller=makeMarshaller;\",\n \"packages/swingset-liveslots/src/message.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var index=require('../../../node_modules/@endo/errors/index.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\ncapdata=require('./capdata.js');/**\\n * @typedef {{\\n * methargs: IMPORT('./types.js').SwingSetCapData, // of [method, args]\\n * result: string | undefined | null,\\n * }} Message\\n */ /**\\n * Assert function to ensure that something expected to be a message object\\n * actually is. A message object should have a .method property that's a\\n * string, a .args property that's a capdata object, and optionally a .result\\n * property that, if present, must be a string.\\n *\\n * @param {any} message The object to be tested\\n *\\n * @throws {Error} if, upon inspection, the parameter does not satisfy the above\\n * criteria.\\n *\\n * @returns {asserts message is Message}\\n */function insistMessage(message){capdata.insistCapData(message.methargs);if(message.result){typeof message.result==='string'||\\nindex.throwRedacted`message has non-string non-null .result ${message.result}`;}}\\n\\n\\n\\n/**\\n * @param {unknown} vdo\\n * @returns {asserts vdo is IMPORT('./types').VatDeliveryObject}\\n */\\n\\nfunction insistVatDeliveryObject(vdo){\\nindex.assert(Array.isArray(vdo));\\nconst[type,...rest]=vdo;\\nswitch(type){\\ncase'message':{\\nconst[target,msg]=rest;\\nindex.assert.typeof(target,'string');\\ninsistMessage(msg);\\nbreak;}\\n\\ncase'notify':{\\nconst[resolutions]=rest;\\nindex.assert(Array.isArray(resolutions));\\nfor(const[vpid,rejected,data]of resolutions){\\nindex.assert.typeof(vpid,'string');\\nindex.assert.typeof(rejected,'boolean');\\ncapdata.insistCapData(data);}\\n\\nbreak;}\\n\\ncase'dropExports':\\ncase'retireExports':\\ncase'retireImports':{\\nconst[slots]=rest;\\nindex.assert(Array.isArray(slots));\\nfor(const slot of slots){\\nindex.assert.typeof(slot,'string');}\\n\\nbreak;}\\n\\ncase'changeVatOptions':{\\nindex.assert(rest.length===1);\\nbreak;}\\n\\ncase'startVat':{\\nindex.assert(rest.length===1);\\nconst[vatParameters]=rest;\\ncapdata.insistCapData(vatParameters);\\nbreak;}\\n\\ncase'stopVat':{\\nindex.assert(rest.length===1);\\nconst[disconnectObjectCapData]=rest;\\ncapdata.insistCapData(disconnectObjectCapData);\\nbreak;}\\n\\ncase'bringOutYourDead':{\\nindex.assert(rest.length===0);\\nbreak;}\\n\\ndefault:\\nindex.throwRedacted`unknown delivery type ${type}`;}}\\n\\n\\n\\n/**\\n * @param {unknown} vdr\\n * @returns {asserts vdr is VatDeliveryResult}\\n */\\n\\nfunction insistVatDeliveryResult(vdr){\\nindex.assert(Array.isArray(vdr));\\nconst[type,problem,_usage]=vdr;\\nswitch(type){\\ncase'ok':{\\nindex.assert.equal(problem,null);\\nbreak;}\\n\\ncase'error':{\\nindex.assert.typeof(problem,'string');\\nbreak;}\\n\\ndefault:\\nindex.throwRedacted`unknown delivery result type ${type}`;}}\\n\\n\\n\\n/**\\n * @param {unknown} vso\\n * @returns {asserts vso is IMPORT('./types').VatSyscallObject}\\n */\\n\\nfunction insistVatSyscallObject(vso){\\nindex.assert(Array.isArray(vso));\\nconst[type,...rest]=vso;\\nswitch(type){\\ncase'send':{\\nconst[target,msg]=rest;\\nindex.assert.typeof(target,'string');\\ninsistMessage(msg);\\nbreak;}\\n\\ncase'callNow':{\\nconst[target,method,args]=rest;\\nindex.assert.typeof(target,'string');\\nindex.assert.typeof(method,'string');\\ncapdata.insistCapData(args);\\nbreak;}\\n\\ncase'subscribe':{\\nconst[vpid]=rest;\\nindex.assert.typeof(vpid,'string');\\nbreak;}\\n\\ncase'resolve':{\\nconst[resolutions]=rest;\\nindex.assert(Array.isArray(resolutions));\\nfor(const[vpid,rejected,data]of resolutions){\\nindex.assert.typeof(vpid,'string');\\nindex.assert.typeof(rejected,'boolean');\\ncapdata.insistCapData(data);}\\n\\nbreak;}\\n\\ncase'exit':{\\nconst[isFailure,info]=rest;\\nindex.assert.typeof(isFailure,'boolean');\\ncapdata.insistCapData(info);\\nbreak;}\\n\\ncase'vatstoreGet':{\\nconst[key]=rest;\\nindex.assert.typeof(key,'string');\\nbreak;}\\n\\ncase'vatstoreSet':{\\nconst[key,data]=rest;\\nindex.assert.typeof(key,'string');\\nindex.assert.typeof(data,'string');\\nbreak;}\\n\\ncase'vatstoreGetNextKey':{\\nconst[priorKey]=rest;\\nindex.assert.typeof(priorKey,'string');\\nbreak;}\\n\\ncase'vatstoreDelete':{\\nconst[key]=rest;\\nindex.assert.typeof(key,'string');\\nbreak;}\\n\\ncase'dropImports':\\ncase'retireImports':\\ncase'retireExports':\\ncase'abandonExports':{\\nconst[slots]=rest;\\nindex.assert(Array.isArray(slots));\\nfor(const slot of slots){\\nindex.assert.typeof(slot,'string');}\\n\\nbreak;}\\n\\ndefault:\\nindex.throwRedacted`unknown syscall type ${type}`;}}\\n\\n\\n\\n/**\\n * @param {unknown} vsr\\n * @returns {asserts vsr is IMPORT('./types').VatSyscallResult}\\n */\\n\\nfunction insistVatSyscallResult(vsr){\\nindex.assert(Array.isArray(vsr));\\nconst[type,...rest]=vsr;\\nswitch(type){\\ncase'ok':{\\nbreak;}\\n\\ncase'error':{\\nconst[err]=rest;\\nindex.assert.typeof(err,'string');\\nbreak;}\\n\\ndefault:\\nindex.throwRedacted`unknown syscall result type ${type}`;}}exports.insistMessage=insistMessage;exports.insistVatDeliveryObject=insistVatDeliveryObject;exports.insistVatDeliveryResult=insistVatDeliveryResult;exports.insistVatSyscallObject=insistVatSyscallObject;exports.insistVatSyscallResult=insistVatSyscallResult;\",\n \"packages/swingset-liveslots/src/parseVatSlots.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var index$1=require('../../../node_modules/@endo/nat/src/index.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nindex=require('../../../node_modules/@endo/errors/index.js');/* NOTE: confusing terminology: \\\"slot\\\" vs. \\\"reference\\\". All these things*/ /* called \\\"slots\\\" are references, but the word \\\"slot\\\" suggests something into*/ /* which something else is put and a reference isn't one of those. So improved*/ /* terminology would be an improvement, though any such change should be*/ /* thought through very carefully since changing these names will touch many*/ /* files. (You could call it a \\\"reference\\\", except that a phrase like \\\"vat*/ /* reference\\\" is ambiguous as to whether it means a reference belonging to a*/ /* vat or a reference *to* a vat, whereas \\\"vat slot\\\" does not have this problem*/ /* as badly. Also, \\\"slot\\\" is a short, single syllable word, which is nice.*/ /* But still \\\"slot\\\" implies containership which I think is wrong.)*/ /**\\n * Parse a vref string into its component parts:\\n * {\\n * type: STRING, // 'object', 'device', 'promise'\\n * allocatedByVat: BOOL, // true=>allocated by vat, false=>by the kernel\\n * id: Nat,\\n * subid: Nat,\\n * baseRef: STRING,\\n * facet: Nat,\\n * virtual: BOOL, // true=>vref designates a \\\"merely virtual\\\" object (not durable, not ephemeral)\\n * durable: BOOL, // designates a durable (not merely virtual, not ephemeral)\\n * }\\n *\\n * A vref string can take one of the forms:\\n *\\n * T-N\\n * T+N\\n * T+DN/I\\n * T+DN/I:F\\n *\\n * Where:\\n *\\n * T is a single character encoding the type of entity being referenced: 'd'\\n * for 'device', 'o' for 'object', or 'p' for 'promise'. One of the string\\n * values 'device', 'object', or 'promise' is returned as the `type`\\n * property of the result.\\n *\\n * '+' or '-' encodes who allocated the reference: '-' for the kernel\\n * (typically an import) or '+ for the vat (typically an export). This is\\n * returned in the `allocatedByVat` property of the result as a boolean.\\n *\\n * D is the durability status: for object exports (\\\"o+\\\"), this will\\n * be the letter 'd' for durable objects, the letter 'v' for\\n * non-durable (\\\"merely virtual\\\") objects, or empty for\\n * \\\"Remotable\\\" (ephemeral) objects. It is empty for object\\n * imports (\\\"o-\\\"), and both both imports and exports of all other\\n * types (promises, devices)\\n *\\n * N is a decimal integer representing the identity of the referenced entity.\\n * This is returned in the `id` property of the result as a BigInt.\\n *\\n * I if present (only allowed if T is 'o') is a decimal integer representing\\n * the instance id of the referenced object. In this case N denotes a\\n * category of objects that share a common shape, either one of the store\\n * types or a virtual object kind, and I indicates which instance of that\\n * category is being referred to. If present this is returned as the\\n * `subid` property of the result as a BigInt.\\n *\\n * F if present (only allowed if I is also present) is a decimal integer\\n * referencing a facet of the referenced object. In this case N/I denotes\\n * a particular object instance and F indicates which of several possible\\n * facets of that instance is being addressed. If present this is returned\\n * in the `facet` property of the result as a BigInt.\\n *\\n * The `baseRef` property of the result is `vref` stripped of any facet indicator.\\n *\\n * A \\\"vref\\\" identifies an entity visible to vat code to which messages may be\\n * sent and which may be compared for equality to other such entities. Let's\\n * call such an entity an \\\"addressable object\\\".\\n *\\n * A \\\"baseRef\\\" designates an entity that is managed by LiveSlots, both as a unit\\n * of garbage collection specifically and as a unit of memory management more\\n * generally. Such an entity may be a promise or remotable object or imported\\n * presence, all of which will always be JavaScript objects in memory, or it may\\n * be a virtual object or collection, which can be in memory or on disk or both.\\n * Let's call such an entity a \\\"base object\\\". In most cases this is one and the\\n * same with the addressable object that the vref designates, but in the case of\\n * a faceted object it is the cohort record as a whole rather than any particular\\n * individual facet.\\n *\\n * XXX TODO: The previous comment suggests some renaming is warranted:\\n *\\n * In the current implementation, a vref string may only include decimal digits,\\n * the letters 'd'/'o'/'p'/'v', and the punctuation characters '+', '-', '/',\\n * and ':'. Future evolution of the vref syntax might add more characters to\\n * this set, but the characters '|' and ',' are permanently excluded: '|' is\\n * used (notably by the collection manager) as delimiter in vatstore keys that\\n * include vrefs, and ',' is used as a separator in lists of vrefs.\\n *\\n * `slotToVal` maps a baseRef to a base object (actually to a weakRef that\\n * points to a base object)\\n * `getValForSlot` maps a baseRef to a base object, or to undefined if it is not\\n * resident in memory\\n * `convertSlotToVal` maps a vref to to an addressable object, loading it from\\n * disk if necessary\\n *\\n * `valToSlot` maps an addressable object to a vref\\n * `getSlotForVal` maps an addressable object to a vref\\n * `convertValToSlot` maps an addressable object to a vref, generating a new\\n * vref if necessary\\n *\\n * @param {string} vref The string to be parsed, as described above.\\n *\\n * @returns {*} a vref components descriptor corresponding to the vref string\\n * parameter, assuming it is syntactically well formed.\\n *\\n * @throws if the given vref string is syntactically incorrect.\\n */\\nfunction parseVatSlot(vref){\\nindex.assert.typeof(vref,'string');\\nconst parts=vref.split(':');\\nparts.length===1||parts.length===2||index.throwRedacted`invalid vref ${vref}`;\\nconst[baseRef,facetStr]=parts;\\nlet type;\\nlet allocatedByVat;\\nconst typechar=baseRef[0];\\nconst allocchar=baseRef[1];\\nlet idSuffix=baseRef.slice(2);\\n\\nif(typechar==='o'){\\ntype='object';}else\\nif(typechar==='d'){\\ntype='device';}else\\nif(typechar==='p'){\\ntype='promise';}else\\n{\\nindex.throwRedacted`invalid vref ${vref}`;}\\n\\n\\nif(allocchar==='+'){\\nallocatedByVat=true;}else\\nif(allocchar==='-'){\\nallocatedByVat=false;}else\\n{\\nindex.throwRedacted`invalid vref ${vref}`;}\\n\\n\\nlet virtual=false;\\nlet durable=false;\\nif(idSuffix.startsWith('d')){\\ndurable=true;\\nidSuffix=idSuffix.slice(1);}else\\nif(idSuffix.startsWith('v')){\\nvirtual=true;/* merely virtual*/\\nidSuffix=idSuffix.slice(1);}\\n\\nconst delim=idSuffix.indexOf('/');\\nlet id;\\nlet subid;\\nlet facet;\\nif(delim>0){\\ntype==='object'&&allocatedByVat||index.throwRedacted`invalid vref ${vref}`;\\nvirtual||durable||index.throwRedacted`invalid vref ${vref}`;/* subid only exists for virtuals/durables*/\\nid=index$1.Nat(BigInt(idSuffix.substr(0,delim)));\\nsubid=index$1.Nat(BigInt(idSuffix.slice(delim+1)));}else\\n{\\nid=index$1.Nat(BigInt(idSuffix));}\\n\\nif(subid!==undefined&&facetStr!==undefined){\\nfacet=index$1.Nat(BigInt(facetStr));}\\n\\n\\nreturn{type,allocatedByVat,virtual,durable,id,subid,baseRef,facet};}\\n\\n\\n/**\\n * Generate a vat slot reference string given a type, ownership, and id.\\n *\\n * @param {'object'|'device'|'promise'} type The type\\n * @param {boolean} allocatedByVat Flag: true=>vat allocated, false=>kernel allocated\\n * @param {number | bigint} id The id, a Nat.\\n *\\n * @returns {string} the corresponding vat slot reference string.\\n *\\n * @throws if type is not one of the above known types.\\n */\\nfunction makeVatSlot(type,allocatedByVat,id){\\nlet idSuffix;\\nif(allocatedByVat){\\nidSuffix=`+${index$1.Nat(id)}`;}else\\n{\\nidSuffix=`-${index$1.Nat(id)}`;}\\n\\n\\nif(type==='object'){\\nreturn`o${idSuffix}`;}\\n\\nif(type==='device'){\\nreturn`d${idSuffix}`;}\\n\\nif(type==='promise'){\\nreturn`p${idSuffix}`;}\\n\\nthrow index.throwRedacted`unknown type ${type}`;}\\n\\n\\nfunction makeBaseRef(kindID,id,isDurable){\\nreturn`o+${isDurable?'d':'v'}${kindID}/${id}`;}\\n\\n\\n/**\\n * Assert function to ensure that a vat slot reference string refers to a\\n * slot of a given type.\\n *\\n * @param {string} type The vat slot type desired, a string.\\n * @param {string} vatSlot The vat slot reference string being tested\\n *\\n * @throws if vatSlot is not of the given type or is malformed.\\n *\\n * @returns {void}\\n */\\nfunction insistVatType(type,vatSlot){\\ntype===parseVatSlot(vatSlot).type||\\nindex.throwRedacted`vatSlot ${vatSlot} is not of type ${type}`;}exports.insistVatType=insistVatType;exports.makeBaseRef=makeBaseRef;exports.makeVatSlot=makeVatSlot;exports.parseVatSlot=parseVatSlot;\",\n \"packages/swingset-liveslots/src/types.js\": \"\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n'use strict';/* Ensure this is a module.*/ /**\\n * @callback makeLiveSlots\\n */ /**\\n * The MeterControl object gives liveslots a mechanism to disable metering for certain GC-sensitive\\n * regions of code. Only the XS worker can actually do metering, but we track the enabled/disabled\\n * status on all workers, so that the assertions can be exercised more thoroughly (via non-XS unit\\n * tests). MeterControl.isMeteringDisabled()===false does not mean metering is happening, it just\\n * means that MeterControl isn't disabling it.\\n *\\n * @typedef {object} MeterControl\\n * @property {() => boolean} isMeteringDisabled Ask whether metering is currently disabled.\\n * @property {*} assertIsMetered\\n * @property {*} assertNotMetered\\n * @property {*} runWithoutMetering Run a callback outside metering\\n * @property {*} runWithoutMeteringAsync Run an async callback outside metering\\n * @property {*} unmetered Wrap a callback with runWithoutMetering\\n */ /**\\n * @typedef {{\\n * enableDisavow?: boolean,\\n * relaxDurabilityRules?: boolean,\\n * allowStateShapeChanges?: boolean,\\n * }} LiveSlotsOptions\\n *\\n * @typedef {IMPORT('@endo/marshal').CapData<string>} SwingSetCapData\\n *\\n * @typedef {{\\n * methargs: SwingSetCapData, // of [method, args]\\n * result: string | undefined | null,\\n * }} Message\\n * @typedef { [tag: 'message', target: string, msg: Message]} VatDeliveryMessage\\n * @typedef { [vpid: string, isReject: boolean, data: SwingSetCapData ] } VatOneResolution\\n * @typedef { [tag: 'notify', resolutions: VatOneResolution[] ]} VatDeliveryNotify\\n * @typedef { [tag: 'dropExports', vrefs: string[] ]} VatDeliveryDropExports\\n * @typedef { [tag: 'retireExports', vrefs: string[] ]} VatDeliveryRetireExports\\n * @typedef { [tag: 'retireImports', vrefs: string[] ]} VatDeliveryRetireImports\\n * @typedef { [tag: 'changeVatOptions', options: Record<string, unknown> ]} VatDeliveryChangeVatOptions\\n * @typedef { [tag: 'startVat', vatParameters: SwingSetCapData ]} VatDeliveryStartVat\\n * @typedef { [tag: 'stopVat', disconnectObject: SwingSetCapData ]} VatDeliveryStopVat\\n * @typedef { [tag: 'bringOutYourDead' ]} VatDeliveryBringOutYourDead\\n * @typedef { VatDeliveryMessage | VatDeliveryNotify | VatDeliveryDropExports\\n * | VatDeliveryRetireExports | VatDeliveryRetireImports | VatDeliveryChangeVatOptions\\n * | VatDeliveryStartVat | VatDeliveryStopVat | VatDeliveryBringOutYourDead\\n * } VatDeliveryObject\\n *\\n * @typedef { { compute: number } } MeterConsumption\\n * @typedef { [tag: 'ok', results: any, usage: MeterConsumption | null] |\\n * [tag: 'error', message: string, usage: MeterConsumption | null] } VatDeliveryResult\\n *\\n *\\n * @typedef { [tag: 'send', target: string, msg: Message] } VatSyscallSend\\n * @typedef { [tag: 'callNow', target: string, method: string, args: SwingSetCapData]} VatSyscallCallNow\\n * @typedef { [tag: 'subscribe', vpid: string ]} VatSyscallSubscribe\\n * @typedef { [tag: 'resolve', resolutions: VatOneResolution[] ]} VatSyscallResolve\\n * @typedef { [tag: 'exit', isFailure: boolean, info: SwingSetCapData ]} VatSyscallExit\\n * @typedef { [tag: 'vatstoreGet', key: string ]} VatSyscallVatstoreGet\\n * @typedef { [tag: 'vatstoreGetNextKey', priorKey: string ]} VatSyscallVatstoreGetNextKey\\n * @typedef { [tag: 'vatstoreSet', key: string, data: string ]} VatSyscallVatstoreSet\\n * @typedef { [tag: 'vatstoreDelete', key: string ]} VatSyscallVatstoreDelete\\n * @typedef { [tag: 'dropImports', slots: string[] ]} VatSyscallDropImports\\n * @typedef { [tag: 'retireImports', slots: string[] ]} VatSyscallRetireImports\\n * @typedef { [tag: 'retireExports', slots: string[] ]} VatSyscallRetireExports\\n * @typedef { [tag: 'abandonExports', slots: string[] ]} VatSyscallAbandonExports\\n *\\n * @typedef { VatSyscallSend | VatSyscallCallNow | VatSyscallSubscribe\\n * | VatSyscallResolve | VatSyscallExit | VatSyscallVatstoreGet | VatSyscallVatstoreGetNextKey\\n * | VatSyscallVatstoreSet | VatSyscallVatstoreDelete | VatSyscallDropImports\\n * | VatSyscallRetireImports | VatSyscallRetireExports | VatSyscallAbandonExports\\n * } VatSyscallObject\\n *\\n * @typedef { [tag: 'ok', data: SwingSetCapData | string | string[] | null ]} VatSyscallResultOk\\n * @typedef { [tag: 'error', err: string ] } VatSyscallResultError\\n * @typedef { VatSyscallResultOk | VatSyscallResultError } VatSyscallResult\\n *\\n * @typedef { (vso: VatSyscallObject) => VatSyscallResult } VatSyscallHandler\\n *\\n */ /**\\n * @template V fulfilled value\\n * @template {any[]} [A=unknown[]] arguments\\n * @typedef { {onFulfilled?: (value: V, ...args: A) => void, onRejected?: (reason: unknown, ...args: A) => void} } PromiseWatcher\\n */\",\n \"packages/swingset-liveslots/src/vatDataTypes.js\": \"'use strict';/* Empty JS file to correspond with vatDataTypes.d.ts*/\",\n \"packages/swingset-liveslots/src/vatstore-iterators.js\": \"'use strict';\\n\\nObject.defineProperty(exports,'__esModule',{value:true});/* return an iterator of all existing keys from start (inclusive) to*/ /* end (exclusive), in lexicographic order, calling checkF after*/ /* each 'yield' (which can throw to break the iterator)*/\\n\\nfunction*enumerateKeysStartEnd(syscall,start,end,checkF){\\nlet dbKey;\\nif(syscall.vatstoreGet(start)){\\ndbKey=start;}else\\n{\\ndbKey=syscall.vatstoreGetNextKey(start);/* maybe undefined*/}\\n\\nwhile(dbKey&&dbKey<end){\\nyield dbKey;\\n/* REENTRANCY HAZARD: we resume here after userspace cycles*/\\n/* the iterator, so check if the generation has changed*/\\ncheckF&&checkF();\\n/* fetch next key (which might be past 'end'), and repeat*/\\ndbKey=syscall.vatstoreGetNextKey(dbKey);}}\\n\\n\\nharden(enumerateKeysStartEnd);\\n\\n/* return an iterator of all existing keys that start with 'prefix'*/\\n/* (excluding the prefix itself)*/\\n\\nfunction*enumerateKeysWithPrefix(syscall,prefix){\\nlet key=prefix;\\nwhile(true){\\nkey=syscall.vatstoreGetNextKey(key);\\nif(!key||!key.startsWith(prefix)){\\nbreak;}\\n\\nyield key;}}\\n\\n\\nharden(enumerateKeysWithPrefix);\\n\\nfunction prefixedKeysExist(syscall,prefix){\\nconst nextKey=syscall.vatstoreGetNextKey(prefix);\\nreturn!!(nextKey&&nextKey.startsWith(prefix));}exports.enumerateKeysStartEnd=enumerateKeysStartEnd;exports.enumerateKeysWithPrefix=enumerateKeysWithPrefix;exports.prefixedKeysExist=prefixedKeysExist;\",\n \"packages/swingset-liveslots/src/virtualObjectManager.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../../node_modules/@endo/env-options/index.js');var index=require('../../../node_modules/@endo/errors/index.js');var index$2=require('../../store/src/index.js');require('../../../node_modules/@endo/exo/tools.js');require('../../../node_modules/@endo/marshal/index.js');var index$1=require('../../../node_modules/@endo/nat/src/index.js');var parseVatSlots=require('./parseVatSlots.js');var vatstoreIterators=require('./vatstore-iterators.js');var cache=require('./cache.js');var facetiousness=require('./facetiousness.js');var envOptions=require('../../../node_modules/@endo/env-options/src/env-options.js');var passStyleOf=require('../../../node_modules/@endo/pass-style/src/passStyleOf.js');var patternMatchers=require('../../../node_modules/@endo/patterns/src/patterns/patternMatchers.js');var exoTools=require('../../../node_modules/@endo/exo/src/exo-tools.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nmakeFar=require('../../../node_modules/@endo/pass-style/src/make-far.js');/* global globalThis */ /**\\n * @import {DurableKindHandle} from '@agoric/swingset-liveslots'\\n * @import {DefineKindOptions} from '@agoric/swingset-liveslots'\\n * @import {ClassContextProvider, KitContextProvider} from '@endo/exo'\\n * @import {ToCapData, FromCapData} from '@endo/marshal';\\n */\\n\\nconst{\\nhasOwn,\\ndefineProperty,\\ngetOwnPropertyNames,\\nvalues,\\nentries,\\nfromEntries}=\\nObject;\\nconst{ownKeys}=Reflect;\\n\\n/* Turn on to give each exo instance its own toStringTag value which exposes*/\\n/* the SwingSet vref.*/\\n/**/\\n/* CONFIDENTIALITY HAZARD NOTE: exposing vrefs to userspace reveals*/\\n/* confidential object-creation activity, so this must not be something*/\\n/* that unprivileged vat code (including unprivileged contracts) can do*/\\n/* for themselves.*/\\nconst LABEL_INSTANCES=envOptions.environmentOptionsListHas('DEBUG','label-instances');\\n\\n/* This file implements the \\\"Virtual Objects\\\" system, currently documented in*/\\n/* {@link https://github.com/Agoric/agoric-sdk/blob/master/packages/SwingSet/docs/virtual-objects.md})*/\\n/**/\\n/* All virtual-object state is keyed by baseRef, like o+v11/5 . For single-facet*/\\n/* Kinds (created with `defineKind`), this is the entire vref. For*/\\n/* multiple-facet Kinds (created with `defineKindMulti`), the cohort of facets*/\\n/* (which all share the same state, but offer different methods, generally*/\\n/* representing different authorities) will each have a vref that extends the*/\\n/* baseRef with a facet identifier, e.g. o+v11/5:0 for the first facet, and*/\\n/* o+v11/5:1 for the second.*/\\n/**/\\n/* To manage context and state and data correctly (not sensitive to GC), we need*/\\n/* two Caches. The first is \\\"dataCache\\\", and maps baseRef to state data. This*/\\n/* data includes the serialized capdata for all properties, and the unserialized*/\\n/* value for properties that have been read or written by an accessor on the*/\\n/* `state` object.*/\\n/**/\\n/* The second cache is \\\"contextCache\\\", and maps baseRef to a context object,*/\\n/* which is either { state, self } or { state, facets } depending on the*/\\n/* facetiousness of the VO. \\\"state\\\" is an object with one accessor pair*/\\n/* (getter+setter) per state property name. The \\\"state\\\" getters/setters know*/\\n/* which baseRef they should use. When invoked, they pull the state data from*/\\n/* `dataCache.get(baseRef).valueMap`. The setter will modify valueMap in place*/\\n/* and mark the entry as dirty, so it can be serialized and written back at*/\\n/* end-of-crank.*/\\n/**/\\n/* Each Representative is built as an Exo with defendPrototype (cohorts of*/\\n/* facets are built with defendPrototypeKit). These are given a*/\\n/* \\\"contextProvider\\\" for later use. For each facet, they build a prototype*/\\n/* object with wrappers for all the methods of that particular facet. When those*/\\n/* wrappers are invoked, the first thing they do is to call*/\\n/* `contextProvider(this)` (where `this` is the representative) to get a*/\\n/* \\\"context\\\" object: { state, self } or { state, facets }, which is passed to*/\\n/* the behavior functions. The contextProvider function uses valToSlot() to*/\\n/* figure out the representative's vref, then derives the baseRef, then consults*/\\n/* contextCache to get (or create) the context.*/\\n/**/\\n/* Our GC sensitivity contraints are:*/\\n/* * userspace must not be able to sense garbage collection*/\\n/* * Representatives are created on-demand when userspace deserializes a vref*/\\n/* * they disappear when UNREACHABLE and GC collects them*/\\n/* {@link https://github.com/Agoric/agoric-sdk/blob/master/packages/SwingSet/docs/garbage-collection.md})*/\\n/* * syscalls must be a deterministic function of userspace behavior*/\\n/* * that includes method invocation and \\\"state\\\" property read/writes*/\\n/* * they should not be influenced by GC until a bringOutYourDead delivery*/\\n/**/\\n/* See the discussion below (near `makeRepresentative`) for more details on how*/\\n/* we meet these constraints.*/\\n\\n/* * Make a cache which maps baseRef to a (mutable) record of {\\n * capdatas, valueMap }.\\n *\\n * 'capdatas' is a mutable Object (record) with state property names\\n * as keys, and their capdata { body, slots } as values, and\\n * 'valueMap' is a Map with state property names as keys, and their\\n * unmarshalled values as values. We need the 'capdatas' record to be\\n * mutable because we will modify its contents in place during\\n * setters, to retain the insertion order later (during flush). We\\n * need capdata at all so we can compare the slots before and after\\n * the update, to adjust the refcounts. Only the values of 'valueMap'\\n * are exposed to userspace.\\n */\\n\\n\\nconst makeDataCache=(syscall)=>{\\n/** @type {(baseRef: string) => { capdatas: any, valueMap: Map<string, any> }} */\\nconst readBacking=(baseRef)=>{\\nconst rawState=syscall.vatstoreGet(`vom.${baseRef}`);\\nindex.assert(rawState);\\nconst capdatas=JSON.parse(rawState);\\nconst valueMap=new Map();/* populated lazily by each state getter*/\\nreturn{capdatas,valueMap};/* both mutable*/};\\n\\n/** @type {(baseRef: string, value: { capdatas: any, valueMap: Map<string, any> }) => void} */\\nconst writeBacking=(baseRef,value)=>{\\nconst rawState=JSON.stringify(value.capdatas);\\nsyscall.vatstoreSet(`vom.${baseRef}`,rawState);};\\n\\n/** @type {(collectionID: string) => void} */\\nconst deleteBacking=(baseRef)=>syscall.vatstoreDelete(`vom.${baseRef}`);\\nreturn cache.makeCache(readBacking,writeBacking,deleteBacking);};\\n\\n\\nconst makeContextCache=(makeState,makeContext)=>{\\n/* non-writeback cache for \\\"context\\\" objects, { state, self/facets }*/\\nconst readBacking=(baseRef)=>{\\nconst state=makeState(baseRef);\\nconst context=makeContext(baseRef,state);\\nreturn context;};\\n\\nconst writeBacking=(_baseRef)=>index.throwRedacted`never called`;\\nconst deleteBacking=(_baseRef)=>index.throwRedacted`never called`;\\nreturn cache.makeCache(readBacking,writeBacking,deleteBacking);};\\n\\n\\n/* The management of single Representatives (i.e. defineKind) is very similar*/\\n/* to that of a cohort of facets (i.e. defineKindMulti). In this description,*/\\n/* we use \\\"self/facets\\\" to refer to either 'self' or 'facets', as appropriate*/\\n/* for the particular Kind. From userspace's perspective, the main difference*/\\n/* is that single-facet Kinds present self/facets as 'context.self', whereas*/\\n/* multi-facet Kinds present it as 'context.facets'.*/\\n\\n/* makeRepresentative/makeFacets returns the self/facets . This serves several*/\\n/* purposes:*/\\n/**/\\n/* * it is returned to userspace when making a new VO instance*/\\n/* * it appears as 'context.self/facets' when VO methods are invoked*/\\n/* * it is stored in the slotToVal table, specifically:*/\\n/* * slotToVal.get(baseref).deref() === self/facets*/\\n/* * (for facets, convertSlotToVal will then extract a single facet)*/\\n/* * it is registered with our FinalizationRegistry*/\\n/* * (for facets, the FR must not fire until all cohort members have been*/\\n/* collected)*/\\n/**/\\n/* Any facet can be passed to valToSlot to learn its vref, from which we learn*/\\n/* the baseRef, which we pass to contextCache.get to retrieve or create a*/\\n/* 'context', which will include self/facets and a 'state' object. So either:*/\\n/* * context = { state, self }*/\\n/* * context = { state, facets }*/\\n/**/\\n/* Userspace might hold on to a Representative, the `facets` record, the context*/\\n/* object, or the state object, for an unbounded length of time: beyond a single*/\\n/* crank/delivery. They might hold on to \\\"context\\\" but drop the Representative,*/\\n/* etc. They may compare these held objects against newer versions they receive*/\\n/* in future interactions. They might attempt to put any of these in a*/\\n/* WeakMap/WeakSet (remembering that they only get the*/\\n/* VirtualObjectAwareWeakMap/Set form that we give them). None of these actions*/\\n/* may allow userspace to sense GC.*/\\n/**/\\n/* Userspace could build a GC sensor out of any object with the following*/\\n/* properties:*/\\n/* * it has a GC-sensitive lifetime (i.e. created by these two functions)*/\\n/* * it is reachable from userspace*/\\n/* * it lacks a vref (else it'd be handled specially by VOAwareWeakMap)*/\\n/**/\\n\\n/* We must mark such objects as \\\"unweakable\\\" to prevent their use in*/\\n/* VOAwareWeakMap -based sensors (unweakable keys are held strongly by those*/\\n/* collections), and we must tie their lifetime to the facets to prevent their*/\\n/* use in a stash-and-compare-later sensor. We achieve the latter by adding a*/\\n/* linkToCohort WeakMap entry from every facet to the cohort record. This also*/\\n/* ensures that the FinalizationRegistry won't see the cohort record go away*/\\n/* until all the individual facets have been collected.*/\\n/**/\\n/* We only need to do this for multi-facet Kinds; single-facet kinds don't*/\\n/* have any extra objects for userspace to work with.*/\\n\\nconst makeRepresentative=(proto,baseRef)=>{\\nconst self={__proto__:proto};\\nif(LABEL_INSTANCES){\\n/* This exposes the vref to userspace, which is a confidentiality hazard*/\\n/* as noted in the CONFIDENTIALITY HAZARD NOTE above.*/\\n/**/\\n/* Aside from that hazard, the frozen string-valued data property is*/\\n/* safe to expose to userspace without enabling a GC sensor.*/\\n/* Strings lack identity and cannot be used as keys in WeakMaps.*/\\n/* If the property were a accessor property, we'd need to*/\\n/* ```js*/\\n/* linkToCohort.set(self, getterFunc);*/\\n/* unweakable.add(getterFunc);*/\\n/* ```*/\\ndefineProperty(self,Symbol.toStringTag,{\\nvalue:`${proto[Symbol.toStringTag]}#${baseRef}`,\\nwritable:false,\\nenumerable:false,\\nconfigurable:false});}\\n\\n\\nreturn harden(self);};\\n\\n\\nconst makeFacets=(\\nfacetNames,\\nprotoKit,\\nlinkToCohort,\\nunweakable,\\nbaseRef)=>\\n{\\nconst facets={};/* aka context.facets*/\\nfor(const name of facetNames){\\nconst facet=makeRepresentative(protoKit[name],baseRef);\\nfacets[name]=facet;\\nlinkToCohort.set(facet,facets);}\\n\\nunweakable.add(facets);\\nreturn harden(facets);};\\n\\n\\nconst insistDurableCapdata=(vrm,what,capdata,valueFor)=>{\\nfor(const[idx,vref]of entries(capdata.slots)){\\nif(!vrm.isDurable(vref)){\\nif(valueFor){\\nindex.throwRedacted`value for ${what} is not durable: slot ${index.bare(idx)} of ${capdata}`;}else\\n{\\nindex.throwRedacted`${what} is not durable: slot ${index.bare(idx)} of ${capdata}`;}}}};\\n\\n\\n\\n\\n\\nconst insistSameCapData=(oldCD,newCD)=>{\\n/* NOTE: this assumes both were marshalled with the same format*/\\n/* (e.g. smallcaps vs pre-smallcaps). To somewhat tolerate new*/\\n/* formats, we'd need to `serialize(unserialize(oldCD))`.*/\\nif(oldCD.body!==newCD.body){\\nindex.throwRedacted`durable Kind stateShape mismatch (body)`;}\\n\\nif(oldCD.slots.length!==newCD.slots.length){\\nindex.throwRedacted`durable Kind stateShape mismatch (slots.length)`;}\\n\\nfor(const[idx,oldVref]of entries(oldCD.slots)){\\nif(newCD.slots[idx]!==oldVref){\\nindex.throwRedacted`durable Kind stateShape mismatch (slot[${idx}])`;}}};\\n\\n\\n\\n\\n/**\\n * Create a new virtual object manager. There is one of these for each vat.\\n *\\n * @param {*} syscall Vat's syscall object, used to access the vatstore operations.\\n * @param {IMPORT('./virtualReferences.js').VirtualReferenceManager} vrm Virtual reference manager, to handle reference counting and GC\\n * of virtual references.\\n * @param {() => number} allocateExportID Function to allocate the next object\\n * export ID for the enclosing vat.\\n * @param {(val: object) => string | undefined} getSlotForVal A function that returns the\\n * object ID (vref) for a given object, if any. their corresponding export\\n * IDs\\n * @param {(slot: string) => object} requiredValForSlot\\n * @param {*} registerValue Function to register a new slot+value in liveSlot's\\n * various tables\\n * @param {ToCapData<string>} serialize Serializer for this vat\\n * @param {FromCapData<string>} unserialize Unserializer for this vat\\n * @param {*} assertAcceptableSyscallCapdataSize Function to check for oversized\\n * syscall params\\n * @param {IMPORT('./types.js').LiveSlotsOptions} [liveSlotsOptions]\\n * @param {{ WeakMap: typeof WeakMap, WeakSet: typeof WeakSet }} [powers]\\n * Specifying the underlying WeakMap/WeakSet objects to wrap with\\n * VirtualObjectAwareWeakMap/Set. By default, capture the ones currently\\n * defined on `globalThis` when the maker is invoked, to avoid infinite\\n * recursion if our returned WeakMap/WeakSet wrappers are subsequently installed\\n * on globalThis.\\n *\\n * @returns a new virtual object manager.\\n *\\n * The virtual object manager allows the creation of persistent objects that do\\n * not need to occupy memory when they are not in use. It provides five\\n * functions:\\n *\\n * - `defineKind`, `defineKindMulti`, `defineDurableKind`, and\\n * `defineDurableKindMulti` enable users to define new types of virtual\\n * object by providing an implementation of the new kind of object's\\n * behavior. The result is a maker function that will produce new\\n * virtualized instances of the defined object type on demand.\\n *\\n * - `VirtualObjectAwareWeakMap` and `VirtualObjectAwareWeakSet` are drop-in\\n * replacements for JavaScript's builtin `WeakMap` and `WeakSet` classes\\n * which understand the magic internal voodoo used to implement virtual\\n * objects and will do the right thing when virtual objects are used as keys.\\n * The intent is that the hosting environment will inject these as\\n * substitutes for their regular JS analogs in way that should be transparent\\n * to ordinary users of those classes.\\n *\\n * - `flushStateCache` will empty the object manager's cache of in-memory object\\n * instances, writing any changed state to the persistent store. This should\\n * be called at the end of each crank, to ensure the syscall trace does not\\n * depend upon GC of Representatives.\\n *\\n * The `defineKind` functions are made available to user vat code in the\\n * `VatData` global (along with various other storage functions defined\\n * elsewhere).\\n */\\nconst makeVirtualObjectManager=(\\nsyscall,\\nvrm,\\nallocateExportID,\\ngetSlotForVal,\\nrequiredValForSlot,\\nregisterValue,\\nserialize,\\nunserialize,\\nassertAcceptableSyscallCapdataSize,\\nliveSlotsOptions={},\\n{WeakMap,WeakSet}=globalThis)=>\\n{\\nconst{allowStateShapeChanges=false}=liveSlotsOptions;\\n\\n/* array of Caches that need to be flushed at end-of-crank, two per Kind*/\\n/* (dataCache, contextCache)*/\\nconst allCaches=[];\\n\\n/* WeakMap tieing VO components together, to prevent anyone who*/\\n/* retains one piece (e.g. the cohort record of facets) from being*/\\n/* able to observe the comings and goings of representatives by*/\\n/* hanging onto that piece while the other pieces are GC'd, then*/\\n/* comparing it to what gets generated when the VO is reconstructed*/\\n/* by a later import.*/\\nconst linkToCohort=new WeakMap();\\n\\nconst canBeDurable=(specimen)=>{\\nconst capData=serialize(specimen);\\nreturn capData.slots.every(vrm.isDurable);};\\n\\n\\n/* Marker associated to flag objects that should be held onto strongly if*/\\n/* somebody attempts to use them as keys in a VirtualObjectAwareWeakSet or*/\\n/* VirtualObjectAwareWeakMap, despite the fact that keys in such collections*/\\n/* are nominally held onto weakly. This to thwart attempts to observe GC by*/\\n/* squirreling away a piece of a VO while the rest of the VO gets GC'd and*/\\n/* then later regenerated.*/\\nconst unweakable=new WeakSet();\\n\\n/* This is a WeakMap from VO aware weak collections to strong Sets that retain*/\\n/* keys used in the associated collection that should not actually be held*/\\n/* weakly.*/\\nconst unweakableKeySets=new WeakMap();\\n\\nconst preserveUnweakableKey=(collection,key)=>{\\nif(unweakable.has(key)){\\nlet uwkeys=unweakableKeySets.get(collection);\\nif(!uwkeys){\\nuwkeys=new Set();\\nunweakableKeySets.set(collection,uwkeys);}\\n\\nuwkeys.add(key);}};\\n\\n\\n\\nconst releaseUnweakableKey=(collection,key)=>{\\nif(unweakable.has(key)){\\nconst uwkeys=unweakableKeySets.get(collection);\\nif(uwkeys){\\nuwkeys.delete(key);}}};\\n\\n\\n\\n\\n/* eslint max-classes-per-file: [\\\"error\\\", 2] */\\n\\nconst actualWeakMaps=new WeakMap();\\nconst virtualObjectMaps=new WeakMap();\\n\\nconst voAwareWeakMapDeleter=(descriptor)=>{\\nfor(const vref of descriptor.vmap.keys()){\\nvrm.removeRecognizableVref(vref,descriptor.vmap);}};\\n\\n\\n\\nclass VirtualObjectAwareWeakMap{\\nconstructor(){\\nactualWeakMaps.set(this,new WeakMap());\\nconst vmap=new Map();\\nvirtualObjectMaps.set(this,vmap);\\nvrm.registerDroppedCollection(this,{\\ncollectionDeleter:voAwareWeakMapDeleter,\\nvmap});}\\n\\n\\n\\nhas(key){\\nconst vkey=vrm.vrefKey(key);\\nif(vkey){\\nreturn virtualObjectMaps.get(this).has(vkey);}else\\n{\\nreturn actualWeakMaps.get(this).has(key);}}\\n\\n\\n\\nget(key){\\nconst vkey=vrm.vrefKey(key);\\nif(vkey){\\nreturn virtualObjectMaps.get(this).get(vkey);}else\\n{\\nreturn actualWeakMaps.get(this).get(key);}}\\n\\n\\n\\nset(key,value){\\nconst vkey=vrm.vrefKey(key);\\nif(vkey){\\nconst vmap=virtualObjectMaps.get(this);\\nif(!vmap.has(vkey)){\\nvrm.addRecognizableValue(key,vmap);}\\n\\nvmap.set(vkey,value);}else\\n{\\npreserveUnweakableKey(this,key);\\nactualWeakMaps.get(this).set(key,value);}\\n\\nreturn this;}\\n\\n\\ndelete(key){\\nconst vkey=vrm.vrefKey(key);\\nif(vkey){\\nconst vmap=virtualObjectMaps.get(this);\\nif(vmap.has(vkey)){\\nvrm.removeRecognizableValue(key,vmap);\\nreturn vmap.delete(vkey);}else\\n{\\nreturn false;}}else\\n\\n{\\nreleaseUnweakableKey(this,key);\\nreturn actualWeakMaps.get(this).delete(key);}}}\\n\\n\\n\\n\\ndefineProperty(VirtualObjectAwareWeakMap,Symbol.toStringTag,{\\nvalue:'WeakMap',\\nwritable:false,\\nenumerable:false,\\nconfigurable:true});\\n\\n\\nconst actualWeakSets=new WeakMap();\\nconst virtualObjectSets=new WeakMap();\\n\\nconst voAwareWeakSetDeleter=(descriptor)=>{\\nfor(const vref of descriptor.vset.values()){\\nvrm.removeRecognizableVref(vref,descriptor.vset);}};\\n\\n\\n\\nclass VirtualObjectAwareWeakSet{\\nconstructor(){\\nactualWeakSets.set(this,new WeakSet());\\nconst vset=new Set();\\nvirtualObjectSets.set(this,vset);\\n\\nvrm.registerDroppedCollection(this,{\\ncollectionDeleter:voAwareWeakSetDeleter,\\nvset});}\\n\\n\\n\\nhas(value){\\nconst vkey=vrm.vrefKey(value);\\nif(vkey){\\nreturn virtualObjectSets.get(this).has(vkey);}else\\n{\\nreturn actualWeakSets.get(this).has(value);}}\\n\\n\\n\\nadd(value){\\nconst vkey=vrm.vrefKey(value);\\nif(vkey){\\nconst vset=virtualObjectSets.get(this);\\nif(!vset.has(value)){\\nvrm.addRecognizableValue(value,vset);\\nvset.add(vkey);}}else\\n\\n{\\npreserveUnweakableKey(this,value);\\nactualWeakSets.get(this).add(value);}\\n\\nreturn this;}\\n\\n\\ndelete(value){\\nconst vkey=vrm.vrefKey(value);\\nif(vkey){\\nconst vset=virtualObjectSets.get(this);\\nif(vset.has(vkey)){\\nvrm.removeRecognizableValue(value,vset);\\nreturn vset.delete(vkey);}else\\n{\\nreturn false;}}else\\n\\n{\\nreleaseUnweakableKey(this,value);\\nreturn actualWeakSets.get(this).delete(value);}}}\\n\\n\\n\\n\\ndefineProperty(VirtualObjectAwareWeakSet,Symbol.toStringTag,{\\nvalue:'WeakSet',\\nwritable:false,\\nenumerable:false,\\nconfigurable:true});\\n\\n\\n/**\\n * @typedef {{\\n * kindID: string,\\n * tag: string,\\n * unfaceted?: boolean,\\n * facets?: string[],\\n * stateShapeCapData?: IMPORT('./types.js').SwingSetCapData\\n * }} DurableKindDescriptor\\n */\\n\\n/**\\n * @param {DurableKindDescriptor} durableKindDescriptor\\n */\\nconst saveDurableKindDescriptor=(durableKindDescriptor)=>{\\nconst{kindID}=durableKindDescriptor;\\nconst key=`vom.dkind.${kindID}.descriptor`;\\nsyscall.vatstoreSet(key,JSON.stringify(durableKindDescriptor));};\\n\\n\\n/**\\n * @param {string} kindID\\n * @returns {DurableKindDescriptor} durableKindDescriptor\\n */\\nconst loadDurableKindDescriptor=(kindID)=>{\\nconst key=`vom.dkind.${kindID}.descriptor`;\\nconst raw=syscall.vatstoreGet(key);\\nraw||index.throwRedacted`unknown kind ID ${kindID}`;\\nreturn JSON.parse(raw);};\\n\\n\\nconst saveNextInstanceID=(kindID)=>{\\nconst key=`vom.dkind.${kindID}.nextID`;\\nsyscall.vatstoreSet(key,`${nextInstanceIDs.get(kindID)}`);};\\n\\n\\nconst loadNextInstanceID=(kindID)=>{\\nconst key=`vom.dkind.${kindID}.nextID`;\\nreturn index$1.Nat(Number(syscall.vatstoreGet(key)));};\\n\\n\\nconst saveVirtualKindDescriptor=(kindID,descriptor)=>{\\n/* we never read these back: they're stored in the DB for the sake*/\\n/* of diagnostics, debugging, and potential external DB*/\\n/* cleanup/upgrade tools*/\\nconst key=`vom.vkind.${kindID}.descriptor`;\\nsyscall.vatstoreSet(key,JSON.stringify(descriptor));};\\n\\n\\n/**\\n * Define a new kind of virtual object.\\n *\\n * @param {string} kindID The kind ID to associate with the new kind.\\n *\\n * @param {string} tag A descriptive tag string as used in calls to `Far`\\n *\\n * @param {*} init An initialization function that will return the initial\\n * state of a new instance of the kind of virtual object being defined.\\n *\\n * @param {boolean} multifaceted True if this should be a multi-faceted\\n * virtual object, false if it should be single-faceted.\\n *\\n * @param {*} behavior A bag of functions (in the case of a single-faceted\\n * object) or a bag of bags of functions (in the case of a multi-faceted\\n * object) that will become the methods of the object or its facets.\\n *\\n * @param {DefineKindOptions<*>} options\\n * Additional options to configure the virtual object kind\\n * being defined. See the documentation of DefineKindOptions\\n * for the meaning of each option.\\n *\\n * @param {boolean} isDurable A flag indicating whether or not the newly defined\\n * kind should be a durable kind.\\n *\\n * @param {DurableKindDescriptor} [durableKindDescriptor] Descriptor for the\\n * durable kind, if it is, in fact, durable\\n *\\n * @returns {*} a maker function that can be called to manufacture new\\n * instances of this kind of object. The parameters of the maker function\\n * are those of the `init` function.\\n *\\n * Notes on theory of operation:\\n *\\n * Virtual objects are structured in three layers: representatives, inner\\n * selves, and state data.\\n *\\n * A representative is the manifestation of a virtual object that vat code has\\n * direct access to. A given virtual object can have at most one\\n * representative, which will be created as needed. This will happen when the\\n * instance is initially made, and can also happen (if it does not already\\n * exist) when the instance's virtual object ID is deserialized, either when\\n * delivered as part of an incoming message or read as part of another virtual\\n * object's state. A representative will be kept alive in memory as long as\\n * there is a variable somewhere that references it directly or indirectly.\\n * However, if a representative becomes unreferenced in memory it is subject\\n * to garbage collection, leaving the representation that is kept in the vat\\n * store as the record of its state from which a mew representative can be\\n * reconstituted at need. Since only one representative exists at a time,\\n * references to them may be compared with the equality operator (===).\\n * Although the identity of a representative can change over time, this is\\n * never visible to code running in the vat. Methods invoked on a\\n * representative always operate on the underlying virtual object state.\\n *\\n * The inner self represents the in-memory information about an object, aside\\n * from its state. There is an inner self for each virtual object that is\\n * currently resident in memory; that is, there is an inner self for each\\n * virtual object for which there is currently a representative present\\n * somewhere in the vat. The inner self maintains two pieces of information:\\n * its corresponding virtual object's virtual object ID, and a pointer to the\\n * virtual object's state in memory if the virtual object's state is, in fact,\\n * currently resident in memory. If the state is not in memory, the inner\\n * self's pointer to the state is null. In addition, the virtual object\\n * manager maintains an LRU cache of inner selves. Inner selves that are in\\n * the cache are not necessarily referenced by any existing representative,\\n * but are available to be used should such a representative be needed. How\\n * this all works will be explained in a moment.\\n *\\n * The state of a virtual object is a collection of mutable properties, each\\n * of whose values is itself immutable and serializable. The methods of a\\n * virtual object have access to this state by closing over a state object.\\n * However, the state object they close over is not the actual state object,\\n * but a wrapper with accessor methods that both ensure that a representation\\n * of the state is in memory when needed and perform deserialization on read\\n * and serialization on write; this wrapper is held by the representative, so\\n * that method invocations always see the wrapper belonging to the invoking\\n * representative. The actual state object holds marshaled serializations of\\n * each of the state properties. When written to persistent storage, this is\\n * represented as a JSON-stringified object each of whose properties is one\\n * of the marshaled property values.\\n *\\n * When a method of a virtual object attempts to access one of the properties\\n * of the object's state, the accessor first checks to see if the state is in\\n * memory. If it is not, it is loaded from persistent storage, the\\n * corresponding inner self is made to point at it, and then the inner self is\\n * placed at the head of the LRU cache (causing the least recently used inner\\n * self to fall off the end of the cache). If it *is* in memory, it is\\n * promoted to the head of the LRU cache but the overall contents of the cache\\n * remain unchanged. When an inner self falls off the end of the LRU, its\\n * reference to the state is nulled out and the object holding the state\\n * becomes garbage collectable.\\n */\\nconst defineKindInternal=(\\nkindID,\\ntag,\\ninit,\\nmultifaceted,\\nbehavior,\\noptions={},\\nisDurable,\\ndurableKindDescriptor=undefined/* only for durables*/)=>\\n{\\nconst{\\nfinish=undefined,\\nstateShape=undefined,\\nreceiveAmplifier=undefined,\\nreceiveInstanceTester=undefined,\\nthisfulMethods=false}=\\noptions;\\nlet{\\n/* These are \\\"let\\\" rather than \\\"const\\\" only to accommodate code*/\\n/* below that tolerates an old version of the vat-data package.*/\\n/* See there for more explanation.*/\\ninterfaceGuard=undefined,\\ninterfaceGuardKit=undefined}=\\noptions;\\n\\nconst statePrototype={};/* Not frozen yet*/\\nconst stateToBaseRefMap=new WeakMap();\\n\\nconst getBaseRef=(state)=>{\\nconst baseRef=stateToBaseRefMap.get(state);\\nbaseRef!==undefined||\\nindex.throwRedacted`state accessors can only be applied to state`;\\nreturn baseRef;};\\n\\n\\nlet proposedFacetNames;/* undefined or a list of strings*/\\n\\n/* 'multifaceted' tells us which API was used: define[Durable]Kind*/\\n/* vs define[Durable]KindMulti. This function checks whether*/\\n/* 'behavior' has one facet, or many, and must match.*/\\nswitch(facetiousness.assessFacetiousness(behavior)){\\ncase'one':{\\nindex.assert(!multifaceted);\\ninterfaceGuardKit===undefined||\\nindex.throwRedacted`Use an interfaceGuard, not interfaceGuardKit, to protect class ${index.quote(\\ntag)\\n}`;\\nproposedFacetNames=undefined;\\nbreak;}\\n\\ncase'many':{\\nindex.assert(multifaceted);\\n\\nif(interfaceGuard&&interfaceGuardKit===undefined){\\n/* This if clause is for the purpose of tolerating versions*/\\n/* of the vata-data package that precede*/\\n/* https://github.com/Agoric/agoric-sdk/pull/8220 .*/\\n/* Before that PR, the options name `interfaceGuard` would*/\\n/* actually carry the InterfaceGuardKit.*/\\n/**/\\n/* Tolerating the old vat-data with the new types.*/\\n/* @ts-expect-error*/\\ninterfaceGuardKit=interfaceGuard;\\ninterfaceGuard=undefined;\\n/* The rest of the code from here makes no further compromise*/\\n/* for that old version of the vat-data package.*/}\\n\\n\\ninterfaceGuard===undefined||\\nindex.throwRedacted`Use an interfaceGuardKit, not an interfaceGuard, to protect class kit ${index.quote(\\ntag)\\n}`;\\nproposedFacetNames=ownKeys(behavior).sort();\\nbreak;}\\n\\ncase'not':{\\nthrow index.throwRedacted`invalid behavior specifier for ${index.quote(tag)}`;}\\n\\ndefault:{\\nthrow index.throwRedacted`invalid facetiousness`;}}\\n\\n\\n/* beyond this point, we use 'multifaceted' to switch modes*/\\n\\n/* The 'stateShape' pattern constrains the `state` of each*/\\n/* instance: which properties it may have, and what their values*/\\n/* are allowed to be. For durable Kinds, the stateShape is*/\\n/* serialized and recorded in the durableKindDescriptor, so future*/\\n/* incarnations (which redefine the kind when they call*/\\n/* defineDurableKind again) can both check for compatibility, and*/\\n/* to decrement refcounts on any slots referenced by the old*/\\n/* shape.*/\\n\\nharden(stateShape);\\nstateShape===undefined||\\npassStyleOf.passStyleOf(stateShape)==='copyRecord'||\\nindex.throwRedacted`A stateShape must be a copyRecord: ${index.quote(stateShape)}`;\\npatternMatchers.assertPattern(stateShape);\\n\\nif(!multifaceted){\\nreceiveAmplifier===undefined||\\nindex.throwRedacted`Only facets of an exo class kit can be amplified, not ${index.quote(tag)}`;}\\n\\n\\nlet facetNames;\\n\\nif(isDurable){\\n/* durableKindDescriptor is created by makeKindHandle, with just*/\\n/* { kindID, tag, nextInstanceID }, then the first*/\\n/* defineDurableKind (maybe us!) will populate*/\\n/* .facets/.unfaceted and a .stateShape . We'll only see those*/\\n/* properties if we're in a non-initial incarnation.*/\\n\\nindex.assert(durableKindDescriptor);\\n\\n/* initial creation will update the descriptor with .facets or*/\\n/* .unfaceted, subsequent re-definitions will assert*/\\n/* compatibility, and reassign facet name->index*/\\nfacetNames=facetiousness.checkAndUpdateFacetiousness(\\ntag,\\ndurableKindDescriptor,\\nproposedFacetNames);\\n\\n\\nconst newShapeCD=serialize(stateShape);\\n\\n/* Durable kinds can only hold durable objects in their state,*/\\n/* so if the stateShape were to require a non-durable object,*/\\n/* nothing could ever match. So we require the shape have only*/\\n/* durable objects*/\\ninsistDurableCapdata(vrm,'stateShape',newShapeCD,false);\\n\\n/* compare against slots of previous definition, incref/decref*/\\nconst oldShapeCD=durableKindDescriptor.stateShapeCapData;\\n\\nconst oldStateShapeSlots=oldShapeCD?oldShapeCD.slots:[];\\nif(oldShapeCD&&!allowStateShapeChanges){\\ninsistSameCapData(oldShapeCD,newShapeCD);}\\n\\nconst newStateShapeSlots=newShapeCD.slots;\\nvrm.updateReferenceCounts(oldStateShapeSlots,newStateShapeSlots);\\ndurableKindDescriptor.stateShapeCapData=newShapeCD;/* replace*/\\n\\nsaveDurableKindDescriptor(durableKindDescriptor);}else\\n{\\nfacetNames=proposedFacetNames;}\\n\\n\\n/** @type {(prop: string) => void} */\\nlet checkStateProperty=(_prop)=>{};\\n/** @type {(value: any, prop: string) => void} */\\nlet checkStatePropertyValue=(_value,_prop)=>{};\\nif(stateShape){\\ncheckStateProperty=(prop)=>{\\nhasOwn(stateShape,prop)||\\nindex.throwRedacted`State must only have fields described by stateShape: ${index.quote(\\nownKeys(stateShape))\\n}`;};\\n\\ncheckStatePropertyValue=(value,prop)=>{\\ncheckStateProperty(prop);\\nindex$2.mustMatch(value,stateShape[prop]);};}\\n\\n\\n\\n/* The dataCache holds both unserialized and still-serialized*/\\n/* (capdata) contents of the virtual-object state record.*/\\n/* dataCache[baseRef] -> { capdatas, valueMap }*/\\n/* valueCD=capdatas[prop], value=valueMap.get(prop)*/\\n/** @type { IMPORT('./cache.js').Cache<{ capdatas: any, valueMap: Map<string, any> }>} */\\nconst dataCache=makeDataCache(syscall);\\nallCaches.push(dataCache);\\n\\n/* Behavior functions will receive a 'state' object that provides*/\\n/* access to their virtualized data, with getters and setters*/\\n/* backed by the vatstore DB. When those functions are invoked and*/\\n/* we miss in contextCache, we'll call makeState() and*/\\n/* makeContext(). The makeState() call might read from the*/\\n/* vatstore DB if we miss in dataCache.*/\\n\\n/* We sample dataCache.get() once each time:*/\\n/* * makeState() is called, which happens the first time in each crank that*/\\n/* a method is invoked (and the prototype does getContext)*/\\n/* * when state.prop is read, invoking the getter*/\\n/* * when state.prop is written, invoking the setter*/\\n/* This will cause a syscall.vatstoreGet only once per crank.*/\\n\\nconst makeFieldDescriptor=(prop)=>{\\nreturn harden({\\nget(){\\nconst baseRef=getBaseRef(this);\\nconst record=dataCache.get(baseRef);\\nindex.assert(record!==undefined);\\nconst{valueMap,capdatas}=record;\\nif(!valueMap.has(prop)){\\nconst value=harden(unserialize(capdatas[prop]));\\ncheckStatePropertyValue(value,prop);\\nvalueMap.set(prop,value);}\\n\\nreturn valueMap.get(prop);},\\n\\nset(value){\\nconst baseRef=getBaseRef(this);\\ncheckStatePropertyValue(value,prop);\\nconst capdata=serialize(value);\\nassertAcceptableSyscallCapdataSize([capdata]);\\nif(isDurable){\\ninsistDurableCapdata(vrm,prop,capdata,true);}\\n\\nconst record=dataCache.get(baseRef);/* mutable*/\\nindex.assert(record!==undefined);\\nconst oldSlots=record.capdatas[prop].slots;\\nconst newSlots=capdata.slots;\\nvrm.updateReferenceCounts(oldSlots,newSlots);\\nrecord.capdatas[prop]=capdata;/* modify in place ..*/\\nrecord.valueMap.set(prop,value);\\ndataCache.set(baseRef,record);/* .. but mark as dirty*/},\\n\\nenumerable:true,\\nconfigurable:false});};\\n\\n\\n\\nif(stateShape!==undefined){\\nfor(const prop of ownKeys(stateShape)){\\ndefineProperty(statePrototype,prop,makeFieldDescriptor(prop));}}\\n\\n\\n\\nharden(statePrototype);\\n\\nconst makeState=(baseRef)=>{\\nconst state={__proto__:statePrototype};\\nif(stateShape===undefined){\\nconst record=dataCache.get(baseRef);\\nindex.assert(record!==undefined);\\nfor(const prop of ownKeys(record.capdatas)){\\nindex.assert(typeof prop==='string');\\ncheckStateProperty(prop);\\ndefineProperty(state,prop,makeFieldDescriptor(prop));}}\\n\\n\\nharden(state);\\nstateToBaseRefMap.set(state,baseRef);\\nreturn state;};\\n\\n\\n/* More specifically, behavior functions receive a \\\"context\\\"*/\\n/* object as their first argument, with { state, self } or {*/\\n/* state, facets }. This makeContext() creates one, and is called*/\\n/* if/when those functions are invoked and the \\\"contextCache\\\"*/\\n/* misses, in which case the makeContextCache/readBacking function*/\\n/* will sample dataCache.get, then call both \\\"makeState()\\\" and*/\\n/* \\\"makeContext\\\". The DB might be read by that dataCache.get.*/\\n\\nconst makeContext=(baseRef,state)=>{\\n/* baseRef came from valToSlot, so must be in slotToVal*/\\nconst val=requiredValForSlot(baseRef);\\n/* val is either 'self' or the facet record*/\\nif(multifaceted){\\nreturn harden({state,facets:val});}else\\n{\\nreturn harden({state,self:val});}};\\n\\n\\n\\n/* The contextCache holds the {state,self} or {state,facets} \\\"context\\\"*/\\n/* object, needed by behavior functions. We keep this in a (per-crank)*/\\n/* cache because creating one requires knowledge of the state property*/\\n/* names, which requires a DB read. The property names are fixed at*/\\n/* instance initialization time, so we never write changes to this cache.*/\\n\\nconst contextCache=makeContextCache(makeState,makeContext);\\nallCaches.push(contextCache);\\n\\n/* defendPrototype/defendPrototypeKit accept a contextProvider function,*/\\n/* or a contextProviderKit record which maps facet name strings to*/\\n/* provider functions. It calls the function during invocation of each*/\\n/* method, and expects to get back the \\\"context\\\" record, either { state,*/\\n/* self } for single-facet VOs, or { state, facets } for multi-facet*/\\n/* ones. The provider we use fetches the state data (if not already in the*/\\n/* cache) at the last minute. This moves any syscalls needed by*/\\n/* stateCache.get() out of deserialization time (which is sensitive to GC)*/\\n/* and into method-invocation time (which is not).*/\\n\\nlet proto;\\n/** @type {ClassContextProvider | undefined} */\\nlet contextProviderVar;\\n/** @type { Record<string, KitContextProvider> | undefined } */\\nlet contextProviderKitVar;\\n\\nif(multifaceted){\\ncontextProviderKitVar=fromEntries(\\nfacetNames.map((name,index)=>[\\nname,\\n(rep)=>{\\nconst vref=getSlotForVal(rep);\\nif(vref===undefined){\\nreturn undefined;}\\n\\nconst{baseRef,facet}=parseVatSlots.parseVatSlot(vref);\\n\\n/* Without this check, an attacker (with access to both*/\\n/* cohort1.facetA and cohort2.facetB)*/\\n/* could effectively forge access to*/\\n/* cohort1.facetB and cohort2.facetA.*/\\n/* They could not forge the identity of those two*/\\n/* objects, but they could invoke all their equivalent methods,*/\\n/* by using e.g.*/\\n/* cohort1.facetA.foo.apply(cohort2.facetB, [...args])*/\\nif(Number(facet)!==index){\\nreturn undefined;}\\n\\n\\nreturn harden(contextCache.get(baseRef));}]));\\n\\n\\n\\n\\nproto=exoTools.defendPrototypeKit(\\ntag,\\nharden(contextProviderKitVar),\\nbehavior,\\nthisfulMethods,\\ninterfaceGuardKit);}else\\n\\n{\\ncontextProviderVar=(rep)=>{\\nconst slot=getSlotForVal(rep);\\nif(slot===undefined){\\nreturn undefined;}\\n\\nreturn harden(contextCache.get(slot));};\\n\\nproto=exoTools.defendPrototype(\\ntag,\\nharden(contextProviderVar),\\nbehavior,\\nthisfulMethods,\\ninterfaceGuard);}\\n\\n\\nharden(proto);\\n\\n/* All this to let typescript know that it won't vary during a closure*/\\nconst contextProvider=contextProviderVar;\\nconst contextProviderKit=contextProviderKitVar;\\n\\n/* this builds new Representatives, both when creating a new instance and*/\\n/* for reanimating an existing one when the old rep gets GCed*/\\n\\nconst reanimateVO=(baseRef)=>{\\nif(multifaceted){\\nreturn makeFacets(facetNames,proto,linkToCohort,unweakable,baseRef);}else\\n{\\nreturn makeRepresentative(proto,baseRef);}};\\n\\n\\n\\nconst deleteStoredVO=(baseRef)=>{\\nlet doMoreGC=false;\\nconst record=dataCache.get(baseRef);\\nindex.assert(record!==undefined);\\nfor(const valueCD of Object.values(record.capdatas)){\\nfor(const vref of valueCD.slots){\\ndoMoreGC=vrm.removeReachableVref(vref)||doMoreGC;}}\\n\\n\\ndataCache.delete(baseRef);\\nreturn doMoreGC;};\\n\\n\\n/* Tell the VRM about this Kind.*/\\nvrm.registerKind(kindID,reanimateVO,deleteStoredVO,isDurable);\\nvrm.rememberFacetNames(kindID,facetNames);\\n\\nconst makeNewInstance=(...args)=>{\\nconst id=getNextInstanceID(kindID,isDurable);\\nconst baseRef=parseVatSlots.makeBaseRef(kindID,id,isDurable);\\n/* kdebug(`vo make ${baseRef}`);*/\\n\\nconst initialData=init?init(...args):{};\\n\\n/* catch mistaken use of `() => { foo: 1 }` rather than `() => ({ foo: 1 })`*/\\n/* (the former being a function with a body having a no-op statement labeled*/\\n/* \\\"foo\\\" and returning undefined, the latter being a function with a concise*/\\n/* body that returns an object having a property named \\\"foo\\\").*/\\ntypeof initialData==='object'||\\nindex.throwRedacted`initial data must be object, not ${initialData}`;\\n\\n/* save (i.e. populate the cache) with the initial serialized record*/\\nconst capdatas={};\\nconst valueMap=new Map();\\nfor(const prop of getOwnPropertyNames(initialData)){\\nconst value=initialData[prop];\\ncheckStatePropertyValue(value,prop);\\nconst valueCD=serialize(value);\\n/* TODO: we're only checking the size of one property at a*/\\n/* time, but the real constraint is the vatstoreSet of the*/\\n/* aggregate record. We should apply this check to the full*/\\n/* list of capdatas, plus its likely JSON overhead.*/\\nassertAcceptableSyscallCapdataSize([valueCD]);\\nif(isDurable){\\ninsistDurableCapdata(vrm,prop,valueCD,true);}\\n\\n/* eslint-disable-next-line github/array-foreach*/\\nvalueCD.slots.forEach(vrm.addReachableVref);\\ncapdatas[prop]=valueCD;\\nvalueMap.set(prop,value);}\\n\\n/* dataCache contents remain mutable: state setter modifies in-place*/\\ndataCache.set(baseRef,{capdatas,valueMap});\\n\\n/* make the initial representative or cohort*/\\nlet val;\\nif(multifaceted){\\nval=makeFacets(facetNames,proto,linkToCohort,unweakable,baseRef);}else\\n{\\nval=makeRepresentative(proto,baseRef);}\\n\\nregisterValue(baseRef,val,multifaceted);\\nfinish&&finish(contextCache.get(baseRef));\\nreturn val;};\\n\\n\\nif(receiveAmplifier){\\nindex.assert(contextProviderKit);\\n\\n/* Amplify a facet to a cohort*/\\nconst amplify=(exoFacet)=>{\\nfor(const cp of values(contextProviderKit)){\\nconst context=cp(exoFacet);\\nif(context!==undefined){\\nreturn context.facets;}}\\n\\n\\nthrow index.throwRedacted`Must be a facet of ${index.quote(tag)}: ${exoFacet}`;};\\n\\nharden(amplify);\\nreceiveAmplifier(amplify);}\\n\\n\\nif(receiveInstanceTester){\\nif(multifaceted){\\nindex.assert(contextProviderKit);\\n\\nconst isInstance=(exoFacet,facetName=undefined)=>{\\nif(facetName===undefined){\\n/* Is exoFacet and instance of any facet of this class kit?*/\\nreturn values(contextProviderKit).some(\\n(cp)=>cp(exoFacet)!==undefined);}\\n\\n\\n/* Is this exoFacet an instance of this specific facet column*/\\n/* of this class kit?*/\\nindex.assert.typeof(facetName,'string');\\nconst cp=contextProviderKit[facetName];\\ncp!==undefined||\\nindex.throwRedacted`exo class kit ${index.quote(tag)} has no facet named ${index.quote(facetName)}`;\\nreturn cp(exoFacet)!==undefined;};\\n\\nharden(isInstance);\\nreceiveInstanceTester(isInstance);}else\\n{\\nindex.assert(contextProvider);\\n/* Is this exo an instance of this class?*/\\nconst isInstance=(exo,facetName=undefined)=>{\\nfacetName===undefined||\\nindex.throwRedacted`facetName can only be used with an exo class kit: ${index.quote(\\ntag)\\n} has no facet ${index.quote(facetName)}`;\\nreturn contextProvider(exo)!==undefined;};\\n\\nharden(isInstance);\\nreceiveInstanceTester(isInstance);}}\\n\\n\\n\\nreturn makeNewInstance;};\\n\\n\\nlet kindIDID;\\n/** @type Map<string, DurableKindDescriptor> */\\nconst kindIDToDescriptor=new Map();\\nconst kindHandleToID=new Map();\\nconst definedDurableKinds=new Set();/* kindID*/\\nconst nextInstanceIDs=new Map();/* kindID -> nextInstanceID*/\\n\\nconst reanimateDurableKindID=(vobjID)=>{\\nconst kindID=`${parseVatSlots.parseVatSlot(vobjID).subid}`;\\nconst durableKindDescriptor=loadDurableKindDescriptor(kindID);\\nconst nextInstanceID=loadNextInstanceID(kindID);\\nkindIDToDescriptor.set(kindID,durableKindDescriptor);\\nnextInstanceIDs.set(kindID,nextInstanceID);\\nconst kindHandle=makeFar.Far('kind',{});\\nkindHandleToID.set(kindHandle,kindID);\\n/* KindHandles are held strongly for the remainder of the incarnation, so*/\\n/* their components do not provide GC sensors*/\\nreturn kindHandle;};\\n\\n\\nconst initializeKindHandleKind=()=>{\\nkindIDID=syscall.vatstoreGet('kindIDID');\\nif(!kindIDID){\\nkindIDID=`${allocateExportID()}`;\\nsyscall.vatstoreSet('kindIDID',kindIDID);}\\n\\nvrm.registerKind(kindIDID,reanimateDurableKindID,()=>false,true);};\\n\\n\\nconst getNextInstanceID=(kindID,isDurable)=>{\\nindex.assert.typeof(kindID,'string');\\n/* nextInstanceID is initialized to 1 for brand new kinds, loaded*/\\n/* from DB when redefining existing kinds, held in RAM, and*/\\n/* written to DB after each increment as part of*/\\n/* kindDescriptors[kindID]*/\\nconst id=nextInstanceIDs.get(kindID);\\nindex.assert(id!==undefined);\\nconst next=id+1n;\\nnextInstanceIDs.set(kindID,next);\\nif(isDurable){\\nsaveNextInstanceID(kindID);}\\n\\nreturn id;};\\n\\n\\n/** @type {IMPORT('./vatDataTypes').VatData['defineKind']} */\\nconst defineKind=(tag,init,behavior,options)=>{\\nconst kindID=`${allocateExportID()}`;\\nsaveVirtualKindDescriptor(kindID,{kindID,tag});\\nnextInstanceIDs.set(kindID,1n);\\nreturn defineKindInternal(\\nkindID,\\ntag,\\ninit,\\nfalse,\\nbehavior,\\noptions,\\nfalse);};\\n\\n\\n\\n/** @type {IMPORT('./vatDataTypes').VatData['defineKindMulti']} */\\nconst defineKindMulti=(tag,init,behavior,options)=>{\\nconst kindID=`${allocateExportID()}`;\\nsaveVirtualKindDescriptor(kindID,{kindID,tag});\\nnextInstanceIDs.set(kindID,1n);\\nreturn defineKindInternal(\\nkindID,\\ntag,\\ninit,\\ntrue,\\nbehavior,\\noptions,\\nfalse);};\\n\\n\\n\\n/**\\n *\\n * @param {string} tag\\n * @returns {DurableKindHandle}\\n */\\nconst makeKindHandle=(tag)=>{\\nindex.assert(kindIDID,'initializeKindHandleKind not called yet');\\nconst kindID=`${allocateExportID()}`;\\nconst durableKindDescriptor={kindID,tag};\\nconst nextInstanceID=1n;\\nkindIDToDescriptor.set(kindID,durableKindDescriptor);\\nnextInstanceIDs.set(kindID,nextInstanceID);\\nsaveDurableKindDescriptor(durableKindDescriptor);\\nsaveNextInstanceID(kindID);\\n/** @type {DurableKindHandle} */\\n\\n/* @ts-expect-error cast*/\\nconst kindHandle=makeFar.Far('kind',{});\\nkindHandleToID.set(kindHandle,kindID);\\nconst kindIDvref=parseVatSlots.makeBaseRef(kindIDID,kindID,true);\\nregisterValue(kindIDvref,kindHandle,false);\\nreturn kindHandle;};\\n\\n\\n/** @type {IMPORT('./vatDataTypes').VatData['defineDurableKind']} */\\nconst defineDurableKind=(kindHandle,init,behavior,options)=>{\\nkindHandleToID.has(kindHandle)||index.throwRedacted`unknown handle ${kindHandle}`;\\nconst kindID=kindHandleToID.get(kindHandle);\\nconst durableKindDescriptor=kindIDToDescriptor.get(kindID);\\nindex.assert(durableKindDescriptor);\\nconst{tag}=durableKindDescriptor;\\n!definedDurableKinds.has(kindID)||\\nindex.throwRedacted`redefinition of durable kind ${tag}`;\\nconst maker=defineKindInternal(\\nkindID,\\ntag,\\ninit,\\nfalse,\\nbehavior,\\noptions,\\ntrue,\\ndurableKindDescriptor);\\n\\ndefinedDurableKinds.add(kindID);\\nreturn maker;};\\n\\n\\n/** @type {IMPORT('./vatDataTypes').VatData['defineDurableKindMulti']} */\\nconst defineDurableKindMulti=(kindHandle,init,behavior,options)=>{\\nkindHandleToID.has(kindHandle)||index.throwRedacted`unknown handle ${kindHandle}`;\\nconst kindID=kindHandleToID.get(kindHandle);\\nconst durableKindDescriptor=kindIDToDescriptor.get(kindID);\\nindex.assert(durableKindDescriptor);\\nconst{tag}=durableKindDescriptor;\\n!definedDurableKinds.has(kindID)||\\nindex.throwRedacted`redefinition of durable kind \\\"${tag}\\\"`;\\nconst maker=defineKindInternal(\\nkindID,\\ntag,\\ninit,\\ntrue,\\nbehavior,\\noptions,\\ntrue,\\ndurableKindDescriptor);\\n\\ndefinedDurableKinds.add(kindID);\\nreturn maker;};\\n\\n\\nconst insistAllDurableKindsReconnected=()=>{\\n/* identify all user-defined durable kinds by iterating `vom.dkind.*`*/\\nconst missing=[];\\nconst prefix='vom.dkind.';\\nfor(const key of vatstoreIterators.enumerateKeysWithPrefix(syscall,prefix)){\\nif(key.endsWith('.descriptor')){\\nconst value=syscall.vatstoreGet(key);\\nconst durableKindDescriptor=JSON.parse(value);\\nif(!definedDurableKinds.has(durableKindDescriptor.kindID)){\\nmissing.push(durableKindDescriptor.tag);}}}\\n\\n\\n\\nif(missing.length){\\nconst tags=missing.join(',');\\nthrow Error(`defineDurableKind not called for tags: [${tags}]`);}};\\n\\n\\n\\nconst countWeakKeysForCollection=(collection)=>{\\nconst virtualObjectMap=virtualObjectMaps.get(collection);\\nif(virtualObjectMap){\\nreturn virtualObjectMap.size;}\\n\\nconst virtualObjectSet=virtualObjectSets.get(collection);\\nif(virtualObjectSet){\\nreturn virtualObjectSet.size;}\\n\\nreturn 0;};\\n\\n\\nconst testHooks={\\ncountWeakKeysForCollection,\\n\\ndefinedDurableKinds,\\nnextInstanceIDs};\\n\\n\\nconst flushStateCache=()=>{\\nfor(const cache of allCaches){\\ncache.flush();}};\\n\\n\\n\\nconst getRetentionStats=()=>{\\nreturn{\\ndefinedDurableKinds:definedDurableKinds.size,\\nnextInstanceIDs:nextInstanceIDs.size};};\\n\\n\\n\\nreturn harden({\\ninitializeKindHandleKind,\\ndefineKind,\\ndefineKindMulti,\\ndefineDurableKind,\\ndefineDurableKindMulti,\\nmakeKindHandle,\\ninsistAllDurableKindsReconnected,\\nVirtualObjectAwareWeakMap,\\nVirtualObjectAwareWeakSet,\\nflushStateCache,\\ngetRetentionStats,\\ntestHooks,\\ncanBeDurable});};\\n\\n\\n/**\\n * @typedef { ReturnType<typeof makeVirtualObjectManager> } VirtualObjectManager\\n */exports.makeVirtualObjectManager=makeVirtualObjectManager;\",\n \"packages/swingset-liveslots/src/virtualReferences.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var index=require('../../../node_modules/@endo/errors/index.js');var index$1=require('../../../node_modules/@endo/nat/src/index.js');var parseVatSlots=require('./parseVatSlots.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nvatstoreIterators=require('./vatstore-iterators.js');/* eslint-disable no-use-before-define, jsdoc/require-returns-type */ /**\\n * @param {*} syscall Vat's syscall object, used to access the vatstore operations.\\n * @param {(val: object) => string | undefined} getSlotForVal A function that returns the\\n * object ID (vref) for a given object, if any. their corresponding export\\n * IDs\\n * @param {(slot: string) => object} requiredValForSlot A function that\\n * converts an object ID (vref) to an object.\\n * @param {*} FinalizationRegistry Powerful JavaScript intrinsic normally denied\\n * by SES\\n * @param {*} WeakRef Powerful JavaScript intrinsic normally denied\\n * by SES\\n * @param {*} addToPossiblyDeadSet Function to record objects whose deaths\\n * should be reinvestigated\\n * @param {*} addToPossiblyRetiredSet Function to record dead objects whose\\n * retirement should be reinvestigated\\n * @param {boolean} relaxDurabilityRules True IFF the associated swingset is\\n * running with relaxed durability rules\\n */\\nfunction makeVirtualReferenceManager(\\nsyscall,\\ngetSlotForVal,\\nrequiredValForSlot,\\nFinalizationRegistry,\\nWeakRef,\\naddToPossiblyDeadSet,\\naddToPossiblyRetiredSet,\\nrelaxDurabilityRules)\\n{\\nconst droppedCollectionRegistry=new FinalizationRegistry(\\nfinalizeDroppedCollection);\\n\\n/* Our JS engine is configured to treat WeakRefs as strong during*/\\n/* organic (non-forced GC), to minimize execution variation. To*/\\n/* prevent FinalizationRegistry callbacks from varying this way, we*/\\n/* must maintain WeakRefs to everything therein. The WeakRef is*/\\n/* retained by the FR \\\"heldValue\\\" context record, next to the*/\\n/* descriptor, and is thus released when the FR fires.*/\\n\\nfunction registerDroppedCollection(target,descriptor){\\nconst wr=new WeakRef(target);\\ndroppedCollectionRegistry.register(target,{descriptor,wr});}\\n\\n\\n/**\\n * Check if a virtual object is unreachable via virtual-data references.\\n *\\n * A virtual object is kept alive if it or any of its facets are reachable by\\n * any of three legs:\\n * - in-memory references (if so, it will have a representative and thus a\\n * non-null slot-to-val entry)\\n * - virtual references (if so, it will have a refcount > 0)\\n * - being exported (if so, its export flag will be set)\\n *\\n * This function is called after a leg has been reported missing,\\n * and reports back on whether the virtual-reference and\\n * export-status legs remain. The caller (liveslots\\n * scanForDeadObjects) will combine this with information about the\\n * RAM leg to decide whether the object is completely unreachable,\\n * and thus should be deleted.\\n *\\n * @param {string} baseRef The virtual object cohort might be dead\\n *\\n * @returns {boolean} True if the object remains referenced, false if unreachable\\n */\\nfunction isVirtualObjectReachable(baseRef){\\nconst refCount=getRefCount(baseRef);\\nconst[reachable,_retirees]=getExportStatus(baseRef);\\nreturn!!(reachable||refCount);}\\n\\n\\n/**\\n * Delete a virtual object\\n *\\n * Once the caller determines that all three legs are gone, they\\n * call us to delete the object.\\n *\\n * Deletion consists of removing the vatstore entries that describe its state\\n * and track its refcount status. In addition, when a virtual object is\\n * deleted, we delete any weak collection entries for which it was a key. If\\n * it had been exported, we also inform the kernel that the vref has been\\n * retired, so other vats can delete their weak collection entries too.\\n *\\n * @param {string} baseRef The virtual object cohort that's certainly dead\\n *\\n * @returns {[boolean, string[]]} A pair of a flag that's true if this\\n * possibly created a new GC opportunity and an array of vrefs that should\\n * now be regarded as unrecognizable\\n */\\nfunction deleteVirtualObject(baseRef){\\nconst refCount=getRefCount(baseRef);\\nconst[reachable,retirees]=getExportStatus(baseRef);\\nindex.assert(!reachable);\\nindex.assert(!refCount);\\nlet doMoreGC=deleteStoredRepresentation(baseRef);\\nsyscall.vatstoreDelete(`vom.rc.${baseRef}`);\\nsyscall.vatstoreDelete(`vom.es.${baseRef}`);\\ndoMoreGC=ceaseRecognition(baseRef)||doMoreGC;\\nreturn[doMoreGC,retirees];}\\n\\n\\n/**\\n * Get information about the export status of a virtual object.\\n *\\n * @param {string} baseRef The baseRef of the virtual object of interest.\\n *\\n * @returns {[boolean, string[]]} A pair of a flag that's true if the\\n * indicated virtual object is reachable and an array of vrefs (to facets\\n * of the object) that should now be regarded as unrecognizable\\n */\\nfunction getExportStatus(baseRef){\\nconst es=syscall.vatstoreGet(`vom.es.${baseRef}`);\\nif(es){\\nconst reachable=es.indexOf('r')>=0;\\nconst retirees=[];\\nif(!reachable){\\nif(es==='s'){\\n/* unfaceted*/\\nretirees.push(baseRef);}else\\n{\\n/* faceted*/\\nfor(let i=0;i<es.length;i+=1){\\nif(es[i]==='s'){\\nretirees.push(`${baseRef}:${i}`);}}}}\\n\\n\\n\\n\\nreturn[reachable,retirees];}else\\n{\\nreturn[false,[]];}}\\n\\n\\n\\nfunction getRefCount(baseRef){\\nconst raw=syscall.vatstoreGet(`vom.rc.${baseRef}`);\\nif(raw){\\nreturn Number(raw);}else\\n{\\nreturn 0;}}\\n\\n\\n\\nfunction setRefCount(baseRef,refCount){\\nconst{facet}=parseVatSlots.parseVatSlot(baseRef);\\n!facet||index.throwRedacted`setRefCount ${baseRef} should not receive individual facets`;\\nif(refCount===0){\\nsyscall.vatstoreDelete(`vom.rc.${baseRef}`);\\naddToPossiblyDeadSet(baseRef);}else\\n{\\nsyscall.vatstoreSet(`vom.rc.${baseRef}`,`${index$1.Nat(refCount)}`);}}\\n\\n\\n\\nfunction setExportStatus(vref,exportStatus){\\nconst{baseRef,id,facet}=parseVatSlots.parseVatSlot(vref);\\nconst key=`vom.es.${baseRef}`;\\nconst esRaw=syscall.vatstoreGet(key);\\n/* 'esRaw' may be undefined (nothing is currently exported), and*/\\n/* it might be short (saved by a previous version that had fewer*/\\n/* facets). Pad it out to the current length, which is '1' for*/\\n/* unfaceted Kinds*/\\nconst es=Array.from((esRaw||'').padEnd(getFacetCount(id),'n'));\\nconst facetIdx=facet===undefined?0:facet;\\n/* The export status of each facet is encoded as:*/\\n/* 's' -> 'recognizable' ('s' for \\\"see\\\"), 'r' -> 'reachable', 'n' -> 'none'*/\\nswitch(exportStatus){\\n/* POSSIBLE TODO: An anticipated refactoring may merge*/\\n/* dispatch.dropExports with dispatch.retireExports. If this happens, and*/\\n/* the export status can drop from 'reachable' to 'none' in a single step, we*/\\n/* must perform this \\\"the export pillar has dropped\\\" check in both the*/\\n/* reachable and the none cases (possibly reading the old status first, if*/\\n/* we must ensure addToPossiblyDeadSet only happens once).*/\\ncase'recognizable':{\\nes[facetIdx]='s';\\nsyscall.vatstoreSet(key,es.join(''));\\nconst refCount=getRefCount(baseRef);\\nif(refCount===0&&es.indexOf('r')<0){\\naddToPossiblyDeadSet(baseRef);}\\n\\nbreak;}\\n\\ncase'reachable':\\nes[facetIdx]='r';\\nsyscall.vatstoreSet(key,es.join(''));\\nbreak;\\ncase'none':\\nes[facetIdx]='n';\\nif(es.indexOf('r')<0&&es.indexOf('s')<0){\\nsyscall.vatstoreDelete(key);}else\\n{\\nsyscall.vatstoreSet(key,es.join(''));}\\n\\nbreak;\\ndefault:\\nindex.throwRedacted`invalid set export status ${exportStatus}`;}}\\n\\n\\n\\nfunction incRefCount(baseRef){\\nconst oldRefCount=getRefCount(baseRef);\\nsetRefCount(baseRef,oldRefCount+1);}\\n\\n\\nfunction decRefCount(baseRef){\\nconst oldRefCount=getRefCount(baseRef);\\noldRefCount>0||index.throwRedacted`attempt to decref ${baseRef} below 0`;\\nsetRefCount(baseRef,oldRefCount-1);}\\n\\n\\n/**\\n * Map from virtual object kind IDs to information about those kinds,\\n * including functions for handling the persistent representations of the\\n * corresponding kinds of objects.\\n */\\nconst kindInfoTable=new Map();\\n\\n/**\\n * Register information describing a persistent object kind.\\n *\\n * @param {string} kindID The kind of persistent object being handle\\n * @param {(string, boolean) => object} [reanimator] Reanimator function for the given kind.\\n * @param {(string) => boolean} [deleter] Deleter function for the given kind.\\n * @param {boolean} [durable] Flag indicating if instances survive vat termination\\n */\\nfunction registerKind(kindID,reanimator,deleter,durable){\\nkindInfoTable.set(`${kindID}`,{reanimator,deleter,durable});}\\n\\n\\n/**\\n * Record the names of the facets of a multi-faceted virtual object.\\n *\\n * @param {string} kindID The kind we're talking about\\n * @param {string[]|null} facetNames A sorted array of facet names to be\\n * recorded, or null if the kind is unfaceted\\n */\\nfunction rememberFacetNames(kindID,facetNames){\\nconst kindInfo=kindInfoTable.get(`${kindID}`);\\nkindInfo||index.throwRedacted`no kind info for ${kindID}`;\\nindex.assert(kindInfo.facetNames===undefined);\\nkindInfo.facetNames=facetNames;}\\n\\n\\nfunction getFacetNames(kindID){\\nreturn kindInfoTable.get(`${kindID}`).facetNames;}\\n\\n\\nfunction getFacetCount(kindID){\\nconst facetNames=getFacetNames(kindID);\\nreturn facetNames?facetNames.length:1;}\\n\\n\\nfunction getFacet(kindID,facets,facetIndex){\\nconst facetName=getFacetNames(kindID)[facetIndex];\\nfacetName!==undefined||/* allow empty-string -named facets*/\\nindex.throwRedacted`getFacet missing, ${kindID} [${facetIndex}]`;\\nconst facet=facets[facetName];\\nfacet||index.throwRedacted`getFacet missing, ${kindID} [${facetIndex}] ${facetName}`;\\nreturn facet;}\\n\\n\\n/**\\n * Inquire if a given persistent object kind is a durable kind or not.\\n *\\n * @param {string} kindID The kind of interest\\n *\\n * @returns {boolean} true if the indicated kind is durable.\\n */\\nfunction isDurableKind(kindID){\\nconst{durable}=kindInfoTable.get(`${kindID}`);\\nreturn durable;}\\n\\n\\n/**\\n * Inquire if a given vref is something that can be stored in a durable store\\n * or virtual object.\\n *\\n * @param {string} vref The vref of interest\\n *\\n * @returns {boolean} true if the indicated object reference is durable.\\n */\\nfunction isDurable(vref){\\nconst{type,id,virtual,durable,allocatedByVat}=parseVatSlots.parseVatSlot(vref);\\nif(type==='promise'){\\n/* promises are not durable even if `relaxDurabilityRules === true`*/\\nreturn false;}else\\nif(relaxDurabilityRules){\\n/* we'll pretend an object is durable if running with relaxed rules*/\\nreturn true;}else\\nif(type==='device'){\\n/* devices are durable*/\\nreturn true;}else\\nif(type!=='object'){\\n/* promises are not durable*/\\nreturn false;}else\\nif(!allocatedByVat){\\n/* imports are durable*/\\nreturn true;}else\\nif(virtual||durable){\\n/* stores and virtual objects are durable if their kinds are so configured*/\\nreturn isDurableKind(id);}else\\n{\\n/* otherwise it's not durable*/\\nreturn false;}}\\n\\n\\n\\n/**\\n * Create an in-memory representation of a given object by reanimating it from\\n * persistent storage. Used for deserializing.\\n *\\n * @param {string} baseRef The baseRef of the object being reanimated\\n *\\n * @returns A representative of the object identified by `baseRef`\\n */\\nfunction reanimate(baseRef){\\nconst{id}=parseVatSlots.parseVatSlot(baseRef);\\nconst kindID=`${id}`;\\nconst kindInfo=kindInfoTable.get(kindID);\\nkindInfo||\\nindex.throwRedacted`no kind info for ${kindID} (${baseRef}); check deserialize preceding kind definitions`;\\nconst{reanimator}=kindInfo;\\nif(reanimator){\\nreturn reanimator(baseRef);}else\\n{\\nthrow index.throwRedacted`unknown kind ${kindID}`;}}\\n\\n\\n\\n/**\\n * Delete the persistent representation of a virtual object given its ID\\n *\\n * @param {string} vobjID The virtual object ID of the object to be expunged\\n */\\nfunction deleteStoredRepresentation(vobjID){\\nconst{id}=parseVatSlots.parseVatSlot(vobjID);\\nconst kindID=`${id}`;\\nconst{deleter}=kindInfoTable.get(kindID);\\nif(deleter){\\nreturn deleter(vobjID);}else\\n{\\nthrow index.throwRedacted`unknown kind ${kindID}`;}}\\n\\n\\n\\n/**\\n * Map of all Remotables which are reachable by our virtualized data, e.g.\\n * `makeScalarWeakMapStore().set(key, remotable)` or `virtualObject.state.foo =\\n * remotable`. The serialization process stores the Remotable's vref to disk,\\n * but doesn't actually retain the Remotable. To correctly unserialize that\\n * offline data later, we must ensure the Remotable remains alive. This Map\\n * keeps a strong reference to the Remotable along with its (virtual) refcount.\\n */\\n/** @type {Map<object, number>} Remotable->refcount */\\nconst remotableRefCounts=new Map();\\n\\n/* Note that since presence refCounts are keyed by vref, `processDeadSet` must*/\\n/* query the refCount directly in order to determine if a presence that found*/\\n/* its way into the dead set is live or not, whereas it never needs to query*/\\n/* the `remotableRefCounts` map because that map holds actual live references*/\\n/* as keys and so Remotable references will only find their way into the dead*/\\n/* set if they are actually unreferenced (including, notably, their absence*/\\n/* from the `remotableRefCounts` map).*/\\n\\nfunction addReachableVref(vref){\\nconst{type,virtual,durable,allocatedByVat,baseRef}=\\nparseVatSlots.parseVatSlot(vref);\\nif(type==='object'){\\nif(allocatedByVat){\\nif(virtual||durable){\\nincRefCount(baseRef);}else\\n{\\n/* exported non-virtual object: Remotable*/\\nconst remotable=requiredValForSlot(vref);\\nconst oldRefCount=remotableRefCounts.get(remotable)||0;\\nremotableRefCounts.set(remotable,oldRefCount+1);}}else\\n\\n{\\n/* We refcount imports, to preserve their vrefs against*/\\n/* syscall.dropImport when the Presence itself goes away.*/\\nincRefCount(baseRef);}}else\\n\\nif(type==='promise'){\\n/* need to track promises too, maybe in remotableRefCounts*/\\nconst p=requiredValForSlot(vref);\\nconst oldRefCount=remotableRefCounts.get(p)||0;\\nremotableRefCounts.set(p,oldRefCount+1);}}\\n\\n\\n\\nfunction removeReachableVref(vref){\\nlet droppedMemoryReference=false;\\nconst{type,virtual,durable,allocatedByVat,baseRef}=\\nparseVatSlots.parseVatSlot(vref);\\nif(type==='object'){\\nif(allocatedByVat){\\nif(virtual||durable){\\ndecRefCount(baseRef);}else\\n{\\n/* exported non-virtual object: Remotable*/\\nconst remotable=requiredValForSlot(vref);\\nconst oldRefCount=remotableRefCounts.get(remotable)||0;\\noldRefCount>0||index.throwRedacted`attempt to decref ${vref} below 0`;\\nif(oldRefCount===1){\\nremotableRefCounts.delete(remotable);\\ndroppedMemoryReference=true;}else\\n{\\nremotableRefCounts.set(remotable,oldRefCount-1);}}}else\\n\\n\\n{\\ndecRefCount(baseRef);}}else\\n\\nif(type==='promise'){\\nconst p=requiredValForSlot(vref);\\nconst oldRefCount=remotableRefCounts.get(p)||0;\\noldRefCount>0||index.throwRedacted`attempt to decref ${vref} below 0`;\\nif(oldRefCount===1){\\nremotableRefCounts.delete(p);\\ndroppedMemoryReference=true;/* true for promises too*/}else\\n{\\nremotableRefCounts.set(p,oldRefCount-1);}}\\n\\n\\nreturn droppedMemoryReference;}\\n\\n\\nfunction getReachablePromiseRefCount(p){\\nreturn remotableRefCounts.get(p)||0;}\\n\\n\\n/* for testing only*/\\nfunction getReachableRefCount(vref){\\nconst{type,virtual,durable,allocatedByVat,baseRef}=\\nparseVatSlots.parseVatSlot(vref);\\nindex.assert(type==='object');\\nif(allocatedByVat){\\nif(virtual||durable){\\nreturn getRefCount(baseRef);}else\\n{\\nconst remotable=requiredValForSlot(baseRef);\\nreturn remotableRefCounts.get(remotable);}}else\\n\\n{\\nreturn getRefCount(baseRef);}}\\n\\n\\n\\nfunction updateReferenceCounts(beforeSlots,afterSlots){\\n/* Note that the slots of a capdata object are not required to be*/\\n/* deduplicated nor are they expected to be presented in any particular*/\\n/* order, so the comparison of which references appear in the before state*/\\n/* to which appear in the after state must look only at the presence or*/\\n/* absence of individual elements from the slots arrays and pay no attention*/\\n/* to the organization of the slots arrays themselves.*/\\nconst vrefStatus=new Map();\\nfor(const vref of beforeSlots){\\nvrefStatus.set(vref,'drop');}\\n\\nfor(const vref of afterSlots){\\nif(vrefStatus.get(vref)==='drop'){\\nvrefStatus.set(vref,'keep');}else\\nif(!vrefStatus.has(vref)){\\nvrefStatus.set(vref,'add');}}\\n\\n\\nconst keys=[...vrefStatus.keys()].sort();\\nfor(const vref of keys){\\nswitch(vrefStatus.get(vref)){\\ncase'add':\\naddReachableVref(vref);\\nbreak;\\ncase'drop':\\nremoveReachableVref(vref);\\nbreak;\\ndefault:\\nbreak;}}}\\n\\n\\n\\n\\n/**\\n * Check if a given vref points to a reachable presence.\\n *\\n * @param {string} vref The vref of the presence being enquired about\\n *\\n * @returns {boolean} true if the indicated presence remains reachable.\\n */\\nfunction isPresenceReachable(vref){\\nreturn!!getRefCount(vref);}\\n\\n\\n/**\\n * A vref is \\\"recognizable\\\" when it is used as the key of a weak\\n * collection, like a virtual/durable WeakMapStore or WeakSetStore,\\n * or the ephemeral voAwareWeakMap/Set that we impose upon userspace\\n * as \\\"WeakMap/WeakSet\\\". The collection can be used to query whether\\n * a future specimen matches the original or not, without holding\\n * onto the original.\\n *\\n * We need \\\"recognition records\\\" to map from the vref to the\\n * collection that can recognize it. When the vref is retired, we\\n * use the record to find all the collections from which we need to\\n * delete entries, so we can release the matching values. This might\\n * happen because the vref was for a Presence and the kernel just\\n * told us the upstream vat has deleted it (dispatch.retireImports),\\n * or because it was for a locally-managed object (an ephemeral\\n * Remotable or a virtual/durable Representative) and we decided to\\n * delete it.\\n *\\n * The virtual/durable collections track their \\\"recognition records\\\"\\n * in the vatstore, in keys like \\\"vom.ir.${vref}|${collectionID}\\\".\\n * These records do not contribute to our RAM usage.\\n *\\n * voAwareWeakMap and voAwareWeakSet store their recognition records\\n * in RAM, using this Map named 'vrefRecognizers'. Each key is a\\n * vref, and the value is a Set of recognizers. Each recognizer is\\n * the internal 'virtualObjectMap' in which the collection maps from\\n * vref to value. These in-RAM collections only use virtualObjectMap\\n * to track Presence-style (imports) and Representative-style\\n * (virtual/durable) vrefs: any Remotable-style keys are stored in\\n * the collection's internal (real) WeakMap under the Remotable\\n * object itself (because the engine handles the bookkeeping, and\\n * there is no virtual data in the value that we need to clean up at\\n * deletion time).\\n *\\n * Each voAwareWeakMap/Set must have a distinct recognizer, so we\\n * can remove the key from the right ones. The recognizer is held\\n * strongly by the recognition record, so it must not be the\\n * voAwareWeakMap/Set itself (which would inhibit GC).\\n *\\n * When an individual entry is deleted from the weak collection, we\\n * must also delete the recognition record. When the collection\\n * itself is deleted (i.e. because nothing was referencing it), we\\n * must both delete all recognition records and also notify the\\n * kernel about any Presence-style vrefs that we can no longer\\n * recognize (syscall.retireImports). The kernel doesn't care about\\n * Remotable- or Representative- style vrefs, only the imports.\\n *\\n * TODO: all the \\\"recognizers\\\" in principle could be, and probably should be,\\n * reduced to deleter functions. However, since the VirtualObjectAware\\n * collections are actual JavaScript classes I need to take some care to\\n * ensure that I've got the exactly-one-per-collection invariant handled\\n * correctly.\\n *\\n * TODO: concoct a better type def than Set<any>\\n */\\n/**\\n * @typedef { Map<string, *> | Set<string> } Recognizer\\n */\\n/** @type {Map<string, Set<Recognizer>>} */\\nconst vrefRecognizers=new Map();\\n\\n/**\\n * @param {*} value The vref-bearing object used as the collection key\\n * @param {string|Recognizer} recognizer The collectionID or virtualObjectMap for the collection\\n * @param {boolean} [recognizerIsVirtual] true for virtual/durable Stores, false for voAwareWeakMap/Set\\n */\\nfunction addRecognizableValue(value,recognizer,recognizerIsVirtual){\\nconst vref=getSlotForVal(value);\\nif(vref){\\nconst{type,allocatedByVat,virtual,durable}=parseVatSlots.parseVatSlot(vref);\\nif(type==='object'){\\n/* recognizerSet (voAwareWeakMap/Set) doesn't track Remotables*/\\nconst notRemotable=!allocatedByVat||virtual||durable;\\n\\nif(recognizerIsVirtual){\\nindex.assert.typeof(recognizer,'string');\\nsyscall.vatstoreSet(`vom.ir.${vref}|${recognizer}`,'1');}else\\nif(notRemotable){\\nindex.assert.typeof(recognizer,'object');\\nlet recognizerSet=vrefRecognizers.get(vref);\\nif(!recognizerSet){\\nrecognizerSet=new Set();\\nvrefRecognizers.set(vref,recognizerSet);}\\n\\nrecognizerSet.add(recognizer);}}}}\\n\\n\\n\\n\\n\\n/**\\n * @param {string} vref The vref or the object used as the collection key\\n * @param {string|Recognizer} recognizer The collectionID or virtualObjectMap for the collection\\n * @param {boolean} [recognizerIsVirtual] true for virtual/durable Stores, false for voAwareWeakMap/Set\\n */\\nfunction removeRecognizableVref(vref,recognizer,recognizerIsVirtual){\\nconst{type,allocatedByVat,virtual,durable}=parseVatSlots.parseVatSlot(vref);\\nif(type==='object'){\\n/* addToPossiblyDeadSet only needs Presence-style vrefs*/\\nconst isPresence=!allocatedByVat;\\n/* recognizerSet (voAwareWeakMap/Set) doesn't track Remotables*/\\nconst notRemotable=!allocatedByVat||virtual||durable;\\n\\nif(recognizerIsVirtual){\\nindex.assert.typeof(recognizer,'string');\\nsyscall.vatstoreDelete(`vom.ir.${vref}|${recognizer}`);\\nif(isPresence){\\naddToPossiblyRetiredSet(vref);}}else\\n\\nif(notRemotable){\\nindex.assert.typeof(recognizer,'object');\\nconst recognizerSet=vrefRecognizers.get(vref);\\nindex.assert(recognizerSet&&recognizerSet.has(recognizer));\\nrecognizerSet.delete(recognizer);\\nif(recognizerSet.size===0){\\nvrefRecognizers.delete(vref);\\nif(isPresence){\\naddToPossiblyRetiredSet(vref);}}}}}\\n\\n\\n\\n\\n\\n\\n/**\\n * @param {*} value The vref-bearing object used as the collection key\\n * @param {string|Recognizer} recognizer The collectionID or virtualObjectMap for the collection\\n * @param {boolean} [recognizerIsVirtual] true for virtual/durable Stores, false for voAwareWeakMap/Set\\n */\\nfunction removeRecognizableValue(value,recognizer,recognizerIsVirtual){\\nconst vref=getSlotForVal(value);\\nif(vref){\\nremoveRecognizableVref(vref,recognizer,recognizerIsVirtual);}}\\n\\n\\n\\nlet deleteCollectionEntry;\\nfunction setDeleteCollectionEntry(fn){\\ndeleteCollectionEntry=fn;}\\n\\n\\n/**\\n * Remove a given vref from all weak collections in which it was used as a\\n * key.\\n *\\n * @param {string} vref The vref that shall henceforth no longer be recognized\\n *\\n * @returns {boolean} true if this possibly creates a GC opportunity\\n */\\nfunction ceaseRecognition(vref){\\nlet doMoreGC=false;\\nconst p=parseVatSlots.parseVatSlot(vref);\\nif(p.allocatedByVat&&(p.virtual||p.durable)&&p.facet===undefined){\\n/* If `vref` identifies a multi-faceted object that should no longer be*/\\n/* \\\"recognized\\\", what that really means that all references to its*/\\n/* individual facets should no longer be recognized -- nobody actually*/\\n/* references the object itself except internal data structures. So in*/\\n/* this case we need individually to stop recognizing the facets*/\\n/* themselves.*/\\nconst kindInfo=kindInfoTable.get(`${p.id}`);\\n/* This function can be called either from `dispatch.retireImports` or*/\\n/* from `deleteVirtualObject`. In the latter case the vref is*/\\n/* actually a baseRef and so needs to be expanded to cease recognition of*/\\n/* all the facets.*/\\nif(kindInfo){\\nconst{facetNames}=kindInfo;\\nif(facetNames){\\nfor(let i=0;i<facetNames.length;i+=1){\\ndoMoreGC=ceaseRecognition(`${vref}:${i}`)||doMoreGC;}\\n\\nreturn doMoreGC;}}}\\n\\n\\n\\n\\n/* remove from all voAwareWeakMap/Sets that knew about it*/\\nconst recognizerSet=vrefRecognizers.get(vref);\\nif(recognizerSet){\\nvrefRecognizers.delete(vref);\\nfor(const recognizer of recognizerSet){\\nif(recognizer instanceof Map){\\nrecognizer.delete(vref);\\ndoMoreGC=true;}else\\nif(recognizer instanceof Set){\\nrecognizer.delete(vref);}else\\n{\\nindex.throwRedacted`unknown recognizer type ${typeof recognizer}`;}}}\\n\\n\\n\\n\\n/* and from (weak) virtual collections that knew about it*/\\nconst prefix=`vom.ir.${vref}|`;\\nfor(const key of vatstoreIterators.enumerateKeysWithPrefix(syscall,prefix)){\\nsyscall.vatstoreDelete(key);\\nconst parts=key.split('|');\\ndoMoreGC=deleteCollectionEntry(parts[1],vref)||doMoreGC;}\\n\\nreturn doMoreGC;}\\n\\n\\nfunction isVrefRecognizable(vref){\\nif(vrefRecognizers.has(vref)){\\nreturn true;}else\\n{\\nreturn vatstoreIterators.prefixedKeysExist(syscall,`vom.ir.${vref}|`);}}\\n\\n\\n\\nfunction finalizeDroppedCollection({descriptor}){\\n/* the 'wr' WeakRef will be dropped about now*/\\n/**/\\n/* note: technically, the engine is allowed to inspect this*/\\n/* callback, observe that 'wr' is not extracted, and then not*/\\n/* retain it in the first place (back in*/\\n/* registerDroppedCollection), but no engine goes that far*/\\ndescriptor.collectionDeleter(descriptor);}\\n\\n\\nfunction vrefKey(value){\\nconst vobjID=getSlotForVal(value);\\nif(vobjID){\\nconst{type,virtual,durable,allocatedByVat}=parseVatSlots.parseVatSlot(vobjID);\\nif(type==='object'&&(virtual||durable||!allocatedByVat)){\\nreturn vobjID;}}\\n\\n\\nreturn undefined;}\\n\\n\\nfunction countCollectionsForWeakKey(vref){\\nconst recognizerSet=vrefRecognizers.get(vref);\\nlet size=recognizerSet?recognizerSet.size:0;\\nconst prefix=`vom.ir.${vref}|`;\\n/* eslint-disable-next-line no-underscore-dangle*/\\nfor(const _key of vatstoreIterators.enumerateKeysWithPrefix(syscall,prefix)){\\nsize+=1;}\\n\\nreturn size;}\\n\\n\\n/**\\n * Counters to track the next number for various categories of allocation.\\n * `exportID` starts at 1 because 'o+0' is always automatically\\n * pre-assigned to the root object.\\n * `promiseID` starts at 5 as a very minor aid to debugging: when puzzling\\n * over trace logs and the like, it helps for the numbers in various species\\n * of IDs that are jumbled together to be a little out of sync and thus a\\n * little less similar to each other.\\n */\\nconst initialIDCounters={exportID:1,collectionID:1,promiseID:5};\\n/** @type {Record<string, number>} */\\nlet idCounters;\\nlet idCountersAreDirty=false;\\n\\nfunction initializeIDCounters(){\\nif(!idCounters){\\n/* the saved value might be missing, or from an older liveslots*/\\n/* (with fewer counters), so merge it with our initial values*/\\nconst saved=JSON.parse(syscall.vatstoreGet('idCounters')||'{}');\\nidCounters={...initialIDCounters,...saved};\\nidCountersAreDirty=true;}}\\n\\n\\n\\nfunction allocateNextID(name){\\nif(!idCounters){\\n/* Normally `initializeIDCounters` would be called from startVat, but some*/\\n/* tests bypass that so this is a backstop. Note that the invocation from*/\\n/* startVat is there to make vatStore access patterns a bit more*/\\n/* consistent from one vat to another, principally as a confusion*/\\n/* reduction measure in service of debugging; it is not a correctness*/\\n/* issue.*/\\ninitializeIDCounters();}\\n\\nconst result=idCounters[name];\\nresult!==undefined||index.throwRedacted`unknown idCounters[${name}]`;\\nidCounters[name]+=1;\\nidCountersAreDirty=true;\\nreturn result;}\\n\\n\\nfunction flushIDCounters(){\\nif(idCountersAreDirty){\\nsyscall.vatstoreSet('idCounters',JSON.stringify(idCounters));\\nidCountersAreDirty=false;}}\\n\\n\\n\\nconst testHooks={\\ngetReachableRefCount,\\ncountCollectionsForWeakKey,\\n\\n/* don't harden() the mock FR, that will break it*/\\ngetDroppedCollectionRegistry:()=>droppedCollectionRegistry,\\nremotableRefCounts,\\nvrefRecognizers,\\nkindInfoTable};\\n\\n\\nfunction getRetentionStats(){\\nreturn{\\nremotableRefCounts:remotableRefCounts.size,\\nvrefRecognizers:vrefRecognizers.size,\\nkindInfoTable:kindInfoTable.size};}\\n\\n\\n\\nreturn harden({\\nregisterDroppedCollection,\\nisDurable,\\nisDurableKind,\\nregisterKind,\\nrememberFacetNames,\\ngetFacet,\\ngetFacetNames,\\nreanimate,\\naddReachableVref,\\nremoveReachableVref,\\nupdateReferenceCounts,\\ngetReachablePromiseRefCount,\\naddRecognizableValue,\\nremoveRecognizableVref,\\nremoveRecognizableValue,\\nvrefKey,\\nisPresenceReachable,\\nisVrefRecognizable,\\nsetExportStatus,\\nisVirtualObjectReachable,\\ndeleteVirtualObject,\\nceaseRecognition,\\nsetDeleteCollectionEntry,\\ngetRetentionStats,\\ninitializeIDCounters,\\nallocateNextID,\\nflushIDCounters,\\ntestHooks});}\\n\\n\\n/** @typedef {ReturnType<typeof makeVirtualReferenceManager>} VirtualReferenceManager */exports.makeVirtualReferenceManager=makeVirtualReferenceManager;\",\n \"packages/swingset-liveslots/src/watchedPromises.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var index=require('../../../node_modules/@endo/errors/index.js');var noShim=require('../../../node_modules/@endo/eventual-send/src/no-shim.js');require('../../store/src/index.js');var parseVatSlots=require('./parseVatSlots.js');var patternMatchers=require('../../../node_modules/@endo/patterns/src/patterns/patternMatchers.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nexoMakers=require('../../../node_modules/@endo/exo/src/exo-makers.js');/* @ts-check*/ /**\\n * @template V\\n * @template {any[]} [A=unknown[]]\\n * @typedef {[watcher: IMPORT('./types.js').PromiseWatcher<V, A>, ...args: A]} PromiseWatcherTuple\\n */ /**\\n * @param {object} options\\n * @param {*} options.syscall\\n * @param {IMPORT('./virtualReferences.js').VirtualReferenceManager} options.vrm\\n * @param {IMPORT('./virtualObjectManager.js').VirtualObjectManager} options.vom\\n * @param {*} options.collectionManager\\n * @param {IMPORT('@endo/marshal').ConvertValToSlot<any>} options.convertValToSlot\\n * @param {IMPORT('@endo/marshal').ConvertSlotToVal<any>} options.convertSlotToVal\\n * @param {(vref: any) => boolean} options.maybeExportPromise\\n */function makeWatchedPromiseManager({syscall,vrm,vom,\\ncollectionManager,\\nconvertValToSlot,\\nconvertSlotToVal,\\nmaybeExportPromise})\\n{\\nconst{makeScalarBigMapStore}=collectionManager;\\nconst{defineDurableKind}=vom;\\n\\n/**\\n * virtual Store (not durable) mapping vpid to Promise objects, to\\n * maintain the slotToVal registration until resolution. Without\\n * this, slotToVal would forget local Promises that aren't exported.\\n *\\n * @type {MapStore<string, Promise<unknown>>}\\n */\\nlet promiseRegistrations;\\n\\n/**\\n * watched promises by vpid: each entry is an array of watches on the\\n * corresponding vpid; each of these is in turn an array of a watcher object\\n * and the arguments associated with it by `watchPromise`.\\n * @type {MapStore<string, PromiseWatcherTuple<unknown>[]>}\\n */\\nlet watchedPromiseTable;\\n\\n/**\\n * defined promise watcher objects indexed by kindHandle\\n *\\n * @type {MapStore<IMPORT('./vatDataTypes.js').DurableKindHandle, IMPORT('./types.js').PromiseWatcher<unknown>>}\\n */\\nlet promiseWatcherByKindTable;\\n\\nfunction preparePromiseWatcherTables(){\\npromiseRegistrations=makeScalarBigMapStore('promiseRegistrations');\\nlet watcherTableID=syscall.vatstoreGet('watcherTableID');\\nif(watcherTableID){\\npromiseWatcherByKindTable=convertSlotToVal(watcherTableID);}else\\n{\\npromiseWatcherByKindTable=makeScalarBigMapStore(\\n'promiseWatcherByKind',\\n{durable:true});\\n\\nwatcherTableID=convertValToSlot(promiseWatcherByKindTable);\\nsyscall.vatstoreSet('watcherTableID',watcherTableID);\\n/* artificially increment the table's refcount so it never gets GC'd*/\\nvrm.addReachableVref(watcherTableID);}\\n\\n\\nlet watchedPromiseTableID=syscall.vatstoreGet('watchedPromiseTableID');\\nif(watchedPromiseTableID){\\nwatchedPromiseTable=convertSlotToVal(watchedPromiseTableID);}else\\n{\\nwatchedPromiseTable=makeScalarBigMapStore('watchedPromises',{\\nkeyShape:patternMatchers.M.string(),/* key is always a vpid*/\\ndurable:true});\\n\\nwatchedPromiseTableID=convertValToSlot(watchedPromiseTable);\\nsyscall.vatstoreSet('watchedPromiseTableID',watchedPromiseTableID);\\n/* artificially increment the table's refcount so it never gets GC'd*/\\nvrm.addReachableVref(watchedPromiseTableID);}}\\n\\n\\n\\n/**\\n * @template T\\n * @param {Promise<T>} p\\n * @param {string} vpid\\n * @returns {void}\\n */\\nfunction pseudoThen(p,vpid){\\n/**\\n *\\n * @param {T} value\\n * @param {boolean} wasFulfilled\\n */\\nfunction settle(value,wasFulfilled){\\nconst watches=watchedPromiseTable.get(vpid);\\nwatchedPromiseTable.delete(vpid);\\npromiseRegistrations.delete(vpid);\\nfor(const watch of watches){\\nconst[watcher,...args]=watch;\\nvoid Promise.resolve().then(()=>{\\nif(wasFulfilled){\\nif(watcher.onFulfilled){\\nwatcher.onFulfilled(value,...args);}}else\\n\\n{\\nif(watcher.onRejected){\\nwatcher.onRejected(value,...args);}else\\n{\\nthrow value;/* for host's unhandled rejection handler to catch*/}}});}}\\n\\n\\n\\n\\n\\n\\nvoid noShim.E.when(\\np,\\n(res)=>settle(res,true),\\n(rej)=>settle(rej,false));}\\n\\n\\n\\n/**\\n * Revives watched promises.\\n *\\n * @param {(vref: any) => Promise<any>} revivePromise\\n * @returns {void}\\n */\\nfunction loadWatchedPromiseTable(revivePromise){\\nfor(const vpid of watchedPromiseTable.keys()){\\nif(promiseRegistrations.has(vpid)){\\n/* We're only interested in reconnecting the promises from the previous*/\\n/* incarnation. Any promise watched during buildRootObject would have*/\\n/* already created a registration.*/\\ncontinue;}\\n\\nconst p=revivePromise(vpid);\\npromiseRegistrations.init(vpid,p);\\npseudoThen(p,vpid);}}\\n\\n\\n\\n/**\\n * @template V\\n * @template {any[]} A]\\n * @param {IMPORT('./vatDataTypes.js').DurableKindHandle} kindHandle\\n * @param {(value: V, ...args: A) => void} fulfillHandler\\n * @param {(reason: any, ...args: A) => void} rejectHandler\\n * @returns {IMPORT('./types.js').PromiseWatcher<V, A>}\\n */\\nfunction providePromiseWatcher(\\nkindHandle,\\n/* @ts-expect-error xxx rest params in typedef*/\\nfulfillHandler=(_value)=>{\\n/* It's fine to not pass the value through since promise watchers are not chainable*/},\\n\\n/* @ts-expect-error xxx rest params in typedef*/\\nrejectHandler=(reason)=>{\\n/* Replicate the unhandled rejection that would have happened if the*/\\n/* watcher had not implemented an `onRejected` method. See `settle` above*/\\nthrow reason;})\\n\\n{\\nindex.assert.typeof(fulfillHandler,'function');\\nindex.assert.typeof(rejectHandler,'function');\\n\\nconst makeWatcher=defineDurableKind(kindHandle,exoMakers.initEmpty,{\\n/** @type {(context: unknown, res: V, ...args: A) => void} */\\nonFulfilled:(_context,res,...args)=>fulfillHandler(res,...args),\\n/** @type {(context: unknown, rej: unknown, ...args: A) => void} */\\nonRejected:(_context,rej,...args)=>rejectHandler(rej,...args)});\\n\\n\\nif(promiseWatcherByKindTable.has(kindHandle)){\\nreturn promiseWatcherByKindTable.get(kindHandle);}else\\n{\\nconst watcher=makeWatcher();\\npromiseWatcherByKindTable.init(kindHandle,watcher);\\nreturn watcher;}}\\n\\n\\n\\n/**\\n * @type {<P extends Promise<any>, A extends any[]>(p: P, watcher: IMPORT('./types.js').PromiseWatcher<Awaited<P>, A>, ...args: A) => void}\\n */\\nfunction watchPromise(p,watcher,...args){\\n/* The following wrapping defers setting up the promise watcher itself to a*/\\n/* later turn so that if the promise to be watched was the return value from*/\\n/* a preceding eventual message send, then the assignment of a vpid to that*/\\n/* promise, which happens in a turn after the initiation of the send, will*/\\n/* have happened by the time the code below executes, and thus when we call*/\\n/* `convertValToSlot` on the promise here we'll get back the vpid that was*/\\n/* assigned rather than generating a new one that nobody knows about.*/\\n\\n/* TODO: add vpid->p virtual table mapping, to keep registration alive*/\\n/* TODO: remove mapping upon resolution*/\\n/* maybe check importedVPIDs here and add to table if !has*/\\nvoid Promise.resolve().then(()=>{\\nconst watcherVref=convertValToSlot(watcher);\\nindex.assert(watcherVref,'invalid watcher');\\nconst{virtual,durable}=parseVatSlots.parseVatSlot(watcherVref);\\nvirtual||\\ndurable||\\n/* separate line so easy to breakpoint on*/\\nindex.throwRedacted`promise watcher must be a virtual object`;\\nif(watcher.onFulfilled){\\nindex.assert.typeof(watcher.onFulfilled,'function');}\\n\\nif(watcher.onRejected){\\nindex.assert.typeof(watcher.onRejected,'function');}\\n\\nindex.assert(\\nwatcher.onFulfilled||watcher.onRejected,\\n'promise watcher must implement at least one handler method');\\n\\n\\nconst vpid=convertValToSlot(p);\\nindex.assert(vpid,'invalid promise');\\nconst{type}=parseVatSlots.parseVatSlot(vpid);\\nindex.assert(type==='promise','watchPromise only watches promises');\\nif(watchedPromiseTable.has(vpid)){\\nconst watches=watchedPromiseTable.get(vpid);\\nwatchedPromiseTable.set(vpid,harden([...watches,[watcher,...args]]));}else\\n{\\nwatchedPromiseTable.init(vpid,harden([[watcher,...args]]));\\n\\n/* Ensure that this vat's promises are rejected at termination.*/\\nif(maybeExportPromise(vpid)){\\nsyscall.subscribe(vpid);}\\n\\n\\npromiseRegistrations.init(vpid,p);\\npseudoThen(p,vpid);}});}\\n\\n\\n\\n\\nreturn harden({\\npreparePromiseWatcherTables,\\nloadWatchedPromiseTable,\\nprovidePromiseWatcher,\\nwatchPromise});}exports.makeWatchedPromiseManager=makeWatchedPromiseManager;\",\n \"packages/swingset-xsnap-supervisor/lib/entry.js\": \"'use strict';require('./supervisor-subprocess-xsnap.js');\",\n \"packages/swingset-xsnap-supervisor/lib/gc-and-finalize.js\": \"'use strict';\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nObject.defineProperty(exports,'__esModule',{value:true});/* global setImmediate */ /* A note on our GC terminology:\\n *\\n * We define four states for any JS object to be in:\\n *\\n * REACHABLE: There exists a path from some root (live export or top-level\\n * global) to this object, making it ineligible for collection. Userspace vat\\n * code has a strong reference to it (and userspace is not given access to\\n * WeakRef, so it has no weak reference that might be used to get access).\\n *\\n * UNREACHABLE: There is no strong reference from a root to the object.\\n * Userspace vat code has no means to access the object, although liveslots\\n * might (via a WeakRef). The object is eligible for collection, but that\\n * collection has not yet happened. The liveslots WeakRef is still alive: if\\n * it were to call `.deref()`, it would get the object.\\n *\\n * COLLECTED: The JS engine has performed enough GC to notice the\\n * unreachability of the object, and has collected it. The liveslots WeakRef\\n * is dead: `wr.deref() === undefined`. Neither liveslots nor userspace has\\n * any way to reach the object, and never will again. A finalizer callback\\n * has been queued, but not yet executed.\\n *\\n * FINALIZED: The JS engine has run the finalizer callback. Once the\\n * callback completes, the object is thoroughly dead and unremembered,\\n * and no longer exists in one of these four states.\\n *\\n * The transition from REACHABLE to UNREACHABLE always happens as a result of\\n * a message delivery or resolution notification (e.g when userspace\\n * overwrites a variable, deletes a Map entry, or a callback on the promise\\n * queue which closed over some objects is retired and deleted).\\n *\\n * The transition from UNREACHABLE to COLLECTED can happen spontaneously, as\\n * the JS engine decides it wants to perform GC. It will also happen\\n * deliberately if we provoke a GC call with a magic function like `gc()`\\n * (when Node.js imports `engine-gc`, which is morally-equivalent to\\n * running with `--expose-gc`, or when XS is configured to provide it as a\\n * C-level callback). We can force GC, but we cannot prevent it from happening\\n * at other times.\\n *\\n * FinalizationRegistry callbacks are defined to run on their own turn, so\\n * the transition from COLLECTED to FINALIZED occurs at a turn boundary.\\n * Node.js appears to schedule these finalizers on the timer/IO queue, not\\n * the promise/microtask queue. So under Node.js, you need a `setImmediate()`\\n * or two to ensure that finalizers have had a chance to run. XS is different\\n * but responds well to similar techniques.\\n */ /* * `gcAndFinalize` must be defined in the start compartment. It uses\\n * platform-specific features to provide a function which provokes a full GC\\n * operation: all \\\"UNREACHABLE\\\" objects should transition to \\\"COLLECTED\\\"\\n * before it returns. In addition, `gcAndFinalize()` returns a Promise. This\\n * Promise will resolve (with `undefined`) after all FinalizationRegistry\\n * callbacks have executed, causing all COLLECTED objects to transition to\\n * FINALIZED. If the caller can manage call gcAndFinalize with an empty\\n * promise queue, then their .then callback will also start with an empty\\n * promise queue, and there will be minimal uncollected unreachable objects\\n * in the heap when it begins.\\n *\\n * `gcAndFinalize` depends upon platform-specific tools to provoke a GC sweep\\n * and wait for finalizers to run: a `gc()` function, and `setImmediate`. If\\n * these tools do not exist, this function will do nothing, and return a\\n * dummy pre-resolved Promise.\\n */function makeGcAndFinalize(gcPower){if(typeof gcPower!=='function'){if(gcPower!==false){/* We weren't explicitly disabled, so warn.*/console.warn(Error(`no gcPower() function; skipping finalizer provocation`));}}return async function gcAndFinalize(){if(typeof gcPower!=='function'){return;}/* on Node.js, GC seems to work better if the promise queue is empty first*/await new Promise(setImmediate);/* on xsnap, we must do it twice for some reason*/await new Promise(setImmediate);gcPower();/* this gives finalizers a chance to run*/await new Promise(setImmediate);/* Node.js seems to need another for promises to get cleared out*/await new Promise(setImmediate);};}exports.makeGcAndFinalize=makeGcAndFinalize;\",\n \"packages/swingset-xsnap-supervisor/lib/supervisor-helper.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});require('../../swingset-liveslots/src/index.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nmessage=require('../../swingset-liveslots/src/message.js');/**\\n * @import {VatDeliveryObject} from '@agoric/swingset-liveslots'\\n * @import {VatDeliveryResult} from '@agoric/swingset-liveslots'\\n * @import {VatSyscallObject} from '@agoric/swingset-liveslots'\\n * @import {VatSyscallHandler} from '@agoric/swingset-liveslots'\\n * @typedef {IMPORT('@endo/marshal').CapData<string>} SwingSetCapData\\n * @typedef { (delivery: VatDeliveryObject) => (VatDeliveryResult | Promise<VatDeliveryResult>) } VatDispatcherSyncAsync\\n * @typedef { (delivery: VatDeliveryObject) => Promise<VatDeliveryResult> } VatDispatcher\\n */ /**\\n * Given the liveslots 'dispatch' function, return a version that never\\n * rejects. It will always return a VatDeliveryResult, even if liveslots\\n * throws or rejects. All supervisors should wrap the liveslots `dispatch`\\n * function with this one, and call it in response to messages from the\\n * manager process.\\n *\\n * @param {VatDispatcherSyncAsync} dispatch\\n * @returns {VatDispatcher}\\n */function makeSupervisorDispatch(dispatch){/**\\n * @param {VatDeliveryObject} delivery\\n * @returns {Promise<VatDeliveryResult>}\\n */async function dispatchToVat(delivery){/* the (low-level) vat is responsible for giving up agency, but we still*/ /* protect against exceptions*/return Promise.resolve(delivery).then(dispatch).then(\\n(res)=>harden(['ok',res,null]),\\n(err)=>{\\n/* TODO react more thoughtfully, maybe terminate the vat*/\\nconsole.warn(`error during vat dispatch() of ${delivery}`,err);\\nreturn harden(['error',`${err}`,null]);});}\\n\\n\\n\\n\\nreturn harden(dispatchToVat);}\\n\\nharden(makeSupervisorDispatch);\\n\\n\\n/**\\n * This returns a function that is provided to liveslots as the 'syscall'\\n * argument: an object with one method per syscall type. These methods return\\n * data, or nothing. If the kernel experiences a problem executing the syscall,\\n * the method will throw, or the kernel will kill the vat, or both.\\n *\\n * I should be given a `syscallToManager` function that accepts a\\n * VatSyscallObject and (synchronously) returns a VatSyscallResult.\\n *\\n * @param {VatSyscallHandler} syscallToManager\\n * @typedef { unknown } TheSyscallObjectWithMethodsThatLiveslotsWants\\n * @returns {TheSyscallObjectWithMethodsThatLiveslotsWants}\\n */\\nfunction makeSupervisorSyscall(syscallToManager){\\nfunction doSyscall(fields){\\nmessage.insistVatSyscallObject(fields);\\n/** @type { VatSyscallObject } */\\nconst vso=harden(fields);\\nlet r;\\ntry{\\nr=syscallToManager(vso);}\\ncatch(err){\\nconsole.warn(`worker got error during syscall:`,err);\\nthrow err;}\\n\\nconst vsr=r;\\nmessage.insistVatSyscallResult(vsr);\\nconst[type,...rest]=vsr;\\nswitch(type){\\ncase'ok':{\\nconst[data]=rest;\\nreturn data;}\\n\\ncase'error':{\\nconst[err]=rest;\\nthrow Error(`syscall.${fields[0]} failed: ${err}`);}\\n\\ndefault:\\nthrow Error(`unknown result type ${type}`);}}\\n\\n\\n\\n/* this will be given to liveslots, it should have distinct methods that*/\\n/* return immediate results or throw errors*/\\nconst syscallForVat={\\n/** @type {(target: string, method: string, args: SwingSetCapData, result?: string) => unknown } */\\nsend:(target,methargs,result)=>\\ndoSyscall(['send',target,{methargs,result}]),\\nsubscribe:(vpid)=>doSyscall(['subscribe',vpid]),\\nresolve:(resolutions)=>doSyscall(['resolve',resolutions]),\\nexit:(isFailure,data)=>doSyscall(['exit',isFailure,data]),\\ndropImports:(vrefs)=>doSyscall(['dropImports',vrefs]),\\nretireImports:(vrefs)=>doSyscall(['retireImports',vrefs]),\\nretireExports:(vrefs)=>doSyscall(['retireExports',vrefs]),\\nabandonExports:(vrefs)=>doSyscall(['abandonExports',vrefs]),\\n\\n/* These syscalls should be omitted if the worker cannot get a*/\\n/* synchronous return value back from the kernel, such as when the worker*/\\n/* is in a child process or thread, and cannot be blocked until the*/\\n/* result gets back. vatstoreSet and vatstoreDelete are included because*/\\n/* vatstoreSet requires a result, and we offer them as a group.*/\\ncallNow:(target,method,args)=>\\ndoSyscall(['callNow',target,method,args]),\\nvatstoreGet:(key)=>{\\nconst result=doSyscall(['vatstoreGet',key]);\\nreturn result===null?undefined:result;},\\n\\nvatstoreGetNextKey:(priorKey)=>doSyscall(['vatstoreGetNextKey',priorKey]),\\nvatstoreSet:(key,value)=>doSyscall(['vatstoreSet',key,value]),\\nvatstoreDelete:(key)=>doSyscall(['vatstoreDelete',key])};\\n\\n\\nreturn harden(syscallForVat);}\\n\\n\\nharden(makeSupervisorSyscall);\\n\\n\\n/**\\n * Create a vat console from a log stream maker.\\n *\\n * TODO: consider other methods per SES VirtualConsole.\\n * See https://github.com/Agoric/agoric-sdk/issues/2146\\n *\\n * @param {(level: string) => (...args: any[]) => void} makeLog\\n */\\nfunction makeVatConsole(makeLog){\\nreturn harden({\\ndebug:makeLog('debug'),\\nlog:makeLog('log'),\\ninfo:makeLog('info'),\\nwarn:makeLog('warn'),\\nerror:makeLog('error')});}\\n\\n\\n\\nharden(makeVatConsole);exports.makeSupervisorDispatch=makeSupervisorDispatch;exports.makeSupervisorSyscall=makeSupervisorSyscall;exports.makeVatConsole=makeVatConsole;\",\n \"packages/swingset-xsnap-supervisor/lib/supervisor-subprocess-xsnap.js\": \"'use strict';var index=require('../../../node_modules/@endo/errors/index.js');var index$1=require('../../../node_modules/@endo/import-bundle/src/index.js');require('../../swingset-liveslots/src/index.js');var waitUntilQuiescent=require('./waitUntilQuiescent.js');var gcAndFinalize=require('./gc-and-finalize.js');var supervisorHelper=require('./supervisor-helper.js');var message=require('../../swingset-liveslots/src/message.js');var\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nliveslots=require('../../swingset-liveslots/src/liveslots.js');/* global globalThis WeakRef FinalizationRegistry */ /**\\n * @import {VatDeliveryObject} from '@agoric/swingset-liveslots'\\n * @import {VatDeliveryResult} from '@agoric/swingset-liveslots'\\n * @import {VatSyscallObject} from '@agoric/swingset-liveslots'\\n * @import {VatSyscallResult} from '@agoric/swingset-liveslots'\\n * @import {VatSyscallHandler} from '@agoric/swingset-liveslots'\\n * @import {LiveSlotsOptions} from '@agoric/swingset-liveslots'\\n * @import {MeterControl} from '@agoric/swingset-liveslots'\\n */\\n\\nconst encoder=new TextEncoder();\\nconst decoder=new TextDecoder();\\n\\n/* eslint-disable-next-line no-unused-vars*/\\nfunction workerLog(first,...args){\\n/* console.log(`---worker: ${first}`, ...args);*/}\\n\\n\\nworkerLog(`supervisor started`);\\n\\nfunction makeMeterControl(){\\nlet meteringDisabled=0;\\n\\nfunction isMeteringDisabled(){\\nreturn!!meteringDisabled;}\\n\\n\\nfunction assertIsMetered(msg){\\nindex.assert(!meteringDisabled,msg);}\\n\\nfunction assertNotMetered(msg){\\nindex.assert(!!meteringDisabled,msg);}\\n\\n\\nfunction runWithoutMetering(thunk){\\nconst limit=globalThis.currentMeterLimit();\\nconst before=globalThis.resetMeter(0,0);\\nmeteringDisabled+=1;\\ntry{\\nreturn thunk();}finally\\n{\\nglobalThis.resetMeter(limit,before);\\nmeteringDisabled-=1;}}\\n\\n\\n\\nasync function runWithoutMeteringAsync(thunk){\\nconst limit=globalThis.currentMeterLimit();\\nconst before=globalThis.resetMeter(0,0);\\nmeteringDisabled+=1;\\nreturn Promise.resolve().\\nthen(()=>thunk()).\\nfinally(()=>{\\nglobalThis.resetMeter(limit,before);\\nmeteringDisabled-=1;});}\\n\\n\\n\\n/* return a version of f that runs outside metering*/\\nfunction unmetered(f){\\nfunction wrapped(...args){\\nreturn runWithoutMetering(()=>f(...args));}\\n\\nreturn harden(wrapped);}\\n\\n\\n/** @type { MeterControl } */\\nconst meterControl={\\nisMeteringDisabled,\\nassertIsMetered,\\nassertNotMetered,\\nrunWithoutMetering,\\nrunWithoutMeteringAsync,\\nunmetered};\\n\\nreturn harden(meterControl);}\\n\\n\\nconst meterControl=makeMeterControl();\\n\\n/**\\n * Wrap byte-level protocols with tagged array codec.\\n *\\n * @param {(cmd: ArrayBuffer) => ArrayBuffer} issueCommand as from xsnap\\n * @typedef { [unknown, ...unknown[]] } Tagged tagged array\\n */\\nfunction managerPort(issueCommand){\\n/** @type { (item: Tagged) => ArrayBuffer } */\\nconst encode=(item)=>{\\nlet txt;\\ntry{\\ntxt=JSON.stringify(item);}\\ncatch(nope){\\nworkerLog(nope.message,item);\\nthrow nope;}\\n\\nreturn encoder.encode(txt).buffer;};\\n\\n\\n/** @type { (msg: ArrayBuffer) => any } */\\nconst decodeData=(msg)=>JSON.parse(decoder.decode(msg)||'null');\\n\\n/** @type { (msg: ArrayBuffer) => Tagged } */\\nfunction decode(msg){\\n/** @type { Tagged } */\\nconst item=decodeData(msg);\\nArray.isArray(item)||index.throwRedacted`expected array`;\\nitem.length>0||index.throwRedacted`empty array lacks tag`;\\nreturn item;}\\n\\n\\nreturn harden({\\n/** @type { (item: Tagged) => void } */\\nsend:(item)=>{\\nissueCommand(encode(item));},\\n\\n/** @type { (item: Tagged) => unknown } */\\ncall:(item)=>decodeData(issueCommand(encode(item))),\\n\\n/**\\n * Wrap an async Tagged handler in the xsnap async reporting idiom.\\n *\\n * @param {(item: Tagged) => Promise<Tagged>} f async Tagged handler\\n * @returns {(msg: ArrayBuffer) => Report<ArrayBuffer>} xsnap style handleCommand\\n *\\n * @typedef { { result?: T } } Report<T> report T when idle\\n * @template T\\n */\\nhandlerFrom(f){\\nconst lastResort=encoder.encode(`exception from ${f.name}`).buffer;\\nreturn(msg)=>{\\nconst report={};\\nf(decode(msg)).\\nthen((item)=>{\\nworkerLog('result',item);\\nreport.result=encode(item);}).\\n\\ncatch((err)=>{\\nreport.result=encode(['err',err.name,err.message]);}).\\n\\ncatch((_err)=>{\\nreport.result=lastResort;});\\n\\nreturn report;};}});}\\n\\n\\n\\n\\n\\n/* please excuse copy-and-paste from kernel.js*/\\nfunction abbreviateReplacer(_,arg){\\nif(typeof arg==='bigint'){\\n/* since testLog is only for testing, 2^53 is enough.*/\\n/* precedent: 32a1dd3*/\\nreturn Number(arg);}\\n\\nif(typeof arg==='string'&&arg.length>=40){\\n/* truncate long strings*/\\nreturn`${arg.slice(0,15)}...${arg.slice(arg.length-15)}`;}\\n\\nreturn arg;}\\n\\n\\n/**\\n * @param {ReturnType<typeof managerPort>} port\\n */\\nfunction makeWorker(port){\\n/** @type { ((delivery: VatDeliveryObject) => Promise<VatDeliveryResult>) | null } */\\nlet dispatch=null;\\n\\n/**\\n * @param {unknown} vatID\\n * @param {unknown} bundle\\n * @param {LiveSlotsOptions} liveSlotsOptions\\n * @returns {Promise<Tagged>}\\n */\\nasync function setBundle(vatID,bundle,liveSlotsOptions){\\n/** @type { VatSyscallHandler } */\\nfunction syscallToManager(vatSyscallObject){\\nworkerLog('doSyscall',vatSyscallObject);\\nconst result=port.call(['syscall',vatSyscallObject]);\\nworkerLog(' ... syscall result:',result);\\nmessage.insistVatSyscallResult(result);\\nreturn result;}\\n\\n\\nconst syscall=supervisorHelper.makeSupervisorSyscall(syscallToManager);\\n\\nconst vatPowers={\\ntestLog:(...args)=>\\nport.send([\\n'testLog',\\n...args.map((arg)=>\\ntypeof arg==='string'?\\narg:\\nJSON.stringify(arg,abbreviateReplacer))])};\\n\\n\\n\\n\\nconst gcTools=harden({\\nWeakRef,\\nFinalizationRegistry,\\nwaitUntilQuiescent:waitUntilQuiescent.waitUntilQuiescent,\\ngcAndFinalize:gcAndFinalize.makeGcAndFinalize(globalThis.gc),\\nmeterControl});\\n\\n\\n/** @param {string} source */\\nconst makeLogMaker=(source)=>{\\n/** @param {string} level */\\nconst makeLog=(level)=>{\\n/* Capture the `console.log`, etc.'s `printAll` function.*/\\nconst printAll=console[level];\\nindex.assert.typeof(printAll,'function');\\nconst portSendingPrinter=(...args)=>{\\nport.send(['sourcedConsole',source,level,...args]);};\\n\\nreturn(...args)=>{\\n/* Use the causal console, but output to the port.*/\\n/**/\\n/* FIXME: This is a hack until the start compartment can create*/\\n/* Console objects that log to a different destination than*/\\n/* `globalThis.console`.*/\\nconst{print:savePrinter}=globalThis;\\ntry{\\nglobalThis.print=portSendingPrinter;\\nprintAll(...args);}finally\\n{\\nglobalThis.print=savePrinter;}};};\\n\\n\\n\\nreturn makeLog;};\\n\\n\\nconst workerEndowments={\\nconsole:supervisorHelper.makeVatConsole(makeLogMaker('vat')),\\n/* See https://github.com/Agoric/agoric-sdk/issues/9515*/\\nassert:globalThis.assert,\\n/* bootstrap provides HandledPromise*/\\nHandledPromise:globalThis.HandledPromise,\\nTextEncoder,\\nTextDecoder,\\nBase64:globalThis.Base64/* Present only in XSnap*/};\\n\\n\\nasync function buildVatNamespace(\\nlsEndowments,\\ninescapableGlobalProperties)\\n{\\nindex.assert(bundle,'bundle undefined (duplicate buildVatNamespace call?)');\\nconst vatNS=await index$1.importBundle(bundle,{\\nendowments:{...workerEndowments,...lsEndowments},\\ninescapableGlobalProperties});\\n\\nbundle=undefined;/* overwrite to allow GC to discard big string*/\\nworkerLog(`got vatNS:`,Object.keys(vatNS).join(','));\\nreturn vatNS;}\\n\\n\\nconst ls=liveslots.makeLiveSlots(\\nsyscall,\\nvatID,\\nvatPowers,\\nliveSlotsOptions,\\ngcTools,\\nsupervisorHelper.makeVatConsole(makeLogMaker('ls')),\\nbuildVatNamespace);\\n\\n\\nindex.assert(ls.dispatch);\\ndispatch=supervisorHelper.makeSupervisorDispatch(ls.dispatch);\\nworkerLog(`got dispatch`);\\nreturn['dispatchReady'];}\\n\\n\\n/** @type { (item: Tagged) => Promise<Tagged> } */\\nasync function handleItem([tag,...args]){\\nworkerLog('handleItem',tag,args.length);\\nswitch(tag){\\ncase'setBundle':{\\nindex.assert(!dispatch,'cannot setBundle again');\\nconst liveSlotsOptions=/** @type LiveSlotsOptions */args[2];\\nreturn setBundle(args[0],args[1],liveSlotsOptions);}\\n\\ncase'deliver':{\\nindex.assert(dispatch,'cannot deliver before setBundle');\\nconst[vatDeliveryObject]=args;\\nharden(vatDeliveryObject);\\nmessage.insistVatDeliveryObject(vatDeliveryObject);\\nreturn dispatch(vatDeliveryObject);}\\n\\ndefault:\\nworkerLog('handleItem: bad tag',tag,args.length);\\nreturn['bad tag',tag];}}\\n\\n\\n\\nreturn harden({\\nhandleItem});}\\n\\n\\n\\n/* xsnap provides issueCommand global*/\\nconst port=managerPort(globalThis.issueCommand);\\nconst worker=makeWorker(port);\\n\\n/* Send unexpected console messages to the manager port.*/\\nglobalThis.print=(...args)=>{\\nport.send(['sourcedConsole','xsnap','error',...args]);};\\n\\n\\nglobalThis.handleCommand=port.handlerFrom(worker.handleItem);\",\n \"packages/swingset-xsnap-supervisor/lib/waitUntilQuiescent.js\": \"'use strict';Object.defineProperty(exports,'__esModule',{value:true});var\\n\\n\\n\\nindex=require('../../../node_modules/@endo/promise-kit/index.js');/* global setImmediate */ /* This can only be imported from the Start Compartment, where 'setImmediate'*/ /* is available.*/\\n\\nfunction waitUntilQuiescent(){\\n/* the delivery might cause some number of (native) Promises to be*/\\n/* created and resolved, so we use the IO queue to detect when the*/\\n/* Promise queue is empty. The IO queue (setImmediate and setTimeout) is*/\\n/* lower-priority than the Promise queue on browsers and Node 11, but on*/\\n/* Node 10 it is higher. So this trick requires Node 11.*/\\n/* https://jsblog.insiderattack.net/new-changes-to-timers-and-microtasks-from-node-v11-0-0-and-above-68d112743eb3*/\\n/** @type {IMPORT('@endo/promise-kit').PromiseKit<void>} */\\nconst{promise:queueEmptyP,resolve}=index.makePromiseKit();\\nsetImmediate(()=>resolve());\\nreturn queueEmptyP;}exports.waitUntilQuiescent=waitUntilQuiescent;\"\n};\n const nsBundle = {};\n\n function createEvalString(filename) {\n const code = sourceBundle[filename];\n if (!code) {\n return undefined;\n }\n return `\\\n(function getExport(require, exports) { \\\n 'use strict'; \\\n const module = { exports }; \\\n \\\n ${code}\n return module.exports;\n})\n//# sourceURL=${filePrefix}/${filename}\n`;\n }\n\n function computeExports(filename, exportPowers, exports) {\n const { require: systemRequire, systemEval, _log } = exportPowers;\n // This captures the endowed require.\n const match = filename.match(/^(.*)\\/[^/]+$/);\n const thisdir = match ? match[1] : '.';\n const contextRequire = mod => {\n // Do path algebra to find the actual source.\n const els = mod.split('/');\n let prefix;\n if (els[0][0] === '@') {\n // Scoped name.\n prefix = els.splice(0, 2).join('/');\n } else if (els[0][0] === '.') {\n // Relative.\n els.unshift(...thisdir.split('/'));\n } else {\n // Bare or absolute.\n prefix = els.splice(0, 1);\n }\n\n const suffix = [];\n for (const el of els) {\n if (el === '.' || el === '') {\n // Do nothing.\n } else if (el === '..') {\n // Traverse upwards.\n suffix.pop();\n } else {\n suffix.push(el);\n }\n }\n\n // log(mod, prefix, suffix);\n if (prefix !== undefined) {\n suffix.unshift(prefix);\n }\n let modPath = suffix.join('/');\n if (modPath.startsWith('./')) {\n modPath = modPath.slice(2);\n }\n // log('requiring', modPath);\n if (!(modPath in nsBundle)) {\n // log('evaluating', modPath);\n // Break cycles, but be tolerant of modules\n // that completely override their exports object.\n nsBundle[modPath] = {};\n nsBundle[modPath] = computeExports(\n modPath,\n exportPowers,\n nsBundle[modPath],\n );\n }\n\n // log('returning', nsBundle[modPath]);\n return nsBundle[modPath];\n };\n\n const code = createEvalString(filename);\n if (!code) {\n // log('missing code for', filename, sourceBundle);\n if (systemRequire) {\n return systemRequire(filename);\n }\n throw Error(\n `require(${JSON.stringify(\n filename,\n )}) failed; no toplevel require endowment`,\n );\n }\n\n // log('evaluating', code);\n // eslint-disable-next-line no-eval\n return (systemEval || eval)(code)(contextRequire, exports);\n }\n\n // Evaluate the entrypoint recursively, seeding the exports.\n const systemRequire = typeof require === 'undefined' ? undefined : require;\n const systemEval = typeof nestedEvaluate === 'undefined' ? undefined : nestedEvaluate;\n return computeExports(entrypoint, { require: systemRequire, systemEval }, {});\n}\n//# sourceURL=/bundled-source/...-preamble.js\n","sourceMap":"//# sourceURL=/bundled-source/...-preamble.js\n"}
|