@runeditrun/rer 0.2.124 → 0.2.126

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/README.md CHANGED
@@ -434,6 +434,9 @@ Licence: MIT.
434
434
 
435
435
  First-party commands acquire the exact `packageManager` pnpm pin when PATH lacks
436
436
  it, verify its registry sha512 integrity and cache it under `$HOME/.rer/pnpm`.
437
+ The verified tool's version check keeps three attempts. Their 10, 20 and
438
+ 30 second deadlines scale with one-minute load per CPU, up to four times.
439
+ If the check fails, rer reports what pnpm did and the final attempt's deadline.
437
440
  No global package manager installation or sudo is needed. Independent projects
438
441
  continue to run their declared commands with their own tools. Server and job
439
442
  state default to `$HOME/.rer/servers` and `$HOME/.rer/jobs`; supplied
@@ -1,22 +1,22 @@
1
1
  import { DatabaseSync } from 'node:sqlite';
2
2
  import { realpath, readFile, readdir } from 'node:fs/promises';
3
3
  import { resolve, relative, isAbsolute, sep } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
4
5
  import { migrationDirectory } from './portability-migrations.mjs';
5
6
  import { ownerMigrationSources } from './portability-owners.mjs';
6
7
  import { collectMigrations } from '../modules/delivery-producer/migrations.mjs';
7
8
  import { splitStatements } from '../modules/portability/sql-text.mjs';
8
9
  import { canonicalJson, sha256 } from '../modules/portability/hash.mjs';
9
- import { quote, insist } from '../modules/portability/storage.mjs';
10
- import { dataStatement, triggerBodies } from '../modules/portability/migration-statements.mjs';
11
- import { sqliteTokens } from '../modules/portability/sqlite-tokens.mjs';
10
+ import { insist } from '../modules/portability/storage.mjs';
11
+ import { migrationRecorder } from '../modules/portability/migration-evidence.mjs';
12
12
 
13
- // Date functions can default to 'now'; even fixed arguments are conservatively
14
- // excluded from seeded-row evidence. Their schema and statements remain intact.
15
- const variable=sql=>/\b(?:random|randomblob|date|time|datetime|julianday|strftime|unixepoch|sqlite_version|sqlite_source_id)\s*\(|\bcurrent_(?:date|time|timestamp)\b/i.test(sqliteTokens(sql).map(t=>t.value).join(' '));
13
+ const wasmPath = fileURLToPath(new URL('./vendor/wa-sqlite/wa-sqlite.wasm', import.meta.url));
14
+ const sqlitePath = fileURLToPath(new URL('./portability-sqlite.mjs', import.meta.url));
15
+ const ownerHistoryPath = fileURLToPath(new URL('../modules/portability/worker-owner-history.mjs', import.meta.url));
16
16
 
17
17
  // Only migration-owned schema and hashed seeded-row identities enter the bundle.
18
18
  // Never open a live database, settings file, archive, or archive-supplied path.
19
- export async function generateMigrationEvidence(root,{binding='DB'}={}) {
19
+ async function migrationEvidence(root,{binding='DB'}={}) {
20
20
  root=await realpath(root);
21
21
  const directory=await realpath(await migrationDirectory(root,binding));
22
22
  const path=relative(root,directory);
@@ -28,51 +28,53 @@ export async function generateMigrationEvidence(root,{binding='DB'}={}) {
28
28
  return {name,sha256:await sha256(bytes),statements:splitStatements(bytes.toString('utf8'))};
29
29
  }));
30
30
  const sources=await ownerMigrationSources(root,binding);
31
- const owners=await collectMigrations(root,sources.filter(source=>source.directory).map(({directory,prefix})=>({binding,path:directory,prefix})),[{kind:'d1',binding}]);
32
- for(const {name,sha256,sql} of owners) {
33
- insist(!files.some(file=>file.name===name),'migration_ledger:ambiguous',409);
34
- files.push({name,sha256,statements:splitStatements(sql)});
31
+ const ownerFiles = (await Promise.all(sources.filter(source => source.directory).map(async ({directory,prefix,table}) => {
32
+ const owners = await collectMigrations(root, [{binding,path:directory,prefix}], [{kind:'d1',binding}]);
33
+ return owners.map(({name,sha256,sql}) => ({name,sha256,statements:splitStatements(sql),table}));
34
+ }))).flat();
35
+ const ownerSources = sources.map(({prefix,table})=>({prefix,table}));
36
+ if (ownerFiles.length) {
37
+ const declared = new Set(files.map(file => file.name));
38
+ for (const file of ownerFiles) {
39
+ insist(!declared.has(file.name),'migration_ledger:ambiguous',409);
40
+ declared.add(file.name);
41
+ files.push(file);
42
+ }
43
+ return {version:2,files,ownerSources};
35
44
  }
45
+ const evidence = await bundledPrefixes(files);
46
+ if (ownerSources.length) evidence.ownerSources = ownerSources;
47
+ return evidence;
48
+ }
49
+
50
+ async function bundledPrefixes(files) {
36
51
  const objects=[],indices=new Map(),prefixes=[];
37
52
  const scratch=new DatabaseSync(':memory:');
38
53
  try {
39
- // Volatile defaults, trigger bodies and reads propagate to their writers.
40
- // Such rows cannot equal a fresh library replay reliably either. Preserve
41
- // deterministic seeds in unrelated tables, and empty evidence everywhere.
42
- const unstable=new Set(),applied=[];
54
+ const recorder=migrationRecorder({exec:sql=>scratch.exec(sql),all:sql=>scratch.prepare(sql).all()});
43
55
  const capture=async()=>{
44
- const schema=scratch.prepare("SELECT name,sql,type,tbl_name FROM sqlite_master WHERE sql IS NOT NULL AND substr(lower(name),1,7)<>'sqlite_' AND substr(lower(name),1,4)<>'_cf_' ORDER BY name,type").all();
56
+ const {objects:schema,kinds}=recorder.inventory();
45
57
  const refs=schema.map(object=>{
46
58
  const key=canonicalJson(object);if(!indices.has(key)){indices.set(key,objects.length);objects.push(object);}return indices.get(key);
47
59
  });
48
- const shadows=scratch.prepare('PRAGMA table_list').all().filter(t=>t.type==='shadow').map(t=>t.name).sort();
49
- const seeds=[];
50
- for(const {name} of schema.filter(o=>o.type==='table')) {
51
- const columns=scratch.prepare(`PRAGMA table_info(${quote(name)})`).all().map(c=>c.name);
52
- const rows=scratch.prepare(`SELECT json_array(${columns.map(c=>`quote(${quote(c)})`).join(',')}) image FROM ${quote(name)} LIMIT 10001`).all().map(r=>r.image);
53
- if(rows.length>10000 || unstable.has(name.toLowerCase()) && rows.length)continue;
54
- seeds.push({name,columns,hashes:(await Promise.all(rows.map(sha256))).sort()});
55
- }
56
- prefixes.push({objects:refs,shadows,seeds});
60
+ prefixes.push({objects:refs,shadows:kinds.map(kind=>kind.name).sort(),seeds:await recorder.seeds(schema)});
57
61
  };
58
62
  await capture();
59
63
  for(const file of files) {
60
- for(const sql of file.statements) {
61
- const data=dataStatement(sql);
62
- if(data) {
63
- const writers=new Set([data.target]);
64
- for(const name of writers)for(const target of triggerBodies(applied,name))writers.add(target);
65
- const definitions=scratch.prepare("SELECT name,sql FROM sqlite_master WHERE sql IS NOT NULL").all();
66
- if(variable(sql) || data.names.some(n=>unstable.has(n)) || definitions.some(d=>writers.has(d.name.toLowerCase()) && variable(d.sql))
67
- || applied.some(s=>variable(s) && [...writers].some(n=>triggerBodies([s],data.target).includes(n))))for(const name of writers)unstable.add(name);
68
- }
69
- scratch.exec(sql);
70
- applied.push(sql);
71
- }
64
+ recorder.apply(file);
72
65
  await capture();
73
66
  }
74
67
  }finally{scratch.close();}
75
- return {version:1,files,objects,prefixes,...(sources.length?{ownerSources:sources.map(({prefix,table})=>({prefix,table}))}:{})};
68
+ return {version:1,files,objects,prefixes};
69
+ }
70
+
71
+ export async function generateMigrationEvidence(root,options) {
72
+ const evidence = await migrationEvidence(root,options);
73
+ if (evidence.version === 1) return evidence;
74
+ const [{sqliteMemory}, {workerOwnerEvidence}] = await Promise.all([
75
+ import('./portability-sqlite.mjs'), import('../modules/portability/worker-owner-history.mjs'),
76
+ ]);
77
+ return workerOwnerEvidence(evidence, sqliteMemory(await WebAssembly.compile(await readFile(wasmPath))));
76
78
  }
77
79
 
78
80
  // Explicit seed opt-in. The module is consumed only by the server/Worker graph;
@@ -87,7 +89,12 @@ export function legacyMigrationEvidence({binding='DB'}={}) {
87
89
  async load(source){
88
90
  if(source!==internal)return;
89
91
  if(this.environment?.name==='client')throw new Error('Legacy migration evidence is server-only.');
90
- return 'export default '+canonicalJson(await generateMigrationEvidence(root,{binding}))+';';
92
+ const evidence = await migrationEvidence(root,{binding});
93
+ if (evidence.version === 1) return 'export default '+canonicalJson(evidence)+';';
94
+ return `import wasm from ${JSON.stringify(wasmPath)};
95
+ import { sqliteMemory } from ${JSON.stringify(sqlitePath)};
96
+ import { workerOwnerEvidence } from ${JSON.stringify(ownerHistoryPath)};
97
+ export default workerOwnerEvidence(${canonicalJson(evidence)}, sqliteMemory(wasm));`;
91
98
  },
92
99
  };
93
100
  }
@@ -6,7 +6,7 @@ import { destinationLedger, ledgerNames, matchMigrationLedger } from '../modules
6
6
  import { all, insist, PortabilityError } from '../modules/portability/storage.mjs';
7
7
  import {migrationDirectory} from '../modules/deploy-kit/migration-directory.mjs';
8
8
  import { collectMigrations } from '../modules/delivery-producer/migrations.mjs';
9
- import { nativeMigrationHistory } from './portability-owners.mjs';
9
+ import { nativeMigrationHistory, requireAppliedOwnerFiles } from '../modules/portability/owner-history.mjs';
10
10
  export {migrationDirectory};
11
11
 
12
12
  // Seed-owned declarations, never archive metadata: the deploymentSpec prefix
@@ -40,6 +40,7 @@ export async function migrationInventory(root,binding,{prefix},split,sources=[])
40
40
  // Preserve the runner's applied order, resolving file identities by hash.
41
41
  export async function appliedMigrations(root,db,binding,declaration,split,sources=[]) {
42
42
  const history=await nativeMigrationHistory(db,sources),files=await migrationInventory(root,binding,declaration,split,sources);
43
+ requireAppliedOwnerFiles(history,files);
43
44
  return matchMigrationLedger(history?.entries ?? [],files,declaration).map(name=>files.find(file=>file.name===name));
44
45
  }
45
46
 
@@ -127,6 +128,7 @@ export async function nativeMigrationPreflight({root,db,binding='DB',platformMig
127
128
  if(ownerSources.length && table!=='rer_migrations') {
128
129
  const history=await nativeMigrationHistory(db,ownerSources);
129
130
  const allFiles=await migrationInventory(root,binding,declaration,undefined,ownerSources);
131
+ requireAppliedOwnerFiles(history,allFiles);
130
132
  try { matchMigrationLedger(history.entries,allFiles,declaration); }
131
133
  catch(error) { throw constantRefusal(error,allFiles); }
132
134
  }
@@ -0,0 +1,72 @@
1
+ import initSQLite from './vendor/wa-sqlite/wa-sqlite.mjs';
2
+
3
+ const SQLITE_ROW = 100, SQLITE_DONE = 101;
4
+
5
+ // A compiled module is supplied by the Worker bundle. Each replay opens its
6
+ // own database in memory and executes only the checkout's bundled statements.
7
+ export function sqliteMemory(module) {
8
+ let ready;
9
+ return async function openDatabase() {
10
+ const sqlite = await (ready ??= initSQLite({
11
+ instantiateWasm(imports, accept) {
12
+ const instance = new WebAssembly.Instance(module, imports);
13
+ accept(instance, module);
14
+ return instance.exports;
15
+ },
16
+ }));
17
+ const pointer = sqlite._malloc(4);
18
+ if (!pointer) throw Error('Cannot allocate SQLite handle');
19
+ let db;
20
+ const check = code => {
21
+ if (code !== 0) throw Error(sqlite.UTF8ToString(sqlite._sqlite3_errmsg(db)));
22
+ };
23
+ const withSql = (sql, operation) => {
24
+ const size = sqlite.lengthBytesUTF8(sql) + 1, text = sqlite._malloc(size);
25
+ if (!text) throw Error('Cannot allocate SQLite statement');
26
+ try {
27
+ sqlite.stringToUTF8(sql, text, size);
28
+ check(operation(text));
29
+ } finally {
30
+ sqlite._free(text);
31
+ }
32
+ };
33
+ const exec = sql => withSql(sql, text => sqlite._sqlite3_exec(db, text, 0, 0, 0));
34
+ try {
35
+ const code = sqlite.ccall('sqlite3_open', 'number', ['string', 'number'], [':memory:', pointer]);
36
+ db = sqlite.getValue(pointer, '*');
37
+ check(code);
38
+ exec('PRAGMA foreign_keys=ON');
39
+ } catch (error) {
40
+ if (db) sqlite._sqlite3_close(db);
41
+ sqlite._free(pointer);
42
+ throw error;
43
+ }
44
+ return {
45
+ exec,
46
+ all(sql) {
47
+ withSql(sql, text => sqlite._sqlite3_prepare_v2(db, text, -1, pointer, 0));
48
+ const statement = sqlite.getValue(pointer, '*');
49
+ try {
50
+ const columns = Array.from({ length: sqlite._sqlite3_column_count(statement) }, (_, index) =>
51
+ sqlite.UTF8ToString(sqlite._sqlite3_column_name(statement, index)));
52
+ const rows = [];
53
+ let code;
54
+ while ((code = sqlite._sqlite3_step(statement)) === SQLITE_ROW) {
55
+ rows.push(Object.fromEntries(columns.map((name, index) => {
56
+ const value = sqlite._sqlite3_column_text(statement, index);
57
+ return [name, value ? sqlite.UTF8ToString(value) : null];
58
+ })));
59
+ }
60
+ if (code !== SQLITE_DONE) check(code);
61
+ return rows;
62
+ } finally {
63
+ sqlite._sqlite3_finalize(statement);
64
+ }
65
+ },
66
+ close() {
67
+ sqlite._sqlite3_close(db);
68
+ sqlite._free(pointer);
69
+ },
70
+ };
71
+ };
72
+ }
@@ -2,7 +2,7 @@
2
2
  // The verified cache is private to rer; the resulting PATH travels to children.
3
3
  import { mkdtemp, readFile, rm } from 'node:fs/promises';
4
4
  import { delimiter, dirname, join } from 'node:path';
5
- import { homedir, tmpdir } from 'node:os';
5
+ import { availableParallelism, homedir, loadavg, tmpdir } from 'node:os';
6
6
  import { setTimeout as delay } from 'node:timers/promises';
7
7
  import { cachedPnpm, downloadPnpm } from './pnpm-runtime.mjs';
8
8
  import { missing, RerError } from './errors.mjs';
@@ -63,14 +63,16 @@ async function ensure(root, { env = process.env, signal, report = () => {}, stor
63
63
  const supplied = { ...env, RER_PNPM_ENTRY: join(directory, '..', 'bin', 'pnpm.cjs'), PATH: [env.PATH, directory, dirname(process.execPath)].filter(value => value !== undefined).join(delimiter) };
64
64
  // A fresh pnpm's first run can stall or fail once (a cold start on a busy
65
65
  // machine): the check settles with a bounded retry, then names what failed.
66
+ const loadFactor = Math.min(4, Math.max(1, loadavg()[0] / availableParallelism()));
67
+ const timeouts = [10000, 20000, 30000].map(ms => Math.round(ms * loadFactor));
66
68
  let result;
67
- for (const [attempt, timeoutMs] of [10000, 20000, 30000].entries()) {
69
+ for (const [attempt, timeoutMs] of timeouts.entries()) {
68
70
  if (attempt) await delay(1000, undefined, { signal });
69
71
  result = await probe(root, supplied, signal, store, timeoutMs);
70
72
  if (result.version === pin) { Object.assign(env, supplied); return env; }
71
73
  }
72
74
  const failed = result.version === undefined ? result.reason : `it reported ${JSON.stringify(result.version.slice(0, 64))}`;
73
- const message = `The verified pnpm ${pin} did not report the project version after 3 tries (${failed}).${result.diagnostic ? `\n${result.diagnostic}\n` : ' '}Run ${shellQuote(join(directory, 'pnpm'))} --version to inspect it, then rerun rer.`;
75
+ const message = `The verified pnpm ${pin} did not report the project version after 3 tries (${failed}). The final attempt allowed ${timeouts.at(-1) / 1000} s.${result.diagnostic ? `\n${result.diagnostic}\n` : ' '}Run ${shellQuote(join(directory, 'pnpm'))} --version to inspect it, then rerun rer.`;
74
76
  store.report(message);
75
77
  throw missing(message);
76
78
  }
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Roy T. Hashimoto
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,13 @@
1
+ # SQLite for Worker migration replay
2
+
3
+ The sync ES module and Wasm binary come from `dist/` in
4
+ [`@journeyapps/wa-sqlite@2.0.10`](https://www.npmjs.com/package/@journeyapps/wa-sqlite/v/2.0.10).
5
+ The glue uses its existing virtual temporary directory as the sandbox home
6
+ and omits the upstream simulated user home. The package builds SQLite 3.53.0
7
+ with FTS5 and is distributed under the MIT license in this directory. Only
8
+ the owner migration evidence module imports this engine.
9
+
10
+ To retrieve the sources, run `npm pack @journeyapps/wa-sqlite@2.0.10` and
11
+ extract the two named files from `package/dist/` and `package/LICENSE`.
12
+ The tarball has npm integrity
13
+ `sha512-6Wo5ZijOc4/6M9u+MDsJdW8zDCdrct/p+7LcG7S7CT5YKu42j6lshMfUvgtGYMaZeuH7rpQHULZupPTQFqbS0w==`.
@@ -0,0 +1,14 @@
1
+ var Module = (() => {
2
+
3
+ return (
4
+ async function(moduleArg = {}) {
5
+ var moduleRtn;
6
+
7
+ var Module=moduleArg;var readyPromiseResolve,readyPromiseReject;var readyPromise=new Promise((resolve,reject)=>{readyPromiseResolve=resolve;readyPromiseReject=reject});var ENVIRONMENT_IS_WEB=typeof window=="object";var ENVIRONMENT_IS_WORKER=typeof WorkerGlobalScope!="undefined";var ENVIRONMENT_IS_NODE=typeof process=="object"&&process.versions?.node&&process.type!="renderer";var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var _scriptName=import.meta.url;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var wasmMemory;var ABORT=false;var EXITSTATUS;var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;var runtimeInitialized=false;function updateMemoryViews(){var b=wasmMemory.buffer;HEAP8=new Int8Array(b);HEAP16=new Int16Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);HEAPU16=new Uint16Array(b);Module["HEAP32"]=HEAP32=new Int32Array(b);HEAPU32=new Uint32Array(b);HEAPF32=new Float32Array(b);HEAPF64=new Float64Array(b)}function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;if(!Module["noFSInit"]&&!FS.initialized)FS.init();TTY.init();wasmExports["qa"]();FS.ignorePermissions=false}function preMain(){}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(onPostRuns)}var runDependencies=0;var dependenciesFulfilled=null;function getUniqueRunDependency(id){return id}function addRunDependency(id){runDependencies++;Module["monitorRunDependencies"]?.(runDependencies)}function removeRunDependency(id){runDependencies--;Module["monitorRunDependencies"]?.(runDependencies);if(runDependencies==0){if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}function abort(what){Module["onAbort"]?.(what);what="Aborted("+what+")";err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject(e);throw e}var wasmBinaryFile;function findWasmBinary(){if(Module["locateFile"]){return locateFile("wa-sqlite.wasm")}return new URL("wa-sqlite.wasm",import.meta.url).href}function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&typeof WebAssembly.instantiateStreaming=="function"){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){return{a:wasmImports}}async function createWasm(){function receiveInstance(instance,module){wasmExports=instance.exports;wasmMemory=wasmExports["pa"];updateMemoryViews();wasmTable=wasmExports["pf"];removeRunDependency("wasm-instantiate");return wasmExports}addRunDependency("wasm-instantiate");function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();if(Module["instantiateWasm"]){return new Promise((resolve,reject)=>{Module["instantiateWasm"](info,(mod,inst)=>{resolve(receiveInstance(mod,inst))})})}wasmBinaryFile??=findWasmBinary();try{var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}catch(e){readyPromiseReject(e);return Promise.reject(e)}}var tempDouble;var tempI64;class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var addOnPostRun=cb=>onPostRuns.push(cb);var onPreRuns=[];var addOnPreRun=cb=>onPreRuns.push(cb);function getValue(ptr,type="i8"){if(type.endsWith("*"))type="*";switch(type){case"i1":return HEAP8[ptr];case"i8":return HEAP8[ptr];case"i16":return HEAP16[ptr>>1];case"i32":return HEAP32[ptr>>2];case"i64":abort("to do getValue(i64) use WASM_BIGINT");case"float":return HEAPF32[ptr>>2];case"double":return HEAPF64[ptr>>3];case"*":return HEAPU32[ptr>>2];default:abort(`invalid type for getValue: ${type}`)}}var noExitRuntime=true;function setValue(ptr,value,type="i8"){if(type.endsWith("*"))type="*";switch(type){case"i1":HEAP8[ptr]=value;break;case"i8":HEAP8[ptr]=value;break;case"i16":HEAP16[ptr>>1]=value;break;case"i32":HEAP32[ptr>>2]=value;break;case"i64":abort("to do setValue(i64) use WASM_BIGINT");case"float":HEAPF32[ptr>>2]=value;break;case"double":HEAPF64[ptr>>3]=value;break;case"*":HEAPU32[ptr>>2]=value;break;default:abort(`invalid type for setValue: ${type}`)}}var stackRestore=val=>__emscripten_stack_restore(val);var stackSave=()=>_emscripten_stack_get_current();var UTF8Decoder=new TextDecoder;var UTF8ToString=(ptr,maxBytesToRead)=>{if(!ptr)return"";var maxPtr=ptr+maxBytesToRead;for(var end=ptr;!(end>=maxPtr)&&HEAPU8[end];)++end;return UTF8Decoder.decode(HEAPU8.subarray(ptr,end))};var ___assert_fail=(condition,filename,line,func)=>abort(`Assertion failed: ${UTF8ToString(condition)}, at: `+[filename?UTF8ToString(filename):"unknown filename",line,func?UTF8ToString(func):"unknown function"]);var PATH={isAbs:path=>path.charAt(0)==="/",splitPath:filename=>{var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;return splitPathRe.exec(filename).slice(1)},normalizeArray:(parts,allowAboveRoot)=>{var up=0;for(var i=parts.length-1;i>=0;i--){var last=parts[i];if(last==="."){parts.splice(i,1)}else if(last===".."){parts.splice(i,1);up++}else if(up){parts.splice(i,1);up--}}if(allowAboveRoot){for(;up;up--){parts.unshift("..")}}return parts},normalize:path=>{var isAbsolute=PATH.isAbs(path),trailingSlash=path.slice(-1)==="/";path=PATH.normalizeArray(path.split("/").filter(p=>!!p),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path},dirname:path=>{var result=PATH.splitPath(path),root=result[0],dir=result[1];if(!root&&!dir){return"."}if(dir){dir=dir.slice(0,-1)}return root+dir},basename:path=>path&&path.match(/([^\/]+|\/)\/*$/)[1],join:(...paths)=>PATH.normalize(paths.join("/")),join2:(l,r)=>PATH.normalize(l+"/"+r)};var initRandomFill=()=>view=>crypto.getRandomValues(view);var randomFill=view=>{(randomFill=initRandomFill())(view)};var PATH_FS={resolve:(...args)=>{var resolvedPath="",resolvedAbsolute=false;for(var i=args.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?args[i]:FS.cwd();if(typeof path!="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!path){return""}resolvedPath=path+"/"+resolvedPath;resolvedAbsolute=PATH.isAbs(path)}resolvedPath=PATH.normalizeArray(resolvedPath.split("/").filter(p=>!!p),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."},relative:(from,to)=>{from=PATH_FS.resolve(from).slice(1);to=PATH_FS.resolve(to).slice(1);function trim(arr){var start=0;for(;start<arr.length;start++){if(arr[start]!=="")break}var end=arr.length-1;for(;end>=0;end--){if(arr[end]!=="")break}if(start>end)return[];return arr.slice(start,end-start+1)}var fromParts=trim(from.split("/"));var toParts=trim(to.split("/"));var length=Math.min(fromParts.length,toParts.length);var samePartsLength=length;for(var i=0;i<length;i++){if(fromParts[i]!==toParts[i]){samePartsLength=i;break}}var outputParts=[];for(var i=samePartsLength;i<fromParts.length;i++){outputParts.push("..")}outputParts=outputParts.concat(toParts.slice(samePartsLength));return outputParts.join("/")}};var UTF8ArrayToString=(heapOrArray,idx=0,maxBytesToRead=NaN)=>{var endIdx=idx+maxBytesToRead;var endPtr=idx;while(heapOrArray[endPtr]&&!(endPtr>=endIdx))++endPtr;return UTF8Decoder.decode(heapOrArray.buffer?heapOrArray.subarray(idx,endPtr):new Uint8Array(heapOrArray.slice(idx,endPtr)))};var FS_stdin_getChar_buffer=[];var lengthBytesUTF8=str=>{var len=0;for(var i=0;i<str.length;++i){var c=str.charCodeAt(i);if(c<=127){len++}else if(c<=2047){len+=2}else if(c>=55296&&c<=57343){len+=4;++i}else{len+=3}}return len};var stringToUTF8Array=(str,heap,outIdx,maxBytesToWrite)=>{if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i<str.length;++i){var u=str.charCodeAt(i);if(u>=55296&&u<=57343){var u1=str.charCodeAt(++i);u=65536+((u&1023)<<10)|u1&1023}if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}}heap[outIdx]=0;return outIdx-startIdx};var intArrayFromString=(stringy,dontAddNull,length)=>{var len=length>0?length:lengthBytesUTF8(stringy)+1;var u8array=new Array(len);var numBytesWritten=stringToUTF8Array(stringy,u8array,0,u8array.length);if(dontAddNull)u8array.length=numBytesWritten;return u8array};var FS_stdin_getChar=()=>{if(!FS_stdin_getChar_buffer.length){var result=null;if(typeof window!="undefined"&&typeof window.prompt=="function"){result=window.prompt("Input: ");if(result!==null){result+="\n"}}else{}if(!result){return null}FS_stdin_getChar_buffer=intArrayFromString(result,true)}return FS_stdin_getChar_buffer.shift()};var TTY={ttys:[],init(){},shutdown(){},register(dev,ops){TTY.ttys[dev]={input:[],output:[],ops};FS.registerDevice(dev,TTY.stream_ops)},stream_ops:{open(stream){var tty=TTY.ttys[stream.node.rdev];if(!tty){throw new FS.ErrnoError(43)}stream.tty=tty;stream.seekable=false},close(stream){stream.tty.ops.fsync(stream.tty)},fsync(stream){stream.tty.ops.fsync(stream.tty)},read(stream,buffer,offset,length,pos){if(!stream.tty||!stream.tty.ops.get_char){throw new FS.ErrnoError(60)}var bytesRead=0;for(var i=0;i<length;i++){var result;try{result=stream.tty.ops.get_char(stream.tty)}catch(e){throw new FS.ErrnoError(29)}if(result===undefined&&bytesRead===0){throw new FS.ErrnoError(6)}if(result===null||result===undefined)break;bytesRead++;buffer[offset+i]=result}if(bytesRead){stream.node.atime=Date.now()}return bytesRead},write(stream,buffer,offset,length,pos){if(!stream.tty||!stream.tty.ops.put_char){throw new FS.ErrnoError(60)}try{for(var i=0;i<length;i++){stream.tty.ops.put_char(stream.tty,buffer[offset+i])}}catch(e){throw new FS.ErrnoError(29)}if(length){stream.node.mtime=stream.node.ctime=Date.now()}return i}},default_tty_ops:{get_char(tty){return FS_stdin_getChar()},put_char(tty,val){if(val===null||val===10){out(UTF8ArrayToString(tty.output));tty.output=[]}else{if(val!=0)tty.output.push(val)}},fsync(tty){if(tty.output?.length>0){out(UTF8ArrayToString(tty.output));tty.output=[]}},ioctl_tcgets(tty){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets(tty,optional_actions,data){return 0},ioctl_tiocgwinsz(tty){return[24,80]}},default_tty1_ops:{put_char(tty,val){if(val===null||val===10){err(UTF8ArrayToString(tty.output));tty.output=[]}else{if(val!=0)tty.output.push(val)}},fsync(tty){if(tty.output?.length>0){err(UTF8ArrayToString(tty.output));tty.output=[]}}}};var zeroMemory=(ptr,size)=>HEAPU8.fill(0,ptr,ptr+size);var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var mmapAlloc=size=>{size=alignMemory(size,65536);var ptr=_emscripten_builtin_memalign(65536,size);if(ptr)zeroMemory(ptr,size);return ptr};var MEMFS={ops_table:null,mount(mount){return MEMFS.createNode(null,"/",16895,0)},createNode(parent,name,mode,dev){if(FS.isBlkdev(mode)||FS.isFIFO(mode)){throw new FS.ErrnoError(63)}MEMFS.ops_table||={dir:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,lookup:MEMFS.node_ops.lookup,mknod:MEMFS.node_ops.mknod,rename:MEMFS.node_ops.rename,unlink:MEMFS.node_ops.unlink,rmdir:MEMFS.node_ops.rmdir,readdir:MEMFS.node_ops.readdir,symlink:MEMFS.node_ops.symlink},stream:{llseek:MEMFS.stream_ops.llseek}},file:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:{llseek:MEMFS.stream_ops.llseek,read:MEMFS.stream_ops.read,write:MEMFS.stream_ops.write,mmap:MEMFS.stream_ops.mmap,msync:MEMFS.stream_ops.msync}},link:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,readlink:MEMFS.node_ops.readlink},stream:{}},chrdev:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:FS.chrdev_stream_ops}};var node=FS.createNode(parent,name,mode,dev);if(FS.isDir(node.mode)){node.node_ops=MEMFS.ops_table.dir.node;node.stream_ops=MEMFS.ops_table.dir.stream;node.contents={}}else if(FS.isFile(node.mode)){node.node_ops=MEMFS.ops_table.file.node;node.stream_ops=MEMFS.ops_table.file.stream;node.usedBytes=0;node.contents=null}else if(FS.isLink(node.mode)){node.node_ops=MEMFS.ops_table.link.node;node.stream_ops=MEMFS.ops_table.link.stream}else if(FS.isChrdev(node.mode)){node.node_ops=MEMFS.ops_table.chrdev.node;node.stream_ops=MEMFS.ops_table.chrdev.stream}node.atime=node.mtime=node.ctime=Date.now();if(parent){parent.contents[name]=node;parent.atime=parent.mtime=parent.ctime=node.atime}return node},getFileDataAsTypedArray(node){if(!node.contents)return new Uint8Array(0);if(node.contents.subarray)return node.contents.subarray(0,node.usedBytes);return new Uint8Array(node.contents)},expandFileStorage(node,newCapacity){var prevCapacity=node.contents?node.contents.length:0;if(prevCapacity>=newCapacity)return;var CAPACITY_DOUBLING_MAX=1024*1024;newCapacity=Math.max(newCapacity,prevCapacity*(prevCapacity<CAPACITY_DOUBLING_MAX?2:1.125)>>>0);if(prevCapacity!=0)newCapacity=Math.max(newCapacity,256);var oldContents=node.contents;node.contents=new Uint8Array(newCapacity);if(node.usedBytes>0)node.contents.set(oldContents.subarray(0,node.usedBytes),0)},resizeFileStorage(node,newSize){if(node.usedBytes==newSize)return;if(newSize==0){node.contents=null;node.usedBytes=0}else{var oldContents=node.contents;node.contents=new Uint8Array(newSize);if(oldContents){node.contents.set(oldContents.subarray(0,Math.min(newSize,node.usedBytes)))}node.usedBytes=newSize}},node_ops:{getattr(node){var attr={};attr.dev=FS.isChrdev(node.mode)?node.id:1;attr.ino=node.id;attr.mode=node.mode;attr.nlink=1;attr.uid=0;attr.gid=0;attr.rdev=node.rdev;if(FS.isDir(node.mode)){attr.size=4096}else if(FS.isFile(node.mode)){attr.size=node.usedBytes}else if(FS.isLink(node.mode)){attr.size=node.link.length}else{attr.size=0}attr.atime=new Date(node.atime);attr.mtime=new Date(node.mtime);attr.ctime=new Date(node.ctime);attr.blksize=4096;attr.blocks=Math.ceil(attr.size/attr.blksize);return attr},setattr(node,attr){for(const key of["mode","atime","mtime","ctime"]){if(attr[key]!=null){node[key]=attr[key]}}if(attr.size!==undefined){MEMFS.resizeFileStorage(node,attr.size)}},lookup(parent,name){throw MEMFS.doesNotExistError},mknod(parent,name,mode,dev){return MEMFS.createNode(parent,name,mode,dev)},rename(old_node,new_dir,new_name){var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(new_node){if(FS.isDir(old_node.mode)){for(var i in new_node.contents){throw new FS.ErrnoError(55)}}FS.hashRemoveNode(new_node)}delete old_node.parent.contents[old_node.name];new_dir.contents[new_name]=old_node;old_node.name=new_name;new_dir.ctime=new_dir.mtime=old_node.parent.ctime=old_node.parent.mtime=Date.now()},unlink(parent,name){delete parent.contents[name];parent.ctime=parent.mtime=Date.now()},rmdir(parent,name){var node=FS.lookupNode(parent,name);for(var i in node.contents){throw new FS.ErrnoError(55)}delete parent.contents[name];parent.ctime=parent.mtime=Date.now()},readdir(node){return[".","..",...Object.keys(node.contents)]},symlink(parent,newname,oldpath){var node=MEMFS.createNode(parent,newname,511|40960,0);node.link=oldpath;return node},readlink(node){if(!FS.isLink(node.mode)){throw new FS.ErrnoError(28)}return node.link}},stream_ops:{read(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=stream.node.usedBytes)return 0;var size=Math.min(stream.node.usedBytes-position,length);if(size>8&&contents.subarray){buffer.set(contents.subarray(position,position+size),offset)}else{for(var i=0;i<size;i++)buffer[offset+i]=contents[position+i]}return size},write(stream,buffer,offset,length,position,canOwn){if(buffer.buffer===HEAP8.buffer){canOwn=false}if(!length)return 0;var node=stream.node;node.mtime=node.ctime=Date.now();if(buffer.subarray&&(!node.contents||node.contents.subarray)){if(canOwn){node.contents=buffer.subarray(offset,offset+length);node.usedBytes=length;return length}else if(node.usedBytes===0&&position===0){node.contents=buffer.slice(offset,offset+length);node.usedBytes=length;return length}else if(position+length<=node.usedBytes){node.contents.set(buffer.subarray(offset,offset+length),position);return length}}MEMFS.expandFileStorage(node,position+length);if(node.contents.subarray&&buffer.subarray){node.contents.set(buffer.subarray(offset,offset+length),position)}else{for(var i=0;i<length;i++){node.contents[position+i]=buffer[offset+i]}}node.usedBytes=Math.max(node.usedBytes,position+length);return length},llseek(stream,offset,whence){var position=offset;if(whence===1){position+=stream.position}else if(whence===2){if(FS.isFile(stream.node.mode)){position+=stream.node.usedBytes}}if(position<0){throw new FS.ErrnoError(28)}return position},mmap(stream,length,position,prot,flags){if(!FS.isFile(stream.node.mode)){throw new FS.ErrnoError(43)}var ptr;var allocated;var contents=stream.node.contents;if(!(flags&2)&&contents&&contents.buffer===HEAP8.buffer){allocated=false;ptr=contents.byteOffset}else{allocated=true;ptr=mmapAlloc(length);if(!ptr){throw new FS.ErrnoError(48)}if(contents){if(position>0||position+length<contents.length){if(contents.subarray){contents=contents.subarray(position,position+length)}else{contents=Array.prototype.slice.call(contents,position,position+length)}}HEAP8.set(contents,ptr)}}return{ptr,allocated}},msync(stream,buffer,offset,length,mmapFlags){MEMFS.stream_ops.write(stream,buffer,0,length,offset,false);return 0}}};var asyncLoad=async url=>{var arrayBuffer=await readAsync(url);return new Uint8Array(arrayBuffer)};var FS_createDataFile=(...args)=>FS.createDataFile(...args);var preloadPlugins=[];var FS_handledByPreloadPlugin=(byteArray,fullname,finish,onerror)=>{if(typeof Browser!="undefined")Browser.init();var handled=false;preloadPlugins.forEach(plugin=>{if(handled)return;if(plugin["canHandle"](fullname)){plugin["handle"](byteArray,fullname,finish,onerror);handled=true}});return handled};var FS_createPreloadedFile=(parent,name,url,canRead,canWrite,onload,onerror,dontCreateFile,canOwn,preFinish)=>{var fullname=name?PATH_FS.resolve(PATH.join2(parent,name)):parent;var dep=getUniqueRunDependency(`cp ${fullname}`);function processData(byteArray){function finish(byteArray){preFinish?.();if(!dontCreateFile){FS_createDataFile(parent,name,byteArray,canRead,canWrite,canOwn)}onload?.();removeRunDependency(dep)}if(FS_handledByPreloadPlugin(byteArray,fullname,finish,()=>{onerror?.();removeRunDependency(dep)})){return}finish(byteArray)}addRunDependency(dep);if(typeof url=="string"){asyncLoad(url).then(processData,onerror)}else{processData(url)}};var FS_modeStringToFlags=str=>{var flagModes={r:0,"r+":2,w:512|64|1,"w+":512|64|2,a:1024|64|1,"a+":1024|64|2};var flags=flagModes[str];if(typeof flags=="undefined"){throw new Error(`Unknown file open mode: ${str}`)}return flags};var FS_getMode=(canRead,canWrite)=>{var mode=0;if(canRead)mode|=292|73;if(canWrite)mode|=146;return mode};var FS={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:false,ignorePermissions:true,filesystems:null,syncFSRequests:0,readFiles:{},ErrnoError:class{name="ErrnoError";constructor(errno){this.errno=errno}},FSStream:class{shared={};get object(){return this.node}set object(val){this.node=val}get isRead(){return(this.flags&2097155)!==1}get isWrite(){return(this.flags&2097155)!==0}get isAppend(){return this.flags&1024}get flags(){return this.shared.flags}set flags(val){this.shared.flags=val}get position(){return this.shared.position}set position(val){this.shared.position=val}},FSNode:class{node_ops={};stream_ops={};readMode=292|73;writeMode=146;mounted=null;constructor(parent,name,mode,rdev){if(!parent){parent=this}this.parent=parent;this.mount=parent.mount;this.id=FS.nextInode++;this.name=name;this.mode=mode;this.rdev=rdev;this.atime=this.mtime=this.ctime=Date.now()}get read(){return(this.mode&this.readMode)===this.readMode}set read(val){val?this.mode|=this.readMode:this.mode&=~this.readMode}get write(){return(this.mode&this.writeMode)===this.writeMode}set write(val){val?this.mode|=this.writeMode:this.mode&=~this.writeMode}get isFolder(){return FS.isDir(this.mode)}get isDevice(){return FS.isChrdev(this.mode)}},lookupPath(path,opts={}){if(!path){throw new FS.ErrnoError(44)}opts.follow_mount??=true;if(!PATH.isAbs(path)){path=FS.cwd()+"/"+path}linkloop:for(var nlinks=0;nlinks<40;nlinks++){var parts=path.split("/").filter(p=>!!p);var current=FS.root;var current_path="/";for(var i=0;i<parts.length;i++){var islast=i===parts.length-1;if(islast&&opts.parent){break}if(parts[i]==="."){continue}if(parts[i]===".."){current_path=PATH.dirname(current_path);if(FS.isRoot(current)){path=current_path+"/"+parts.slice(i+1).join("/");continue linkloop}else{current=current.parent}continue}current_path=PATH.join2(current_path,parts[i]);try{current=FS.lookupNode(current,parts[i])}catch(e){if(e?.errno===44&&islast&&opts.noent_okay){return{path:current_path}}throw e}if(FS.isMountpoint(current)&&(!islast||opts.follow_mount)){current=current.mounted.root}if(FS.isLink(current.mode)&&(!islast||opts.follow)){if(!current.node_ops.readlink){throw new FS.ErrnoError(52)}var link=current.node_ops.readlink(current);if(!PATH.isAbs(link)){link=PATH.dirname(current_path)+"/"+link}path=link+"/"+parts.slice(i+1).join("/");continue linkloop}}return{path:current_path,node:current}}throw new FS.ErrnoError(32)},getPath(node){var path;while(true){if(FS.isRoot(node)){var mount=node.mount.mountpoint;if(!path)return mount;return mount[mount.length-1]!=="/"?`${mount}/${path}`:mount+path}path=path?`${node.name}/${path}`:node.name;node=node.parent}},hashName(parentid,name){var hash=0;for(var i=0;i<name.length;i++){hash=(hash<<5)-hash+name.charCodeAt(i)|0}return(parentid+hash>>>0)%FS.nameTable.length},hashAddNode(node){var hash=FS.hashName(node.parent.id,node.name);node.name_next=FS.nameTable[hash];FS.nameTable[hash]=node},hashRemoveNode(node){var hash=FS.hashName(node.parent.id,node.name);if(FS.nameTable[hash]===node){FS.nameTable[hash]=node.name_next}else{var current=FS.nameTable[hash];while(current){if(current.name_next===node){current.name_next=node.name_next;break}current=current.name_next}}},lookupNode(parent,name){var errCode=FS.mayLookup(parent);if(errCode){throw new FS.ErrnoError(errCode)}var hash=FS.hashName(parent.id,name);for(var node=FS.nameTable[hash];node;node=node.name_next){var nodeName=node.name;if(node.parent.id===parent.id&&nodeName===name){return node}}return FS.lookup(parent,name)},createNode(parent,name,mode,rdev){var node=new FS.FSNode(parent,name,mode,rdev);FS.hashAddNode(node);return node},destroyNode(node){FS.hashRemoveNode(node)},isRoot(node){return node===node.parent},isMountpoint(node){return!!node.mounted},isFile(mode){return(mode&61440)===32768},isDir(mode){return(mode&61440)===16384},isLink(mode){return(mode&61440)===40960},isChrdev(mode){return(mode&61440)===8192},isBlkdev(mode){return(mode&61440)===24576},isFIFO(mode){return(mode&61440)===4096},isSocket(mode){return(mode&49152)===49152},flagsToPermissionString(flag){var perms=["r","w","rw"][flag&3];if(flag&512){perms+="w"}return perms},nodePermissions(node,perms){if(FS.ignorePermissions){return 0}if(perms.includes("r")&&!(node.mode&292)){return 2}else if(perms.includes("w")&&!(node.mode&146)){return 2}else if(perms.includes("x")&&!(node.mode&73)){return 2}return 0},mayLookup(dir){if(!FS.isDir(dir.mode))return 54;var errCode=FS.nodePermissions(dir,"x");if(errCode)return errCode;if(!dir.node_ops.lookup)return 2;return 0},mayCreate(dir,name){if(!FS.isDir(dir.mode)){return 54}try{var node=FS.lookupNode(dir,name);return 20}catch(e){}return FS.nodePermissions(dir,"wx")},mayDelete(dir,name,isdir){var node;try{node=FS.lookupNode(dir,name)}catch(e){return e.errno}var errCode=FS.nodePermissions(dir,"wx");if(errCode){return errCode}if(isdir){if(!FS.isDir(node.mode)){return 54}if(FS.isRoot(node)||FS.getPath(node)===FS.cwd()){return 10}}else{if(FS.isDir(node.mode)){return 31}}return 0},mayOpen(node,flags){if(!node){return 44}if(FS.isLink(node.mode)){return 32}else if(FS.isDir(node.mode)){if(FS.flagsToPermissionString(flags)!=="r"||flags&(512|64)){return 31}}return FS.nodePermissions(node,FS.flagsToPermissionString(flags))},checkOpExists(op,err){if(!op){throw new FS.ErrnoError(err)}return op},MAX_OPEN_FDS:4096,nextfd(){for(var fd=0;fd<=FS.MAX_OPEN_FDS;fd++){if(!FS.streams[fd]){return fd}}throw new FS.ErrnoError(33)},getStreamChecked(fd){var stream=FS.getStream(fd);if(!stream){throw new FS.ErrnoError(8)}return stream},getStream:fd=>FS.streams[fd],createStream(stream,fd=-1){stream=Object.assign(new FS.FSStream,stream);if(fd==-1){fd=FS.nextfd()}stream.fd=fd;FS.streams[fd]=stream;return stream},closeStream(fd){FS.streams[fd]=null},dupStream(origStream,fd=-1){var stream=FS.createStream(origStream,fd);stream.stream_ops?.dup?.(stream);return stream},doSetAttr(stream,node,attr){var setattr=stream?.stream_ops.setattr;var arg=setattr?stream:node;setattr??=node.node_ops.setattr;FS.checkOpExists(setattr,63);setattr(arg,attr)},chrdev_stream_ops:{open(stream){var device=FS.getDevice(stream.node.rdev);stream.stream_ops=device.stream_ops;stream.stream_ops.open?.(stream)},llseek(){throw new FS.ErrnoError(70)}},major:dev=>dev>>8,minor:dev=>dev&255,makedev:(ma,mi)=>ma<<8|mi,registerDevice(dev,ops){FS.devices[dev]={stream_ops:ops}},getDevice:dev=>FS.devices[dev],getMounts(mount){var mounts=[];var check=[mount];while(check.length){var m=check.pop();mounts.push(m);check.push(...m.mounts)}return mounts},syncfs(populate,callback){if(typeof populate=="function"){callback=populate;populate=false}FS.syncFSRequests++;if(FS.syncFSRequests>1){err(`warning: ${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`)}var mounts=FS.getMounts(FS.root.mount);var completed=0;function doCallback(errCode){FS.syncFSRequests--;return callback(errCode)}function done(errCode){if(errCode){if(!done.errored){done.errored=true;return doCallback(errCode)}return}if(++completed>=mounts.length){doCallback(null)}}mounts.forEach(mount=>{if(!mount.type.syncfs){return done(null)}mount.type.syncfs(mount,populate,done)})},mount(type,opts,mountpoint){var root=mountpoint==="/";var pseudo=!mountpoint;var node;if(root&&FS.root){throw new FS.ErrnoError(10)}else if(!root&&!pseudo){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});mountpoint=lookup.path;node=lookup.node;if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}if(!FS.isDir(node.mode)){throw new FS.ErrnoError(54)}}var mount={type,opts,mountpoint,mounts:[]};var mountRoot=type.mount(mount);mountRoot.mount=mount;mount.root=mountRoot;if(root){FS.root=mountRoot}else if(node){node.mounted=mount;if(node.mount){node.mount.mounts.push(mount)}}return mountRoot},unmount(mountpoint){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});if(!FS.isMountpoint(lookup.node)){throw new FS.ErrnoError(28)}var node=lookup.node;var mount=node.mounted;var mounts=FS.getMounts(mount);Object.keys(FS.nameTable).forEach(hash=>{var current=FS.nameTable[hash];while(current){var next=current.name_next;if(mounts.includes(current.mount)){FS.destroyNode(current)}current=next}});node.mounted=null;var idx=node.mount.mounts.indexOf(mount);node.mount.mounts.splice(idx,1)},lookup(parent,name){return parent.node_ops.lookup(parent,name)},mknod(path,mode,dev){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);if(!name){throw new FS.ErrnoError(28)}if(name==="."||name===".."){throw new FS.ErrnoError(20)}var errCode=FS.mayCreate(parent,name);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.mknod){throw new FS.ErrnoError(63)}return parent.node_ops.mknod(parent,name,mode,dev)},statfs(path){return FS.statfsNode(FS.lookupPath(path,{follow:true}).node)},statfsStream(stream){return FS.statfsNode(stream.node)},statfsNode(node){var rtn={bsize:4096,frsize:4096,blocks:1e6,bfree:5e5,bavail:5e5,files:FS.nextInode,ffree:FS.nextInode-1,fsid:42,flags:2,namelen:255};if(node.node_ops.statfs){Object.assign(rtn,node.node_ops.statfs(node.mount.opts.root))}return rtn},create(path,mode=438){mode&=4095;mode|=32768;return FS.mknod(path,mode,0)},mkdir(path,mode=511){mode&=511|512;mode|=16384;return FS.mknod(path,mode,0)},mkdirTree(path,mode){var dirs=path.split("/");var d="";for(var dir of dirs){if(!dir)continue;if(d||PATH.isAbs(path))d+="/";d+=dir;try{FS.mkdir(d,mode)}catch(e){if(e.errno!=20)throw e}}},mkdev(path,mode,dev){if(typeof dev=="undefined"){dev=mode;mode=438}mode|=8192;return FS.mknod(path,mode,dev)},symlink(oldpath,newpath){if(!PATH_FS.resolve(oldpath)){throw new FS.ErrnoError(44)}var lookup=FS.lookupPath(newpath,{parent:true});var parent=lookup.node;if(!parent){throw new FS.ErrnoError(44)}var newname=PATH.basename(newpath);var errCode=FS.mayCreate(parent,newname);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.symlink){throw new FS.ErrnoError(63)}return parent.node_ops.symlink(parent,newname,oldpath)},rename(old_path,new_path){var old_dirname=PATH.dirname(old_path);var new_dirname=PATH.dirname(new_path);var old_name=PATH.basename(old_path);var new_name=PATH.basename(new_path);var lookup,old_dir,new_dir;lookup=FS.lookupPath(old_path,{parent:true});old_dir=lookup.node;lookup=FS.lookupPath(new_path,{parent:true});new_dir=lookup.node;if(!old_dir||!new_dir)throw new FS.ErrnoError(44);if(old_dir.mount!==new_dir.mount){throw new FS.ErrnoError(75)}var old_node=FS.lookupNode(old_dir,old_name);var relative=PATH_FS.relative(old_path,new_dirname);if(relative.charAt(0)!=="."){throw new FS.ErrnoError(28)}relative=PATH_FS.relative(new_path,old_dirname);if(relative.charAt(0)!=="."){throw new FS.ErrnoError(55)}var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(old_node===new_node){return}var isdir=FS.isDir(old_node.mode);var errCode=FS.mayDelete(old_dir,old_name,isdir);if(errCode){throw new FS.ErrnoError(errCode)}errCode=new_node?FS.mayDelete(new_dir,new_name,isdir):FS.mayCreate(new_dir,new_name);if(errCode){throw new FS.ErrnoError(errCode)}if(!old_dir.node_ops.rename){throw new FS.ErrnoError(63)}if(FS.isMountpoint(old_node)||new_node&&FS.isMountpoint(new_node)){throw new FS.ErrnoError(10)}if(new_dir!==old_dir){errCode=FS.nodePermissions(old_dir,"w");if(errCode){throw new FS.ErrnoError(errCode)}}FS.hashRemoveNode(old_node);try{old_dir.node_ops.rename(old_node,new_dir,new_name);old_node.parent=new_dir}catch(e){throw e}finally{FS.hashAddNode(old_node)}},rmdir(path){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);var node=FS.lookupNode(parent,name);var errCode=FS.mayDelete(parent,name,true);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.rmdir){throw new FS.ErrnoError(63)}if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}parent.node_ops.rmdir(parent,name);FS.destroyNode(node)},readdir(path){var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;var readdir=FS.checkOpExists(node.node_ops.readdir,54);return readdir(node)},unlink(path){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;if(!parent){throw new FS.ErrnoError(44)}var name=PATH.basename(path);var node=FS.lookupNode(parent,name);var errCode=FS.mayDelete(parent,name,false);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.unlink){throw new FS.ErrnoError(63)}if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}parent.node_ops.unlink(parent,name);FS.destroyNode(node)},readlink(path){var lookup=FS.lookupPath(path);var link=lookup.node;if(!link){throw new FS.ErrnoError(44)}if(!link.node_ops.readlink){throw new FS.ErrnoError(28)}return link.node_ops.readlink(link)},stat(path,dontFollow){var lookup=FS.lookupPath(path,{follow:!dontFollow});var node=lookup.node;var getattr=FS.checkOpExists(node.node_ops.getattr,63);return getattr(node)},fstat(fd){var stream=FS.getStreamChecked(fd);var node=stream.node;var getattr=stream.stream_ops.getattr;var arg=getattr?stream:node;getattr??=node.node_ops.getattr;FS.checkOpExists(getattr,63);return getattr(arg)},lstat(path){return FS.stat(path,true)},doChmod(stream,node,mode,dontFollow){FS.doSetAttr(stream,node,{mode:mode&4095|node.mode&~4095,ctime:Date.now(),dontFollow})},chmod(path,mode,dontFollow){var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else{node=path}FS.doChmod(null,node,mode,dontFollow)},lchmod(path,mode){FS.chmod(path,mode,true)},fchmod(fd,mode){var stream=FS.getStreamChecked(fd);FS.doChmod(stream,stream.node,mode,false)},doChown(stream,node,dontFollow){FS.doSetAttr(stream,node,{timestamp:Date.now(),dontFollow})},chown(path,uid,gid,dontFollow){var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else{node=path}FS.doChown(null,node,dontFollow)},lchown(path,uid,gid){FS.chown(path,uid,gid,true)},fchown(fd,uid,gid){var stream=FS.getStreamChecked(fd);FS.doChown(stream,stream.node,false)},doTruncate(stream,node,len){if(FS.isDir(node.mode)){throw new FS.ErrnoError(31)}if(!FS.isFile(node.mode)){throw new FS.ErrnoError(28)}var errCode=FS.nodePermissions(node,"w");if(errCode){throw new FS.ErrnoError(errCode)}FS.doSetAttr(stream,node,{size:len,timestamp:Date.now()})},truncate(path,len){if(len<0){throw new FS.ErrnoError(28)}var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:true});node=lookup.node}else{node=path}FS.doTruncate(null,node,len)},ftruncate(fd,len){var stream=FS.getStreamChecked(fd);if(len<0||(stream.flags&2097155)===0){throw new FS.ErrnoError(28)}FS.doTruncate(stream,stream.node,len)},utime(path,atime,mtime){var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;var setattr=FS.checkOpExists(node.node_ops.setattr,63);setattr(node,{atime,mtime})},open(path,flags,mode=438){if(path===""){throw new FS.ErrnoError(44)}flags=typeof flags=="string"?FS_modeStringToFlags(flags):flags;if(flags&64){mode=mode&4095|32768}else{mode=0}var node;var isDirPath;if(typeof path=="object"){node=path}else{isDirPath=path.endsWith("/");var lookup=FS.lookupPath(path,{follow:!(flags&131072),noent_okay:true});node=lookup.node;path=lookup.path}var created=false;if(flags&64){if(node){if(flags&128){throw new FS.ErrnoError(20)}}else if(isDirPath){throw new FS.ErrnoError(31)}else{node=FS.mknod(path,mode|511,0);created=true}}if(!node){throw new FS.ErrnoError(44)}if(FS.isChrdev(node.mode)){flags&=~512}if(flags&65536&&!FS.isDir(node.mode)){throw new FS.ErrnoError(54)}if(!created){var errCode=FS.mayOpen(node,flags);if(errCode){throw new FS.ErrnoError(errCode)}}if(flags&512&&!created){FS.truncate(node,0)}flags&=~(128|512|131072);var stream=FS.createStream({node,path:FS.getPath(node),flags,seekable:true,position:0,stream_ops:node.stream_ops,ungotten:[],error:false});if(stream.stream_ops.open){stream.stream_ops.open(stream)}if(created){FS.chmod(node,mode&511)}if(Module["logReadFiles"]&&!(flags&1)){if(!(path in FS.readFiles)){FS.readFiles[path]=1}}return stream},close(stream){if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if(stream.getdents)stream.getdents=null;try{if(stream.stream_ops.close){stream.stream_ops.close(stream)}}catch(e){throw e}finally{FS.closeStream(stream.fd)}stream.fd=null},isClosed(stream){return stream.fd===null},llseek(stream,offset,whence){if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if(!stream.seekable||!stream.stream_ops.llseek){throw new FS.ErrnoError(70)}if(whence!=0&&whence!=1&&whence!=2){throw new FS.ErrnoError(28)}stream.position=stream.stream_ops.llseek(stream,offset,whence);stream.ungotten=[];return stream.position},read(stream,buffer,offset,length,position){if(length<0||position<0){throw new FS.ErrnoError(28)}if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if((stream.flags&2097155)===1){throw new FS.ErrnoError(8)}if(FS.isDir(stream.node.mode)){throw new FS.ErrnoError(31)}if(!stream.stream_ops.read){throw new FS.ErrnoError(28)}var seeking=typeof position!="undefined";if(!seeking){position=stream.position}else if(!stream.seekable){throw new FS.ErrnoError(70)}var bytesRead=stream.stream_ops.read(stream,buffer,offset,length,position);if(!seeking)stream.position+=bytesRead;return bytesRead},write(stream,buffer,offset,length,position,canOwn){if(length<0||position<0){throw new FS.ErrnoError(28)}if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if((stream.flags&2097155)===0){throw new FS.ErrnoError(8)}if(FS.isDir(stream.node.mode)){throw new FS.ErrnoError(31)}if(!stream.stream_ops.write){throw new FS.ErrnoError(28)}if(stream.seekable&&stream.flags&1024){FS.llseek(stream,0,2)}var seeking=typeof position!="undefined";if(!seeking){position=stream.position}else if(!stream.seekable){throw new FS.ErrnoError(70)}var bytesWritten=stream.stream_ops.write(stream,buffer,offset,length,position,canOwn);if(!seeking)stream.position+=bytesWritten;return bytesWritten},mmap(stream,length,position,prot,flags){if((prot&2)!==0&&(flags&2)===0&&(stream.flags&2097155)!==2){throw new FS.ErrnoError(2)}if((stream.flags&2097155)===1){throw new FS.ErrnoError(2)}if(!stream.stream_ops.mmap){throw new FS.ErrnoError(43)}if(!length){throw new FS.ErrnoError(28)}return stream.stream_ops.mmap(stream,length,position,prot,flags)},msync(stream,buffer,offset,length,mmapFlags){if(!stream.stream_ops.msync){return 0}return stream.stream_ops.msync(stream,buffer,offset,length,mmapFlags)},ioctl(stream,cmd,arg){if(!stream.stream_ops.ioctl){throw new FS.ErrnoError(59)}return stream.stream_ops.ioctl(stream,cmd,arg)},readFile(path,opts={}){opts.flags=opts.flags||0;opts.encoding=opts.encoding||"binary";if(opts.encoding!=="utf8"&&opts.encoding!=="binary"){throw new Error(`Invalid encoding type "${opts.encoding}"`)}var ret;var stream=FS.open(path,opts.flags);var stat=FS.stat(path);var length=stat.size;var buf=new Uint8Array(length);FS.read(stream,buf,0,length,0);if(opts.encoding==="utf8"){ret=UTF8ArrayToString(buf)}else if(opts.encoding==="binary"){ret=buf}FS.close(stream);return ret},writeFile(path,data,opts={}){opts.flags=opts.flags||577;var stream=FS.open(path,opts.flags,opts.mode);if(typeof data=="string"){var buf=new Uint8Array(lengthBytesUTF8(data)+1);var actualNumBytes=stringToUTF8Array(data,buf,0,buf.length);FS.write(stream,buf,0,actualNumBytes,undefined,opts.canOwn)}else if(ArrayBuffer.isView(data)){FS.write(stream,data,0,data.byteLength,undefined,opts.canOwn)}else{throw new Error("Unsupported data type")}FS.close(stream)},cwd:()=>FS.currentPath,chdir(path){var lookup=FS.lookupPath(path,{follow:true});if(lookup.node===null){throw new FS.ErrnoError(44)}if(!FS.isDir(lookup.node.mode)){throw new FS.ErrnoError(54)}var errCode=FS.nodePermissions(lookup.node,"x");if(errCode){throw new FS.ErrnoError(errCode)}FS.currentPath=lookup.path},createDefaultDirectories(){FS.mkdir("/tmp")},createDefaultDevices(){FS.mkdir("/dev");FS.registerDevice(FS.makedev(1,3),{read:()=>0,write:(stream,buffer,offset,length,pos)=>length,llseek:()=>0});FS.mkdev("/dev/null",FS.makedev(1,3));TTY.register(FS.makedev(5,0),TTY.default_tty_ops);TTY.register(FS.makedev(6,0),TTY.default_tty1_ops);FS.mkdev("/dev/tty",FS.makedev(5,0));FS.mkdev("/dev/tty1",FS.makedev(6,0));var randomBuffer=new Uint8Array(1024),randomLeft=0;var randomByte=()=>{if(randomLeft===0){randomFill(randomBuffer);randomLeft=randomBuffer.byteLength}return randomBuffer[--randomLeft]};FS.createDevice("/dev","random",randomByte);FS.createDevice("/dev","urandom",randomByte);FS.mkdir("/dev/shm");FS.mkdir("/dev/shm/tmp")},createSpecialDirectories(){FS.mkdir("/proc");var proc_self=FS.mkdir("/proc/self");FS.mkdir("/proc/self/fd");FS.mount({mount(){var node=FS.createNode(proc_self,"fd",16895,73);node.stream_ops={llseek:MEMFS.stream_ops.llseek};node.node_ops={lookup(parent,name){var fd=+name;var stream=FS.getStreamChecked(fd);var ret={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>stream.path},id:fd+1};ret.parent=ret;return ret},readdir(){return Array.from(FS.streams.entries()).filter(([k,v])=>v).map(([k,v])=>k.toString())}};return node}},{},"/proc/self/fd")},createStandardStreams(input,output,error){if(input){FS.createDevice("/dev","stdin",input)}else{FS.symlink("/dev/tty","/dev/stdin")}if(output){FS.createDevice("/dev","stdout",null,output)}else{FS.symlink("/dev/tty","/dev/stdout")}if(error){FS.createDevice("/dev","stderr",null,error)}else{FS.symlink("/dev/tty1","/dev/stderr")}var stdin=FS.open("/dev/stdin",0);var stdout=FS.open("/dev/stdout",1);var stderr=FS.open("/dev/stderr",1)},staticInit(){FS.nameTable=new Array(4096);FS.mount(MEMFS,{},"/");FS.createDefaultDirectories();FS.createDefaultDevices();FS.createSpecialDirectories();FS.filesystems={MEMFS}},init(input,output,error){FS.initialized=true;input??=Module["stdin"];output??=Module["stdout"];error??=Module["stderr"];FS.createStandardStreams(input,output,error)},quit(){FS.initialized=false;for(var stream of FS.streams){if(stream){FS.close(stream)}}},findObject(path,dontResolveLastLink){var ret=FS.analyzePath(path,dontResolveLastLink);if(!ret.exists){return null}return ret.object},analyzePath(path,dontResolveLastLink){try{var lookup=FS.lookupPath(path,{follow:!dontResolveLastLink});path=lookup.path}catch(e){}var ret={isRoot:false,exists:false,error:0,name:null,path:null,object:null,parentExists:false,parentPath:null,parentObject:null};try{var lookup=FS.lookupPath(path,{parent:true});ret.parentExists=true;ret.parentPath=lookup.path;ret.parentObject=lookup.node;ret.name=PATH.basename(path);lookup=FS.lookupPath(path,{follow:!dontResolveLastLink});ret.exists=true;ret.path=lookup.path;ret.object=lookup.node;ret.name=lookup.node.name;ret.isRoot=lookup.path==="/"}catch(e){ret.error=e.errno}return ret},createPath(parent,path,canRead,canWrite){parent=typeof parent=="string"?parent:FS.getPath(parent);var parts=path.split("/").reverse();while(parts.length){var part=parts.pop();if(!part)continue;var current=PATH.join2(parent,part);try{FS.mkdir(current)}catch(e){if(e.errno!=20)throw e}parent=current}return current},createFile(parent,name,properties,canRead,canWrite){var path=PATH.join2(typeof parent=="string"?parent:FS.getPath(parent),name);var mode=FS_getMode(canRead,canWrite);return FS.create(path,mode)},createDataFile(parent,name,data,canRead,canWrite,canOwn){var path=name;if(parent){parent=typeof parent=="string"?parent:FS.getPath(parent);path=name?PATH.join2(parent,name):parent}var mode=FS_getMode(canRead,canWrite);var node=FS.create(path,mode);if(data){if(typeof data=="string"){var arr=new Array(data.length);for(var i=0,len=data.length;i<len;++i)arr[i]=data.charCodeAt(i);data=arr}FS.chmod(node,mode|146);var stream=FS.open(node,577);FS.write(stream,data,0,data.length,0,canOwn);FS.close(stream);FS.chmod(node,mode)}},createDevice(parent,name,input,output){var path=PATH.join2(typeof parent=="string"?parent:FS.getPath(parent),name);var mode=FS_getMode(!!input,!!output);FS.createDevice.major??=64;var dev=FS.makedev(FS.createDevice.major++,0);FS.registerDevice(dev,{open(stream){stream.seekable=false},close(stream){if(output?.buffer?.length){output(10)}},read(stream,buffer,offset,length,pos){var bytesRead=0;for(var i=0;i<length;i++){var result;try{result=input()}catch(e){throw new FS.ErrnoError(29)}if(result===undefined&&bytesRead===0){throw new FS.ErrnoError(6)}if(result===null||result===undefined)break;bytesRead++;buffer[offset+i]=result}if(bytesRead){stream.node.atime=Date.now()}return bytesRead},write(stream,buffer,offset,length,pos){for(var i=0;i<length;i++){try{output(buffer[offset+i])}catch(e){throw new FS.ErrnoError(29)}}if(length){stream.node.mtime=stream.node.ctime=Date.now()}return i}});return FS.mkdev(path,mode,dev)},forceLoadFile(obj){if(obj.isDevice||obj.isFolder||obj.link||obj.contents)return true;if(typeof XMLHttpRequest!="undefined"){throw new Error("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.")}else{try{obj.contents=readBinary(obj.url);obj.usedBytes=obj.contents.length}catch(e){throw new FS.ErrnoError(29)}}},createLazyFile(parent,name,url,canRead,canWrite){class LazyUint8Array{lengthKnown=false;chunks=[];get(idx){if(idx>this.length-1||idx<0){return undefined}var chunkOffset=idx%this.chunkSize;var chunkNum=idx/this.chunkSize|0;return this.getter(chunkNum)[chunkOffset]}setDataGetter(getter){this.getter=getter}cacheLength(){var xhr=new XMLHttpRequest;xhr.open("HEAD",url,false);xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))throw new Error("Couldn't load "+url+". Status: "+xhr.status);var datalength=Number(xhr.getResponseHeader("Content-length"));var header;var hasByteServing=(header=xhr.getResponseHeader("Accept-Ranges"))&&header==="bytes";var usesGzip=(header=xhr.getResponseHeader("Content-Encoding"))&&header==="gzip";var chunkSize=1024*1024;if(!hasByteServing)chunkSize=datalength;var doXHR=(from,to)=>{if(from>to)throw new Error("invalid range ("+from+", "+to+") or no bytes requested!");if(to>datalength-1)throw new Error("only "+datalength+" bytes available! programmer error!");var xhr=new XMLHttpRequest;xhr.open("GET",url,false);if(datalength!==chunkSize)xhr.setRequestHeader("Range","bytes="+from+"-"+to);xhr.responseType="arraybuffer";if(xhr.overrideMimeType){xhr.overrideMimeType("text/plain; charset=x-user-defined")}xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))throw new Error("Couldn't load "+url+". Status: "+xhr.status);if(xhr.response!==undefined){return new Uint8Array(xhr.response||[])}return intArrayFromString(xhr.responseText||"",true)};var lazyArray=this;lazyArray.setDataGetter(chunkNum=>{var start=chunkNum*chunkSize;var end=(chunkNum+1)*chunkSize-1;end=Math.min(end,datalength-1);if(typeof lazyArray.chunks[chunkNum]=="undefined"){lazyArray.chunks[chunkNum]=doXHR(start,end)}if(typeof lazyArray.chunks[chunkNum]=="undefined")throw new Error("doXHR failed!");return lazyArray.chunks[chunkNum]});if(usesGzip||!datalength){chunkSize=datalength=1;datalength=this.getter(0).length;chunkSize=datalength;out("LazyFiles on gzip forces download of the whole file when length is accessed")}this._length=datalength;this._chunkSize=chunkSize;this.lengthKnown=true}get length(){if(!this.lengthKnown){this.cacheLength()}return this._length}get chunkSize(){if(!this.lengthKnown){this.cacheLength()}return this._chunkSize}}if(typeof XMLHttpRequest!="undefined"){if(!ENVIRONMENT_IS_WORKER)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var lazyArray=new LazyUint8Array;var properties={isDevice:false,contents:lazyArray}}else{var properties={isDevice:false,url}}var node=FS.createFile(parent,name,properties,canRead,canWrite);if(properties.contents){node.contents=properties.contents}else if(properties.url){node.contents=null;node.url=properties.url}Object.defineProperties(node,{usedBytes:{get:function(){return this.contents.length}}});var stream_ops={};var keys=Object.keys(node.stream_ops);keys.forEach(key=>{var fn=node.stream_ops[key];stream_ops[key]=(...args)=>{FS.forceLoadFile(node);return fn(...args)}});function writeChunks(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=contents.length)return 0;var size=Math.min(contents.length-position,length);if(contents.slice){for(var i=0;i<size;i++){buffer[offset+i]=contents[position+i]}}else{for(var i=0;i<size;i++){buffer[offset+i]=contents.get(position+i)}}return size}stream_ops.read=(stream,buffer,offset,length,position)=>{FS.forceLoadFile(node);return writeChunks(stream,buffer,offset,length,position)};stream_ops.mmap=(stream,length,position,prot,flags)=>{FS.forceLoadFile(node);var ptr=mmapAlloc(length);if(!ptr){throw new FS.ErrnoError(48)}writeChunks(stream,HEAP8,ptr,length,position);return{ptr,allocated:true}};node.stream_ops=stream_ops;return node}};var SYSCALLS={DEFAULT_POLLMASK:5,calculateAt(dirfd,path,allowEmpty){if(PATH.isAbs(path)){return path}var dir;if(dirfd===-100){dir=FS.cwd()}else{var dirstream=SYSCALLS.getStreamFromFD(dirfd);dir=dirstream.path}if(path.length==0){if(!allowEmpty){throw new FS.ErrnoError(44)}return dir}return dir+"/"+path},writeStat(buf,stat){HEAP32[buf>>2]=stat.dev;HEAP32[buf+4>>2]=stat.mode;HEAPU32[buf+8>>2]=stat.nlink;HEAP32[buf+12>>2]=stat.uid;HEAP32[buf+16>>2]=stat.gid;HEAP32[buf+20>>2]=stat.rdev;tempI64=[stat.size>>>0,(tempDouble=stat.size,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+24>>2]=tempI64[0],HEAP32[buf+28>>2]=tempI64[1];HEAP32[buf+32>>2]=4096;HEAP32[buf+36>>2]=stat.blocks;var atime=stat.atime.getTime();var mtime=stat.mtime.getTime();var ctime=stat.ctime.getTime();tempI64=[Math.floor(atime/1e3)>>>0,(tempDouble=Math.floor(atime/1e3),+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+40>>2]=tempI64[0],HEAP32[buf+44>>2]=tempI64[1];HEAPU32[buf+48>>2]=atime%1e3*1e3*1e3;tempI64=[Math.floor(mtime/1e3)>>>0,(tempDouble=Math.floor(mtime/1e3),+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+56>>2]=tempI64[0],HEAP32[buf+60>>2]=tempI64[1];HEAPU32[buf+64>>2]=mtime%1e3*1e3*1e3;tempI64=[Math.floor(ctime/1e3)>>>0,(tempDouble=Math.floor(ctime/1e3),+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+72>>2]=tempI64[0],HEAP32[buf+76>>2]=tempI64[1];HEAPU32[buf+80>>2]=ctime%1e3*1e3*1e3;tempI64=[stat.ino>>>0,(tempDouble=stat.ino,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+88>>2]=tempI64[0],HEAP32[buf+92>>2]=tempI64[1];return 0},writeStatFs(buf,stats){HEAP32[buf+4>>2]=stats.bsize;HEAP32[buf+40>>2]=stats.bsize;HEAP32[buf+8>>2]=stats.blocks;HEAP32[buf+12>>2]=stats.bfree;HEAP32[buf+16>>2]=stats.bavail;HEAP32[buf+20>>2]=stats.files;HEAP32[buf+24>>2]=stats.ffree;HEAP32[buf+28>>2]=stats.fsid;HEAP32[buf+44>>2]=stats.flags;HEAP32[buf+36>>2]=stats.namelen},doMsync(addr,stream,len,flags,offset){if(!FS.isFile(stream.node.mode)){throw new FS.ErrnoError(43)}if(flags&2){return 0}var buffer=HEAPU8.slice(addr,addr+len);FS.msync(stream,buffer,offset,len,flags)},getStreamFromFD(fd){var stream=FS.getStreamChecked(fd);return stream},varargs:undefined,getStr(ptr){var ret=UTF8ToString(ptr);return ret}};function ___syscall_chmod(path,mode){try{path=SYSCALLS.getStr(path);FS.chmod(path,mode);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_faccessat(dirfd,path,amode,flags){try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);if(amode&~7){return-28}var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;if(!node){return-44}var perms="";if(amode&4)perms+="r";if(amode&2)perms+="w";if(amode&1)perms+="x";if(perms&&FS.nodePermissions(node,perms)){return-2}return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_fchmod(fd,mode){try{FS.fchmod(fd,mode);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_fchown32(fd,owner,group){try{FS.fchown(fd,owner,group);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var syscallGetVarargI=()=>{var ret=HEAP32[+SYSCALLS.varargs>>2];SYSCALLS.varargs+=4;return ret};var syscallGetVarargP=syscallGetVarargI;function ___syscall_fcntl64(fd,cmd,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(cmd){case 0:{var arg=syscallGetVarargI();if(arg<0){return-28}while(FS.streams[arg]){arg++}var newStream;newStream=FS.dupStream(stream,arg);return newStream.fd}case 1:case 2:return 0;case 3:return stream.flags;case 4:{var arg=syscallGetVarargI();stream.flags|=arg;return 0}case 12:{var arg=syscallGetVarargP();var offset=0;HEAP16[arg+offset>>1]=2;return 0}case 13:case 14:return 0}return-28}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_fstat64(fd,buf){try{return SYSCALLS.writeStat(buf,FS.fstat(fd))}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var convertI32PairToI53Checked=(lo,hi)=>hi+2097152>>>0<4194305-!!lo?(lo>>>0)+hi*4294967296:NaN;function ___syscall_ftruncate64(fd,length_low,length_high){var length=convertI32PairToI53Checked(length_low,length_high);try{if(isNaN(length))return-61;FS.ftruncate(fd,length);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var stringToUTF8=(str,outPtr,maxBytesToWrite)=>stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite);function ___syscall_getcwd(buf,size){try{if(size===0)return-28;var cwd=FS.cwd();var cwdLengthInBytes=lengthBytesUTF8(cwd)+1;if(size<cwdLengthInBytes)return-68;stringToUTF8(cwd,buf,size);return cwdLengthInBytes}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_lstat64(path,buf){try{path=SYSCALLS.getStr(path);return SYSCALLS.writeStat(buf,FS.lstat(path))}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_mkdirat(dirfd,path,mode){try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);FS.mkdir(path,mode,0);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_newfstatat(dirfd,path,buf,flags){try{path=SYSCALLS.getStr(path);var nofollow=flags&256;var allowEmpty=flags&4096;flags=flags&~6400;path=SYSCALLS.calculateAt(dirfd,path,allowEmpty);return SYSCALLS.writeStat(buf,nofollow?FS.lstat(path):FS.stat(path))}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_openat(dirfd,path,flags,varargs){SYSCALLS.varargs=varargs;try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);var mode=varargs?syscallGetVarargI():0;return FS.open(path,flags,mode).fd}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_readlinkat(dirfd,path,buf,bufsize){try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);if(bufsize<=0)return-28;var ret=FS.readlink(path);var len=Math.min(bufsize,lengthBytesUTF8(ret));var endChar=HEAP8[buf+len];stringToUTF8(ret,buf,bufsize+1);HEAP8[buf+len]=endChar;return len}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_rmdir(path){try{path=SYSCALLS.getStr(path);FS.rmdir(path);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_stat64(path,buf){try{path=SYSCALLS.getStr(path);return SYSCALLS.writeStat(buf,FS.stat(path))}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_unlinkat(dirfd,path,flags){try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);if(!flags){FS.unlink(path)}else if(flags===512){FS.rmdir(path)}else{return-28}return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var readI53FromI64=ptr=>HEAPU32[ptr>>2]+HEAP32[ptr+4>>2]*4294967296;function ___syscall_utimensat(dirfd,path,times,flags){try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path,true);var now=Date.now(),atime,mtime;if(!times){atime=now;mtime=now}else{var seconds=readI53FromI64(times);var nanoseconds=HEAP32[times+8>>2];if(nanoseconds==1073741823){atime=now}else if(nanoseconds==1073741822){atime=null}else{atime=seconds*1e3+nanoseconds/(1e3*1e3)}times+=16;seconds=readI53FromI64(times);nanoseconds=HEAP32[times+8>>2];if(nanoseconds==1073741823){mtime=now}else if(nanoseconds==1073741822){mtime=null}else{mtime=seconds*1e3+nanoseconds/(1e3*1e3)}}if((mtime??atime)!==null){FS.utime(path,atime,mtime)}return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var __abort_js=()=>abort("");var runtimeKeepaliveCounter=0;var __emscripten_runtime_keepalive_clear=()=>{noExitRuntime=false;runtimeKeepaliveCounter=0};var isLeapYear=year=>year%4===0&&(year%100!==0||year%400===0);var MONTH_DAYS_LEAP_CUMULATIVE=[0,31,60,91,121,152,182,213,244,274,305,335];var MONTH_DAYS_REGULAR_CUMULATIVE=[0,31,59,90,120,151,181,212,243,273,304,334];var ydayFromDate=date=>{var leap=isLeapYear(date.getFullYear());var monthDaysCumulative=leap?MONTH_DAYS_LEAP_CUMULATIVE:MONTH_DAYS_REGULAR_CUMULATIVE;var yday=monthDaysCumulative[date.getMonth()]+date.getDate()-1;return yday};function __localtime_js(time_low,time_high,tmPtr){var time=convertI32PairToI53Checked(time_low,time_high);var date=new Date(time*1e3);HEAP32[tmPtr>>2]=date.getSeconds();HEAP32[tmPtr+4>>2]=date.getMinutes();HEAP32[tmPtr+8>>2]=date.getHours();HEAP32[tmPtr+12>>2]=date.getDate();HEAP32[tmPtr+16>>2]=date.getMonth();HEAP32[tmPtr+20>>2]=date.getFullYear()-1900;HEAP32[tmPtr+24>>2]=date.getDay();var yday=ydayFromDate(date)|0;HEAP32[tmPtr+28>>2]=yday;HEAP32[tmPtr+36>>2]=-(date.getTimezoneOffset()*60);var start=new Date(date.getFullYear(),0,1);var summerOffset=new Date(date.getFullYear(),6,1).getTimezoneOffset();var winterOffset=start.getTimezoneOffset();var dst=(summerOffset!=winterOffset&&date.getTimezoneOffset()==Math.min(winterOffset,summerOffset))|0;HEAP32[tmPtr+32>>2]=dst}function __mmap_js(len,prot,flags,fd,offset_low,offset_high,allocated,addr){var offset=convertI32PairToI53Checked(offset_low,offset_high);try{var stream=SYSCALLS.getStreamFromFD(fd);var res=FS.mmap(stream,len,offset,prot,flags);var ptr=res.ptr;HEAP32[allocated>>2]=res.allocated;HEAPU32[addr>>2]=ptr;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function __munmap_js(addr,len,prot,flags,fd,offset_low,offset_high){var offset=convertI32PairToI53Checked(offset_low,offset_high);try{var stream=SYSCALLS.getStreamFromFD(fd);if(prot&2){SYSCALLS.doMsync(addr,stream,len,flags,offset)}}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var timers={};var handleException=e=>{if(e instanceof ExitStatus||e=="unwind"){return EXITSTATUS}quit_(1,e)};var keepRuntimeAlive=()=>noExitRuntime||runtimeKeepaliveCounter>0;var _proc_exit=code=>{EXITSTATUS=code;if(!keepRuntimeAlive()){Module["onExit"]?.(code);ABORT=true}quit_(code,new ExitStatus(code))};var exitJS=(status,implicit)=>{EXITSTATUS=status;_proc_exit(status)};var _exit=exitJS;var maybeExit=()=>{if(!keepRuntimeAlive()){try{_exit(EXITSTATUS)}catch(e){handleException(e)}}};var callUserCallback=func=>{if(ABORT){return}try{func();maybeExit()}catch(e){handleException(e)}};var _emscripten_get_now=()=>performance.now();var __setitimer_js=(which,timeout_ms)=>{if(timers[which]){clearTimeout(timers[which].id);delete timers[which]}if(!timeout_ms)return 0;var id=setTimeout(()=>{delete timers[which];callUserCallback(()=>__emscripten_timeout(which,_emscripten_get_now()))},timeout_ms);timers[which]={id,timeout_ms};return 0};var __tzset_js=(timezone,daylight,std_name,dst_name)=>{var currentYear=(new Date).getFullYear();var winter=new Date(currentYear,0,1);var summer=new Date(currentYear,6,1);var winterOffset=winter.getTimezoneOffset();var summerOffset=summer.getTimezoneOffset();var stdTimezoneOffset=Math.max(winterOffset,summerOffset);HEAPU32[timezone>>2]=stdTimezoneOffset*60;HEAP32[daylight>>2]=Number(winterOffset!=summerOffset);var extractZone=timezoneOffset=>{var sign=timezoneOffset>=0?"-":"+";var absOffset=Math.abs(timezoneOffset);var hours=String(Math.floor(absOffset/60)).padStart(2,"0");var minutes=String(absOffset%60).padStart(2,"0");return`UTC${sign}${hours}${minutes}`};var winterName=extractZone(winterOffset);var summerName=extractZone(summerOffset);if(summerOffset<winterOffset){stringToUTF8(winterName,std_name,17);stringToUTF8(summerName,dst_name,17)}else{stringToUTF8(winterName,dst_name,17);stringToUTF8(summerName,std_name,17)}};var _emscripten_date_now=()=>Date.now();var getHeapMax=()=>2147483648;var growMemory=size=>{var b=wasmMemory.buffer;var pages=(size-b.byteLength+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};var ENV={};var getExecutableName=()=>thisProgram||"./this.program";var getEnvStrings=()=>{if(!getEnvStrings.strings){var lang=(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8";var env={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/tmp",LANG:lang,_:getExecutableName()};for(var x in ENV){if(ENV[x]===undefined)delete env[x];else env[x]=ENV[x]}var strings=[];for(var x in env){strings.push(`${x}=${env[x]}`)}getEnvStrings.strings=strings}return getEnvStrings.strings};var _environ_get=(__environ,environ_buf)=>{var bufSize=0;var envp=0;for(var string of getEnvStrings()){var ptr=environ_buf+bufSize;HEAPU32[__environ+envp>>2]=ptr;bufSize+=stringToUTF8(string,ptr,Infinity)+1;envp+=4}return 0};var _environ_sizes_get=(penviron_count,penviron_buf_size)=>{var strings=getEnvStrings();HEAPU32[penviron_count>>2]=strings.length;var bufSize=0;for(var string of strings){bufSize+=lengthBytesUTF8(string)+1}HEAPU32[penviron_buf_size>>2]=bufSize;return 0};function _fd_close(fd){try{var stream=SYSCALLS.getStreamFromFD(fd);FS.close(stream);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}function _fd_fdstat_get(fd,pbuf){try{var rightsBase=0;var rightsInheriting=0;var flags=0;{var stream=SYSCALLS.getStreamFromFD(fd);var type=stream.tty?2:FS.isDir(stream.mode)?3:FS.isLink(stream.mode)?7:4}HEAP8[pbuf]=type;HEAP16[pbuf+2>>1]=flags;tempI64=[rightsBase>>>0,(tempDouble=rightsBase,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[pbuf+8>>2]=tempI64[0],HEAP32[pbuf+12>>2]=tempI64[1];tempI64=[rightsInheriting>>>0,(tempDouble=rightsInheriting,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[pbuf+16>>2]=tempI64[0],HEAP32[pbuf+20>>2]=tempI64[1];return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var doReadv=(stream,iov,iovcnt,offset)=>{var ret=0;for(var i=0;i<iovcnt;i++){var ptr=HEAPU32[iov>>2];var len=HEAPU32[iov+4>>2];iov+=8;var curr=FS.read(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr;if(curr<len)break;if(typeof offset!="undefined"){offset+=curr}}return ret};function _fd_read(fd,iov,iovcnt,pnum){try{var stream=SYSCALLS.getStreamFromFD(fd);var num=doReadv(stream,iov,iovcnt);HEAPU32[pnum>>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}function _fd_seek(fd,offset_low,offset_high,whence,newOffset){var offset=convertI32PairToI53Checked(offset_low,offset_high);try{if(isNaN(offset))return 61;var stream=SYSCALLS.getStreamFromFD(fd);FS.llseek(stream,offset,whence);tempI64=[stream.position>>>0,(tempDouble=stream.position,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[newOffset>>2]=tempI64[0],HEAP32[newOffset+4>>2]=tempI64[1];if(stream.getdents&&offset===0&&whence===0)stream.getdents=null;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}function _fd_sync(fd){try{var stream=SYSCALLS.getStreamFromFD(fd);if(stream.stream_ops?.fsync){return stream.stream_ops.fsync(stream)}return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var doWritev=(stream,iov,iovcnt,offset)=>{var ret=0;for(var i=0;i<iovcnt;i++){var ptr=HEAPU32[iov>>2];var len=HEAPU32[iov+4>>2];iov+=8;var curr=FS.write(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr;if(curr<len){break}if(typeof offset!="undefined"){offset+=curr}}return ret};function _fd_write(fd,iov,iovcnt,pnum){try{var stream=SYSCALLS.getStreamFromFD(fd);var num=doWritev(stream,iov,iovcnt);HEAPU32[pnum>>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var adapters_support=function(){const handleAsync=typeof Asyncify==="object"?Asyncify.handleAsync.bind(Asyncify):null;Module["handleAsync"]=handleAsync;const targets=new Map;Module["setCallback"]=(key,target)=>targets.set(key,target);Module["getCallback"]=key=>targets.get(key);Module["deleteCallback"]=key=>targets.delete(key);adapters_support=function(isAsync,key,...args){const receiver=targets.get(key);let methodName=null;const f=typeof receiver==="function"?receiver:receiver[methodName=UTF8ToString(args.shift())];if(isAsync){if(handleAsync){return handleAsync(()=>f.apply(receiver,args))}throw new Error("Synchronous WebAssembly cannot call async function")}const result=f.apply(receiver,args);if(typeof result?.then=="function"){console.error("unexpected Promise",f);throw new Error(`${methodName} unexpectedly returned a Promise`)}return result}};function _ipp(...args){return adapters_support(false,...args)}function _ipp_async(...args){return adapters_support(true,...args)}function _ippipppp(...args){return adapters_support(false,...args)}function _ippipppp_async(...args){return adapters_support(true,...args)}function _ippp(...args){return adapters_support(false,...args)}function _ippp_async(...args){return adapters_support(true,...args)}function _ipppi(...args){return adapters_support(false,...args)}function _ipppi_async(...args){return adapters_support(true,...args)}function _ipppiii(...args){return adapters_support(false,...args)}function _ipppiii_async(...args){return adapters_support(true,...args)}function _ipppiiip(...args){return adapters_support(false,...args)}function _ipppiiip_async(...args){return adapters_support(true,...args)}function _ipppip(...args){return adapters_support(false,...args)}function _ipppip_async(...args){return adapters_support(true,...args)}function _ipppj(...args){return adapters_support(false,...args)}function _ipppj_async(...args){return adapters_support(true,...args)}function _ipppp(...args){return adapters_support(false,...args)}function _ipppp_async(...args){return adapters_support(true,...args)}function _ippppi(...args){return adapters_support(false,...args)}function _ippppi_async(...args){return adapters_support(true,...args)}function _ippppij(...args){return adapters_support(false,...args)}function _ippppij_async(...args){return adapters_support(true,...args)}function _ippppip(...args){return adapters_support(false,...args)}function _ippppip_async(...args){return adapters_support(true,...args)}function _ipppppip(...args){return adapters_support(false,...args)}function _ipppppip_async(...args){return adapters_support(true,...args)}function _vppippii(...args){return adapters_support(false,...args)}function _vppippii_async(...args){return adapters_support(true,...args)}function _vppp(...args){return adapters_support(false,...args)}function _vppp_async(...args){return adapters_support(true,...args)}function _vpppip(...args){return adapters_support(false,...args)}function _vpppip_async(...args){return adapters_support(true,...args)}var uleb128Encode=(n,target)=>{if(n<128){target.push(n)}else{target.push(n%128|128,n>>7)}};var sigToWasmTypes=sig=>{var typeNames={i:"i32",j:"i64",f:"f32",d:"f64",e:"externref",p:"i32"};var type={parameters:[],results:sig[0]=="v"?[]:[typeNames[sig[0]]]};for(var i=1;i<sig.length;++i){type.parameters.push(typeNames[sig[i]])}return type};var generateFuncType=(sig,target)=>{var sigRet=sig.slice(0,1);var sigParam=sig.slice(1);var typeCodes={i:127,p:127,j:126,f:125,d:124,e:111};target.push(96);uleb128Encode(sigParam.length,target);for(var paramType of sigParam){target.push(typeCodes[paramType])}if(sigRet=="v"){target.push(0)}else{target.push(1,typeCodes[sigRet])}};var convertJsFunctionToWasm=(func,sig)=>{if(typeof WebAssembly.Function=="function"){return new WebAssembly.Function(sigToWasmTypes(sig),func)}var typeSectionBody=[1];generateFuncType(sig,typeSectionBody);var bytes=[0,97,115,109,1,0,0,0,1];uleb128Encode(typeSectionBody.length,bytes);bytes.push(...typeSectionBody);bytes.push(2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0);var module=new WebAssembly.Module(new Uint8Array(bytes));var instance=new WebAssembly.Instance(module,{e:{f:func}});var wrappedFunc=instance.exports["f"];return wrappedFunc};var wasmTable;var getWasmTableEntry=funcPtr=>wasmTable.get(funcPtr);var updateTableMap=(offset,count)=>{if(functionsInTableMap){for(var i=offset;i<offset+count;i++){var item=getWasmTableEntry(i);if(item){functionsInTableMap.set(item,i)}}}};var functionsInTableMap;var getFunctionAddress=func=>{if(!functionsInTableMap){functionsInTableMap=new WeakMap;updateTableMap(0,wasmTable.length)}return functionsInTableMap.get(func)||0};var freeTableIndexes=[];var getEmptyTableSlot=()=>{if(freeTableIndexes.length){return freeTableIndexes.pop()}try{wasmTable.grow(1)}catch(err){if(!(err instanceof RangeError)){throw err}throw"Unable to grow wasm table. Set ALLOW_TABLE_GROWTH."}return wasmTable.length-1};var setWasmTableEntry=(idx,func)=>wasmTable.set(idx,func);var addFunction=(func,sig)=>{var rtn=getFunctionAddress(func);if(rtn){return rtn}var ret=getEmptyTableSlot();try{setWasmTableEntry(ret,func)}catch(err){if(!(err instanceof TypeError)){throw err}var wrapped=convertJsFunctionToWasm(func,sig);setWasmTableEntry(ret,wrapped)}functionsInTableMap.set(func,ret);return ret};var getCFunc=ident=>{var func=Module["_"+ident];return func};var writeArrayToMemory=(array,buffer)=>{HEAP8.set(array,buffer)};var stackAlloc=sz=>__emscripten_stack_alloc(sz);var stringToUTF8OnStack=str=>{var size=lengthBytesUTF8(str)+1;var ret=stackAlloc(size);stringToUTF8(str,ret,size);return ret};var ccall=(ident,returnType,argTypes,args,opts)=>{var toC={string:str=>{var ret=0;if(str!==null&&str!==undefined&&str!==0){ret=stringToUTF8OnStack(str)}return ret},array:arr=>{var ret=stackAlloc(arr.length);writeArrayToMemory(arr,ret);return ret}};function convertReturnValue(ret){if(returnType==="string"){return UTF8ToString(ret)}if(returnType==="boolean")return Boolean(ret);return ret}var func=getCFunc(ident);var cArgs=[];var stack=0;if(args){for(var i=0;i<args.length;i++){var converter=toC[argTypes[i]];if(converter){if(stack===0)stack=stackSave();cArgs[i]=converter(args[i])}else{cArgs[i]=args[i]}}}var ret=func(...cArgs);function onDone(ret){if(stack!==0)stackRestore(stack);return convertReturnValue(ret)}ret=onDone(ret);return ret};var cwrap=(ident,returnType,argTypes,opts)=>{var numericArgs=!argTypes||argTypes.every(type=>type==="number"||type==="boolean");var numericRet=returnType!=="string";if(numericRet&&numericArgs&&!opts){return getCFunc(ident)}return(...args)=>ccall(ident,returnType,argTypes,args,opts)};var getTempRet0=val=>__emscripten_tempret_get();var stringToUTF16=(str,outPtr,maxBytesToWrite)=>{maxBytesToWrite??=2147483647;if(maxBytesToWrite<2)return 0;maxBytesToWrite-=2;var startPtr=outPtr;var numCharsToWrite=maxBytesToWrite<str.length*2?maxBytesToWrite/2:str.length;for(var i=0;i<numCharsToWrite;++i){var codeUnit=str.charCodeAt(i);HEAP16[outPtr>>1]=codeUnit;outPtr+=2}HEAP16[outPtr>>1]=0;return outPtr-startPtr};var stringToUTF32=(str,outPtr,maxBytesToWrite)=>{maxBytesToWrite??=2147483647;if(maxBytesToWrite<4)return 0;var startPtr=outPtr;var endPtr=startPtr+maxBytesToWrite-4;for(var i=0;i<str.length;++i){var codeUnit=str.charCodeAt(i);if(codeUnit>=55296&&codeUnit<=57343){var trailSurrogate=str.charCodeAt(++i);codeUnit=65536+((codeUnit&1023)<<10)|trailSurrogate&1023}HEAP32[outPtr>>2]=codeUnit;outPtr+=4;if(outPtr+4>endPtr)break}HEAP32[outPtr>>2]=0;return outPtr-startPtr};var AsciiToString=ptr=>{var str="";while(1){var ch=HEAPU8[ptr++];if(!ch)return str;str+=String.fromCharCode(ch)}};var UTF16Decoder=new TextDecoder("utf-16le");var UTF16ToString=(ptr,maxBytesToRead)=>{var idx=ptr>>1;var maxIdx=idx+maxBytesToRead/2;var endIdx=idx;while(!(endIdx>=maxIdx)&&HEAPU16[endIdx])++endIdx;return UTF16Decoder.decode(HEAPU16.subarray(idx,endIdx))};var UTF32ToString=(ptr,maxBytesToRead)=>{var i=0;var str="";while(!(i>=maxBytesToRead/4)){var utf32=HEAP32[ptr+i*4>>2];if(utf32==0)break;++i;if(utf32>=65536){var ch=utf32-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}else{str+=String.fromCharCode(utf32)}}return str};var intArrayToString=array=>{var ret=[];for(var i=0;i<array.length;i++){var chr=array[i];if(chr>255){chr&=255}ret.push(String.fromCharCode(chr))}return ret.join("")};var _getTempRet0=getTempRet0;FS.createPreloadedFile=FS_createPreloadedFile;FS.staticInit();MEMFS.doesNotExistError=new FS.ErrnoError(44);MEMFS.doesNotExistError.stack="<generic error, no stack>";adapters_support();{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["preloadPlugins"])preloadPlugins=Module["preloadPlugins"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"]}Module["getTempRet0"]=getTempRet0;Module["ccall"]=ccall;Module["cwrap"]=cwrap;Module["addFunction"]=addFunction;Module["setValue"]=setValue;Module["getValue"]=getValue;Module["UTF8ToString"]=UTF8ToString;Module["stringToUTF8"]=stringToUTF8;Module["lengthBytesUTF8"]=lengthBytesUTF8;Module["intArrayFromString"]=intArrayFromString;Module["intArrayToString"]=intArrayToString;Module["AsciiToString"]=AsciiToString;Module["UTF16ToString"]=UTF16ToString;Module["stringToUTF16"]=stringToUTF16;Module["UTF32ToString"]=UTF32ToString;Module["stringToUTF32"]=stringToUTF32;Module["writeArrayToMemory"]=writeArrayToMemory;Module["_getTempRet0"]=_getTempRet0;var wasmImports={a:___assert_fail,aa:___syscall_chmod,da:___syscall_faccessat,ba:___syscall_fchmod,$:___syscall_fchown32,b:___syscall_fcntl64,_:___syscall_fstat64,y:___syscall_ftruncate64,U:___syscall_getcwd,Y:___syscall_lstat64,R:___syscall_mkdirat,X:___syscall_newfstatat,P:___syscall_openat,N:___syscall_readlinkat,M:___syscall_rmdir,Z:___syscall_stat64,K:___syscall_unlinkat,J:___syscall_utimensat,F:__abort_js,E:__emscripten_runtime_keepalive_clear,w:__localtime_js,u:__mmap_js,v:__munmap_js,G:__setitimer_js,Q:__tzset_js,n:_emscripten_date_now,g:_emscripten_get_now,H:_emscripten_resize_heap,S:_environ_get,T:_environ_sizes_get,o:_fd_close,I:_fd_fdstat_get,O:_fd_read,x:_fd_seek,V:_fd_sync,L:_fd_write,s:_ipp,t:_ipp_async,ka:_ippipppp,oa:_ippipppp_async,j:_ippp,k:_ippp_async,c:_ipppi,d:_ipppi_async,ga:_ipppiii,ha:_ipppiii_async,ia:_ipppiiip,ja:_ipppiiip_async,h:_ipppip,i:_ipppip_async,z:_ipppj,A:_ipppj_async,e:_ipppp,f:_ipppp_async,ea:_ippppi,fa:_ippppi_async,B:_ippppij,C:_ippppij_async,p:_ippppip,q:_ippppip_async,la:_ipppppip,ma:_ipppppip_async,D:_proc_exit,na:_vppippii,r:_vppippii_async,l:_vppp,m:_vppp_async,W:_vpppip,ca:_vpppip_async};var wasmExports=await createWasm();var ___wasm_call_ctors=wasmExports["qa"];var _powersync_init_static=Module["_powersync_init_static"]=wasmExports["ra"];var _memcpy=Module["_memcpy"]=wasmExports["sa"];var _memset=Module["_memset"]=wasmExports["ta"];var _memcmp=Module["_memcmp"]=wasmExports["ua"];var _sqlite3_status64=Module["_sqlite3_status64"]=wasmExports["va"];var _sqlite3_status=Module["_sqlite3_status"]=wasmExports["wa"];var _sqlite3_msize=Module["_sqlite3_msize"]=wasmExports["xa"];var _sqlite3_db_status=Module["_sqlite3_db_status"]=wasmExports["ya"];var _sqlite3_vfs_find=Module["_sqlite3_vfs_find"]=wasmExports["za"];var _sqlite3_vfs_register=Module["_sqlite3_vfs_register"]=wasmExports["Aa"];var _sqlite3_vfs_unregister=Module["_sqlite3_vfs_unregister"]=wasmExports["Ba"];var _sqlite3_release_memory=Module["_sqlite3_release_memory"]=wasmExports["Ca"];var _sqlite3_soft_heap_limit64=Module["_sqlite3_soft_heap_limit64"]=wasmExports["Da"];var _sqlite3_memory_used=Module["_sqlite3_memory_used"]=wasmExports["Ea"];var _sqlite3_hard_heap_limit64=Module["_sqlite3_hard_heap_limit64"]=wasmExports["Fa"];var _sqlite3_memory_highwater=Module["_sqlite3_memory_highwater"]=wasmExports["Ga"];var _sqlite3_malloc=Module["_sqlite3_malloc"]=wasmExports["Ha"];var _sqlite3_malloc64=Module["_sqlite3_malloc64"]=wasmExports["Ia"];var _sqlite3_free=Module["_sqlite3_free"]=wasmExports["Ja"];var _sqlite3_realloc=Module["_sqlite3_realloc"]=wasmExports["Ka"];var _sqlite3_realloc64=Module["_sqlite3_realloc64"]=wasmExports["La"];var _sqlite3_str_vappendf=Module["_sqlite3_str_vappendf"]=wasmExports["Ma"];var _sqlite3_str_append=Module["_sqlite3_str_append"]=wasmExports["Na"];var _sqlite3_str_appendchar=Module["_sqlite3_str_appendchar"]=wasmExports["Oa"];var _sqlite3_str_appendall=Module["_sqlite3_str_appendall"]=wasmExports["Pa"];var _sqlite3_str_appendf=Module["_sqlite3_str_appendf"]=wasmExports["Qa"];var _sqlite3_str_finish=Module["_sqlite3_str_finish"]=wasmExports["Ra"];var _sqlite3_str_errcode=Module["_sqlite3_str_errcode"]=wasmExports["Sa"];var _sqlite3_str_length=Module["_sqlite3_str_length"]=wasmExports["Ta"];var _sqlite3_str_value=Module["_sqlite3_str_value"]=wasmExports["Ua"];var _sqlite3_str_reset=Module["_sqlite3_str_reset"]=wasmExports["Va"];var _sqlite3_str_new=Module["_sqlite3_str_new"]=wasmExports["Wa"];var _sqlite3_vmprintf=Module["_sqlite3_vmprintf"]=wasmExports["Xa"];var _sqlite3_mprintf=Module["_sqlite3_mprintf"]=wasmExports["Ya"];var _sqlite3_vsnprintf=Module["_sqlite3_vsnprintf"]=wasmExports["Za"];var _sqlite3_snprintf=Module["_sqlite3_snprintf"]=wasmExports["_a"];var _sqlite3_log=Module["_sqlite3_log"]=wasmExports["$a"];var _sqlite3_randomness=Module["_sqlite3_randomness"]=wasmExports["ab"];var _sqlite3_stricmp=Module["_sqlite3_stricmp"]=wasmExports["bb"];var _sqlite3_strnicmp=Module["_sqlite3_strnicmp"]=wasmExports["cb"];var _sqlite3_os_init=Module["_sqlite3_os_init"]=wasmExports["db"];var _sqlite3_os_end=Module["_sqlite3_os_end"]=wasmExports["eb"];var _sqlite3_serialize=Module["_sqlite3_serialize"]=wasmExports["fb"];var _sqlite3_prepare_v2=Module["_sqlite3_prepare_v2"]=wasmExports["gb"];var _sqlite3_step=Module["_sqlite3_step"]=wasmExports["hb"];var _sqlite3_column_int64=Module["_sqlite3_column_int64"]=wasmExports["ib"];var _sqlite3_reset=Module["_sqlite3_reset"]=wasmExports["jb"];var _sqlite3_exec=Module["_sqlite3_exec"]=wasmExports["kb"];var _sqlite3_column_int=Module["_sqlite3_column_int"]=wasmExports["lb"];var _sqlite3_finalize=Module["_sqlite3_finalize"]=wasmExports["mb"];var _sqlite3_deserialize=Module["_sqlite3_deserialize"]=wasmExports["nb"];var _sqlite3_database_file_object=Module["_sqlite3_database_file_object"]=wasmExports["ob"];var _sqlite3_backup_init=Module["_sqlite3_backup_init"]=wasmExports["pb"];var _sqlite3_backup_step=Module["_sqlite3_backup_step"]=wasmExports["qb"];var _sqlite3_backup_finish=Module["_sqlite3_backup_finish"]=wasmExports["rb"];var _sqlite3_backup_remaining=Module["_sqlite3_backup_remaining"]=wasmExports["sb"];var _sqlite3_backup_pagecount=Module["_sqlite3_backup_pagecount"]=wasmExports["tb"];var _sqlite3_clear_bindings=Module["_sqlite3_clear_bindings"]=wasmExports["ub"];var _sqlite3_value_blob=Module["_sqlite3_value_blob"]=wasmExports["vb"];var _sqlite3_value_text=Module["_sqlite3_value_text"]=wasmExports["wb"];var _sqlite3_value_bytes=Module["_sqlite3_value_bytes"]=wasmExports["xb"];var _sqlite3_value_bytes16=Module["_sqlite3_value_bytes16"]=wasmExports["yb"];var _sqlite3_value_double=Module["_sqlite3_value_double"]=wasmExports["zb"];var _sqlite3_value_int=Module["_sqlite3_value_int"]=wasmExports["Ab"];var _sqlite3_value_int64=Module["_sqlite3_value_int64"]=wasmExports["Bb"];var _sqlite3_value_subtype=Module["_sqlite3_value_subtype"]=wasmExports["Cb"];var _sqlite3_value_pointer=Module["_sqlite3_value_pointer"]=wasmExports["Db"];var _sqlite3_value_text16=Module["_sqlite3_value_text16"]=wasmExports["Eb"];var _sqlite3_value_text16be=Module["_sqlite3_value_text16be"]=wasmExports["Fb"];var _sqlite3_value_text16le=Module["_sqlite3_value_text16le"]=wasmExports["Gb"];var _sqlite3_value_type=Module["_sqlite3_value_type"]=wasmExports["Hb"];var _sqlite3_value_encoding=Module["_sqlite3_value_encoding"]=wasmExports["Ib"];var _sqlite3_value_nochange=Module["_sqlite3_value_nochange"]=wasmExports["Jb"];var _sqlite3_value_frombind=Module["_sqlite3_value_frombind"]=wasmExports["Kb"];var _sqlite3_value_dup=Module["_sqlite3_value_dup"]=wasmExports["Lb"];var _sqlite3_value_free=Module["_sqlite3_value_free"]=wasmExports["Mb"];var _sqlite3_result_blob=Module["_sqlite3_result_blob"]=wasmExports["Nb"];var _sqlite3_result_blob64=Module["_sqlite3_result_blob64"]=wasmExports["Ob"];var _sqlite3_result_double=Module["_sqlite3_result_double"]=wasmExports["Pb"];var _sqlite3_result_error=Module["_sqlite3_result_error"]=wasmExports["Qb"];var _sqlite3_result_error16=Module["_sqlite3_result_error16"]=wasmExports["Rb"];var _sqlite3_result_int=Module["_sqlite3_result_int"]=wasmExports["Sb"];var _sqlite3_result_int64=Module["_sqlite3_result_int64"]=wasmExports["Tb"];var _sqlite3_result_null=Module["_sqlite3_result_null"]=wasmExports["Ub"];var _sqlite3_result_pointer=Module["_sqlite3_result_pointer"]=wasmExports["Vb"];var _sqlite3_result_subtype=Module["_sqlite3_result_subtype"]=wasmExports["Wb"];var _sqlite3_result_text=Module["_sqlite3_result_text"]=wasmExports["Xb"];var _sqlite3_result_text64=Module["_sqlite3_result_text64"]=wasmExports["Yb"];var _sqlite3_result_text16=Module["_sqlite3_result_text16"]=wasmExports["Zb"];var _sqlite3_result_text16be=Module["_sqlite3_result_text16be"]=wasmExports["_b"];var _sqlite3_result_text16le=Module["_sqlite3_result_text16le"]=wasmExports["$b"];var _sqlite3_result_value=Module["_sqlite3_result_value"]=wasmExports["ac"];var _sqlite3_result_error_toobig=Module["_sqlite3_result_error_toobig"]=wasmExports["bc"];var _sqlite3_result_zeroblob=Module["_sqlite3_result_zeroblob"]=wasmExports["cc"];var _sqlite3_result_zeroblob64=Module["_sqlite3_result_zeroblob64"]=wasmExports["dc"];var _sqlite3_result_error_code=Module["_sqlite3_result_error_code"]=wasmExports["ec"];var _sqlite3_result_error_nomem=Module["_sqlite3_result_error_nomem"]=wasmExports["fc"];var _sqlite3_user_data=Module["_sqlite3_user_data"]=wasmExports["gc"];var _sqlite3_context_db_handle=Module["_sqlite3_context_db_handle"]=wasmExports["hc"];var _sqlite3_vtab_nochange=Module["_sqlite3_vtab_nochange"]=wasmExports["ic"];var _sqlite3_vtab_in_first=Module["_sqlite3_vtab_in_first"]=wasmExports["jc"];var _sqlite3_vtab_in_next=Module["_sqlite3_vtab_in_next"]=wasmExports["kc"];var _sqlite3_aggregate_context=Module["_sqlite3_aggregate_context"]=wasmExports["lc"];var _sqlite3_get_auxdata=Module["_sqlite3_get_auxdata"]=wasmExports["mc"];var _sqlite3_set_auxdata=Module["_sqlite3_set_auxdata"]=wasmExports["nc"];var _sqlite3_column_count=Module["_sqlite3_column_count"]=wasmExports["oc"];var _sqlite3_data_count=Module["_sqlite3_data_count"]=wasmExports["pc"];var _sqlite3_column_blob=Module["_sqlite3_column_blob"]=wasmExports["qc"];var _sqlite3_column_bytes=Module["_sqlite3_column_bytes"]=wasmExports["rc"];var _sqlite3_column_bytes16=Module["_sqlite3_column_bytes16"]=wasmExports["sc"];var _sqlite3_column_double=Module["_sqlite3_column_double"]=wasmExports["tc"];var _sqlite3_column_text=Module["_sqlite3_column_text"]=wasmExports["uc"];var _sqlite3_column_value=Module["_sqlite3_column_value"]=wasmExports["vc"];var _sqlite3_column_text16=Module["_sqlite3_column_text16"]=wasmExports["wc"];var _sqlite3_column_type=Module["_sqlite3_column_type"]=wasmExports["xc"];var _sqlite3_column_name=Module["_sqlite3_column_name"]=wasmExports["yc"];var _sqlite3_column_name16=Module["_sqlite3_column_name16"]=wasmExports["zc"];var _sqlite3_bind_blob=Module["_sqlite3_bind_blob"]=wasmExports["Ac"];var _sqlite3_bind_blob64=Module["_sqlite3_bind_blob64"]=wasmExports["Bc"];var _sqlite3_bind_double=Module["_sqlite3_bind_double"]=wasmExports["Cc"];var _sqlite3_bind_int=Module["_sqlite3_bind_int"]=wasmExports["Dc"];var _sqlite3_bind_int64=Module["_sqlite3_bind_int64"]=wasmExports["Ec"];var _sqlite3_bind_null=Module["_sqlite3_bind_null"]=wasmExports["Fc"];var _sqlite3_bind_pointer=Module["_sqlite3_bind_pointer"]=wasmExports["Gc"];var _sqlite3_bind_text=Module["_sqlite3_bind_text"]=wasmExports["Hc"];var _sqlite3_bind_text64=Module["_sqlite3_bind_text64"]=wasmExports["Ic"];var _sqlite3_bind_text16=Module["_sqlite3_bind_text16"]=wasmExports["Jc"];var _sqlite3_bind_value=Module["_sqlite3_bind_value"]=wasmExports["Kc"];var _sqlite3_bind_zeroblob=Module["_sqlite3_bind_zeroblob"]=wasmExports["Lc"];var _sqlite3_bind_zeroblob64=Module["_sqlite3_bind_zeroblob64"]=wasmExports["Mc"];var _sqlite3_bind_parameter_count=Module["_sqlite3_bind_parameter_count"]=wasmExports["Nc"];var _sqlite3_bind_parameter_name=Module["_sqlite3_bind_parameter_name"]=wasmExports["Oc"];var _sqlite3_bind_parameter_index=Module["_sqlite3_bind_parameter_index"]=wasmExports["Pc"];var _sqlite3_db_handle=Module["_sqlite3_db_handle"]=wasmExports["Qc"];var _sqlite3_stmt_readonly=Module["_sqlite3_stmt_readonly"]=wasmExports["Rc"];var _sqlite3_stmt_isexplain=Module["_sqlite3_stmt_isexplain"]=wasmExports["Sc"];var _sqlite3_stmt_explain=Module["_sqlite3_stmt_explain"]=wasmExports["Tc"];var _sqlite3_stmt_busy=Module["_sqlite3_stmt_busy"]=wasmExports["Uc"];var _sqlite3_next_stmt=Module["_sqlite3_next_stmt"]=wasmExports["Vc"];var _sqlite3_stmt_status=Module["_sqlite3_stmt_status"]=wasmExports["Wc"];var _sqlite3_sql=Module["_sqlite3_sql"]=wasmExports["Xc"];var _sqlite3_expanded_sql=Module["_sqlite3_expanded_sql"]=wasmExports["Yc"];var _sqlite3_value_numeric_type=Module["_sqlite3_value_numeric_type"]=wasmExports["Zc"];var _sqlite3_blob_open=Module["_sqlite3_blob_open"]=wasmExports["_c"];var _sqlite3_blob_close=Module["_sqlite3_blob_close"]=wasmExports["$c"];var _sqlite3_blob_read=Module["_sqlite3_blob_read"]=wasmExports["ad"];var _sqlite3_blob_write=Module["_sqlite3_blob_write"]=wasmExports["bd"];var _sqlite3_blob_bytes=Module["_sqlite3_blob_bytes"]=wasmExports["cd"];var _sqlite3_blob_reopen=Module["_sqlite3_blob_reopen"]=wasmExports["dd"];var _sqlite3_set_authorizer=Module["_sqlite3_set_authorizer"]=wasmExports["ed"];var _sqlite3_strglob=Module["_sqlite3_strglob"]=wasmExports["fd"];var _sqlite3_strlike=Module["_sqlite3_strlike"]=wasmExports["gd"];var _sqlite3_errmsg=Module["_sqlite3_errmsg"]=wasmExports["hd"];var _sqlite3_load_extension=Module["_sqlite3_load_extension"]=wasmExports["id"];var _sqlite3_enable_load_extension=Module["_sqlite3_enable_load_extension"]=wasmExports["jd"];var _sqlite3_auto_extension=Module["_sqlite3_auto_extension"]=wasmExports["kd"];var _sqlite3_cancel_auto_extension=Module["_sqlite3_cancel_auto_extension"]=wasmExports["ld"];var _sqlite3_reset_auto_extension=Module["_sqlite3_reset_auto_extension"]=wasmExports["md"];var _sqlite3_prepare=Module["_sqlite3_prepare"]=wasmExports["nd"];var _sqlite3_prepare_v3=Module["_sqlite3_prepare_v3"]=wasmExports["od"];var _sqlite3_prepare16=Module["_sqlite3_prepare16"]=wasmExports["pd"];var _sqlite3_prepare16_v2=Module["_sqlite3_prepare16_v2"]=wasmExports["qd"];var _sqlite3_prepare16_v3=Module["_sqlite3_prepare16_v3"]=wasmExports["rd"];var _sqlite3_get_table=Module["_sqlite3_get_table"]=wasmExports["sd"];var _sqlite3_free_table=Module["_sqlite3_free_table"]=wasmExports["td"];var _sqlite3_create_module=Module["_sqlite3_create_module"]=wasmExports["ud"];var _sqlite3_create_module_v2=Module["_sqlite3_create_module_v2"]=wasmExports["vd"];var _sqlite3_drop_modules=Module["_sqlite3_drop_modules"]=wasmExports["wd"];var _sqlite3_declare_vtab=Module["_sqlite3_declare_vtab"]=wasmExports["xd"];var _sqlite3_vtab_on_conflict=Module["_sqlite3_vtab_on_conflict"]=wasmExports["yd"];var _sqlite3_vtab_config=Module["_sqlite3_vtab_config"]=wasmExports["zd"];var _sqlite3_vtab_collation=Module["_sqlite3_vtab_collation"]=wasmExports["Ad"];var _sqlite3_vtab_in=Module["_sqlite3_vtab_in"]=wasmExports["Bd"];var _sqlite3_vtab_rhs_value=Module["_sqlite3_vtab_rhs_value"]=wasmExports["Cd"];var _sqlite3_vtab_distinct=Module["_sqlite3_vtab_distinct"]=wasmExports["Dd"];var _sqlite3_keyword_name=Module["_sqlite3_keyword_name"]=wasmExports["Ed"];var _sqlite3_keyword_count=Module["_sqlite3_keyword_count"]=wasmExports["Fd"];var _sqlite3_keyword_check=Module["_sqlite3_keyword_check"]=wasmExports["Gd"];var _sqlite3_complete=Module["_sqlite3_complete"]=wasmExports["Hd"];var _sqlite3_complete16=Module["_sqlite3_complete16"]=wasmExports["Id"];var _sqlite3_libversion=Module["_sqlite3_libversion"]=wasmExports["Jd"];var _sqlite3_libversion_number=Module["_sqlite3_libversion_number"]=wasmExports["Kd"];var _sqlite3_threadsafe=Module["_sqlite3_threadsafe"]=wasmExports["Ld"];var _sqlite3_initialize=Module["_sqlite3_initialize"]=wasmExports["Md"];var _sqlite3_shutdown=Module["_sqlite3_shutdown"]=wasmExports["Nd"];var _sqlite3_config=Module["_sqlite3_config"]=wasmExports["Od"];var _sqlite3_db_mutex=Module["_sqlite3_db_mutex"]=wasmExports["Pd"];var _sqlite3_db_release_memory=Module["_sqlite3_db_release_memory"]=wasmExports["Qd"];var _sqlite3_db_cacheflush=Module["_sqlite3_db_cacheflush"]=wasmExports["Rd"];var _sqlite3_db_config=Module["_sqlite3_db_config"]=wasmExports["Sd"];var _sqlite3_last_insert_rowid=Module["_sqlite3_last_insert_rowid"]=wasmExports["Td"];var _sqlite3_set_last_insert_rowid=Module["_sqlite3_set_last_insert_rowid"]=wasmExports["Ud"];var _sqlite3_changes64=Module["_sqlite3_changes64"]=wasmExports["Vd"];var _sqlite3_changes=Module["_sqlite3_changes"]=wasmExports["Wd"];var _sqlite3_total_changes64=Module["_sqlite3_total_changes64"]=wasmExports["Xd"];var _sqlite3_total_changes=Module["_sqlite3_total_changes"]=wasmExports["Yd"];var _sqlite3_txn_state=Module["_sqlite3_txn_state"]=wasmExports["Zd"];var _sqlite3_close=Module["_sqlite3_close"]=wasmExports["_d"];var _sqlite3_close_v2=Module["_sqlite3_close_v2"]=wasmExports["$d"];var _sqlite3_busy_handler=Module["_sqlite3_busy_handler"]=wasmExports["ae"];var _sqlite3_progress_handler=Module["_sqlite3_progress_handler"]=wasmExports["be"];var _sqlite3_busy_timeout=Module["_sqlite3_busy_timeout"]=wasmExports["ce"];var _sqlite3_interrupt=Module["_sqlite3_interrupt"]=wasmExports["de"];var _sqlite3_is_interrupted=Module["_sqlite3_is_interrupted"]=wasmExports["ee"];var _sqlite3_create_function=Module["_sqlite3_create_function"]=wasmExports["fe"];var _sqlite3_create_function_v2=Module["_sqlite3_create_function_v2"]=wasmExports["ge"];var _sqlite3_create_window_function=Module["_sqlite3_create_window_function"]=wasmExports["he"];var _sqlite3_create_function16=Module["_sqlite3_create_function16"]=wasmExports["ie"];var _sqlite3_overload_function=Module["_sqlite3_overload_function"]=wasmExports["je"];var _sqlite3_trace_v2=Module["_sqlite3_trace_v2"]=wasmExports["ke"];var _sqlite3_commit_hook=Module["_sqlite3_commit_hook"]=wasmExports["le"];var _sqlite3_update_hook=Module["_sqlite3_update_hook"]=wasmExports["me"];var _sqlite3_rollback_hook=Module["_sqlite3_rollback_hook"]=wasmExports["ne"];var _sqlite3_autovacuum_pages=Module["_sqlite3_autovacuum_pages"]=wasmExports["oe"];var _sqlite3_wal_autocheckpoint=Module["_sqlite3_wal_autocheckpoint"]=wasmExports["pe"];var _sqlite3_wal_hook=Module["_sqlite3_wal_hook"]=wasmExports["qe"];var _sqlite3_wal_checkpoint_v2=Module["_sqlite3_wal_checkpoint_v2"]=wasmExports["re"];var _sqlite3_wal_checkpoint=Module["_sqlite3_wal_checkpoint"]=wasmExports["se"];var _sqlite3_error_offset=Module["_sqlite3_error_offset"]=wasmExports["te"];var _sqlite3_errmsg16=Module["_sqlite3_errmsg16"]=wasmExports["ue"];var _sqlite3_errcode=Module["_sqlite3_errcode"]=wasmExports["ve"];var _sqlite3_extended_errcode=Module["_sqlite3_extended_errcode"]=wasmExports["we"];var _sqlite3_system_errno=Module["_sqlite3_system_errno"]=wasmExports["xe"];var _sqlite3_errstr=Module["_sqlite3_errstr"]=wasmExports["ye"];var _sqlite3_limit=Module["_sqlite3_limit"]=wasmExports["ze"];var _sqlite3_open=Module["_sqlite3_open"]=wasmExports["Ae"];var _sqlite3_open_v2=Module["_sqlite3_open_v2"]=wasmExports["Be"];var _sqlite3_open16=Module["_sqlite3_open16"]=wasmExports["Ce"];var _sqlite3_create_collation=Module["_sqlite3_create_collation"]=wasmExports["De"];var _sqlite3_create_collation_v2=Module["_sqlite3_create_collation_v2"]=wasmExports["Ee"];var _sqlite3_create_collation16=Module["_sqlite3_create_collation16"]=wasmExports["Fe"];var _sqlite3_collation_needed=Module["_sqlite3_collation_needed"]=wasmExports["Ge"];var _sqlite3_collation_needed16=Module["_sqlite3_collation_needed16"]=wasmExports["He"];var _sqlite3_get_clientdata=Module["_sqlite3_get_clientdata"]=wasmExports["Ie"];var _sqlite3_set_clientdata=Module["_sqlite3_set_clientdata"]=wasmExports["Je"];var _sqlite3_get_autocommit=Module["_sqlite3_get_autocommit"]=wasmExports["Ke"];var _sqlite3_table_column_metadata=Module["_sqlite3_table_column_metadata"]=wasmExports["Le"];var _sqlite3_sleep=Module["_sqlite3_sleep"]=wasmExports["Me"];var _sqlite3_extended_result_codes=Module["_sqlite3_extended_result_codes"]=wasmExports["Ne"];var _sqlite3_file_control=Module["_sqlite3_file_control"]=wasmExports["Oe"];var _sqlite3_test_control=Module["_sqlite3_test_control"]=wasmExports["Pe"];var _sqlite3_create_filename=Module["_sqlite3_create_filename"]=wasmExports["Qe"];var _sqlite3_free_filename=Module["_sqlite3_free_filename"]=wasmExports["Re"];var _sqlite3_uri_parameter=Module["_sqlite3_uri_parameter"]=wasmExports["Se"];var _sqlite3_uri_key=Module["_sqlite3_uri_key"]=wasmExports["Te"];var _sqlite3_uri_boolean=Module["_sqlite3_uri_boolean"]=wasmExports["Ue"];var _sqlite3_uri_int64=Module["_sqlite3_uri_int64"]=wasmExports["Ve"];var _sqlite3_filename_database=Module["_sqlite3_filename_database"]=wasmExports["We"];var _sqlite3_filename_journal=Module["_sqlite3_filename_journal"]=wasmExports["Xe"];var _sqlite3_filename_wal=Module["_sqlite3_filename_wal"]=wasmExports["Ye"];var _sqlite3_db_name=Module["_sqlite3_db_name"]=wasmExports["Ze"];var _sqlite3_db_filename=Module["_sqlite3_db_filename"]=wasmExports["_e"];var _sqlite3_db_readonly=Module["_sqlite3_db_readonly"]=wasmExports["$e"];var _sqlite3_compileoption_used=Module["_sqlite3_compileoption_used"]=wasmExports["af"];var _sqlite3_compileoption_get=Module["_sqlite3_compileoption_get"]=wasmExports["bf"];var _sqlite3_sourceid=Module["_sqlite3_sourceid"]=wasmExports["cf"];var _malloc=Module["_malloc"]=wasmExports["df"];var _free=Module["_free"]=wasmExports["ef"];var _RegisterExtensionFunctions=Module["_RegisterExtensionFunctions"]=wasmExports["ff"];var _getSqliteFree=Module["_getSqliteFree"]=wasmExports["gf"];var _main=Module["_main"]=wasmExports["hf"];var _libauthorizer_set_authorizer=Module["_libauthorizer_set_authorizer"]=wasmExports["jf"];var _libfunction_create_function=Module["_libfunction_create_function"]=wasmExports["kf"];var _libhook_commit_hook=Module["_libhook_commit_hook"]=wasmExports["lf"];var _libhook_update_hook=Module["_libhook_update_hook"]=wasmExports["mf"];var _libprogress_progress_handler=Module["_libprogress_progress_handler"]=wasmExports["nf"];var _libvfs_vfs_register=Module["_libvfs_vfs_register"]=wasmExports["of"];var _emscripten_builtin_memalign=wasmExports["qf"];var __emscripten_timeout=wasmExports["rf"];var __emscripten_tempret_get=wasmExports["sf"];var __emscripten_stack_restore=wasmExports["tf"];var __emscripten_stack_alloc=wasmExports["uf"];var _emscripten_stack_get_current=wasmExports["vf"];var dynCall_viiiij=Module["dynCall_viiiij"]=wasmExports["dynCall_viiiij"];var dynCall_vijii=Module["dynCall_vijii"]=wasmExports["dynCall_vijii"];var dynCall_iiiij=Module["dynCall_iiiij"]=wasmExports["dynCall_iiiij"];var dynCall_viji=Module["dynCall_viji"]=wasmExports["dynCall_viji"];var dynCall_iij=Module["dynCall_iij"]=wasmExports["dynCall_iij"];var dynCall_iijii=Module["dynCall_iijii"]=wasmExports["dynCall_iijii"];var dynCall_iiji=Module["dynCall_iiji"]=wasmExports["dynCall_iiji"];var dynCall_iiiiiij=Module["dynCall_iiiiiij"]=wasmExports["dynCall_iiiiiij"];var dynCall_iiij=Module["dynCall_iiij"]=wasmExports["dynCall_iiij"];var dynCall_jii=Module["dynCall_jii"]=wasmExports["dynCall_jii"];var dynCall_ji=Module["dynCall_ji"]=wasmExports["dynCall_ji"];var dynCall_vij=Module["dynCall_vij"]=wasmExports["dynCall_vij"];var dynCall_iiiiijii=Module["dynCall_iiiiijii"]=wasmExports["dynCall_iiiiijii"];var dynCall_j=Module["dynCall_j"]=wasmExports["dynCall_j"];var dynCall_jj=Module["dynCall_jj"]=wasmExports["dynCall_jj"];var dynCall_jiij=Module["dynCall_jiij"]=wasmExports["dynCall_jiij"];var dynCall_iiiiji=Module["dynCall_iiiiji"]=wasmExports["dynCall_iiiiji"];var dynCall_iiiijii=Module["dynCall_iiiijii"]=wasmExports["dynCall_iiiijii"];var dynCall_ij=Module["dynCall_ij"]=wasmExports["dynCall_ij"];var dynCall_viiji=Module["dynCall_viiji"]=wasmExports["dynCall_viiji"];var dynCall_viijii=Module["dynCall_viijii"]=wasmExports["dynCall_viijii"];var dynCall_iiiijji=Module["dynCall_iiiijji"]=wasmExports["dynCall_iiiijji"];var _sqlite3_version=Module["_sqlite3_version"]=79828;function callMain(){var entryFunction=_main;var argc=0;var argv=0;try{var ret=entryFunction(argc,argv);exitJS(ret,true);return ret}catch(e){return handleException(e)}}function run(){if(runDependencies>0){dependenciesFulfilled=run;return}preRun();if(runDependencies>0){dependenciesFulfilled=run;return}function doRun(){Module["calledRun"]=true;if(ABORT)return;initRuntime();preMain();readyPromiseResolve(Module);Module["onRuntimeInitialized"]?.();var noInitialRun=Module["noInitialRun"]||false;if(!noInitialRun)callMain();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(()=>{setTimeout(()=>Module["setStatus"](""),1);doRun()},1)}else{doRun()}}function preInit(){if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].shift()()}}}preInit();run();(function(){const AsyncFunction=Object.getPrototypeOf(async function(){}).constructor;let pAsyncFlags=0;Module["set_authorizer"]=function(db,xAuthorizer,pApp){if(pAsyncFlags){Module["deleteCallback"](pAsyncFlags);Module["_sqlite3_free"](pAsyncFlags);pAsyncFlags=0}pAsyncFlags=Module["_sqlite3_malloc"](4);setValue(pAsyncFlags,xAuthorizer instanceof AsyncFunction?1:0,"i32");const result=ccall("libauthorizer_set_authorizer","number",["number","number","number"],[db,xAuthorizer?1:0,pAsyncFlags]);if(!result&&xAuthorizer){Module["setCallback"](pAsyncFlags,(_,iAction,p3,p4,p5,p6)=>xAuthorizer(pApp,iAction,p3,p4,p5,p6))}return result}})();(function(){const AsyncFunction=Object.getPrototypeOf(async function(){}).constructor;const FUNC_METHODS=["xFunc","xStep","xFinal"];const mapFunctionNameToKey=new Map;Module["create_function"]=function(db,zFunctionName,nArg,eTextRep,pApp,xFunc,xStep,xFinal){const pAsyncFlags=Module["_sqlite3_malloc"](4);const target={xFunc,xStep,xFinal};setValue(pAsyncFlags,FUNC_METHODS.reduce((mask,method,i)=>{if(target[method]instanceof AsyncFunction){return mask|1<<i}return mask},0),"i32");const result=ccall("libfunction_create_function","number",["number","string","number","number","number","number","number","number"],[db,zFunctionName,nArg,eTextRep,pAsyncFlags,xFunc?1:0,xStep?1:0,xFinal?1:0]);if(!result){if(mapFunctionNameToKey.has(zFunctionName)){const oldKey=mapFunctionNameToKey.get(zFunctionName);Module["deleteCallback"](oldKey)}mapFunctionNameToKey.set(zFunctionName,pAsyncFlags);Module["setCallback"](pAsyncFlags,{xFunc,xStep,xFinal})}return result}})();(function(){const AsyncFunction=Object.getPrototypeOf(async function(){}).constructor;let pAsyncFlags=0;Module["update_hook"]=function(db,xUpdateHook){if(pAsyncFlags){Module["deleteCallback"](pAsyncFlags);Module["_sqlite3_free"](pAsyncFlags);pAsyncFlags=0}pAsyncFlags=Module["_sqlite3_malloc"](4);setValue(pAsyncFlags,xUpdateHook instanceof AsyncFunction?1:0,"i32");ccall("libhook_update_hook","void",["number","number","number"],[db,xUpdateHook?1:0,pAsyncFlags]);if(xUpdateHook){Module["setCallback"](pAsyncFlags,(_,iUpdateType,dbName,tblName,lo32,hi32)=>xUpdateHook(iUpdateType,dbName,tblName,lo32,hi32))}}})();(function(){const AsyncFunction=Object.getPrototypeOf(async function(){}).constructor;let pAsyncFlags=0;Module["commit_hook"]=function(db,xCommitHook){if(pAsyncFlags){Module["deleteCallback"](pAsyncFlags);Module["_sqlite3_free"](pAsyncFlags);pAsyncFlags=0}pAsyncFlags=Module["_sqlite3_malloc"](4);setValue(pAsyncFlags,xCommitHook instanceof AsyncFunction?1:0,"i32");ccall("libhook_commit_hook","void",["number","number","number"],[db,xCommitHook?1:0,pAsyncFlags]);if(xCommitHook){Module["setCallback"](pAsyncFlags,_=>xCommitHook())}}})();(function(){const AsyncFunction=Object.getPrototypeOf(async function(){}).constructor;let pAsyncFlags=0;Module["progress_handler"]=function(db,nOps,xProgress,pApp){if(pAsyncFlags){Module["deleteCallback"](pAsyncFlags);Module["_sqlite3_free"](pAsyncFlags);pAsyncFlags=0}pAsyncFlags=Module["_sqlite3_malloc"](4);setValue(pAsyncFlags,xProgress instanceof AsyncFunction?1:0,"i32");ccall("libprogress_progress_handler","number",["number","number","number","number"],[db,nOps,xProgress?1:0,pAsyncFlags]);if(xProgress){Module["setCallback"](pAsyncFlags,_=>xProgress(pApp))}}})();(function(){const VFS_METHODS=["xOpen","xDelete","xAccess","xFullPathname","xRandomness","xSleep","xCurrentTime","xGetLastError","xCurrentTimeInt64","xClose","xRead","xWrite","xTruncate","xSync","xFileSize","xLock","xUnlock","xCheckReservedLock","xFileControl","xSectorSize","xDeviceCharacteristics","xShmMap","xShmLock","xShmBarrier","xShmUnmap"];const mapVFSNameToKey=new Map;Module["vfs_register"]=function(vfs,makeDefault){let methodMask=0;let asyncMask=0;VFS_METHODS.forEach((method,i)=>{if(vfs[method]){methodMask|=1<<i;if(vfs["hasAsyncMethod"](method)){asyncMask|=1<<i}}});const vfsReturn=Module["_sqlite3_malloc"](4);try{const result=ccall("libvfs_vfs_register","number",["string","number","number","number","number","number"],[vfs.name,vfs.mxPathname,methodMask,asyncMask,makeDefault?1:0,vfsReturn]);if(!result){if(mapVFSNameToKey.has(vfs.name)){const oldKey=mapVFSNameToKey.get(vfs.name);Module["deleteCallback"](oldKey)}const key=getValue(vfsReturn,"*");mapVFSNameToKey.set(vfs.name,key);Module["setCallback"](key,vfs)}return result}finally{Module["_sqlite3_free"](vfsReturn)}}})();moduleRtn=readyPromise;
8
+
9
+
10
+ return moduleRtn;
11
+ }
12
+ );
13
+ })();
14
+ export default Module;
@@ -1,5 +1,45 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.126
4
+
5
+ Signed: Run Edit Run fleet, 2026-11-20.
6
+
7
+ ### Platform archives into native destinations
8
+
9
+ - A Platform-origin archive can restore into a native destination with applied owner migrations even when Platform recorded the core and owner files in a different order. Restore matches the recorded hashes to the destination's own files, replays them in the destination's applied order, and requires the result to reproduce the archive schema before bridging later migrations. This covers the qualified Platform-to-native path that rer 0.2.124 and 0.2.125 refused with `schema_mismatch`.
10
+ - Changed migration bytes, a missing recorded entry, an archive-extra owner migration, an absent applied owner file, or a reorder that changes the archived schema still refuse before importing product rows or creating import jobs. The Worker returns HTTP 409 and the CLI exits 4; invalid native owner history reports `schema_mismatch:owner_migration_history`.
11
+ - Core-only Worker bundles grow by about 0.7 KB compared with 0.2.125 in the qualified fixture. SQLite WASM and owner replay remain excluded when there are no owner migration files.
12
+
13
+ ### Bounded local inspection
14
+
15
+ - Port inspection stops waiting when its inspection deadline expires, even if an `lsof` child remains hung, and reports the port unchecked. A host-scoped probe skips process inspection only after a successful bind and explicit TCP refusal on the applicable loopback addresses; ambiguous and any-address probes still inspect.
16
+ - The verified pnpm version probe keeps three cached-tool attempts at 10, 20 and 30 seconds at idle. Deadlines scale with one-minute load per CPU, capped at 40, 80 and 120 seconds. A failed probe reports the final attempt's deadline.
17
+ - Maintained CLI and onboarding copies and inventory are regenerated.
18
+
19
+ Archives written by rer 0.2.124 or 0.2.125 import into 0.2.126, and 0.2.126 archives import into those versions for the same compatible fixtures: the archive format identity remains `runeditrun-portability` version 2, unchanged from 0.2.125. This does not give older readers the new Platform-to-native restore behavior.
20
+
21
+ HappyToHelp and any seed with Platform-origin history on rer 0.2.124 or 0.2.125 need a re-pin to 0.2.126. ChargeDesk pins rer 0.2.118 and other seeds have older pins; re-pin to receive these fixes.
22
+
23
+ These changes require adoption through the seed's pinned package or refreshed source. This preparation establishes no seed adoption, live deployment, provider delivery or production result. The source range changes portability, onboarding inspection and their maintained copies, with no import-kit or product migration change.
24
+
25
+ ## 0.2.125
26
+
27
+ Signed: Run Edit Run fleet, 2026-11-19.
28
+
29
+ ### Worker archive restore in applied order
30
+
31
+ - Worker restore replays interleaved core and owner migrations in their recorded applied order. This resolves the 0.2.124 known limit where an owner ALTER followed by a later core upgrade could cause a matching archive to refuse with HTTP 409.
32
+ - The Worker bundles the SQLite WASM and owner replay module only when at least one owner migration SQL file exists. A declared optional owner directory that is absent or empty keeps the core-only build path. Core-only Worker bundles add 330 bytes of shared evidence dispatch compared with 0.2.124 in the qualified fixture.
33
+ - The portability adoption list documents the replay modules. Maintained CLI copies and inventory are regenerated.
34
+
35
+ Archives with owner migrations written by rer 0.2.124 or later are not readable by rer 0.2.123 or older (`manifest_inventory`), unchanged from 0.2.124. The archive format remains `runeditrun-portability` version 2, unchanged from 0.2.124.
36
+
37
+ An owner-enabled Worker bundle grows by about 1.18 MB for the SQLite WASM and replay support compared with 0.2.124; this applies only to an owner-enabled build.
38
+
39
+ ChargeDesk checkouts pin rer 0.2.118 and other seeds have older pins, and need a re-pin to receive this fix.
40
+
41
+ These changes require adoption through the seed's pinned package or refreshed source. This preparation establishes no seed adoption, live Spool deployment, provider delivery or production result. The source range changes portability and its maintained copies, with no import-kit or product migration change.
42
+
3
43
  ## 0.2.124
4
44
 
5
45
  Signed: Run Edit Run fleet, 2026-11-19.
package/global/README.md CHANGED
@@ -434,6 +434,9 @@ Licence: MIT.
434
434
 
435
435
  First-party commands acquire the exact `packageManager` pnpm pin when PATH lacks
436
436
  it, verify its registry sha512 integrity and cache it under `$HOME/.rer/pnpm`.
437
+ The verified tool's version check keeps three attempts. Their 10, 20 and
438
+ 30 second deadlines scale with one-minute load per CPU, up to four times.
439
+ If the check fails, rer reports what pnpm did and the final attempt's deadline.
437
440
  No global package manager installation or sudo is needed. Independent projects
438
441
  continue to run their declared commands with their own tools. Server and job
439
442
  state default to `$HOME/.rer/servers` and `$HOME/.rer/jobs`; supplied
@@ -611,18 +611,22 @@ declare module 'virtual:rer-legacy-migration-evidence' {
611
611
  }
612
612
  ```
613
613
 
614
- The generated JavaScript contains ordered checkout file hashes and statements,
615
- deduplicated complete schema inventories for every prefix, and hashed identities
616
- of bounded deterministic seeded rows. Volatile seeded rows cannot be vouched for;
617
- their values are never bundled. Runtime policy projects each inventory through
618
- the same schema identity code as live SQLite. The Worker adapter binds evidence
619
- to the live hashed ledger and complete schema, then supplies the existing legacy
620
- collector, archived-ledger validation, bridge and restore guards.
614
+ The generated JavaScript contains checkout file hashes and statements. A checkout
615
+ with only core migrations bundles its prefix inventories and bounded deterministic
616
+ seed-row hashes at build time, including when declared owner migration directories
617
+ are absent or empty. At least one owner SQL migration file enables the SQLite
618
+ engine and replay module. The Worker makes those inventories in a
619
+ fresh in-memory database using the combined order recorded by the live core and
620
+ owner ledgers. Volatile seeded rows cannot be vouched for. Runtime policy
621
+ projects each inventory through the same schema identity code as live SQLite.
622
+ The Worker adapter binds evidence to the live ledger and complete schema, then
623
+ supplies the legacy collector, archived-ledger validation, bridge and restore
624
+ guards.
621
625
 
622
626
  The same explicit build-evidence adoption supports native Wrangler's plain
623
627
  `d1_migrations` ledger. Keep the reviewed, unchanged applied migration files in
624
- the binding's declared directory when building. Every live name must select the
625
- exact ordered prefix of those files, and replay of that prefix must reproduce
628
+ the binding's declared directories when building. Each ledger's live names must
629
+ select the exact ordered prefix of its files, and combined replay must reproduce
626
630
  the complete live schema, including indexes and triggers on excluded tables.
627
631
  Unknown names, gaps, reordered names, tracked but missing hashes, and schema
628
632
  drift refuse before restore writes. Existing hashes must still match; the
@@ -681,12 +685,18 @@ them into a scratch database to find the archive's place in that history:
681
685
  recorded. Where the exporter has no checkout files (a hosted export), the
682
686
  ledger's own names are kept beside their hashes. Import resolves each entry
683
687
  by hash exactly as it does an archived ledger table (next item), so a
684
- Platform prefix needs no declaration and a changed file refuses. Platform's
685
- ledger is never imported as product tables. Native sources with applied
688
+ Platform prefix needs no declaration and a changed file refuses. For archives
689
+ with a schema object inventory, the matched files replay in the destination's
690
+ order, which may differ from Platform's. That replay must still reproduce the
691
+ archive schema before any later migrations can be bridged. Platform's ledger
692
+ is never imported as product tables. Native sources with applied
686
693
  owner migrations carry `{origin:'d1_migrations',entries:[{name,sha256}]}`
687
694
  in the same field. The entries combine core names and prefixed owner names
688
695
  in recorded application order. Restore checks those names and hashes against
689
- the destination's applied history and keeps both ledgers in place. Core-only
696
+ the destination's applied history and keeps both ledgers in place. A changed,
697
+ reordered or incomplete native owner history that cannot reproduce the archive
698
+ schema, or an applied owner migration missing from the destination checkout,
699
+ refuses with `schema_mismatch:owner_migration_history`. Core-only
690
700
  native archives use `manifest.migrations` as before, and v1 and earlier v2
691
701
  archives remain importable.
692
702
  - Older archives that still carry their source's migration ledger as a table
@@ -1150,9 +1160,11 @@ modules/portability/bridge.mjs
1150
1160
  modules/portability/library-history.mjs
1151
1161
  modules/portability/checkout-history.mjs
1152
1162
  modules/portability/owner-history.mjs
1163
+ modules/portability/worker-owner-history.mjs
1153
1164
  modules/portability/migration-history.mjs
1154
1165
  modules/portability/ledgers.mjs
1155
1166
  modules/portability/migration-statements.mjs
1167
+ modules/portability/migration-evidence.mjs
1156
1168
  modules/portability/sql-text.mjs
1157
1169
  modules/portability/backfills.mjs
1158
1170
  modules/portability/transient-tables.mjs
@@ -1,4 +1,4 @@
1
- import { all, quote, insist } from './storage.mjs';
1
+ import { all, quote, insist, PortabilityError } from './storage.mjs';
2
2
  import { canonicalJson } from './hash.mjs';
3
3
  import { tokens, identifier, folded } from './generated.mjs';
4
4
  import { laterData } from './backfills.mjs';
@@ -15,6 +15,34 @@ function recordedMigrations(manifest, archived, files, replay) {
15
15
  'schema_mismatch:owner_migration_history',409);
16
16
  return entries.map(entry=>entry.name);
17
17
  }
18
+
19
+ function platformPlacement(manifest) {
20
+ return manifest.migrationLedger?.origin==='rer_migrations' && manifest.schemaObjects!==undefined;
21
+ }
22
+
23
+ function recordedPlacement(manifest, recorded, applied) {
24
+ const selected=applied.filter(name=>recorded.includes(name));
25
+ // Platform and Wrangler may order the same files differently. The hashes
26
+ // already matched; replay their destination order and check the archive schema.
27
+ if(platformPlacement(manifest))return selected;
28
+ const mismatch=manifest.migrationLedger?.origin==='d1_migrations'?'schema_mismatch:owner_migration_history':'schema_mismatch:migration_history';
29
+ insist(canonicalJson(selected)===canonicalJson(recorded),mismatch,409);
30
+ return recorded;
31
+ }
32
+
33
+ async function verifyRecordedSchema(manifest, earlier, schemaAfter) {
34
+ const owner=manifest.migrationLedger?.origin==='d1_migrations';
35
+ const platform=platformPlacement(manifest);
36
+ let schema;
37
+ try { schema=await schemaAfter(earlier,platform); }
38
+ catch(error) {
39
+ // The full destination replay succeeded. An incomplete native history can
40
+ // now fail on a missing SQL dependency or the Worker's prefix requirement.
41
+ if(!owner || !(error?.code==='ERR_SQLITE_ERROR' || error instanceof PortabilityError && error.code==='schema_mismatch:legacy_evidence'))throw error;
42
+ throw new PortabilityError('schema_mismatch:owner_migration_history',409);
43
+ }
44
+ insist(schema===manifest.schema,owner?'schema_mismatch:owner_migration_history':'schema_mismatch',owner || platform?409:400);
45
+ }
18
46
  // Where an archive sits in the destination's applied migrations: those its
19
47
  // rows passed through (earlier) and those applied after it (unapplied).
20
48
  // migrations() is the runner's replay of the destination's applied migrations
@@ -37,14 +65,12 @@ async function placement(db,manifest,cat,replay,ledger,history,legacyRecovery,un
37
65
  // archive placement. The live destination check above remains complete, and
38
66
  // current v2 imports use their authenticated object inventory. Verified legacy
39
67
  // v2 uses the replayed complete identity; acknowledged recovery places by tables only.
40
- const schemaAfter=names=>replay.schemaAfter(names,legacyRecovery && manifest.schemaObjects===undefined?{legacyExcludedObjects:true}:unverified?{tablesOnly:true}:undefined);
68
+ const schemaAfter=(names,allowSubsequence)=>replay.schemaAfter(names,legacyRecovery && manifest.schemaObjects===undefined?{legacyExcludedObjects:true}:unverified?{tablesOnly:true}:undefined,allowSubsequence);
41
69
  if(unverified && archived && manifest.migrations)insist(canonicalJson(matchMigrationLedger(archived,files,replay))===canonicalJson(recorded),'schema_mismatch:migration_history',409);
42
70
  let earlier,unapplied;
43
71
  if(recorded) {
44
- const mismatch=manifest.migrationLedger?.origin==='d1_migrations'?'schema_mismatch:owner_migration_history':'schema_mismatch:migration_history';
45
- insist(recorded.every((name,i)=>applied.indexOf(name)>(i?applied.indexOf(recorded[i-1]):-1)),mismatch,409);
46
- earlier=recorded;
47
- insist(await schemaAfter(earlier)===manifest.schema,'schema_mismatch');
72
+ earlier=recordedPlacement(manifest,recorded,applied);
73
+ await verifyRecordedSchema(manifest,earlier,schemaAfter);
48
74
  unapplied=applied.filter(name=>!earlier.includes(name));
49
75
  }else{
50
76
  // Unrecorded: the latest matching prefix. Migrations that change no archived
@@ -85,12 +111,12 @@ export async function verifiedLegacySchema(ledger,manifest,cat,migrations,histor
85
111
  const files=replay.names.map(name=>({name,sha256:replay.sha256?.(name),aliases:replay.aliases?.(name)}));
86
112
  const archived=history(),recorded=recordedMigrations(manifest,archived,files,replay);
87
113
  const applied=matchMigrationLedger(ledger,files,replay);
88
- if(!recorded?.length || canonicalJson(applied)!==canonicalJson(replay.names)
89
- || !recorded.every((name,i)=>applied.indexOf(name)>(i?applied.indexOf(recorded[i-1]):-1)))return false;
114
+ if(!recorded?.length || canonicalJson(applied)!==canonicalJson(replay.names))return false;
115
+ const earlier=recordedPlacement(manifest,recorded,applied);
90
116
  if(archived && manifest.migrations && canonicalJson(matchMigrationLedger(archived,files,replay))!==canonicalJson(recorded))return false;
91
117
  if(await replay.schemaAfter(applied)!==cat.identity
92
- || await replay.schemaAfter(recorded,manifest.schemaObjects===undefined?{tablesOnly:true}:{legacyExcludedObjects:true})!==manifest.schema)return false;
93
- return await replay.schemaAfter(recorded);
118
+ || await replay.schemaAfter(earlier,manifest.schemaObjects===undefined?{tablesOnly:true}:{legacyExcludedObjects:true})!==manifest.schema)return false;
119
+ return await replay.schemaAfter(earlier);
94
120
  }catch{return false;} // Unknown history or a failed replay is not verification.
95
121
  }
96
122
  // An archive with the destination's schema identity can still predate later
@@ -1,17 +1,21 @@
1
1
  import { catalogue, policy } from './catalogue.mjs';
2
2
  import { readLedger, matchMigrationLedger } from './ledgers.mjs';
3
- import { nativeMigrationHistory, ownerMigrationPolicy } from './owner-history.mjs';
3
+ import { nativeMigrationHistory, ownerMigrationPolicy, requireAppliedOwnerFiles } from './owner-history.mjs';
4
4
  import { insist } from './storage.mjs';
5
5
 
6
+ function bundledPrefix(history,files) {
7
+ return history.entries.every((row,i)=>row.name===files[i]?.name && (history.owners || row.sha256===undefined));
8
+ }
9
+
6
10
  // Both evidence adapters bind the seed's files to live history and the complete
7
- // schema. Only an explicitly bundled Worker may bind plain Wrangler history:
8
- // literal names must select an ordered checkout prefix, never aliases or gaps.
9
- export async function checkoutHistory(db,input,files,replayFor,{nativeWrangler=false,ownerSources=[]}={}) {
11
+ // schema. Plain Wrangler history must select a literal ordered prefix within
12
+ // each ledger. The merged chronology chooses how those prefixes are replayed.
13
+ export async function checkoutHistory(db,input,files,replayFor,{nativeWrangler=false,ownerSources=[],nativePrefix=bundledPrefix}={}) {
10
14
  const history=await (ownerSources.length?nativeMigrationHistory(db,ownerSources):readLedger(db)),ledger=history?.entries??[];
11
15
  insist(ledger.length,'schema_mismatch:legacy_evidence',409);
16
+ requireAppliedOwnerFiles(history,files);
12
17
  if(!ledger.every(row=>row.sha256)) {
13
- insist(nativeWrangler && history.table==='d1_migrations'
14
- && ledger.every((row,i)=>row.name===files[i]?.name && (history.owners || row.sha256===undefined)),
18
+ insist(nativeWrangler && history.table==='d1_migrations' && nativePrefix(history,files),
15
19
  'schema_mismatch:legacy_evidence',409);
16
20
  }
17
21
  const applied=matchMigrationLedger(ledger,files);
@@ -0,0 +1,47 @@
1
+ import { sha256 } from './hash.mjs';
2
+ import { quote } from './storage.mjs';
3
+ import { dataStatement, triggerBodies } from './migration-statements.mjs';
4
+ import { sqliteTokens } from './sqlite-tokens.mjs';
5
+
6
+ // Date functions can default to 'now', so even fixed arguments are
7
+ // conservatively excluded from seeded-row evidence.
8
+ const variable = sql => /\b(?:random|randomblob|date|time|datetime|julianday|strftime|unixepoch|sqlite_version|sqlite_source_id)\s*\(|\bcurrent_(?:date|time|timestamp)\b/i
9
+ .test(sqliteTokens(sql).map(token => token.value).join(' '));
10
+
11
+ export function migrationRecorder(scratch) {
12
+ const unstable = new Set(), applied = [];
13
+ return {
14
+ apply(file) {
15
+ for (const sql of file.statements) {
16
+ const data = dataStatement(sql);
17
+ if (data) {
18
+ const writers = new Set([data.target]);
19
+ for (const name of writers) for (const target of triggerBodies(applied, name)) writers.add(target);
20
+ const definitions = scratch.all('SELECT name,sql FROM sqlite_master WHERE sql IS NOT NULL');
21
+ if (variable(sql) || data.names.some(name => unstable.has(name))
22
+ || definitions.some(row => writers.has(row.name.toLowerCase()) && variable(row.sql))
23
+ || applied.some(statement => variable(statement) && triggerBodies([statement], data.target).some(name => writers.has(name)))) {
24
+ for (const name of writers) unstable.add(name);
25
+ }
26
+ }
27
+ scratch.exec(sql);
28
+ applied.push(sql);
29
+ }
30
+ },
31
+ inventory() {
32
+ const objects = scratch.all("SELECT name,sql,type,tbl_name FROM sqlite_master WHERE sql IS NOT NULL AND substr(lower(name),1,7)<>'sqlite_' AND substr(lower(name),1,4)<>'_cf_' ORDER BY name,type");
33
+ const kinds = scratch.all('PRAGMA table_list').filter(table => table.type === 'shadow').map(({ name, type }) => ({ name, type }));
34
+ return { objects, kinds };
35
+ },
36
+ async seeds(objects) {
37
+ const seeds = [];
38
+ for (const { name } of objects.filter(object => object.type === 'table')) {
39
+ const columns = scratch.all(`PRAGMA table_info(${quote(name)})`).map(column => column.name);
40
+ const rows = scratch.all(`SELECT json_array(${columns.map(column => `quote(${quote(column)})`).join(',')}) image FROM ${quote(name)} LIMIT 10001`);
41
+ if (rows.length > 10000 || unstable.has(name.toLowerCase()) && rows.length) continue;
42
+ seeds.push({ name, columns, hashes: (await Promise.all(rows.map(row => sha256(row.image)))).sort() });
43
+ }
44
+ return seeds;
45
+ },
46
+ };
47
+ }
@@ -32,11 +32,18 @@ export async function nativeMigrationHistory(db, sources) {
32
32
  const rows = [...core, ...owners].sort((a, b) => a.applied_at.localeCompare(b.applied_at));
33
33
  // IDs order each ledger. Across ledgers equal timestamps carry no order.
34
34
  insist(rows.every((row, i) => !i || row.applied_at !== rows[i - 1].applied_at || row.table === rows[i - 1].table), 'migration_ledger:uncertain', 409);
35
- const entries = rows.map(({ name, sha256 }) => ({ name, ...(sha256 ? { sha256 } : {}) }));
35
+ const entries = rows.map(({ name, sha256, table }) => ({ name, table, ...(sha256 ? { sha256 } : {}) }));
36
36
  insist(new Set(entries.map(row => row.name)).size === entries.length, 'migration_ledger:ambiguous', 409);
37
37
  return { table: ledger.table, entries, owners: true };
38
38
  }
39
39
 
40
+ export function requireAppliedOwnerFiles(history, files) {
41
+ if (!history?.owners) return;
42
+ const names = new Set(files.map(file => file.name));
43
+ insist(history.entries.every(row => row.table === history.table || names.has(row.name)),
44
+ 'schema_mismatch:owner_migration_history', 409);
45
+ }
46
+
40
47
  // The existing service callback is also used for core-only replay. Consult it
41
48
  // early only when native owner bookkeeping may exist. The replay supplies the
42
49
  // declared table identities; a similar product table never becomes bookkeeping.
@@ -1,10 +1,26 @@
1
1
  import type { ArchivePolicy, MigrationReplay } from './index.mjs';
2
- export interface MigrationEvidence {
2
+ type MigrationFile = {name:string;sha256:string;statements:string[]};
3
+ type OwnerSource = {prefix:string;table:string};
4
+ type SchemaObject = {name:string;sql:string;type:string;tbl_name:string};
5
+ type SeedRows = {name:string;columns:string[];hashes:string[]};
6
+ interface BundledEvidence {
3
7
  version:1;
4
- files:{name:string;sha256:string;statements:string[]}[];
5
- ownerSources?:{prefix:string;table:string}[];
6
- objects:{name:string;sql:string;type:string;tbl_name:string}[];
7
- prefixes:{objects:number[];shadows:string[];seeds:{name:string;columns:string[];hashes:string[]}[]}[];
8
+ files:MigrationFile[];
9
+ ownerSources?:OwnerSource[];
10
+ objects:SchemaObject[];
11
+ prefixes:{objects:number[];shadows:string[];seeds:SeedRows[]}[];
8
12
  }
13
+ type OrderedFile = MigrationFile & {table?:string};
14
+ interface OrderedEvidence {
15
+ version:2;
16
+ files:OrderedFile[];
17
+ ownerSources:OwnerSource[];
18
+ nativePrefix(history:{table:string;owners?:boolean;entries:{name:string;table?:string;sha256?:string}[]},files:OrderedFile[]):boolean;
19
+ snapshots(names:string[]):Promise<{
20
+ inventory(index:number):{objects:SchemaObject[];kinds:{name:string;type:string}[]};
21
+ seeds:SeedRows[];
22
+ }>;
23
+ }
24
+ export type MigrationEvidence = BundledEvidence | OrderedEvidence;
9
25
  /** Return a replay bound to the destination's hashed history or exact native Wrangler prefix, and complete schema. */
10
26
  export function workerMigrations(db:D1Database,policy:ArchivePolicy,evidence:MigrationEvidence):Promise<MigrationReplay>;
@@ -3,27 +3,36 @@ import { canonicalJson } from './hash.mjs';
3
3
  import { checkoutHistory } from './checkout-history.mjs';
4
4
  import { insist, PortabilityError } from './storage.mjs';
5
5
 
6
+ function bundledSnapshots(evidence,names) {
7
+ insist(evidence.prefixes.length===evidence.files.length+1
8
+ && names.every((name,i)=>name===evidence.files[i]?.name),'schema_mismatch:legacy_evidence',409);
9
+ return {
10
+ inventory(index){
11
+ const snapshot=evidence.prefixes[index];
12
+ return {objects:snapshot.objects.map(i=>evidence.objects[i]),kinds:snapshot.shadows.map(name=>({name,type:'shadow'}))};
13
+ },
14
+ seeds:evidence.prefixes[names.length].seeds,
15
+ };
16
+ }
17
+
6
18
  // This adapter supplies replay evidence, never archive validation. The same
7
19
  // collector, ledger matching, schema bridge and restore guards serve both doors.
8
20
  export async function workerMigrations(db,input,evidence) {
9
21
  try {
10
- insist(evidence?.version===1 && evidence.prefixes.length===evidence.files.length+1,'schema_mismatch:legacy_evidence',409);
22
+ insist(evidence?.version===1 || evidence?.version===2 && evidence.ownerSources?.length
23
+ && typeof evidence.snapshots==='function' && typeof evidence.nativePrefix==='function','schema_mismatch:legacy_evidence',409);
11
24
  const {files,ownerSources}=evidence;
12
- return await checkoutHistory(db,input,files,(names,config)=>{
13
- const prefix=selected=>{
14
- insist(selected.length<=names.length && canonicalJson(selected)===canonicalJson(files.slice(0,selected.length).map(f=>f.name)),'schema_mismatch:legacy_evidence',409);
15
- const found=evidence.prefixes[selected.length];
16
- insist(found,'schema_mismatch:legacy_evidence',409);return found;
17
- };
18
- const final=prefix(names);
19
- return {names,statements:name=>files.find(f=>f.name===name)?.statements,sha256:name=>files.find(f=>f.name===name)?.sha256,
20
- schemaAfter(selected,options){
21
- const snapshot=prefix(selected);
22
- return inventorySchemaIdentity({objects:snapshot.objects.map(i=>evidence.objects[i]),kinds:snapshot.shadows.map(name=>({name,type:'shadow'}))},config,options);
25
+ return await checkoutHistory(db,input,files,async (names,config)=>{
26
+ const {inventory,seeds,replayInventory}=evidence.version===2?await evidence.snapshots(names):bundledSnapshots(evidence,names);
27
+ return {names,statements:name=>files.find(file=>file.name===name)?.statements,sha256:name=>files.find(file=>file.name===name)?.sha256,
28
+ async schemaAfter(selected,options,allowSubsequence){
29
+ if(selected.length<=names.length && selected.every((name,i)=>name===names[i]))return inventorySchemaIdentity(inventory(selected.length),config,options);
30
+ insist(allowSubsequence && replayInventory,'schema_mismatch:legacy_evidence',409);
31
+ return inventorySchemaIdentity(await replayInventory(selected),config,options);
23
32
  },
24
- async rowImages(requests){return new Map(requests.filter(r=>final.seeds.some(s=>s.name===r.name && !s.hashes.length)).map(r=>[r.name,[]]));},
25
- async rowHashes(requests,limit){return new Map(requests.flatMap(r=>{const found=final.seeds.find(s=>s.name===r.name && s.hashes.length<=limit && canonicalJson(s.columns)===canonicalJson(r.columns));return found?[[r.name,found.hashes]]:[];}));},
33
+ async rowImages(requests){return new Map(requests.filter(r=>seeds.some(s=>s.name===r.name && !s.hashes.length)).map(r=>[r.name,[]]));},
34
+ async rowHashes(requests,limit){return new Map(requests.flatMap(r=>{const found=seeds.find(s=>s.name===r.name && s.hashes.length<=limit && canonicalJson(s.columns)===canonicalJson(r.columns));return found?[[r.name,found.hashes]]:[];}));},
26
35
  };
27
- },{nativeWrangler:true,ownerSources});
36
+ },{nativeWrangler:true,ownerSources,nativePrefix:evidence.nativePrefix});
28
37
  }catch(error){if(error instanceof PortabilityError)throw error;throw new PortabilityError('schema_mismatch:legacy_evidence',409);}
29
38
  }
@@ -0,0 +1,55 @@
1
+ import { migrationRecorder } from './migration-evidence.mjs';
2
+ import { insist, PortabilityError } from './storage.mjs';
3
+
4
+ function nativePrefix(history,files) {
5
+ if(!history.owners)return history.entries.every((row,i)=>
6
+ row.sha256===undefined && row.name===files[i]?.name && files[i].table===undefined);
7
+ const byTable=new Map();
8
+ for(const file of files) {
9
+ const table=file.table??history.table;
10
+ if(!byTable.has(table))byTable.set(table,[]);
11
+ byTable.get(table).push(file.name);
12
+ }
13
+ const offsets=new Map();
14
+ return history.entries.every(({name,table})=>{
15
+ const offset=offsets.get(table)??0;
16
+ offsets.set(table,offset+1);
17
+ return name===byTable.get(table)?.[offset];
18
+ });
19
+ }
20
+
21
+ // Only the build evidence for a checkout with owner SQL links this module.
22
+ export function workerOwnerEvidence(evidence,openDatabase) {
23
+ const files=new Map(evidence.files.map(file=>[file.name,file]));
24
+ return {
25
+ ...evidence,
26
+ nativePrefix,
27
+ async snapshots(names) {
28
+ async function replayInventory(selected) {
29
+ let offset=0;
30
+ for(const name of selected) {
31
+ const index=names.indexOf(name,offset);
32
+ insist(index>=0,'schema_mismatch:legacy_evidence',409);
33
+ offset=index+1;
34
+ }
35
+ const scratch=await openDatabase();
36
+ try {
37
+ const recorder=migrationRecorder(scratch);
38
+ for(const name of selected)recorder.apply(files.get(name));
39
+ return recorder.inventory();
40
+ }catch{
41
+ throw new PortabilityError('schema_mismatch:legacy_evidence',409);
42
+ }finally{scratch.close();}
43
+ }
44
+ const scratch=await openDatabase();
45
+ try {
46
+ const recorder=migrationRecorder(scratch),prefixes=[recorder.inventory()];
47
+ for(const name of names) {
48
+ recorder.apply(files.get(name));
49
+ prefixes.push(recorder.inventory());
50
+ }
51
+ return {inventory:index=>prefixes[index],seeds:await recorder.seeds(prefixes.at(-1).objects),replayInventory};
52
+ }finally{scratch.close();}
53
+ },
54
+ };
55
+ }
@@ -0,0 +1,30 @@
1
+ import { execFile } from 'node:child_process';
2
+
3
+ export function inspectionCommand(command, args, { timeout, maxBuffer, signal, keepPartialOutput }) {
4
+ signal?.throwIfAborted();
5
+ return new Promise((resolve, reject) => {
6
+ let timer, stdout = '';
7
+ const finish = (error, output, stderr) => {
8
+ clearTimeout(timer);
9
+ signal?.removeEventListener('abort', abort);
10
+ if (error) reject(Object.assign(error, { stdout: output, stderr }));
11
+ else resolve(output);
12
+ };
13
+ const child = execFile(command, args, { maxBuffer, killSignal: 'SIGKILL' }, finish);
14
+ const abandon = error => {
15
+ // Even SIGKILL can leave a process in a kernel wait. Release rer's
16
+ // handles and settle here, independently of the child and its callback.
17
+ finish(error, stdout, '');
18
+ try { child.kill('SIGKILL'); } catch { /* the deadline still applies */ }
19
+ child.stdin?.destroy();
20
+ child.stdout?.destroy();
21
+ child.stderr?.destroy();
22
+ child.unref();
23
+ };
24
+ const abort = () => abandon(new Error('Inspection cancelled'));
25
+ // Only a positive observation of state-file custody can use partial output.
26
+ if (keepPartialOutput) child?.stdout?.on('data', data => { stdout = (stdout + data).slice(0, maxBuffer); });
27
+ timer = setTimeout(() => abandon(Object.assign(new Error('Inspection timed out'), { killed: true })), timeout);
28
+ signal?.addEventListener('abort', abort, { once: true });
29
+ });
30
+ }
@@ -1,4 +1,4 @@
1
- import { createServer } from 'node:net';
1
+ import { createServer, Socket } from 'node:net';
2
2
  import { setTimeout as delay } from 'node:timers/promises';
3
3
  import { inspectionContext, portListener, searchContext, uncheckedInspection } from './process-diagnostics.mjs';
4
4
 
@@ -13,6 +13,25 @@ async function bind(host, port) {
13
13
  } finally { if (socket.listening) await new Promise(resolve => socket.close(resolve)); }
14
14
  }
15
15
 
16
+ async function loopbackRefuses(host, port, context) {
17
+ // An IPv6 wildcard may appear in an IPv4 ownership check even when it is
18
+ // v6-only. For IPv4 and localhost, require both loopbacks to refuse.
19
+ if (!['127.0.0.1', 'localhost', '::1'].includes(host)) return false;
20
+ const addresses = host === '::1' ? ['::1'] : ['127.0.0.1', '::1'];
21
+ const timeout = Math.min(250, Math.floor(context.deadline - performance.now()));
22
+ if (timeout <= 0) return false;
23
+ const refused = await Promise.all(addresses.map(address => new Promise(resolve => {
24
+ const socket = new Socket({ signal: context.signal });
25
+ const finish = refused => { clearTimeout(timer); socket.destroy(); resolve(refused); };
26
+ const timer = setTimeout(() => finish(false), timeout);
27
+ socket.once('connect', () => finish(false));
28
+ socket.once('error', error => finish(error.code === 'ECONNREFUSED'));
29
+ socket.connect({ host: address, port });
30
+ })));
31
+ context.signal?.throwIfAborted();
32
+ return refused.every(Boolean);
33
+ }
34
+
16
35
  // A failed diagnostic is unknown, never evidence of a foreign owner. A real
17
36
  // bind can still prove availability. If a bind loses a race but inspection
18
37
  // finds no listener, retry the bind within the same inspection deadline.
@@ -25,6 +44,12 @@ export async function probePort(host, port, { context = inspectionContext({ port
25
44
  };
26
45
  let bound = await bindings(), listener, unchecked;
27
46
  if (!bound.available && (bound.code !== 'EADDRINUSE' || searching)) return bound;
47
+ // An any-address search must still see listeners bound only to non-loopback
48
+ // addresses. A failed bind is also ambiguous, even with a refused connect.
49
+ if (bound.available && !anyAddress && await loopbackRefuses(host, port, context)) {
50
+ bound = await bindings();
51
+ if (bound.available || bound.code !== 'EADDRINUSE') return bound;
52
+ }
28
53
  try { listener = await portListener(port, anyAddress ? undefined : host, context); }
29
54
  catch (error) { if (!uncheckedInspection(error)) throw error; unchecked = error; }
30
55
  if (listener) return { available: false, listener };
@@ -1,5 +1,3 @@
1
- import {execFile} from 'node:child_process';
2
- import {promisify} from 'node:util';
3
1
  import {lstat,realpath,readFile,readdir,readlink} from 'node:fs/promises';
4
2
  import {basename,join} from 'node:path';
5
3
  import {availableParallelism,homedir,loadavg} from 'node:os';
@@ -7,7 +5,7 @@ import {isIP} from 'node:net';
7
5
  import {setTimeout as delay} from 'node:timers/promises';
8
6
  import {commandFailure,approvedFailure} from './failures.mjs';
9
7
  import {stateFiles} from './local/state-files.mjs';
10
- const exec=promisify(execFile);
8
+ import {inspectionCommand} from './inspection-command.mjs';
11
9
  // macOS supplies lsof in /usr/sbin, which a command PATH may omit.
12
10
  // Diagnose sockets with the system utility even when that PATH is constrained.
13
11
  const lsof=process.platform==='darwin'?'/usr/sbin/lsof':'lsof';
@@ -25,7 +23,7 @@ const run=async(command,args,context=inspectionContext(),{maxBuffer=1024*1024,no
25
23
  const remaining=Math.floor(context.deadline-performance.now());
26
24
  if(remaining<=0)break;
27
25
  const timeout=attempt===0?Math.min(3000,remaining):remaining;
28
- try{return (await exec(command,args,{timeout,maxBuffer,signal:context.signal})).stdout;}
26
+ try{return await inspectionCommand(command,args,{timeout,maxBuffer,signal:context.signal,keepPartialOutput:Boolean(positiveResult)});}
29
27
  catch(error){
30
28
  // A cancelled caller stops inspecting: the abort is never an ownership verdict.
31
29
  if(context.signal?.aborted)throw context.signal.reason;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runeditrun/rer",
3
- "version": "0.2.124",
3
+ "version": "0.2.126",
4
4
  "description": "The rer command: install, set up, run and launch Run Edit Run checkouts.",
5
5
  "license": "MIT",
6
6
  "type": "module",