bedrock-sqlite 0.16.20 → 0.16.21

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.
@@ -0,0 +1,92 @@
1
+ # Native FTS5 tokenizers
2
+
3
+ The shared SQLite build statically links `better_trigram` and `html` alongside
4
+ `vec0`. SQLite's existing `SQLITE_EXTRA_INIT` owner registers native auto-extensions;
5
+ every connection receives the tokenizers. The callback adapts SQLite's three-argument
6
+ extension ABI to the upstream one-argument core initializers and returns their errors.
7
+ There is one SQLite engine and no SQL rewriting or tokenizer substitution.
8
+
9
+ ## Reproducible inputs
10
+
11
+ The native identity comes from [Notesnook commit
12
+ 5748795b9920a4ba71f5456e126f5227bd5b8a51](https://github.com/streetwriters/notesnook/tree/5748795b9920a4ba71f5456e126f5227bd5b8a51),
13
+ `apps/mobile/patches/react-native-quick-sqlite+8.2.7.patch`, SHA256
14
+ `3cc27458802c4897114d3162b9d18869eec586dff08635c31185938ee490868c`.
15
+ Its installed CommonJS entry is unchanged quick-sqlite 8.2.7, SHA256
16
+ `8e49360e259987d8722d047e6d1b3664bdef025ee8ca1c35d24f4a1f69d6cc39`.
17
+ The package version alone does not identify its native sources.
18
+
19
+ The Makefile checks the patch's digest before extracting its new C/header files
20
+ from `better-trigram`, `sqlite3-fts5-html`, and `lexbor`. All 446 files match the
21
+ retained installed app inputs byte for byte. No upstream source is modified.
22
+ `SQLITE_CORE` selects their existing native initializers; `SQLITE_PRIVATE=` gives
23
+ those initializers external linkage in separate translation units. Lexbor builds
24
+ as a static archive with Windows ports excluded, matching the app's podspec.
25
+ LTO discards unused code. The app's SQLite amalgamation and bridge patches are
26
+ excluded: Orez keeps its existing Bedrock SQLite engine and VFS.
27
+
28
+ The tokenizers are Abdullah Atta's public-domain
29
+ [better-trigram](https://github.com/streetwriters/sqlite-better-trigram) and
30
+ [sqlite3-fts5-html](https://github.com/streetwriters/sqlite3-fts5-html).
31
+ Their notices ship in `LICENSE.fts5-tokenizers`. Lexbor is copyright Alexander
32
+ Borisov and contributors, licensed under Apache-2.0 (`LICENSE.lexbor`). Its pinned
33
+ app copy differs from release v2.4.0; that release is not a substitute build input.
34
+
35
+ Build all entry points with the existing pinned toolchain:
36
+
37
+ ```sh
38
+ bun install --frozen-lockfile
39
+ cd sqlite-wasm
40
+ make docker
41
+ ```
42
+
43
+ ## Scope and limits
44
+
45
+ Assigned native scope, 2026-10-15: "Compile the real better_trigram and html
46
+ tokenizers with their Lexbor dependency, preserving exact upstream C semantics."
47
+ Browser app integration and Notesnook offline home acceptance belong to the parent
48
+ Contrast task, t-mv9iupcn-13ri0. A native build is not UI or production acceptance.
49
+
50
+ Focused regression coverage lives in `test/database.test.ts`: exact vocabulary,
51
+ short words, BMP CJK, HTML and numeric/named entities, ignored script/style text,
52
+ diacritic folding, two connections, persisted close/reopen, invalid constructors,
53
+ transaction rollback and coexistence with nearest-neighbor vec queries.
54
+
55
+ Known upstream limits are preserved. Custom `better_trigram` does not provide
56
+ FTS5's built-in trigram LIKE/GLOB index optimization. The pinned tokenizer defines
57
+ `u32` as `uint16_t`, so supplementary-plane Unicode is not claimed here. The HTML
58
+ extension can return incorrect original-byte highlight offsets for entities;
59
+ search results and highlight offsets are separate claims. Allocation-exhaustion
60
+ behavior inside the unmodified HTML parser is not certified by ordinary query
61
+ coverage. This build adds no Durable Object queries, tables or writes.
62
+
63
+ ## Native validation and cost
64
+
65
+ TESTED on studio-64 with Emscripten 5.0.0, container digest
66
+ `sha256:67df07bc59f86685818fa801d340b54e576fe4276cfd3bcfc4da61d564217737`:
67
+ SQLite suite 42/42, existing WASM compatibility suite 22/22, Node and Bun
68
+ synchronous/asynchronous entry points, and Chromium 149.0.7827.55 browser queries.
69
+ The original browser pair rejects both tokenizer names. A control rebuilt with
70
+ the original initializer and the same toolchain reproduces that pair byte for byte.
71
+ A separate native probe injects `SQLITE_ERROR` and `SQLITE_NOMEM` from the real
72
+ HTML initializer's `xCreateTokenizer` call. `sqlite3_open_v2` returns exactly 1
73
+ and 7; the JavaScript constructor throws, and open/search succeeds after restoring
74
+ the ordinary auto-extension list. Probe exports are excluded from shipped binaries.
75
+
76
+ The browser JavaScript is unchanged, SHA256
77
+ `d764c46f93618142ee20c58d0bc3a6e5d16b05281c36d2ab63e82ddf272e3d71`.
78
+ The original WASM is SHA256
79
+ `fa82879ab4085e02f2a47e215ba201eeff64f48d7246178a1ac6a68799533b97`;
80
+ the new browser and Node WASM are both SHA256
81
+ `5a4e809301dfdcd10eea4f27aed6e45e56300ea3020a9c4e659d6017449ab3fc`.
82
+ WASM grows from 1,654,808 to 1,910,243 bytes, adding 255,435 bytes (15.4%).
83
+ Gzip grows from 660,479 to 763,693 bytes, adding 103,214 bytes. The pinned build,
84
+ including control and failure-probe links, took 43 seconds after image acquisition.
85
+
86
+ The first browser probe observed factory/load/open at 22 ms for the original pair
87
+ and 16.7 ms for the new pair; this single sequential sample does not establish a
88
+ startup improvement. Both had open/close p95 near the browser's 0.1 ms timer step.
89
+ Source manifests, paired artifacts, build logs and executable probes are retained
90
+ under `orez/scripts/tmp/peach-sqlite-fts-native` on studio-64. Further optimization
91
+ could reduce archive compilation to Lexbor's required dependency closure; this
92
+ change keeps the app's original source selection and lets LTO remove unused code.
@@ -0,0 +1,14 @@
1
+ better-trigram and sqlite3-fts5-html, by Abdullah Atta
2
+
3
+ /*
4
+ ** 2024-10-21
5
+ **
6
+ ** The author disclaims copyright to this source code. In place of
7
+ ** a legal notice, here is a blessing:
8
+ **
9
+ ** May you do good and not evil.
10
+ ** May you find forgiveness for yourself and forgive others.
11
+ ** May you share freely, never taking more than you give.
12
+ **
13
+ */
14
+
package/LICENSE.lexbor ADDED
@@ -0,0 +1,193 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ Lexbor.
180
+
181
+ Copyright 2018-2020 Alexander Borisov
182
+
183
+ Licensed under the Apache License, Version 2.0 (the "License");
184
+ you may not use this file except in compliance with the License.
185
+ You may obtain a copy of the License at
186
+
187
+ http://www.apache.org/licenses/LICENSE-2.0
188
+
189
+ Unless required by applicable law or agreed to in writing, software
190
+ distributed under the License is distributed on an "AS IS" BASIS,
191
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
192
+ See the License for the specific language governing permissions and
193
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,30 @@
1
+ # Bedrock SQLite WASM
2
+
3
+ This build shares native SQLite across Node and browser consumers. The Makefile
4
+ keeps its existing Bedrock, FTS, vector and VFS inputs and enables
5
+ `SQLITE_ENABLE_SESSION` and `SQLITE_ENABLE_PREUPDATE_HOOK` for native sessions.
6
+ Build the synchronous, asynchronous and browser outputs together with
7
+ `make all browser`. Publish the JavaScript and WASM from the same build.
8
+
9
+ `Database.backupTo(destination, sourceName, destinationName)` uses SQLite's
10
+ backup API, including named attached schemas. `filename(name)` reads
11
+ SQLite's actual schema filename. `updateHook(callback)` installs one callback
12
+ per connection with operation code, database name, table name and row ID.
13
+ Row IDs above JavaScript's safe integer range remain bigint. Passing null
14
+ removes the callback; closing a connection removes it and closes its sessions.
15
+ `commitHook(callback)` and `rollbackHook(callback)` likewise use SQLite native
16
+ hooks. The commit callback returns zero to accept the commit or nonzero to
17
+ roll it back. Hook callbacks run inside SQLite and must not modify that
18
+ connection. Passing null removes a hook.
19
+
20
+ `createSession(databaseName)` creates a native SQLite session. Its `attach`,
21
+ `enable`, `changeset` and `close` methods call the SQLite session API. A null
22
+ attachment selects all tables. Changeset buffers are copied before release
23
+ with `sqlite3_free`. `applyChangeset(bytes, onConflict)` exposes SQLite's
24
+ conflict disposition values; its default aborts. `invertChangeset(bytes)` uses
25
+ the native inverse operation. Neither method rewrites SQL or replays queries.
26
+
27
+ The integration case in `test/database.test.ts` covers backup, changeset
28
+ application and inversion, conflict callbacks, large row IDs and cleanup.
29
+ `FTS5-SOURCES.md` records the unchanged pinned native extension inputs and
30
+ their earlier validation. These APIs add no cloud queries or writes.
@@ -49,6 +49,13 @@ declare module "bedrock-sqlite/async" {
49
49
  bind(...params: any[]): this;
50
50
  }
51
51
 
52
+ interface Session {
53
+ attach(table?: string | null): void;
54
+ enable(enabled: boolean): void;
55
+ changeset(): Uint8Array;
56
+ close(): void;
57
+ }
58
+
52
59
  interface Database {
53
60
  readonly open: boolean;
54
61
  readonly readonly: boolean;
@@ -71,6 +78,14 @@ declare module "bedrock-sqlite/async" {
71
78
  options?: FunctionOptions
72
79
  ): this;
73
80
  aggregate(name: string, options: AggregateOptions): this;
81
+ filename(databaseName?: string): string;
82
+ backupTo(destination: Database, sourceName?: string, destinationName?: string): void;
83
+ updateHook(callback: ((operation: number, database: string, table: string, rowid: number | bigint) => void) | null): this;
84
+ commitHook(callback: (() => number) | null): this;
85
+ rollbackHook(callback: (() => void) | null): this;
86
+ createSession(databaseName?: string): Session;
87
+ applyChangeset(changeset: Uint8Array | ArrayBuffer, onConflict?: (reason: number) => number): void;
88
+ invertChangeset(changeset: Uint8Array | ArrayBuffer): Uint8Array;
74
89
  close(): void;
75
90
  }
76
91
 
@@ -103,6 +118,7 @@ declare module "bedrock-sqlite/async" {
103
118
 
104
119
  export type {
105
120
  RunResult,
121
+ Session,
106
122
  ColumnDefinition,
107
123
  DatabaseOptions,
108
124
  FunctionOptions,
@@ -51,6 +51,13 @@ declare module "bedrock-sqlite/browser" {
51
51
  bind(...params: any[]): this;
52
52
  }
53
53
 
54
+ interface Session {
55
+ attach(table?: string | null): void;
56
+ enable(enabled: boolean): void;
57
+ changeset(): Uint8Array;
58
+ close(): void;
59
+ }
60
+
54
61
  interface Database {
55
62
  readonly open: boolean;
56
63
  readonly readonly: boolean;
@@ -73,6 +80,14 @@ declare module "bedrock-sqlite/browser" {
73
80
  options?: FunctionOptions
74
81
  ): this;
75
82
  aggregate(name: string, options: AggregateOptions): this;
83
+ filename(databaseName?: string): string;
84
+ backupTo(destination: Database, sourceName?: string, destinationName?: string): void;
85
+ updateHook(callback: ((operation: number, database: string, table: string, rowid: number | bigint) => void) | null): this;
86
+ commitHook(callback: (() => number) | null): this;
87
+ rollbackHook(callback: (() => void) | null): this;
88
+ createSession(databaseName?: string): Session;
89
+ applyChangeset(changeset: Uint8Array | ArrayBuffer, onConflict?: (reason: number) => number): void;
90
+ invertChangeset(changeset: Uint8Array | ArrayBuffer): Uint8Array;
76
91
  close(): void;
77
92
  }
78
93
 
@@ -104,6 +119,7 @@ declare module "bedrock-sqlite/browser" {
104
119
 
105
120
  export type {
106
121
  RunResult,
122
+ Session,
107
123
  ColumnDefinition,
108
124
  DatabaseOptions,
109
125
  FunctionOptions,
@@ -49,6 +49,13 @@ declare module "bedrock-sqlite" {
49
49
  bind(...params: any[]): this;
50
50
  }
51
51
 
52
+ interface Session {
53
+ attach(table?: string | null): void;
54
+ enable(enabled: boolean): void;
55
+ changeset(): Uint8Array;
56
+ close(): void;
57
+ }
58
+
52
59
  interface Database {
53
60
  readonly open: boolean;
54
61
  readonly readonly: boolean;
@@ -71,6 +78,14 @@ declare module "bedrock-sqlite" {
71
78
  options?: FunctionOptions
72
79
  ): this;
73
80
  aggregate(name: string, options: AggregateOptions): this;
81
+ filename(databaseName?: string): string;
82
+ backupTo(destination: Database, sourceName?: string, destinationName?: string): void;
83
+ updateHook(callback: ((operation: number, database: string, table: string, rowid: number | bigint) => void) | null): this;
84
+ commitHook(callback: (() => number) | null): this;
85
+ rollbackHook(callback: (() => void) | null): this;
86
+ createSession(databaseName?: string): Session;
87
+ applyChangeset(changeset: Uint8Array | ArrayBuffer, onConflict?: (reason: number) => number): void;
88
+ invertChangeset(changeset: Uint8Array | ArrayBuffer): Uint8Array;
74
89
  close(): void;
75
90
  }
76
91
 
@@ -88,6 +103,7 @@ declare module "bedrock-sqlite" {
88
103
  export { Database, SqliteError };
89
104
  export type {
90
105
  RunResult,
106
+ Session,
91
107
  ColumnDefinition,
92
108
  DatabaseOptions,
93
109
  FunctionOptions,
@@ -1,2 +1,2 @@
1
- async function createSqliteModule(moduleArg={}){var moduleRtn;var Module=moduleArg;var ENVIRONMENT_IS_NODE=true;const SQLITE_OK=0;const SQLITE_ROW=100;const SQLITE_DONE=101;const SQLITE_INTEGER=1;const SQLITE_FLOAT=2;const SQLITE_TEXT=3;const SQLITE_BLOB=4;const SQLITE_NULL=5;const SQLITE_UTF8=1;const SQLITE_TRANSIENT=-1;const SQLITE_DETERMINISTIC=2048;const SQLITE_DIRECTONLY=524288;const INT32_MIN=-2147483648;const INT32_MAX=2147483647;const NULL=0;function isByteArray(value){return value instanceof Uint8Array}function copyByteArray(value){const NodeBuffer=globalThis.Buffer;return NodeBuffer?NodeBuffer.from(value):Uint8Array.from(value)}function emptyByteArray(){const NodeBuffer=globalThis.Buffer;return NodeBuffer?NodeBuffer.alloc(0):new Uint8Array}let temp;const sqlite3={};Module.onRuntimeInitialized=()=>{temp=stackAlloc(8);const v=null;const n="number";const s="string";const n1=[n];const n2=[n,...n1];const n3=[n,...n2];const n4=[n,...n3];const n5=[n,...n4];const signatures={open_v2:[n,[s,n,n,s]],exec:[n,n5],errmsg:[s,n1],prepare_v2:[n,n5],close_v2:[n,n1],finalize:[n,n1],reset:[n,n1],clear_bindings:[n,n1],bind_int:[n,n3],bind_int64:[n,n3],bind_double:[n,n3],bind_text:[n,n5],bind_blob:[n,n5],bind_null:[n,n2],bind_parameter_index:[n,[n,s]],bind_parameter_count:[n,n1],bind_parameter_name:[s,n2],step:[n,n1],column_int64:[n,n2],column_double:[n,n2],column_text:[s,n2],column_blob:[n,n2],column_type:[n,n2],column_name:[s,n2],column_count:[n,n1],column_bytes:[n,n2],column_table_name:[s,n2],column_origin_name:[s,n2],column_database_name:[s,n2],data_count:[n,n1],sql:[s,n1],stmt_readonly:[n,n1],last_insert_rowid:[n,n1],changes:[n,n1],total_changes:[n,n1],create_function_v2:[n,[n,s,n,n,n,n,n,n,n]],value_type:[n,n1],value_text:[s,n1],value_blob:[n,n1],value_int64:[n,n1],value_double:[n,n1],value_bytes:[n,n1],result_double:[v,n2],result_null:[v,n1],result_text:[v,n4],result_blob:[v,n4],result_int:[v,n2],result_int64:[v,n2],result_error:[v,n3],get_autocommit:[n,n1]};for(const[name,sig]of Object.entries(signatures)){sqlite3[name]=cwrap(`sqlite3_${name}`,sig[0],sig[1])}function arrayToHeap(array){const ptr=_malloc(array.byteLength);HEAPU8.set(array,ptr);return ptr}function stringToHeap(str){const size=lengthBytesUTF8(str)+1;const ptr=_malloc(size);stringToUTF8(str,ptr,size);return ptr}function toNumberOrNot(val){if(typeof val==="bigint"){if(val>=Number.MIN_SAFE_INTEGER&&val<=Number.MAX_SAFE_INTEGER){return Number(val)}return val}return val}const SQLITE_ERROR_NAMES={1:"SQLITE_ERROR",2:"SQLITE_INTERNAL",3:"SQLITE_PERM",4:"SQLITE_ABORT",5:"SQLITE_BUSY",6:"SQLITE_LOCKED",7:"SQLITE_NOMEM",8:"SQLITE_READONLY",9:"SQLITE_INTERRUPT",10:"SQLITE_IOERR",11:"SQLITE_CORRUPT",12:"SQLITE_NOTFOUND",13:"SQLITE_FULL",14:"SQLITE_CANTOPEN",15:"SQLITE_PROTOCOL",16:"SQLITE_EMPTY",17:"SQLITE_SCHEMA",18:"SQLITE_TOOBIG",19:"SQLITE_CONSTRAINT",20:"SQLITE_MISMATCH",21:"SQLITE_MISUSE",23:"SQLITE_AUTH",24:"SQLITE_FORMAT",25:"SQLITE_RANGE",26:"SQLITE_NOTADB",100:"SQLITE_ROW",101:"SQLITE_DONE"};class SqliteError extends Error{constructor(message,code){super(message);this.name="SqliteError";if(typeof code==="number"){this.code=SQLITE_ERROR_NAMES[code&255]||SQLITE_ERROR_NAMES[code]||"SQLITE_ERROR"}else{this.code=code||"SQLITE_ERROR"}}}function resolveBindParams(args){if(args.length===0)return null;if(args.length===1){const arg=args[0];if(arg===undefined||arg===null)return null;if(Array.isArray(arg))return arg;if(typeof arg==="object"&&!isByteArray(arg))return arg;return[arg]}return Array.from(args)}function parseFunctionArgs(argc,argv){const args=[];for(let i=0;i<argc;i++){const ptr=getValue(argv+4*i,"i32");const type=sqlite3.value_type(ptr);switch(type){case SQLITE_INTEGER:args.push(toNumberOrNot(sqlite3.value_int64(ptr)));break;case SQLITE_FLOAT:args.push(sqlite3.value_double(ptr));break;case SQLITE_TEXT:args.push(sqlite3.value_text(ptr));break;case SQLITE_BLOB:{const p=sqlite3.value_blob(ptr);args.push(p!==NULL?copyByteArray(HEAPU8.slice(p,p+sqlite3.value_bytes(ptr))):emptyByteArray());break}case SQLITE_NULL:args.push(null);break}}return args}function setFunctionResult(cx,result){switch(typeof result){case"boolean":sqlite3.result_int(cx,result?1:0);break;case"number":if(Number.isSafeInteger(result)){if(result>=INT32_MIN&&result<=INT32_MAX){sqlite3.result_int(cx,result)}else{sqlite3.result_int64(cx,BigInt(result))}}else{sqlite3.result_double(cx,result)}break;case"bigint":sqlite3.result_int64(cx,result);break;case"string":{const tp=stringToHeap(result);sqlite3.result_text(cx,tp,-1,SQLITE_TRANSIENT);_free(tp);break}case"object":if(result===null){sqlite3.result_null(cx)}else if(isByteArray(result)){const tp=arrayToHeap(result);sqlite3.result_blob(cx,tp,result.byteLength,SQLITE_TRANSIENT);_free(tp)}else{sqlite3.result_error(cx,stringToHeap("unsupported return type"),-1)}break;default:sqlite3.result_null(cx);break}}class Database{constructor(filename,options={}){if(typeof filename!=="string"&&!isByteArray(filename)){throw new TypeError("Expected first argument to be a string")}filename=String(filename);const readonly=!!options.readonly;const fileMustExist=!!options.fileMustExist;let flags;if(readonly){flags=1}else{flags=2;if(!fileMustExist)flags|=4}const rc=sqlite3.open_v2(filename,temp,flags,NULL);this._ptr=getValue(temp,"i32");if(rc!==SQLITE_OK){const msg=this._ptr!==NULL?sqlite3.errmsg(this._ptr):"unable to open database";if(this._ptr!==NULL)sqlite3.close_v2(this._ptr);this._ptr=null;throw new SqliteError(msg)}this._open=true;this._readonly=readonly;this._unsafe=false;this._name=filename;this._statements=new Set;this._functions=new Map;this.exec("PRAGMA busy_timeout = 5000")}unsafeMode(enabled){if(enabled===undefined)enabled=true;this._unsafe=!!enabled;return this}get open(){return this._open}get readonly(){return this._readonly}get name(){return this._name}get inTransaction(){return this._open&&sqlite3.get_autocommit(this._ptr)===0}prepare(source){this._assertOpen();if(typeof source!=="string"){throw new TypeError("Expected first argument to be a string")}const stmt=new Statement(this,source);this._statements.add(stmt);return stmt}exec(sql,{resetStatements=true}={}){this._assertOpen();if(resetStatements){for(const stmt of this._statements){if(!stmt._finalized)sqlite3.reset(stmt._ptr)}}const tp=stringToHeap(sql);try{const rc=sqlite3.exec(this._ptr,tp,NULL,NULL,NULL);if(rc!==SQLITE_OK){throw new SqliteError(sqlite3.errmsg(this._ptr),rc)}}finally{_free(tp)}return this}transaction(fn){if(typeof fn!=="function"){throw new TypeError("Expected first argument to be a function")}const db=this;const wrapTxn=begin=>{const beginStmt=db.prepare(begin);const commitStmt=db.prepare("COMMIT");const rollbackStmt=db.prepare("ROLLBACK");const runner=function(...args){let result;if(db.inTransaction){return fn.apply(this,args)}beginStmt.run();try{result=fn.apply(this,args);commitStmt.run()}catch(err){if(db.inTransaction){rollbackStmt.run()}throw err}return result};return runner};const result=wrapTxn("BEGIN");result.deferred=wrapTxn("BEGIN DEFERRED");result.immediate=wrapTxn("BEGIN IMMEDIATE");result.exclusive=wrapTxn("BEGIN EXCLUSIVE");result.database=db;return result}pragma(source,options){if(typeof source!=="string"){throw new TypeError("Expected first argument to be a string")}const simple=options&&options.simple;const sql=`PRAGMA ${source}`;const stmt=this.prepare(sql);try{if(stmt.reader){return simple?stmt.pluck().get():stmt.all()}else{return stmt.run()}}finally{stmt.finalize()}}function(name,fn,options={}){this._assertOpen();if(typeof name!=="string")throw new TypeError("Expected first argument to be a string");if(typeof fn!=="function")throw new TypeError("Expected second argument to be a function");const deterministic=!!options.deterministic;const directOnly=!!options.directOnly;const varargs=options.varargs||false;if(this._functions.has(name)){removeFunction(this._functions.get(name));this._functions.delete(name)}const wrappedFunc=(cx,argc,argv)=>{const args=parseFunctionArgs(argc,argv);try{const result=fn(...args);setFunctionResult(cx,result)}catch(err){const tp=stringToHeap(err.toString());sqlite3.result_error(cx,tp,-1);_free(tp)}};const funcPtr=addFunction(wrappedFunc,"viii");this._functions.set(name,funcPtr);let eTextRep=SQLITE_UTF8;if(deterministic)eTextRep|=SQLITE_DETERMINISTIC;if(directOnly)eTextRep|=SQLITE_DIRECTONLY;const rc=sqlite3.create_function_v2(this._ptr,name,varargs?-1:fn.length,eTextRep,NULL,funcPtr,NULL,NULL,NULL);if(rc!==SQLITE_OK)throw new SqliteError(sqlite3.errmsg(this._ptr));return this}aggregate(name,options){this._assertOpen();if(typeof name!=="string")throw new TypeError("Expected first argument to be a string");if(!options||typeof options!=="object")throw new TypeError("Expected second argument to be an options object");const step=options.step;const result=options.result||(acc=>acc);const start=options.start;const inverse=options.inverse;const deterministic=!!options.deterministic;const directOnly=!!options.directOnly;const varargs=!!options.varargs;if(typeof step!=="function")throw new TypeError("Expected options.step to be a function");let accumulator;const stepWrapper=(cx,argc,argv)=>{const args=parseFunctionArgs(argc,argv);try{accumulator=step(accumulator,...args)}catch(err){const tp=stringToHeap(err.toString());sqlite3.result_error(cx,tp,-1);_free(tp)}};const finalWrapper=cx=>{try{const val=result(accumulator);setFunctionResult(cx,val)}catch(err){const tp=stringToHeap(err.toString());sqlite3.result_error(cx,tp,-1);_free(tp)}accumulator=typeof start==="function"?start():start};accumulator=typeof start==="function"?start():start;if(this._functions.has(name+"_step")){removeFunction(this._functions.get(name+"_step"));this._functions.delete(name+"_step")}if(this._functions.has(name+"_final")){removeFunction(this._functions.get(name+"_final"));this._functions.delete(name+"_final")}const stepPtr=addFunction(stepWrapper,"viii");const finalPtr=addFunction(finalWrapper,"vi");this._functions.set(name+"_step",stepPtr);this._functions.set(name+"_final",finalPtr);let eTextRep=SQLITE_UTF8;if(deterministic)eTextRep|=SQLITE_DETERMINISTIC;if(directOnly)eTextRep|=SQLITE_DIRECTONLY;const argCount=varargs?-1:step.length-1;const rc=sqlite3.create_function_v2(this._ptr,name,argCount,eTextRep,NULL,NULL,stepPtr,finalPtr,NULL);if(rc!==SQLITE_OK)throw new SqliteError(sqlite3.errmsg(this._ptr));return this}close(){if(!this._open)return;for(const stmt of this._statements){if(!stmt._finalized){sqlite3.finalize(stmt._ptr);stmt._finalized=true}}this._statements.clear();for(const func of this._functions.values()){removeFunction(func)}this._functions.clear();const rc=sqlite3.close_v2(this._ptr);if(rc!==SQLITE_OK){throw new SqliteError(sqlite3.errmsg(this._ptr))}this._ptr=null;this._open=false}_assertOpen(){if(!this._open)throw new SqliteError("The database connection is not open")}_handleError(rc){if(rc!==SQLITE_OK){throw new SqliteError(sqlite3.errmsg(this._ptr),rc)}}}class Statement{constructor(db,source){this._db=db;this._source=source;this._finalized=false;this._pluck=false;this._expand=false;this._raw=false;this._bound=false;this._numbersAsDoubles=false;const tp=stringToHeap(source);try{const rc=sqlite3.prepare_v2(db._ptr,tp,-1,temp,NULL);if(rc!==SQLITE_OK){throw new SqliteError(sqlite3.errmsg(db._ptr),rc)}}finally{_free(tp)}this._ptr=getValue(temp,"i32");if(this._ptr===NULL){throw new SqliteError("Nothing to prepare")}this._columnCount=sqlite3.column_count(this._ptr);this._reader=this._columnCount>0;this._readonly=!!sqlite3.stmt_readonly(this._ptr)}get source(){return this._source}get reader(){return this._reader}get readonly(){return this._readonly}get parameterCount(){this._assertReady();return sqlite3.bind_parameter_count(this._ptr)}numbersAsDoubles(toggle=true){this._numbersAsDoubles=toggle;return this}finalize(){if(this._finalized)return;sqlite3.finalize(this._ptr);this._finalized=true;this._ptr=null;this._db._statements.delete(this)}run(...args){this._assertReady();const params=resolveBindParams(args);this._reset();if(params)this._bind(params);this._step();const result={changes:sqlite3.changes(this._db._ptr),lastInsertRowid:toNumberOrNot(sqlite3.last_insert_rowid(this._db._ptr))};sqlite3.reset(this._ptr);return result}get(...args){this._assertReady();const params=resolveBindParams(args);this._reset();if(params)this._bind(params);if(!this._step()){sqlite3.reset(this._ptr);return undefined}const row=this._getRow();sqlite3.reset(this._ptr);return row}all(...args){this._assertReady();const params=resolveBindParams(args);this._reset();if(params)this._bind(params);const rows=[];while(this._step()){rows.push(this._getRow());if(rows.length===1e5){console.warn(`[bedrock-sqlite] all() returned 100k rows, query: ${this._source.slice(0,200)}`)}if(rows.length>=1e7){sqlite3.reset(this._ptr);throw new SqliteError(`all() exceeded 10M row safety limit, likely infinite loop. query: ${this._source.slice(0,200)}`)}}sqlite3.reset(this._ptr);return rows}*iterate(...args){this._assertReady();const params=resolveBindParams(args);this._reset();if(params)this._bind(params);while(this._step()){yield this._getRow()}}pluck(toggle=true){this._pluck=toggle;this._raw=false;this._expand=false;return this}expand(toggle=true){this._expand=toggle;this._pluck=false;this._raw=false;return this}raw(toggle=true){this._raw=toggle;this._pluck=false;this._expand=false;return this}columns(){this._assertReady();const cols=[];for(let i=0;i<this._columnCount;i++){cols.push({name:sqlite3.column_name(this._ptr,i),column:sqlite3.column_origin_name(this._ptr,i),table:sqlite3.column_table_name(this._ptr,i),database:sqlite3.column_database_name(this._ptr,i),type:null})}return cols}scanStatusV2(){return[]}scanStatusReset(){}safeIntegers(){return this}bind(...args){this._assertReady();const params=resolveBindParams(args);this._reset();if(params)this._bind(params);this._bound=true;return this}_reset(){sqlite3.clear_bindings(this._ptr);sqlite3.reset(this._ptr)}_step(){const rc=sqlite3.step(this._ptr);if(rc===SQLITE_ROW)return true;if(rc===SQLITE_DONE)return false;sqlite3.reset(this._ptr);throw new SqliteError(sqlite3.errmsg(this._db._ptr),rc)}_getRow(){if(this._pluck){return this._getColumnValue(0)}if(this._raw){const row=[];for(let i=0;i<this._columnCount;i++){row.push(this._getColumnValue(i))}return row}if(this._expand){const row={};for(let i=0;i<this._columnCount;i++){let table=sqlite3.column_table_name(this._ptr,i);table=table===""||table===null?"$":table;const name=sqlite3.column_name(this._ptr,i);if(!row[table])row[table]={};row[table][name]=this._getColumnValue(i)}return row}const row={};for(let i=0;i<this._columnCount;i++){row[sqlite3.column_name(this._ptr,i)]=this._getColumnValue(i)}return row}_getColumnValue(i){const type=sqlite3.column_type(this._ptr,i);switch(type){case SQLITE_INTEGER:return toNumberOrNot(sqlite3.column_int64(this._ptr,i));case SQLITE_FLOAT:return sqlite3.column_double(this._ptr,i);case SQLITE_TEXT:return sqlite3.column_text(this._ptr,i);case SQLITE_BLOB:{const p=sqlite3.column_blob(this._ptr,i);if(p!==NULL){const nbytes=sqlite3.column_bytes(this._ptr,i);if(nbytes>104857600){throw new SqliteError(`blob column ${i} has unreasonable size: ${nbytes} bytes`)}return copyByteArray(HEAPU8.slice(p,p+nbytes))}return emptyByteArray()}case SQLITE_NULL:return null;default:return null}}_bind(params){if(Array.isArray(params)){for(let i=0;i<params.length;i++){this._bindValue(params[i],i+1)}}else if(typeof params==="object"){const count=sqlite3.bind_parameter_count(this._ptr);for(let i=1;i<=count;i++){const pname=sqlite3.bind_parameter_name(this._ptr,i);if(!pname)continue;const stripped=pname.slice(1);const value=pname in params?params[pname]:stripped in params?params[stripped]:undefined;if(value!==undefined){this._bindValue(value,i)}}}}_bindValue(value,position){let rc;switch(typeof value){case"string":{const tp=stringToHeap(value);rc=sqlite3.bind_text(this._ptr,position,tp,-1,SQLITE_TRANSIENT);_free(tp);break}case"number":if(!this._numbersAsDoubles&&Number.isSafeInteger(value)){if(value>=INT32_MIN&&value<=INT32_MAX){rc=sqlite3.bind_int(this._ptr,position,value)}else{rc=sqlite3.bind_int64(this._ptr,position,BigInt(value))}}else{rc=sqlite3.bind_double(this._ptr,position,value)}break;case"bigint":rc=sqlite3.bind_int64(this._ptr,position,value);break;case"boolean":rc=sqlite3.bind_int(this._ptr,position,value?1:0);break;case"object":if(value===null){rc=sqlite3.bind_null(this._ptr,position)}else if(isByteArray(value)){const tp=arrayToHeap(value);rc=sqlite3.bind_blob(this._ptr,position,tp,value.byteLength,SQLITE_TRANSIENT);_free(tp)}else{throw new SqliteError(`Unsupported binding type at position ${position}`)}break;default:if(value===undefined){rc=sqlite3.bind_null(this._ptr,position)}else{throw new SqliteError(`Unsupported binding type: ${typeof value}`)}}if(rc!==SQLITE_OK){throw new SqliteError(sqlite3.errmsg(this._db._ptr))}}_assertReady(){if(this._finalized)throw new SqliteError("This statement has been finalized");if(!this._db._open)throw new SqliteError("The database connection is not open")}}Module.Database=Database;Module.SqliteError=SqliteError};const path=require("node:path");const crypto=require("node:crypto");const SQLITE_CANTOPEN=14;const SQLITE_IOERR_READ=266;const SQLITE_IOERR_SHORT_READ=522;const SQLITE_IOERR_FSYNC=1034;const SQLITE_IOERR_WRITE=778;const SQLITE_IOERR_DELETE=2570;const SQLITE_IOERR_CLOSE=4106;const SQLITE_IOERR_TRUNCATE=1546;const SQLITE_IOERR_FSTAT=1802;const SQLITE_OPEN_READONLY=1;const SQLITE_OPEN_READWRITE=2;const SQLITE_OPEN_CREATE=4;const SQLITE_OPEN_EXCLUSIVE=16;const SQLITE_ACCESS_READWRITE=1;const SQLITE_ACCESS_READ=2;const SQLITE_LOCK_NONE=0;const SQLITE_LOCK_SHARED=1;const SQLITE_LOCK_RESERVED=2;const SQLITE_LOCK_EXCLUSIVE=4;const SQLITE_BUSY=5;function _fd(fileInfo){return getValue(fileInfo+4,"i32")}function _setLocked(fileInfo,locked){setValue(fileInfo+8,locked?1:0,"i32")}function _path(fileInfo){return UTF8ToString(getValue(fileInfo+12,"i32"))}function _safeInt(bigInt){if(bigInt<Number.MIN_SAFE_INTEGER||bigInt>Number.MAX_SAFE_INTEGER)throw 0;return Number(bigInt)}var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var _scriptName;if(typeof __filename!="undefined"){_scriptName=__filename}else{}var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");scriptDirectory=__dirname+"/";readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(process.argv.length>1){thisProgram=process.argv[1].replace(/\\/g,"/")}arguments_=process.argv.slice(2);quit_=(status,toThrow)=>{process.exitCode=status;throw toThrow}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var EXITSTATUS;var isFileURI=filename=>filename.startsWith("file://");var readyPromiseResolve,readyPromiseReject;var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;var HEAP64,HEAPU64;var runtimeInitialized=false;function updateMemoryViews(){var b=wasmMemory.buffer;HEAP8=new Int8Array(b);HEAP16=new Int16Array(b);HEAPU8=new Uint8Array(b);HEAPU16=new Uint16Array(b);HEAP32=new Int32Array(b);HEAPU32=new Uint32Array(b);HEAPF32=new Float32Array(b);HEAPF64=new Float64Array(b);HEAP64=new BigInt64Array(b);HEAPU64=new BigUint64Array(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;wasmExports["E"]()}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(onPostRuns)}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(){return locateFile("sqlite3.wasm")}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&&!ENVIRONMENT_IS_NODE){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(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance,module){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();if(Module["instantiateWasm"]){return new Promise((resolve,reject)=>{Module["instantiateWasm"](info,(inst,mod)=>{resolve(receiveInstance(inst,mod))})})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}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":return HEAP64[ptr>>3];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":HEAP64[ptr>>3]=BigInt(value);break;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=globalThis.TextDecoder&&new TextDecoder;var findStringEnd=(heapOrArray,idx,maxBytesToRead,ignoreNul)=>{var maxIdx=idx+maxBytesToRead;if(ignoreNul)return maxIdx;while(heapOrArray[idx]&&!(idx>=maxIdx))++idx;return idx};var UTF8ArrayToString=(heapOrArray,idx=0,maxBytesToRead,ignoreNul)=>{var endPtr=findStringEnd(heapOrArray,idx,maxBytesToRead,ignoreNul);if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr))}var str="";while(idx<endPtr){var u0=heapOrArray[idx++];if(!(u0&128)){str+=String.fromCharCode(u0);continue}var u1=heapOrArray[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=heapOrArray[idx++]&63;if((u0&240)==224){u0=(u0&15)<<12|u1<<6|u2}else{u0=(u0&7)<<18|u1<<12|u2<<6|heapOrArray[idx++]&63}if(u0<65536){str+=String.fromCharCode(u0)}else{var ch=u0-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}return str};var UTF8ToString=(ptr,maxBytesToRead,ignoreNul)=>ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead,ignoreNul):"";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 __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};var INT53_MAX=9007199254740992;var INT53_MIN=-9007199254740992;var bigintToI53Checked=num=>num<INT53_MIN||num>INT53_MAX?NaN:Number(num);function __localtime_js(time,tmPtr){time=bigintToI53Checked(time);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}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{return func()}catch(e){handleException(e)}finally{maybeExit()}};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 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.codePointAt(i);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;i++}}heap[outIdx]=0;return outIdx-startIdx};var stringToUTF8=(str,outPtr,maxBytesToWrite)=>stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite);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=()=>536870912;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+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};function _nodejsAccess(vfs,filePath,flags,outResult){let aflags=fs.constants.F_OK;if(flags==SQLITE_ACCESS_READWRITE)aflags=fs.constants.R_OK|fs.constants.W_OK;if(flags==SQLITE_ACCESS_READ)aflags=fs.constants.R_OK;try{fs.accessSync(UTF8ToString(filePath),aflags);setValue(outResult,1,"i32")}catch{setValue(outResult,0,"i32")}return SQLITE_OK}var _fileLocks={};function _nodejsCheckReservedLock(fi,outResult){var filePath=_path(fi);var holders=_fileLocks[filePath];var reserved=0;if(holders){for(var[other,otherLevel]of holders){if(other!==fi&&otherLevel>=SQLITE_LOCK_RESERVED){reserved=1;break}}}setValue(outResult,reserved,"i32");return SQLITE_OK}function _nodejsClose(fi){_nodejsUnlock(fi,SQLITE_LOCK_NONE);try{fs.closeSync(_fd(fi))}catch{return SQLITE_IOERR_CLOSE}return SQLITE_OK}function _nodejsDelete(vfs,filePath,dirSync){const pathStr=UTF8ToString(filePath);try{fs.unlinkSync(pathStr)}catch(err){if(err.code!="ENOENT")return SQLITE_IOERR_DELETE}if(dirSync){let fd=-1;try{fd=fs.openSync(path.dirname(pathStr),"r");fs.fsyncSync(fd)}catch{return SQLITE_IOERR_FSYNC}finally{try{fs.closeSync(fd)}catch{return SQLITE_IOERR_FSYNC}}}return SQLITE_OK}function _nodejsFileSize(fi,outSize){try{setValue(outSize,fs.fstatSync(_fd(fi)).size,"i64")}catch{return SQLITE_IOERR_FSTAT}return SQLITE_OK}function _nodejsFullPathname(vfs,relPath,sizeFullPath,outFullPath){const full=path.resolve(UTF8ToString(relPath));stringToUTF8(full,outFullPath,sizeFullPath);return full.length<sizeFullPath?SQLITE_OK:SQLITE_CANTOPEN}function _nodejsLock(fi,level){var filePath=_path(fi);if(!_fileLocks[filePath])_fileLocks[filePath]=new Map;var holders=_fileLocks[filePath];var myLevel=holders.get(fi)||SQLITE_LOCK_NONE;if(level>=SQLITE_LOCK_RESERVED&&myLevel<SQLITE_LOCK_RESERVED){for(var[other,otherLevel]of holders){if(other!==fi&&otherLevel>=SQLITE_LOCK_RESERVED){return SQLITE_BUSY}}}if(level>=SQLITE_LOCK_EXCLUSIVE&&myLevel<SQLITE_LOCK_EXCLUSIVE){for(var[other,otherLevel]of holders){if(other!==fi&&otherLevel>=SQLITE_LOCK_SHARED){return SQLITE_BUSY}}}holders.set(fi,level);if(level>SQLITE_LOCK_NONE)_setLocked(fi,true);return SQLITE_OK}function _nodejsRandomness(vfs,bytes,outBuffer){const buf=HEAPU8.subarray(outBuffer,outBuffer+bytes);crypto.randomFillSync(buf);return bytes}function _nodejsRead(fi,outBuffer,bytes,offset){const buf=HEAPU8.subarray(outBuffer,outBuffer+bytes);let bytesRead;try{bytesRead=fs.readSync(_fd(fi),buf,0,bytes,_safeInt(offset))}catch{return SQLITE_IOERR_READ}if(bytesRead==bytes){return SQLITE_OK}else if(bytesRead>=0){if(bytesRead<bytes){try{buf.fill(0,bytesRead)}catch{return SQLITE_IOERR_READ}}return SQLITE_IOERR_SHORT_READ}return SQLITE_IOERR_READ}function _nodejsShmBarrier(fi){var filePath=_path(fi);var reg=_shmRegistry[filePath];if(!reg||reg._hasExclusiveLock)return;var shmPath=filePath+"-shm";var stat;try{stat=fs.statSync(shmPath)}catch(e){return}if(reg._lastShmWrite&&stat.mtimeMs<=reg._lastShmWrite)return;var fd;try{fd=fs.openSync(shmPath,fs.constants.O_RDONLY)}catch(e){return}for(var pgno in reg){if(typeof reg[pgno]!=="object"||!reg[pgno].ptr)continue;var r=reg[pgno];try{fs.readSync(fd,HEAPU8.subarray(r.ptr,r.ptr+r.pgsz),0,r.pgsz,Number(pgno)*r.pgsz)}catch(e){}}fs.closeSync(fd);reg._lastShmWrite=stat.mtimeMs}function _nodejsShmLock(fi,offset,n,flags){var filePath=_path(fi);if(!_shmRegistry[filePath])_shmRegistry[filePath]={};var reg=_shmRegistry[filePath];if(flags&2&&flags&8){reg._hasExclusiveLock=true}if(flags&1&&flags&8&&reg._hasExclusiveLock){var shmPath=filePath+"-shm";var fd;try{fd=fs.openSync(shmPath,fs.constants.O_RDWR|fs.constants.O_CREAT,420)}catch(e){reg._hasExclusiveLock=false;return SQLITE_OK}for(var pgno in reg){if(typeof reg[pgno]!=="object"||!reg[pgno].ptr)continue;var r=reg[pgno];try{fs.writeSync(fd,HEAPU8.subarray(r.ptr,r.ptr+r.pgsz),0,r.pgsz,Number(pgno)*r.pgsz)}catch(e){}}try{fs.fsyncSync(fd)}catch(e){}try{reg._lastShmWrite=fs.fstatSync(fd).mtimeMs}catch(e){reg._lastShmWrite=Date.now()}fs.closeSync(fd);reg._hasExclusiveLock=false}return SQLITE_OK}var _shmRegistry={};function _nodejsShmMap(fi,pgno,pgsz,isWrite,ppOut){var filePath=_path(fi);if(!_shmRegistry[filePath])_shmRegistry[filePath]={};var regions=_shmRegistry[filePath];if(!(pgno in regions)||typeof regions[pgno]!=="object"){if(!isWrite){setValue(ppOut,0,"*");return SQLITE_OK}var buf=_malloc(pgsz);HEAPU8.fill(0,buf,buf+pgsz);regions[pgno]={ptr:buf,pgsz}}setValue(ppOut,regions[pgno].ptr,"*");return SQLITE_OK}function _nodejsShmUnmap(fi,deleteFlag){if(deleteFlag){var filePath=_path(fi);var regions=_shmRegistry[filePath];if(regions){for(var pgno in regions){if(typeof regions[pgno]==="object"&&regions[pgno].ptr)_free(regions[pgno].ptr)}delete _shmRegistry[filePath]}}return SQLITE_OK}function _nodejsSleep(vfs,nMicro){var ms=Math.max(1,Math.floor(nMicro/1e3));var sab=new SharedArrayBuffer(4);Atomics.wait(new Int32Array(sab),0,0,ms);return nMicro}function _nodejsSync(fi,flags){try{fs.fsyncSync(_fd(fi))}catch{return SQLITE_IOERR_FSYNC}return SQLITE_OK}function _nodejsTruncate(fi,size){try{fs.ftruncateSync(_fd(fi),_safeInt(size))}catch{return SQLITE_IOERR_TRUNCATE}return SQLITE_OK}function _nodejsUnlock(fi,level){var filePath=_path(fi);var holders=_fileLocks[filePath];if(holders){if(level==SQLITE_LOCK_NONE){holders.delete(fi);_setLocked(fi,false)}else{holders.set(fi,level)}}else{if(level==SQLITE_LOCK_NONE)_setLocked(fi,false)}return SQLITE_OK}function _nodejsWrite(fi,buffer,bytes,offset){try{const bytesWritten=fs.writeSync(_fd(fi),HEAPU8.subarray(buffer,buffer+bytes),0,bytes,_safeInt(offset));return bytesWritten!=bytes?SQLITE_IOERR_WRITE:SQLITE_OK}catch{return SQLITE_IOERR_WRITE}}function _nodejs_max_path_length(){return process.platform=="win32"?260:4096}function _nodejs_open(filePath,flags,mode){let oflags=0;if(flags&SQLITE_OPEN_EXCLUSIVE)oflags|=fs.constants.O_EXCL;if(flags&SQLITE_OPEN_CREATE)oflags|=fs.constants.O_CREAT;if(flags&SQLITE_OPEN_READONLY)oflags|=fs.constants.O_RDONLY;if(flags&SQLITE_OPEN_READWRITE)oflags|=fs.constants.O_RDWR;try{return fs.openSync(UTF8ToString(filePath),oflags,mode)}catch{return-1}}var getCFunc=ident=>{var func=Module["_"+ident];return func};var writeArrayToMemory=(array,buffer)=>{HEAP8.set(array,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 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 wasmTableMirror=[];var getWasmTableEntry=funcPtr=>{var func=wasmTableMirror[funcPtr];if(!func){wasmTableMirror[funcPtr]=func=wasmTable.get(funcPtr)}return func};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()}return wasmTable["grow"](1)};var setWasmTableEntry=(idx,func)=>{wasmTable.set(idx,func);wasmTableMirror[idx]=wasmTable.get(idx)};var uleb128EncodeWithLen=arr=>{const n=arr.length;return[n%128|128,n>>7,...arr]};var wasmTypeCodes={i:127,p:127,j:126,f:125,d:124,e:111};var generateTypePack=types=>uleb128EncodeWithLen(Array.from(types,type=>{var code=wasmTypeCodes[type];return code}));var convertJsFunctionToWasm=(func,sig)=>{var bytes=Uint8Array.of(0,97,115,109,1,0,0,0,1,...uleb128EncodeWithLen([1,96,...generateTypePack(sig.slice(1)),...generateTypePack(sig[0]==="v"?"":sig[0])]),2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0);var module=new WebAssembly.Module(bytes);var instance=new WebAssembly.Instance(module,{e:{f:func}});var wrappedFunc=instance.exports["f"];return wrappedFunc};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 removeFunction=index=>{functionsInTableMap.delete(getWasmTableEntry(index));setWasmTableEntry(index,null);freeTableIndexes.push(index)};{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];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"];if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].shift()()}}}Module["cwrap"]=cwrap;Module["addFunction"]=addFunction;Module["removeFunction"]=removeFunction;var _sqlite3_prepare_v2,_sqlite3_step,_sqlite3_column_int64,_sqlite3_reset,_sqlite3_exec,_sqlite3_finalize,_sqlite3_clear_bindings,_sqlite3_value_blob,_sqlite3_value_text,_sqlite3_value_bytes,_sqlite3_value_double,_sqlite3_value_int64,_sqlite3_value_type,_sqlite3_result_blob,_sqlite3_result_double,_sqlite3_result_error,_sqlite3_result_int,_sqlite3_result_int64,_sqlite3_result_null,_sqlite3_result_text,_sqlite3_column_count,_sqlite3_data_count,_sqlite3_column_blob,_sqlite3_column_bytes,_sqlite3_column_double,_sqlite3_column_text,_sqlite3_column_type,_sqlite3_column_name,_sqlite3_column_database_name,_sqlite3_column_table_name,_sqlite3_column_origin_name,_sqlite3_bind_blob,_sqlite3_bind_double,_sqlite3_bind_int,_sqlite3_bind_int64,_sqlite3_bind_null,_sqlite3_bind_text,_sqlite3_bind_parameter_count,_sqlite3_bind_parameter_name,_sqlite3_bind_parameter_index,_sqlite3_stmt_readonly,_sqlite3_sql,_sqlite3_errmsg,_sqlite3_last_insert_rowid,_sqlite3_changes,_sqlite3_total_changes,_sqlite3_close_v2,_sqlite3_create_function_v2,_sqlite3_open_v2,_sqlite3_get_autocommit,_malloc,_free,__emscripten_timeout,__emscripten_stack_restore,__emscripten_stack_alloc,_emscripten_stack_get_current,memory,__indirect_function_table,wasmMemory,wasmTable;function assignWasmExports(wasmExports){_sqlite3_prepare_v2=Module["_sqlite3_prepare_v2"]=wasmExports["F"];_sqlite3_step=Module["_sqlite3_step"]=wasmExports["G"];_sqlite3_column_int64=Module["_sqlite3_column_int64"]=wasmExports["H"];_sqlite3_reset=Module["_sqlite3_reset"]=wasmExports["I"];_sqlite3_exec=Module["_sqlite3_exec"]=wasmExports["J"];_sqlite3_finalize=Module["_sqlite3_finalize"]=wasmExports["K"];_sqlite3_clear_bindings=Module["_sqlite3_clear_bindings"]=wasmExports["L"];_sqlite3_value_blob=Module["_sqlite3_value_blob"]=wasmExports["M"];_sqlite3_value_text=Module["_sqlite3_value_text"]=wasmExports["N"];_sqlite3_value_bytes=Module["_sqlite3_value_bytes"]=wasmExports["O"];_sqlite3_value_double=Module["_sqlite3_value_double"]=wasmExports["P"];_sqlite3_value_int64=Module["_sqlite3_value_int64"]=wasmExports["Q"];_sqlite3_value_type=Module["_sqlite3_value_type"]=wasmExports["R"];_sqlite3_result_blob=Module["_sqlite3_result_blob"]=wasmExports["S"];_sqlite3_result_double=Module["_sqlite3_result_double"]=wasmExports["T"];_sqlite3_result_error=Module["_sqlite3_result_error"]=wasmExports["U"];_sqlite3_result_int=Module["_sqlite3_result_int"]=wasmExports["V"];_sqlite3_result_int64=Module["_sqlite3_result_int64"]=wasmExports["W"];_sqlite3_result_null=Module["_sqlite3_result_null"]=wasmExports["X"];_sqlite3_result_text=Module["_sqlite3_result_text"]=wasmExports["Y"];_sqlite3_column_count=Module["_sqlite3_column_count"]=wasmExports["Z"];_sqlite3_data_count=Module["_sqlite3_data_count"]=wasmExports["_"];_sqlite3_column_blob=Module["_sqlite3_column_blob"]=wasmExports["$"];_sqlite3_column_bytes=Module["_sqlite3_column_bytes"]=wasmExports["aa"];_sqlite3_column_double=Module["_sqlite3_column_double"]=wasmExports["ba"];_sqlite3_column_text=Module["_sqlite3_column_text"]=wasmExports["ca"];_sqlite3_column_type=Module["_sqlite3_column_type"]=wasmExports["da"];_sqlite3_column_name=Module["_sqlite3_column_name"]=wasmExports["ea"];_sqlite3_column_database_name=Module["_sqlite3_column_database_name"]=wasmExports["fa"];_sqlite3_column_table_name=Module["_sqlite3_column_table_name"]=wasmExports["ga"];_sqlite3_column_origin_name=Module["_sqlite3_column_origin_name"]=wasmExports["ha"];_sqlite3_bind_blob=Module["_sqlite3_bind_blob"]=wasmExports["ia"];_sqlite3_bind_double=Module["_sqlite3_bind_double"]=wasmExports["ja"];_sqlite3_bind_int=Module["_sqlite3_bind_int"]=wasmExports["ka"];_sqlite3_bind_int64=Module["_sqlite3_bind_int64"]=wasmExports["la"];_sqlite3_bind_null=Module["_sqlite3_bind_null"]=wasmExports["ma"];_sqlite3_bind_text=Module["_sqlite3_bind_text"]=wasmExports["na"];_sqlite3_bind_parameter_count=Module["_sqlite3_bind_parameter_count"]=wasmExports["oa"];_sqlite3_bind_parameter_name=Module["_sqlite3_bind_parameter_name"]=wasmExports["pa"];_sqlite3_bind_parameter_index=Module["_sqlite3_bind_parameter_index"]=wasmExports["qa"];_sqlite3_stmt_readonly=Module["_sqlite3_stmt_readonly"]=wasmExports["ra"];_sqlite3_sql=Module["_sqlite3_sql"]=wasmExports["sa"];_sqlite3_errmsg=Module["_sqlite3_errmsg"]=wasmExports["ta"];_sqlite3_last_insert_rowid=Module["_sqlite3_last_insert_rowid"]=wasmExports["ua"];_sqlite3_changes=Module["_sqlite3_changes"]=wasmExports["va"];_sqlite3_total_changes=Module["_sqlite3_total_changes"]=wasmExports["wa"];_sqlite3_close_v2=Module["_sqlite3_close_v2"]=wasmExports["xa"];_sqlite3_create_function_v2=Module["_sqlite3_create_function_v2"]=wasmExports["ya"];_sqlite3_open_v2=Module["_sqlite3_open_v2"]=wasmExports["za"];_sqlite3_get_autocommit=Module["_sqlite3_get_autocommit"]=wasmExports["Aa"];_malloc=Module["_malloc"]=wasmExports["Ba"];_free=Module["_free"]=wasmExports["Ca"];__emscripten_timeout=wasmExports["Ea"];__emscripten_stack_restore=wasmExports["Fa"];__emscripten_stack_alloc=wasmExports["Ga"];_emscripten_stack_get_current=wasmExports["Ha"];memory=wasmMemory=wasmExports["D"];__indirect_function_table=wasmTable=wasmExports["Da"]}var wasmImports={a:___assert_fail,p:__abort_js,j:__emscripten_runtime_keepalive_clear,m:__localtime_js,k:__setitimer_js,n:__tzset_js,o:_emscripten_date_now,l:_emscripten_resize_heap,B:_nodejsAccess,w:_nodejsCheckReservedLock,e:_nodejsClose,C:_nodejsDelete,z:_nodejsFileSize,q:_nodejsFullPathname,y:_nodejsLock,h:_nodejsRandomness,d:_nodejsRead,t:_nodejsShmBarrier,u:_nodejsShmLock,v:_nodejsShmMap,s:_nodejsShmUnmap,g:_nodejsSleep,A:_nodejsSync,b:_nodejsTruncate,x:_nodejsUnlock,c:_nodejsWrite,f:_nodejs_max_path_length,r:_nodejs_open,i:_proc_exit};function run(){preRun();function doRun(){Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve?.(Module);Module["onRuntimeInitialized"]?.();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(()=>{setTimeout(()=>Module["setStatus"](""),1);doRun()},1)}else{doRun()}}var wasmExports;wasmExports=await (createWasm());run();if(runtimeInitialized){moduleRtn=Module}else{moduleRtn=new Promise((resolve,reject)=>{readyPromiseResolve=resolve;readyPromiseReject=reject})}
1
+ async function createSqliteModule(moduleArg={}){var moduleRtn;var Module=moduleArg;var ENVIRONMENT_IS_NODE=true;const SQLITE_OK=0;const SQLITE_ROW=100;const SQLITE_DONE=101;const SQLITE_INTEGER=1;const SQLITE_FLOAT=2;const SQLITE_TEXT=3;const SQLITE_BLOB=4;const SQLITE_NULL=5;const SQLITE_UTF8=1;const SQLITE_TRANSIENT=-1;const SQLITE_DETERMINISTIC=2048;const SQLITE_DIRECTONLY=524288;const INT32_MIN=-2147483648;const INT32_MAX=2147483647;const NULL=0;function isByteArray(value){return value instanceof Uint8Array}function copyByteArray(value){const NodeBuffer=globalThis.Buffer;return NodeBuffer?NodeBuffer.from(value):Uint8Array.from(value)}function emptyByteArray(){const NodeBuffer=globalThis.Buffer;return NodeBuffer?NodeBuffer.alloc(0):new Uint8Array}let temp;const sqlite3={};Module.onRuntimeInitialized=()=>{temp=stackAlloc(8);const v=null;const n="number";const s="string";const n1=[n];const n2=[n,...n1];const n3=[n,...n2];const n4=[n,...n3];const n5=[n,...n4];const signatures={open_v2:[n,[s,n,n,s]],exec:[n,n5],errmsg:[s,n1],prepare_v2:[n,n5],close_v2:[n,n1],finalize:[n,n1],reset:[n,n1],clear_bindings:[n,n1],bind_int:[n,n3],bind_int64:[n,n3],bind_double:[n,n3],bind_text:[n,n5],bind_blob:[n,n5],bind_null:[n,n2],bind_parameter_index:[n,[n,s]],bind_parameter_count:[n,n1],bind_parameter_name:[s,n2],step:[n,n1],column_int64:[n,n2],column_double:[n,n2],column_text:[s,n2],column_blob:[n,n2],column_type:[n,n2],column_name:[s,n2],column_count:[n,n1],column_bytes:[n,n2],column_table_name:[s,n2],column_origin_name:[s,n2],column_database_name:[s,n2],data_count:[n,n1],sql:[s,n1],stmt_readonly:[n,n1],last_insert_rowid:[n,n1],changes:[n,n1],total_changes:[n,n1],create_function_v2:[n,[n,s,n,n,n,n,n,n,n]],value_type:[n,n1],value_text:[s,n1],value_blob:[n,n1],value_int64:[n,n1],value_double:[n,n1],value_bytes:[n,n1],result_double:[v,n2],result_null:[v,n1],result_text:[v,n4],result_blob:[v,n4],result_int:[v,n2],result_int64:[v,n2],result_error:[v,n3],get_autocommit:[n,n1],free:[v,n1],db_filename:[s,[n,s]],backup_init:[n,[n,s,n,s]],backup_step:[n,n2],backup_finish:[n,n1],update_hook:[n,n3],commit_hook:[n,n3],rollback_hook:[n,n3],session_create:[n,[n,s,n]],session_attach:[n,[n,s]],session_enable:[n,n2],session_delete:[v,n1],session_changeset:[n,n3],changeset_apply:[n,[n,n,n,n,n,n]],changeset_invert:[n,n4]};for(const[name,sig]of Object.entries(signatures)){const prefix=/^(session|changeset)_/.test(name)?"sqlite3":"sqlite3_";sqlite3[name]=cwrap(`${prefix}${name}`,sig[0],sig[1])}function arrayToHeap(array){const ptr=_malloc(array.byteLength);HEAPU8.set(array instanceof ArrayBuffer?new Uint8Array(array):array,ptr);return ptr}function stringToHeap(str){const size=lengthBytesUTF8(str)+1;const ptr=_malloc(size);stringToUTF8(str,ptr,size);return ptr}function toNumberOrNot(val){if(typeof val==="bigint"){if(val>=Number.MIN_SAFE_INTEGER&&val<=Number.MAX_SAFE_INTEGER){return Number(val)}return val}return val}const SQLITE_ERROR_NAMES={1:"SQLITE_ERROR",2:"SQLITE_INTERNAL",3:"SQLITE_PERM",4:"SQLITE_ABORT",5:"SQLITE_BUSY",6:"SQLITE_LOCKED",7:"SQLITE_NOMEM",8:"SQLITE_READONLY",9:"SQLITE_INTERRUPT",10:"SQLITE_IOERR",11:"SQLITE_CORRUPT",12:"SQLITE_NOTFOUND",13:"SQLITE_FULL",14:"SQLITE_CANTOPEN",15:"SQLITE_PROTOCOL",16:"SQLITE_EMPTY",17:"SQLITE_SCHEMA",18:"SQLITE_TOOBIG",19:"SQLITE_CONSTRAINT",20:"SQLITE_MISMATCH",21:"SQLITE_MISUSE",23:"SQLITE_AUTH",24:"SQLITE_FORMAT",25:"SQLITE_RANGE",26:"SQLITE_NOTADB",100:"SQLITE_ROW",101:"SQLITE_DONE"};class SqliteError extends Error{constructor(message,code){super(message);this.name="SqliteError";if(typeof code==="number"){this.code=SQLITE_ERROR_NAMES[code&255]||SQLITE_ERROR_NAMES[code]||"SQLITE_ERROR"}else{this.code=code||"SQLITE_ERROR"}}}function resolveBindParams(args){if(args.length===0)return null;if(args.length===1){const arg=args[0];if(arg===undefined||arg===null)return null;if(Array.isArray(arg))return arg;if(typeof arg==="object"&&!isByteArray(arg))return arg;return[arg]}return Array.from(args)}function parseFunctionArgs(argc,argv){const args=[];for(let i=0;i<argc;i++){const ptr=getValue(argv+4*i,"i32");const type=sqlite3.value_type(ptr);switch(type){case SQLITE_INTEGER:args.push(toNumberOrNot(sqlite3.value_int64(ptr)));break;case SQLITE_FLOAT:args.push(sqlite3.value_double(ptr));break;case SQLITE_TEXT:args.push(sqlite3.value_text(ptr));break;case SQLITE_BLOB:{const p=sqlite3.value_blob(ptr);args.push(p!==NULL?copyByteArray(HEAPU8.slice(p,p+sqlite3.value_bytes(ptr))):emptyByteArray());break}case SQLITE_NULL:args.push(null);break}}return args}function setFunctionResult(cx,result){switch(typeof result){case"boolean":sqlite3.result_int(cx,result?1:0);break;case"number":if(Number.isSafeInteger(result)){if(result>=INT32_MIN&&result<=INT32_MAX){sqlite3.result_int(cx,result)}else{sqlite3.result_int64(cx,BigInt(result))}}else{sqlite3.result_double(cx,result)}break;case"bigint":sqlite3.result_int64(cx,result);break;case"string":{const tp=stringToHeap(result);sqlite3.result_text(cx,tp,-1,SQLITE_TRANSIENT);_free(tp);break}case"object":if(result===null){sqlite3.result_null(cx)}else if(isByteArray(result)){const tp=arrayToHeap(result);sqlite3.result_blob(cx,tp,result.byteLength,SQLITE_TRANSIENT);_free(tp)}else{sqlite3.result_error(cx,stringToHeap("unsupported return type"),-1)}break;default:sqlite3.result_null(cx);break}}class Database{constructor(filename,options={}){if(typeof filename!=="string"&&!isByteArray(filename)){throw new TypeError("Expected first argument to be a string")}filename=String(filename);const readonly=!!options.readonly;const fileMustExist=!!options.fileMustExist;let flags;if(readonly){flags=1}else{flags=2;if(!fileMustExist)flags|=4}const rc=sqlite3.open_v2(filename,temp,flags,NULL);this._ptr=getValue(temp,"i32");if(rc!==SQLITE_OK){const msg=this._ptr!==NULL?sqlite3.errmsg(this._ptr):"unable to open database";if(this._ptr!==NULL)sqlite3.close_v2(this._ptr);this._ptr=null;throw new SqliteError(msg)}this._open=true;this._readonly=readonly;this._unsafe=false;this._name=filename;this._statements=new Set;this._functions=new Map;this._sessions=new Set;this._updateHook=0;this._commitHook=0;this._rollbackHook=0;this.exec("PRAGMA busy_timeout = 5000")}unsafeMode(enabled){if(enabled===undefined)enabled=true;this._unsafe=!!enabled;return this}get open(){return this._open}get readonly(){return this._readonly}get name(){return this._name}get inTransaction(){return this._open&&sqlite3.get_autocommit(this._ptr)===0}prepare(source){this._assertOpen();if(typeof source!=="string"){throw new TypeError("Expected first argument to be a string")}const stmt=new Statement(this,source);this._statements.add(stmt);return stmt}exec(sql,{resetStatements=true}={}){this._assertOpen();if(resetStatements){for(const stmt of this._statements){if(!stmt._finalized)sqlite3.reset(stmt._ptr)}}const tp=stringToHeap(sql);try{const rc=sqlite3.exec(this._ptr,tp,NULL,NULL,NULL);if(rc!==SQLITE_OK){throw new SqliteError(sqlite3.errmsg(this._ptr),rc)}}finally{_free(tp)}return this}transaction(fn){if(typeof fn!=="function"){throw new TypeError("Expected first argument to be a function")}const db=this;const wrapTxn=begin=>{const beginStmt=db.prepare(begin);const commitStmt=db.prepare("COMMIT");const rollbackStmt=db.prepare("ROLLBACK");const runner=function(...args){let result;if(db.inTransaction){return fn.apply(this,args)}beginStmt.run();try{result=fn.apply(this,args);commitStmt.run()}catch(err){if(db.inTransaction){rollbackStmt.run()}throw err}return result};return runner};const result=wrapTxn("BEGIN");result.deferred=wrapTxn("BEGIN DEFERRED");result.immediate=wrapTxn("BEGIN IMMEDIATE");result.exclusive=wrapTxn("BEGIN EXCLUSIVE");result.database=db;return result}pragma(source,options){if(typeof source!=="string"){throw new TypeError("Expected first argument to be a string")}const simple=options&&options.simple;const sql=`PRAGMA ${source}`;const stmt=this.prepare(sql);try{if(stmt.reader){return simple?stmt.pluck().get():stmt.all()}else{return stmt.run()}}finally{stmt.finalize()}}function(name,fn,options={}){this._assertOpen();if(typeof name!=="string")throw new TypeError("Expected first argument to be a string");if(typeof fn!=="function")throw new TypeError("Expected second argument to be a function");const deterministic=!!options.deterministic;const directOnly=!!options.directOnly;const varargs=options.varargs||false;if(this._functions.has(name)){removeFunction(this._functions.get(name));this._functions.delete(name)}const wrappedFunc=(cx,argc,argv)=>{const args=parseFunctionArgs(argc,argv);try{const result=fn(...args);setFunctionResult(cx,result)}catch(err){const tp=stringToHeap(err.toString());sqlite3.result_error(cx,tp,-1);_free(tp)}};const funcPtr=addFunction(wrappedFunc,"viii");this._functions.set(name,funcPtr);let eTextRep=SQLITE_UTF8;if(deterministic)eTextRep|=SQLITE_DETERMINISTIC;if(directOnly)eTextRep|=SQLITE_DIRECTONLY;const rc=sqlite3.create_function_v2(this._ptr,name,varargs?-1:fn.length,eTextRep,NULL,funcPtr,NULL,NULL,NULL);if(rc!==SQLITE_OK)throw new SqliteError(sqlite3.errmsg(this._ptr));return this}aggregate(name,options){this._assertOpen();if(typeof name!=="string")throw new TypeError("Expected first argument to be a string");if(!options||typeof options!=="object")throw new TypeError("Expected second argument to be an options object");const step=options.step;const result=options.result||(acc=>acc);const start=options.start;const inverse=options.inverse;const deterministic=!!options.deterministic;const directOnly=!!options.directOnly;const varargs=!!options.varargs;if(typeof step!=="function")throw new TypeError("Expected options.step to be a function");let accumulator;const stepWrapper=(cx,argc,argv)=>{const args=parseFunctionArgs(argc,argv);try{accumulator=step(accumulator,...args)}catch(err){const tp=stringToHeap(err.toString());sqlite3.result_error(cx,tp,-1);_free(tp)}};const finalWrapper=cx=>{try{const val=result(accumulator);setFunctionResult(cx,val)}catch(err){const tp=stringToHeap(err.toString());sqlite3.result_error(cx,tp,-1);_free(tp)}accumulator=typeof start==="function"?start():start};accumulator=typeof start==="function"?start():start;if(this._functions.has(name+"_step")){removeFunction(this._functions.get(name+"_step"));this._functions.delete(name+"_step")}if(this._functions.has(name+"_final")){removeFunction(this._functions.get(name+"_final"));this._functions.delete(name+"_final")}const stepPtr=addFunction(stepWrapper,"viii");const finalPtr=addFunction(finalWrapper,"vi");this._functions.set(name+"_step",stepPtr);this._functions.set(name+"_final",finalPtr);let eTextRep=SQLITE_UTF8;if(deterministic)eTextRep|=SQLITE_DETERMINISTIC;if(directOnly)eTextRep|=SQLITE_DIRECTONLY;const argCount=varargs?-1:step.length-1;const rc=sqlite3.create_function_v2(this._ptr,name,argCount,eTextRep,NULL,NULL,stepPtr,finalPtr,NULL);if(rc!==SQLITE_OK)throw new SqliteError(sqlite3.errmsg(this._ptr));return this}updateHook(fn){this._assertOpen();if(fn!==null&&typeof fn!=="function")throw new TypeError("Expected first argument to be a function or null");const previous=this._updateHook;this._updateHook=fn===null?null:addFunction((_arg,op,databaseName,tableName,rowid)=>{fn(op,UTF8ToString(databaseName),UTF8ToString(tableName),toNumberOrNot(rowid))},"viiiij");sqlite3.update_hook(this._ptr,this._updateHook??NULL,NULL);if(previous)removeFunction(previous);return this}commitHook(fn){this._assertOpen();if(fn!==null&&typeof fn!=="function")throw new TypeError("Expected first argument to be a function or null");const previous=this._commitHook;this._commitHook=fn===null?null:addFunction(()=>fn(),"ii");sqlite3.commit_hook(this._ptr,this._commitHook??NULL,NULL);if(previous)removeFunction(previous);return this}rollbackHook(fn){this._assertOpen();if(fn!==null&&typeof fn!=="function")throw new TypeError("Expected first argument to be a function or null");const previous=this._rollbackHook;this._rollbackHook=fn===null?null:addFunction(()=>fn(),"vi");sqlite3.rollback_hook(this._ptr,this._rollbackHook??NULL,NULL);if(previous)removeFunction(previous);return this}filename(databaseName="main"){this._assertOpen();return sqlite3.db_filename(this._ptr,databaseName)}backupTo(destination,sourceName="main",destinationName="main"){this._assertOpen();destination._assertOpen();const backup=sqlite3.backup_init(destination._ptr,destinationName,this._ptr,sourceName);if(!backup)throw new SqliteError(sqlite3.errmsg(destination._ptr));sqlite3.backup_step(backup,-1);const finish=sqlite3.backup_finish(backup);if(finish!==SQLITE_OK){throw new SqliteError(sqlite3.errmsg(destination._ptr),finish)}}createSession(databaseName="main"){this._assertOpen();const rc=sqlite3.session_create(this._ptr,databaseName,temp);if(rc!==SQLITE_OK)throw new SqliteError(sqlite3.errmsg(this._ptr),rc);const pointer=getValue(temp,"i32");const database=this;let closed=false;const check=()=>{database._assertOpen();if(closed)throw new SqliteError("The session is closed",21)};const session={attach(table=null){check();const result=sqlite3.session_attach(pointer,table);if(result!==SQLITE_OK)throw new SqliteError(sqlite3.errmsg(database._ptr),result)},enable(enabled){check();sqlite3.session_enable(pointer,enabled?1:0)},changeset(){check();const output=_malloc(8);try{const result=sqlite3.session_changeset(pointer,output,output+4);if(result!==SQLITE_OK)throw new SqliteError(sqlite3.errmsg(database._ptr),result);const size=getValue(output,"i32");const buffer=getValue(output+4,"i32");try{return HEAPU8.slice(buffer,buffer+size)}finally{sqlite3.free(buffer)}}finally{_free(output)}},close(){if(closed)return;sqlite3.session_delete(pointer);closed=true;database._sessions.delete(session)}};this._sessions.add(session);return session}applyChangeset(changeset,onConflict=(()=>2)){this._assertOpen();const input=arrayToHeap(changeset);const conflict=addFunction((context,reason)=>onConflict(reason),"iiii");try{const rc=sqlite3.changeset_apply(this._ptr,changeset.byteLength,input,NULL,conflict,NULL);if(rc!==SQLITE_OK)throw new SqliteError(sqlite3.errmsg(this._ptr),rc)}finally{removeFunction(conflict);_free(input)}}invertChangeset(changeset){this._assertOpen();const input=arrayToHeap(changeset);const output=_malloc(8);try{const rc=sqlite3.changeset_invert(changeset.byteLength,input,output,output+4);if(rc!==SQLITE_OK)throw new SqliteError(sqlite3.errmsg(this._ptr),rc);const size=getValue(output,"i32");const buffer=getValue(output+4,"i32");try{return HEAPU8.slice(buffer,buffer+size)}finally{sqlite3.free(buffer)}}finally{_free(output);_free(input)}}close(){if(!this._open)return;for(const session of this._sessions)session.close();this.updateHook(null);this.commitHook(null);this.rollbackHook(null);for(const stmt of this._statements){if(!stmt._finalized){sqlite3.finalize(stmt._ptr);stmt._finalized=true}}this._statements.clear();for(const func of this._functions.values()){removeFunction(func)}this._functions.clear();if(this._updateHook){sqlite3.update_hook(this._ptr,NULL,NULL);removeFunction(this._updateHook);this._updateHook=null}const rc=sqlite3.close_v2(this._ptr);if(rc!==SQLITE_OK){throw new SqliteError(sqlite3.errmsg(this._ptr))}this._ptr=null;this._open=false}_assertOpen(){if(!this._open)throw new SqliteError("The database connection is not open")}_handleError(rc){if(rc!==SQLITE_OK){throw new SqliteError(sqlite3.errmsg(this._ptr),rc)}}}class Statement{constructor(db,source){this._db=db;this._source=source;this._finalized=false;this._pluck=false;this._expand=false;this._raw=false;this._bound=false;this._numbersAsDoubles=false;const tp=stringToHeap(source);try{const rc=sqlite3.prepare_v2(db._ptr,tp,-1,temp,NULL);if(rc!==SQLITE_OK){throw new SqliteError(sqlite3.errmsg(db._ptr),rc)}}finally{_free(tp)}this._ptr=getValue(temp,"i32");if(this._ptr===NULL){throw new SqliteError("Nothing to prepare")}this._columnCount=sqlite3.column_count(this._ptr);this._reader=this._columnCount>0;this._readonly=!!sqlite3.stmt_readonly(this._ptr)}get source(){return this._source}get reader(){return this._reader}get readonly(){return this._readonly}get parameterCount(){this._assertReady();return sqlite3.bind_parameter_count(this._ptr)}numbersAsDoubles(toggle=true){this._numbersAsDoubles=toggle;return this}finalize(){if(this._finalized)return;sqlite3.finalize(this._ptr);this._finalized=true;this._ptr=null;this._db._statements.delete(this)}run(...args){this._assertReady();const params=resolveBindParams(args);this._reset();if(params)this._bind(params);this._step();const result={changes:sqlite3.changes(this._db._ptr),lastInsertRowid:toNumberOrNot(sqlite3.last_insert_rowid(this._db._ptr))};sqlite3.reset(this._ptr);return result}get(...args){this._assertReady();const params=resolveBindParams(args);this._reset();if(params)this._bind(params);if(!this._step()){sqlite3.reset(this._ptr);return undefined}const row=this._getRow();sqlite3.reset(this._ptr);return row}all(...args){this._assertReady();const params=resolveBindParams(args);this._reset();if(params)this._bind(params);const rows=[];while(this._step()){rows.push(this._getRow());if(rows.length===1e5){console.warn(`[bedrock-sqlite] all() returned 100k rows, query: ${this._source.slice(0,200)}`)}if(rows.length>=1e7){sqlite3.reset(this._ptr);throw new SqliteError(`all() exceeded 10M row safety limit, likely infinite loop. query: ${this._source.slice(0,200)}`)}}sqlite3.reset(this._ptr);return rows}*iterate(...args){this._assertReady();const params=resolveBindParams(args);this._reset();if(params)this._bind(params);while(this._step()){yield this._getRow()}}pluck(toggle=true){this._pluck=toggle;this._raw=false;this._expand=false;return this}expand(toggle=true){this._expand=toggle;this._pluck=false;this._raw=false;return this}raw(toggle=true){this._raw=toggle;this._pluck=false;this._expand=false;return this}columns(){this._assertReady();const cols=[];for(let i=0;i<this._columnCount;i++){cols.push({name:sqlite3.column_name(this._ptr,i),column:sqlite3.column_origin_name(this._ptr,i),table:sqlite3.column_table_name(this._ptr,i),database:sqlite3.column_database_name(this._ptr,i),type:null})}return cols}scanStatusV2(){return[]}scanStatusReset(){}safeIntegers(){return this}bind(...args){this._assertReady();const params=resolveBindParams(args);this._reset();if(params)this._bind(params);this._bound=true;return this}_reset(){sqlite3.clear_bindings(this._ptr);sqlite3.reset(this._ptr)}_step(){const rc=sqlite3.step(this._ptr);if(rc===SQLITE_ROW)return true;if(rc===SQLITE_DONE)return false;sqlite3.reset(this._ptr);throw new SqliteError(sqlite3.errmsg(this._db._ptr),rc)}_getRow(){if(this._pluck){return this._getColumnValue(0)}if(this._raw){const row=[];for(let i=0;i<this._columnCount;i++){row.push(this._getColumnValue(i))}return row}if(this._expand){const row={};for(let i=0;i<this._columnCount;i++){let table=sqlite3.column_table_name(this._ptr,i);table=table===""||table===null?"$":table;const name=sqlite3.column_name(this._ptr,i);if(!row[table])row[table]={};row[table][name]=this._getColumnValue(i)}return row}const row={};for(let i=0;i<this._columnCount;i++){row[sqlite3.column_name(this._ptr,i)]=this._getColumnValue(i)}return row}_getColumnValue(i){const type=sqlite3.column_type(this._ptr,i);switch(type){case SQLITE_INTEGER:return toNumberOrNot(sqlite3.column_int64(this._ptr,i));case SQLITE_FLOAT:return sqlite3.column_double(this._ptr,i);case SQLITE_TEXT:return sqlite3.column_text(this._ptr,i);case SQLITE_BLOB:{const p=sqlite3.column_blob(this._ptr,i);if(p!==NULL){const nbytes=sqlite3.column_bytes(this._ptr,i);if(nbytes>104857600){throw new SqliteError(`blob column ${i} has unreasonable size: ${nbytes} bytes`)}return copyByteArray(HEAPU8.slice(p,p+nbytes))}return emptyByteArray()}case SQLITE_NULL:return null;default:return null}}_bind(params){if(Array.isArray(params)){for(let i=0;i<params.length;i++){this._bindValue(params[i],i+1)}}else if(typeof params==="object"){const count=sqlite3.bind_parameter_count(this._ptr);for(let i=1;i<=count;i++){const pname=sqlite3.bind_parameter_name(this._ptr,i);if(!pname)continue;const stripped=pname.slice(1);const value=pname in params?params[pname]:stripped in params?params[stripped]:undefined;if(value!==undefined){this._bindValue(value,i)}}}}_bindValue(value,position){let rc;switch(typeof value){case"string":{const tp=stringToHeap(value);rc=sqlite3.bind_text(this._ptr,position,tp,-1,SQLITE_TRANSIENT);_free(tp);break}case"number":if(!this._numbersAsDoubles&&Number.isSafeInteger(value)){if(value>=INT32_MIN&&value<=INT32_MAX){rc=sqlite3.bind_int(this._ptr,position,value)}else{rc=sqlite3.bind_int64(this._ptr,position,BigInt(value))}}else{rc=sqlite3.bind_double(this._ptr,position,value)}break;case"bigint":rc=sqlite3.bind_int64(this._ptr,position,value);break;case"boolean":rc=sqlite3.bind_int(this._ptr,position,value?1:0);break;case"object":if(value===null){rc=sqlite3.bind_null(this._ptr,position)}else if(isByteArray(value)){const tp=arrayToHeap(value);rc=sqlite3.bind_blob(this._ptr,position,tp,value.byteLength,SQLITE_TRANSIENT);_free(tp)}else{throw new SqliteError(`Unsupported binding type at position ${position}`)}break;default:if(value===undefined){rc=sqlite3.bind_null(this._ptr,position)}else{throw new SqliteError(`Unsupported binding type: ${typeof value}`)}}if(rc!==SQLITE_OK){throw new SqliteError(sqlite3.errmsg(this._db._ptr))}}_assertReady(){if(this._finalized)throw new SqliteError("This statement has been finalized");if(!this._db._open)throw new SqliteError("The database connection is not open")}}Module.Database=Database;Module.SqliteError=SqliteError};const path=require("node:path");const crypto=require("node:crypto");const SQLITE_CANTOPEN=14;const SQLITE_IOERR_READ=266;const SQLITE_IOERR_SHORT_READ=522;const SQLITE_IOERR_FSYNC=1034;const SQLITE_IOERR_WRITE=778;const SQLITE_IOERR_DELETE=2570;const SQLITE_IOERR_CLOSE=4106;const SQLITE_IOERR_TRUNCATE=1546;const SQLITE_IOERR_FSTAT=1802;const SQLITE_OPEN_READONLY=1;const SQLITE_OPEN_READWRITE=2;const SQLITE_OPEN_CREATE=4;const SQLITE_OPEN_EXCLUSIVE=16;const SQLITE_ACCESS_READWRITE=1;const SQLITE_ACCESS_READ=2;const SQLITE_LOCK_NONE=0;const SQLITE_LOCK_SHARED=1;const SQLITE_LOCK_RESERVED=2;const SQLITE_LOCK_EXCLUSIVE=4;const SQLITE_BUSY=5;function _fd(fileInfo){return getValue(fileInfo+4,"i32")}function _setLocked(fileInfo,locked){setValue(fileInfo+8,locked?1:0,"i32")}function _path(fileInfo){return UTF8ToString(getValue(fileInfo+12,"i32"))}function _safeInt(bigInt){if(bigInt<Number.MIN_SAFE_INTEGER||bigInt>Number.MAX_SAFE_INTEGER)throw 0;return Number(bigInt)}var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var _scriptName;if(typeof __filename!="undefined"){_scriptName=__filename}else{}var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");scriptDirectory=__dirname+"/";readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(process.argv.length>1){thisProgram=process.argv[1].replace(/\\/g,"/")}arguments_=process.argv.slice(2);quit_=(status,toThrow)=>{process.exitCode=status;throw toThrow}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var EXITSTATUS;var isFileURI=filename=>filename.startsWith("file://");var readyPromiseResolve,readyPromiseReject;var runtimeInitialized=false;function updateMemoryViews(){var b=wasmMemory.buffer;HEAP8=new Int8Array(b);HEAP16=new Int16Array(b);HEAPU8=new Uint8Array(b);HEAPU16=new Uint16Array(b);HEAP32=new Int32Array(b);HEAPU32=new Uint32Array(b);HEAPF32=new Float32Array(b);HEAPF64=new Float64Array(b);HEAP64=new BigInt64Array(b);HEAPU64=new BigUint64Array(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;wasmExports["E"]()}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(onPostRuns)}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(){return locateFile("sqlite3.wasm")}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&&!ENVIRONMENT_IS_NODE){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(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance,module){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();if(Module["instantiateWasm"]){return new Promise((resolve,reject)=>{Module["instantiateWasm"](info,(inst,mod)=>{resolve(receiveInstance(inst,mod))})})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var HEAP16;var HEAP32;var HEAP64;var HEAP8;var HEAPF32;var HEAPF64;var HEAPU16;var HEAPU32;var HEAPU64;var HEAPU8;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":return HEAP64[ptr>>3];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":HEAP64[ptr>>3]=BigInt(value);break;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=globalThis.TextDecoder&&new TextDecoder;var findStringEnd=(heapOrArray,idx,maxBytesToRead,ignoreNul)=>{var maxIdx=idx+maxBytesToRead;if(ignoreNul)return maxIdx;while(heapOrArray[idx]&&!(idx>=maxIdx))++idx;return idx};var UTF8ArrayToString=(heapOrArray,idx=0,maxBytesToRead,ignoreNul)=>{var endPtr=findStringEnd(heapOrArray,idx,maxBytesToRead,ignoreNul);if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr))}var str="";while(idx<endPtr){var u0=heapOrArray[idx++];if(!(u0&128)){str+=String.fromCharCode(u0);continue}var u1=heapOrArray[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=heapOrArray[idx++]&63;if((u0&240)==224){u0=(u0&15)<<12|u1<<6|u2}else{u0=(u0&7)<<18|u1<<12|u2<<6|heapOrArray[idx++]&63}if(u0<65536){str+=String.fromCharCode(u0)}else{var ch=u0-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}return str};var UTF8ToString=(ptr,maxBytesToRead,ignoreNul)=>ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead,ignoreNul):"";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 __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};var INT53_MAX=9007199254740992;var INT53_MIN=-9007199254740992;var bigintToI53Checked=num=>num<INT53_MIN||num>INT53_MAX?NaN:Number(num);function __localtime_js(time,tmPtr){time=bigintToI53Checked(time);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}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{return func()}catch(e){handleException(e)}finally{maybeExit()}};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 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.codePointAt(i);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;i++}}heap[outIdx]=0;return outIdx-startIdx};var stringToUTF8=(str,outPtr,maxBytesToWrite)=>stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite);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=()=>536870912;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+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};function _nodejsAccess(vfs,filePath,flags,outResult){let aflags=fs.constants.F_OK;if(flags==SQLITE_ACCESS_READWRITE)aflags=fs.constants.R_OK|fs.constants.W_OK;if(flags==SQLITE_ACCESS_READ)aflags=fs.constants.R_OK;try{fs.accessSync(UTF8ToString(filePath),aflags);setValue(outResult,1,"i32")}catch{setValue(outResult,0,"i32")}return SQLITE_OK}var _fileLocks={};function _nodejsCheckReservedLock(fi,outResult){var filePath=_path(fi);var holders=_fileLocks[filePath];var reserved=0;if(holders){for(var[other,otherLevel]of holders){if(other!==fi&&otherLevel>=SQLITE_LOCK_RESERVED){reserved=1;break}}}setValue(outResult,reserved,"i32");return SQLITE_OK}function _nodejsClose(fi){_nodejsUnlock(fi,SQLITE_LOCK_NONE);try{fs.closeSync(_fd(fi))}catch{return SQLITE_IOERR_CLOSE}return SQLITE_OK}function _nodejsDelete(vfs,filePath,dirSync){const pathStr=UTF8ToString(filePath);try{fs.unlinkSync(pathStr)}catch(err){if(err.code!="ENOENT")return SQLITE_IOERR_DELETE}if(dirSync){let fd=-1;try{fd=fs.openSync(path.dirname(pathStr),"r");fs.fsyncSync(fd)}catch{return SQLITE_IOERR_FSYNC}finally{try{fs.closeSync(fd)}catch{return SQLITE_IOERR_FSYNC}}}return SQLITE_OK}function _nodejsFileSize(fi,outSize){try{setValue(outSize,fs.fstatSync(_fd(fi)).size,"i64")}catch{return SQLITE_IOERR_FSTAT}return SQLITE_OK}function _nodejsFullPathname(vfs,relPath,sizeFullPath,outFullPath){const full=path.resolve(UTF8ToString(relPath));stringToUTF8(full,outFullPath,sizeFullPath);return full.length<sizeFullPath?SQLITE_OK:SQLITE_CANTOPEN}function _nodejsLock(fi,level){var filePath=_path(fi);if(!_fileLocks[filePath])_fileLocks[filePath]=new Map;var holders=_fileLocks[filePath];var myLevel=holders.get(fi)||SQLITE_LOCK_NONE;if(level>=SQLITE_LOCK_RESERVED&&myLevel<SQLITE_LOCK_RESERVED){for(var[other,otherLevel]of holders){if(other!==fi&&otherLevel>=SQLITE_LOCK_RESERVED){return SQLITE_BUSY}}}if(level>=SQLITE_LOCK_EXCLUSIVE&&myLevel<SQLITE_LOCK_EXCLUSIVE){for(var[other,otherLevel]of holders){if(other!==fi&&otherLevel>=SQLITE_LOCK_SHARED){return SQLITE_BUSY}}}holders.set(fi,level);if(level>SQLITE_LOCK_NONE)_setLocked(fi,true);return SQLITE_OK}function _nodejsRandomness(vfs,bytes,outBuffer){const buf=HEAPU8.subarray(outBuffer,outBuffer+bytes);crypto.randomFillSync(buf);return bytes}function _nodejsRead(fi,outBuffer,bytes,offset){const buf=HEAPU8.subarray(outBuffer,outBuffer+bytes);let bytesRead;try{bytesRead=fs.readSync(_fd(fi),buf,0,bytes,_safeInt(offset))}catch{return SQLITE_IOERR_READ}if(bytesRead==bytes){return SQLITE_OK}else if(bytesRead>=0){if(bytesRead<bytes){try{buf.fill(0,bytesRead)}catch{return SQLITE_IOERR_READ}}return SQLITE_IOERR_SHORT_READ}return SQLITE_IOERR_READ}function _nodejsShmBarrier(fi){var filePath=_path(fi);var reg=_shmRegistry[filePath];if(!reg||reg._hasExclusiveLock)return;var shmPath=filePath+"-shm";var stat;try{stat=fs.statSync(shmPath)}catch(e){return}if(reg._lastShmWrite&&stat.mtimeMs<=reg._lastShmWrite)return;var fd;try{fd=fs.openSync(shmPath,fs.constants.O_RDONLY)}catch(e){return}for(var pgno in reg){if(typeof reg[pgno]!=="object"||!reg[pgno].ptr)continue;var r=reg[pgno];try{fs.readSync(fd,HEAPU8.subarray(r.ptr,r.ptr+r.pgsz),0,r.pgsz,Number(pgno)*r.pgsz)}catch(e){}}fs.closeSync(fd);reg._lastShmWrite=stat.mtimeMs}function _nodejsShmLock(fi,offset,n,flags){var filePath=_path(fi);if(!_shmRegistry[filePath])_shmRegistry[filePath]={};var reg=_shmRegistry[filePath];if(flags&2&&flags&8){reg._hasExclusiveLock=true}if(flags&1&&flags&8&&reg._hasExclusiveLock){var shmPath=filePath+"-shm";var fd;try{fd=fs.openSync(shmPath,fs.constants.O_RDWR|fs.constants.O_CREAT,420)}catch(e){reg._hasExclusiveLock=false;return SQLITE_OK}for(var pgno in reg){if(typeof reg[pgno]!=="object"||!reg[pgno].ptr)continue;var r=reg[pgno];try{fs.writeSync(fd,HEAPU8.subarray(r.ptr,r.ptr+r.pgsz),0,r.pgsz,Number(pgno)*r.pgsz)}catch(e){}}try{fs.fsyncSync(fd)}catch(e){}try{reg._lastShmWrite=fs.fstatSync(fd).mtimeMs}catch(e){reg._lastShmWrite=Date.now()}fs.closeSync(fd);reg._hasExclusiveLock=false}return SQLITE_OK}var _shmRegistry={};function _nodejsShmMap(fi,pgno,pgsz,isWrite,ppOut){var filePath=_path(fi);if(!_shmRegistry[filePath])_shmRegistry[filePath]={};var regions=_shmRegistry[filePath];if(!(pgno in regions)||typeof regions[pgno]!=="object"){if(!isWrite){setValue(ppOut,0,"*");return SQLITE_OK}var buf=_malloc(pgsz);HEAPU8.fill(0,buf,buf+pgsz);regions[pgno]={ptr:buf,pgsz}}setValue(ppOut,regions[pgno].ptr,"*");return SQLITE_OK}function _nodejsShmUnmap(fi,deleteFlag){if(deleteFlag){var filePath=_path(fi);var regions=_shmRegistry[filePath];if(regions){for(var pgno in regions){if(typeof regions[pgno]==="object"&&regions[pgno].ptr)_free(regions[pgno].ptr)}delete _shmRegistry[filePath]}}return SQLITE_OK}function _nodejsSleep(vfs,nMicro){var ms=Math.max(1,Math.floor(nMicro/1e3));var sab=new SharedArrayBuffer(4);Atomics.wait(new Int32Array(sab),0,0,ms);return nMicro}function _nodejsSync(fi,flags){try{fs.fsyncSync(_fd(fi))}catch{return SQLITE_IOERR_FSYNC}return SQLITE_OK}function _nodejsTruncate(fi,size){try{fs.ftruncateSync(_fd(fi),_safeInt(size))}catch{return SQLITE_IOERR_TRUNCATE}return SQLITE_OK}function _nodejsUnlock(fi,level){var filePath=_path(fi);var holders=_fileLocks[filePath];if(holders){if(level==SQLITE_LOCK_NONE){holders.delete(fi);_setLocked(fi,false)}else{holders.set(fi,level)}}else{if(level==SQLITE_LOCK_NONE)_setLocked(fi,false)}return SQLITE_OK}function _nodejsWrite(fi,buffer,bytes,offset){try{const bytesWritten=fs.writeSync(_fd(fi),HEAPU8.subarray(buffer,buffer+bytes),0,bytes,_safeInt(offset));return bytesWritten!=bytes?SQLITE_IOERR_WRITE:SQLITE_OK}catch{return SQLITE_IOERR_WRITE}}function _nodejs_max_path_length(){return process.platform=="win32"?260:4096}function _nodejs_open(filePath,flags,mode){let oflags=0;if(flags&SQLITE_OPEN_EXCLUSIVE)oflags|=fs.constants.O_EXCL;if(flags&SQLITE_OPEN_CREATE)oflags|=fs.constants.O_CREAT;if(flags&SQLITE_OPEN_READONLY)oflags|=fs.constants.O_RDONLY;if(flags&SQLITE_OPEN_READWRITE)oflags|=fs.constants.O_RDWR;try{return fs.openSync(UTF8ToString(filePath),oflags,mode)}catch{return-1}}var getCFunc=ident=>{var func=Module["_"+ident];return func};var writeArrayToMemory=(array,buffer)=>{HEAP8.set(array,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 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 wasmTableMirror=[];var getWasmTableEntry=funcPtr=>{var func=wasmTableMirror[funcPtr];if(!func){wasmTableMirror[funcPtr]=func=wasmTable.get(funcPtr)}return func};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()}return wasmTable["grow"](1)};var setWasmTableEntry=(idx,func)=>{wasmTable.set(idx,func);wasmTableMirror[idx]=wasmTable.get(idx)};var uleb128EncodeWithLen=arr=>{const n=arr.length;return[n%128|128,n>>7,...arr]};var wasmTypeCodes={i:127,p:127,j:126,f:125,d:124,e:111};var generateTypePack=types=>uleb128EncodeWithLen(Array.from(types,type=>{var code=wasmTypeCodes[type];return code}));var convertJsFunctionToWasm=(func,sig)=>{var bytes=Uint8Array.of(0,97,115,109,1,0,0,0,1,...uleb128EncodeWithLen([1,96,...generateTypePack(sig.slice(1)),...generateTypePack(sig[0]==="v"?"":sig[0])]),2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0);var module=new WebAssembly.Module(bytes);var instance=new WebAssembly.Instance(module,{e:{f:func}});var wrappedFunc=instance.exports["f"];return wrappedFunc};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 removeFunction=index=>{functionsInTableMap.delete(getWasmTableEntry(index));setWasmTableEntry(index,null);freeTableIndexes.push(index)};{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];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"];if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].shift()()}}}Module["cwrap"]=cwrap;Module["addFunction"]=addFunction;Module["removeFunction"]=removeFunction;var _sqlite3_free,_sqlite3_prepare_v2,_sqlite3_step,_sqlite3_column_int64,_sqlite3_reset,_sqlite3_exec,_sqlite3_finalize,_sqlite3_backup_init,_sqlite3_backup_step,_sqlite3_backup_finish,_sqlite3_clear_bindings,_sqlite3_value_blob,_sqlite3_value_text,_sqlite3_value_bytes,_sqlite3_value_double,_sqlite3_value_int64,_sqlite3_value_type,_sqlite3_result_blob,_sqlite3_result_double,_sqlite3_result_error,_sqlite3_result_int,_sqlite3_result_int64,_sqlite3_result_null,_sqlite3_result_text,_sqlite3_column_count,_sqlite3_data_count,_sqlite3_column_blob,_sqlite3_column_bytes,_sqlite3_column_double,_sqlite3_column_text,_sqlite3_column_type,_sqlite3_column_name,_sqlite3_column_database_name,_sqlite3_column_table_name,_sqlite3_column_origin_name,_sqlite3_bind_blob,_sqlite3_bind_double,_sqlite3_bind_int,_sqlite3_bind_int64,_sqlite3_bind_null,_sqlite3_bind_text,_sqlite3_bind_parameter_count,_sqlite3_bind_parameter_name,_sqlite3_bind_parameter_index,_sqlite3_stmt_readonly,_sqlite3_sql,_sqlite3_errmsg,_sqlite3_last_insert_rowid,_sqlite3_changes,_sqlite3_total_changes,_sqlite3_close_v2,_sqlite3_create_function_v2,_sqlite3_commit_hook,_sqlite3_update_hook,_sqlite3_rollback_hook,_sqlite3_open_v2,_sqlite3_get_autocommit,_sqlite3_db_filename,_sqlite3session_create,_sqlite3session_delete,_sqlite3session_attach,_sqlite3session_changeset,_sqlite3session_enable,_sqlite3changeset_invert,_sqlite3changeset_apply,_malloc,_free,__emscripten_timeout,__emscripten_stack_restore,__emscripten_stack_alloc,_emscripten_stack_get_current,memory,__indirect_function_table,wasmMemory,wasmTable;function assignWasmExports(wasmExports){_sqlite3_free=Module["_sqlite3_free"]=wasmExports["F"];_sqlite3_prepare_v2=Module["_sqlite3_prepare_v2"]=wasmExports["G"];_sqlite3_step=Module["_sqlite3_step"]=wasmExports["H"];_sqlite3_column_int64=Module["_sqlite3_column_int64"]=wasmExports["I"];_sqlite3_reset=Module["_sqlite3_reset"]=wasmExports["J"];_sqlite3_exec=Module["_sqlite3_exec"]=wasmExports["K"];_sqlite3_finalize=Module["_sqlite3_finalize"]=wasmExports["L"];_sqlite3_backup_init=Module["_sqlite3_backup_init"]=wasmExports["M"];_sqlite3_backup_step=Module["_sqlite3_backup_step"]=wasmExports["N"];_sqlite3_backup_finish=Module["_sqlite3_backup_finish"]=wasmExports["O"];_sqlite3_clear_bindings=Module["_sqlite3_clear_bindings"]=wasmExports["P"];_sqlite3_value_blob=Module["_sqlite3_value_blob"]=wasmExports["Q"];_sqlite3_value_text=Module["_sqlite3_value_text"]=wasmExports["R"];_sqlite3_value_bytes=Module["_sqlite3_value_bytes"]=wasmExports["S"];_sqlite3_value_double=Module["_sqlite3_value_double"]=wasmExports["T"];_sqlite3_value_int64=Module["_sqlite3_value_int64"]=wasmExports["U"];_sqlite3_value_type=Module["_sqlite3_value_type"]=wasmExports["V"];_sqlite3_result_blob=Module["_sqlite3_result_blob"]=wasmExports["W"];_sqlite3_result_double=Module["_sqlite3_result_double"]=wasmExports["X"];_sqlite3_result_error=Module["_sqlite3_result_error"]=wasmExports["Y"];_sqlite3_result_int=Module["_sqlite3_result_int"]=wasmExports["Z"];_sqlite3_result_int64=Module["_sqlite3_result_int64"]=wasmExports["_"];_sqlite3_result_null=Module["_sqlite3_result_null"]=wasmExports["$"];_sqlite3_result_text=Module["_sqlite3_result_text"]=wasmExports["aa"];_sqlite3_column_count=Module["_sqlite3_column_count"]=wasmExports["ba"];_sqlite3_data_count=Module["_sqlite3_data_count"]=wasmExports["ca"];_sqlite3_column_blob=Module["_sqlite3_column_blob"]=wasmExports["da"];_sqlite3_column_bytes=Module["_sqlite3_column_bytes"]=wasmExports["ea"];_sqlite3_column_double=Module["_sqlite3_column_double"]=wasmExports["fa"];_sqlite3_column_text=Module["_sqlite3_column_text"]=wasmExports["ga"];_sqlite3_column_type=Module["_sqlite3_column_type"]=wasmExports["ha"];_sqlite3_column_name=Module["_sqlite3_column_name"]=wasmExports["ia"];_sqlite3_column_database_name=Module["_sqlite3_column_database_name"]=wasmExports["ja"];_sqlite3_column_table_name=Module["_sqlite3_column_table_name"]=wasmExports["ka"];_sqlite3_column_origin_name=Module["_sqlite3_column_origin_name"]=wasmExports["la"];_sqlite3_bind_blob=Module["_sqlite3_bind_blob"]=wasmExports["ma"];_sqlite3_bind_double=Module["_sqlite3_bind_double"]=wasmExports["na"];_sqlite3_bind_int=Module["_sqlite3_bind_int"]=wasmExports["oa"];_sqlite3_bind_int64=Module["_sqlite3_bind_int64"]=wasmExports["pa"];_sqlite3_bind_null=Module["_sqlite3_bind_null"]=wasmExports["qa"];_sqlite3_bind_text=Module["_sqlite3_bind_text"]=wasmExports["ra"];_sqlite3_bind_parameter_count=Module["_sqlite3_bind_parameter_count"]=wasmExports["sa"];_sqlite3_bind_parameter_name=Module["_sqlite3_bind_parameter_name"]=wasmExports["ta"];_sqlite3_bind_parameter_index=Module["_sqlite3_bind_parameter_index"]=wasmExports["ua"];_sqlite3_stmt_readonly=Module["_sqlite3_stmt_readonly"]=wasmExports["va"];_sqlite3_sql=Module["_sqlite3_sql"]=wasmExports["wa"];_sqlite3_errmsg=Module["_sqlite3_errmsg"]=wasmExports["xa"];_sqlite3_last_insert_rowid=Module["_sqlite3_last_insert_rowid"]=wasmExports["ya"];_sqlite3_changes=Module["_sqlite3_changes"]=wasmExports["za"];_sqlite3_total_changes=Module["_sqlite3_total_changes"]=wasmExports["Aa"];_sqlite3_close_v2=Module["_sqlite3_close_v2"]=wasmExports["Ba"];_sqlite3_create_function_v2=Module["_sqlite3_create_function_v2"]=wasmExports["Ca"];_sqlite3_commit_hook=Module["_sqlite3_commit_hook"]=wasmExports["Da"];_sqlite3_update_hook=Module["_sqlite3_update_hook"]=wasmExports["Ea"];_sqlite3_rollback_hook=Module["_sqlite3_rollback_hook"]=wasmExports["Fa"];_sqlite3_open_v2=Module["_sqlite3_open_v2"]=wasmExports["Ga"];_sqlite3_get_autocommit=Module["_sqlite3_get_autocommit"]=wasmExports["Ha"];_sqlite3_db_filename=Module["_sqlite3_db_filename"]=wasmExports["Ia"];_sqlite3session_create=Module["_sqlite3session_create"]=wasmExports["Ja"];_sqlite3session_delete=Module["_sqlite3session_delete"]=wasmExports["Ka"];_sqlite3session_attach=Module["_sqlite3session_attach"]=wasmExports["La"];_sqlite3session_changeset=Module["_sqlite3session_changeset"]=wasmExports["Ma"];_sqlite3session_enable=Module["_sqlite3session_enable"]=wasmExports["Na"];_sqlite3changeset_invert=Module["_sqlite3changeset_invert"]=wasmExports["Oa"];_sqlite3changeset_apply=Module["_sqlite3changeset_apply"]=wasmExports["Pa"];_malloc=Module["_malloc"]=wasmExports["Qa"];_free=Module["_free"]=wasmExports["Ra"];__emscripten_timeout=wasmExports["Ta"];__emscripten_stack_restore=wasmExports["Ua"];__emscripten_stack_alloc=wasmExports["Va"];_emscripten_stack_get_current=wasmExports["Wa"];memory=wasmMemory=wasmExports["D"];__indirect_function_table=wasmTable=wasmExports["Sa"]}var wasmImports={a:___assert_fail,p:__abort_js,j:__emscripten_runtime_keepalive_clear,m:__localtime_js,k:__setitimer_js,n:__tzset_js,o:_emscripten_date_now,l:_emscripten_resize_heap,B:_nodejsAccess,w:_nodejsCheckReservedLock,e:_nodejsClose,C:_nodejsDelete,z:_nodejsFileSize,q:_nodejsFullPathname,y:_nodejsLock,h:_nodejsRandomness,d:_nodejsRead,t:_nodejsShmBarrier,u:_nodejsShmLock,v:_nodejsShmMap,s:_nodejsShmUnmap,g:_nodejsSleep,A:_nodejsSync,b:_nodejsTruncate,x:_nodejsUnlock,c:_nodejsWrite,f:_nodejs_max_path_length,r:_nodejs_open,i:_proc_exit};function run(){preRun();function doRun(){Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve?.(Module);Module["onRuntimeInitialized"]?.();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(()=>{setTimeout(()=>Module["setStatus"](""),1);doRun()},1)}else{doRun()}}var wasmExports;wasmExports=await (createWasm());run();if(runtimeInitialized){moduleRtn=Module}else{moduleRtn=new Promise((resolve,reject)=>{readyPromiseResolve=resolve;readyPromiseReject=reject})}
2
2
  ;return moduleRtn}if(typeof exports==="object"&&typeof module==="object"){module.exports=createSqliteModule;module.exports.default=createSqliteModule}else if(typeof define==="function"&&define["amd"])define([],()=>createSqliteModule);
@@ -1,2 +1,2 @@
1
- async function createSqliteModule(moduleArg={}){var moduleRtn;var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer";const SQLITE_OK=0;const SQLITE_ROW=100;const SQLITE_DONE=101;const SQLITE_INTEGER=1;const SQLITE_FLOAT=2;const SQLITE_TEXT=3;const SQLITE_BLOB=4;const SQLITE_NULL=5;const SQLITE_UTF8=1;const SQLITE_TRANSIENT=-1;const SQLITE_DETERMINISTIC=2048;const SQLITE_DIRECTONLY=524288;const INT32_MIN=-2147483648;const INT32_MAX=2147483647;const NULL=0;function isByteArray(value){return value instanceof Uint8Array}function copyByteArray(value){const NodeBuffer=globalThis.Buffer;return NodeBuffer?NodeBuffer.from(value):Uint8Array.from(value)}function emptyByteArray(){const NodeBuffer=globalThis.Buffer;return NodeBuffer?NodeBuffer.alloc(0):new Uint8Array}let temp;const sqlite3={};Module.onRuntimeInitialized=()=>{temp=stackAlloc(8);const v=null;const n="number";const s="string";const n1=[n];const n2=[n,...n1];const n3=[n,...n2];const n4=[n,...n3];const n5=[n,...n4];const signatures={open_v2:[n,[s,n,n,s]],exec:[n,n5],errmsg:[s,n1],prepare_v2:[n,n5],close_v2:[n,n1],finalize:[n,n1],reset:[n,n1],clear_bindings:[n,n1],bind_int:[n,n3],bind_int64:[n,n3],bind_double:[n,n3],bind_text:[n,n5],bind_blob:[n,n5],bind_null:[n,n2],bind_parameter_index:[n,[n,s]],bind_parameter_count:[n,n1],bind_parameter_name:[s,n2],step:[n,n1],column_int64:[n,n2],column_double:[n,n2],column_text:[s,n2],column_blob:[n,n2],column_type:[n,n2],column_name:[s,n2],column_count:[n,n1],column_bytes:[n,n2],column_table_name:[s,n2],column_origin_name:[s,n2],column_database_name:[s,n2],data_count:[n,n1],sql:[s,n1],stmt_readonly:[n,n1],last_insert_rowid:[n,n1],changes:[n,n1],total_changes:[n,n1],create_function_v2:[n,[n,s,n,n,n,n,n,n,n]],value_type:[n,n1],value_text:[s,n1],value_blob:[n,n1],value_int64:[n,n1],value_double:[n,n1],value_bytes:[n,n1],result_double:[v,n2],result_null:[v,n1],result_text:[v,n4],result_blob:[v,n4],result_int:[v,n2],result_int64:[v,n2],result_error:[v,n3],get_autocommit:[n,n1]};for(const[name,sig]of Object.entries(signatures)){sqlite3[name]=cwrap(`sqlite3_${name}`,sig[0],sig[1])}function arrayToHeap(array){const ptr=_malloc(array.byteLength);HEAPU8.set(array,ptr);return ptr}function stringToHeap(str){const size=lengthBytesUTF8(str)+1;const ptr=_malloc(size);stringToUTF8(str,ptr,size);return ptr}function toNumberOrNot(val){if(typeof val==="bigint"){if(val>=Number.MIN_SAFE_INTEGER&&val<=Number.MAX_SAFE_INTEGER){return Number(val)}return val}return val}const SQLITE_ERROR_NAMES={1:"SQLITE_ERROR",2:"SQLITE_INTERNAL",3:"SQLITE_PERM",4:"SQLITE_ABORT",5:"SQLITE_BUSY",6:"SQLITE_LOCKED",7:"SQLITE_NOMEM",8:"SQLITE_READONLY",9:"SQLITE_INTERRUPT",10:"SQLITE_IOERR",11:"SQLITE_CORRUPT",12:"SQLITE_NOTFOUND",13:"SQLITE_FULL",14:"SQLITE_CANTOPEN",15:"SQLITE_PROTOCOL",16:"SQLITE_EMPTY",17:"SQLITE_SCHEMA",18:"SQLITE_TOOBIG",19:"SQLITE_CONSTRAINT",20:"SQLITE_MISMATCH",21:"SQLITE_MISUSE",23:"SQLITE_AUTH",24:"SQLITE_FORMAT",25:"SQLITE_RANGE",26:"SQLITE_NOTADB",100:"SQLITE_ROW",101:"SQLITE_DONE"};class SqliteError extends Error{constructor(message,code){super(message);this.name="SqliteError";if(typeof code==="number"){this.code=SQLITE_ERROR_NAMES[code&255]||SQLITE_ERROR_NAMES[code]||"SQLITE_ERROR"}else{this.code=code||"SQLITE_ERROR"}}}function resolveBindParams(args){if(args.length===0)return null;if(args.length===1){const arg=args[0];if(arg===undefined||arg===null)return null;if(Array.isArray(arg))return arg;if(typeof arg==="object"&&!isByteArray(arg))return arg;return[arg]}return Array.from(args)}function parseFunctionArgs(argc,argv){const args=[];for(let i=0;i<argc;i++){const ptr=getValue(argv+4*i,"i32");const type=sqlite3.value_type(ptr);switch(type){case SQLITE_INTEGER:args.push(toNumberOrNot(sqlite3.value_int64(ptr)));break;case SQLITE_FLOAT:args.push(sqlite3.value_double(ptr));break;case SQLITE_TEXT:args.push(sqlite3.value_text(ptr));break;case SQLITE_BLOB:{const p=sqlite3.value_blob(ptr);args.push(p!==NULL?copyByteArray(HEAPU8.slice(p,p+sqlite3.value_bytes(ptr))):emptyByteArray());break}case SQLITE_NULL:args.push(null);break}}return args}function setFunctionResult(cx,result){switch(typeof result){case"boolean":sqlite3.result_int(cx,result?1:0);break;case"number":if(Number.isSafeInteger(result)){if(result>=INT32_MIN&&result<=INT32_MAX){sqlite3.result_int(cx,result)}else{sqlite3.result_int64(cx,BigInt(result))}}else{sqlite3.result_double(cx,result)}break;case"bigint":sqlite3.result_int64(cx,result);break;case"string":{const tp=stringToHeap(result);sqlite3.result_text(cx,tp,-1,SQLITE_TRANSIENT);_free(tp);break}case"object":if(result===null){sqlite3.result_null(cx)}else if(isByteArray(result)){const tp=arrayToHeap(result);sqlite3.result_blob(cx,tp,result.byteLength,SQLITE_TRANSIENT);_free(tp)}else{sqlite3.result_error(cx,stringToHeap("unsupported return type"),-1)}break;default:sqlite3.result_null(cx);break}}class Database{constructor(filename,options={}){if(typeof filename!=="string"&&!isByteArray(filename)){throw new TypeError("Expected first argument to be a string")}filename=String(filename);const readonly=!!options.readonly;const fileMustExist=!!options.fileMustExist;let flags;if(readonly){flags=1}else{flags=2;if(!fileMustExist)flags|=4}const rc=sqlite3.open_v2(filename,temp,flags,NULL);this._ptr=getValue(temp,"i32");if(rc!==SQLITE_OK){const msg=this._ptr!==NULL?sqlite3.errmsg(this._ptr):"unable to open database";if(this._ptr!==NULL)sqlite3.close_v2(this._ptr);this._ptr=null;throw new SqliteError(msg)}this._open=true;this._readonly=readonly;this._unsafe=false;this._name=filename;this._statements=new Set;this._functions=new Map;this.exec("PRAGMA busy_timeout = 5000")}unsafeMode(enabled){if(enabled===undefined)enabled=true;this._unsafe=!!enabled;return this}get open(){return this._open}get readonly(){return this._readonly}get name(){return this._name}get inTransaction(){return this._open&&sqlite3.get_autocommit(this._ptr)===0}prepare(source){this._assertOpen();if(typeof source!=="string"){throw new TypeError("Expected first argument to be a string")}const stmt=new Statement(this,source);this._statements.add(stmt);return stmt}exec(sql,{resetStatements=true}={}){this._assertOpen();if(resetStatements){for(const stmt of this._statements){if(!stmt._finalized)sqlite3.reset(stmt._ptr)}}const tp=stringToHeap(sql);try{const rc=sqlite3.exec(this._ptr,tp,NULL,NULL,NULL);if(rc!==SQLITE_OK){throw new SqliteError(sqlite3.errmsg(this._ptr),rc)}}finally{_free(tp)}return this}transaction(fn){if(typeof fn!=="function"){throw new TypeError("Expected first argument to be a function")}const db=this;const wrapTxn=begin=>{const beginStmt=db.prepare(begin);const commitStmt=db.prepare("COMMIT");const rollbackStmt=db.prepare("ROLLBACK");const runner=function(...args){let result;if(db.inTransaction){return fn.apply(this,args)}beginStmt.run();try{result=fn.apply(this,args);commitStmt.run()}catch(err){if(db.inTransaction){rollbackStmt.run()}throw err}return result};return runner};const result=wrapTxn("BEGIN");result.deferred=wrapTxn("BEGIN DEFERRED");result.immediate=wrapTxn("BEGIN IMMEDIATE");result.exclusive=wrapTxn("BEGIN EXCLUSIVE");result.database=db;return result}pragma(source,options){if(typeof source!=="string"){throw new TypeError("Expected first argument to be a string")}const simple=options&&options.simple;const sql=`PRAGMA ${source}`;const stmt=this.prepare(sql);try{if(stmt.reader){return simple?stmt.pluck().get():stmt.all()}else{return stmt.run()}}finally{stmt.finalize()}}function(name,fn,options={}){this._assertOpen();if(typeof name!=="string")throw new TypeError("Expected first argument to be a string");if(typeof fn!=="function")throw new TypeError("Expected second argument to be a function");const deterministic=!!options.deterministic;const directOnly=!!options.directOnly;const varargs=options.varargs||false;if(this._functions.has(name)){removeFunction(this._functions.get(name));this._functions.delete(name)}const wrappedFunc=(cx,argc,argv)=>{const args=parseFunctionArgs(argc,argv);try{const result=fn(...args);setFunctionResult(cx,result)}catch(err){const tp=stringToHeap(err.toString());sqlite3.result_error(cx,tp,-1);_free(tp)}};const funcPtr=addFunction(wrappedFunc,"viii");this._functions.set(name,funcPtr);let eTextRep=SQLITE_UTF8;if(deterministic)eTextRep|=SQLITE_DETERMINISTIC;if(directOnly)eTextRep|=SQLITE_DIRECTONLY;const rc=sqlite3.create_function_v2(this._ptr,name,varargs?-1:fn.length,eTextRep,NULL,funcPtr,NULL,NULL,NULL);if(rc!==SQLITE_OK)throw new SqliteError(sqlite3.errmsg(this._ptr));return this}aggregate(name,options){this._assertOpen();if(typeof name!=="string")throw new TypeError("Expected first argument to be a string");if(!options||typeof options!=="object")throw new TypeError("Expected second argument to be an options object");const step=options.step;const result=options.result||(acc=>acc);const start=options.start;const inverse=options.inverse;const deterministic=!!options.deterministic;const directOnly=!!options.directOnly;const varargs=!!options.varargs;if(typeof step!=="function")throw new TypeError("Expected options.step to be a function");let accumulator;const stepWrapper=(cx,argc,argv)=>{const args=parseFunctionArgs(argc,argv);try{accumulator=step(accumulator,...args)}catch(err){const tp=stringToHeap(err.toString());sqlite3.result_error(cx,tp,-1);_free(tp)}};const finalWrapper=cx=>{try{const val=result(accumulator);setFunctionResult(cx,val)}catch(err){const tp=stringToHeap(err.toString());sqlite3.result_error(cx,tp,-1);_free(tp)}accumulator=typeof start==="function"?start():start};accumulator=typeof start==="function"?start():start;if(this._functions.has(name+"_step")){removeFunction(this._functions.get(name+"_step"));this._functions.delete(name+"_step")}if(this._functions.has(name+"_final")){removeFunction(this._functions.get(name+"_final"));this._functions.delete(name+"_final")}const stepPtr=addFunction(stepWrapper,"viii");const finalPtr=addFunction(finalWrapper,"vi");this._functions.set(name+"_step",stepPtr);this._functions.set(name+"_final",finalPtr);let eTextRep=SQLITE_UTF8;if(deterministic)eTextRep|=SQLITE_DETERMINISTIC;if(directOnly)eTextRep|=SQLITE_DIRECTONLY;const argCount=varargs?-1:step.length-1;const rc=sqlite3.create_function_v2(this._ptr,name,argCount,eTextRep,NULL,NULL,stepPtr,finalPtr,NULL);if(rc!==SQLITE_OK)throw new SqliteError(sqlite3.errmsg(this._ptr));return this}close(){if(!this._open)return;for(const stmt of this._statements){if(!stmt._finalized){sqlite3.finalize(stmt._ptr);stmt._finalized=true}}this._statements.clear();for(const func of this._functions.values()){removeFunction(func)}this._functions.clear();const rc=sqlite3.close_v2(this._ptr);if(rc!==SQLITE_OK){throw new SqliteError(sqlite3.errmsg(this._ptr))}this._ptr=null;this._open=false}_assertOpen(){if(!this._open)throw new SqliteError("The database connection is not open")}_handleError(rc){if(rc!==SQLITE_OK){throw new SqliteError(sqlite3.errmsg(this._ptr),rc)}}}class Statement{constructor(db,source){this._db=db;this._source=source;this._finalized=false;this._pluck=false;this._expand=false;this._raw=false;this._bound=false;this._numbersAsDoubles=false;const tp=stringToHeap(source);try{const rc=sqlite3.prepare_v2(db._ptr,tp,-1,temp,NULL);if(rc!==SQLITE_OK){throw new SqliteError(sqlite3.errmsg(db._ptr),rc)}}finally{_free(tp)}this._ptr=getValue(temp,"i32");if(this._ptr===NULL){throw new SqliteError("Nothing to prepare")}this._columnCount=sqlite3.column_count(this._ptr);this._reader=this._columnCount>0;this._readonly=!!sqlite3.stmt_readonly(this._ptr)}get source(){return this._source}get reader(){return this._reader}get readonly(){return this._readonly}get parameterCount(){this._assertReady();return sqlite3.bind_parameter_count(this._ptr)}numbersAsDoubles(toggle=true){this._numbersAsDoubles=toggle;return this}finalize(){if(this._finalized)return;sqlite3.finalize(this._ptr);this._finalized=true;this._ptr=null;this._db._statements.delete(this)}run(...args){this._assertReady();const params=resolveBindParams(args);this._reset();if(params)this._bind(params);this._step();const result={changes:sqlite3.changes(this._db._ptr),lastInsertRowid:toNumberOrNot(sqlite3.last_insert_rowid(this._db._ptr))};sqlite3.reset(this._ptr);return result}get(...args){this._assertReady();const params=resolveBindParams(args);this._reset();if(params)this._bind(params);if(!this._step()){sqlite3.reset(this._ptr);return undefined}const row=this._getRow();sqlite3.reset(this._ptr);return row}all(...args){this._assertReady();const params=resolveBindParams(args);this._reset();if(params)this._bind(params);const rows=[];while(this._step()){rows.push(this._getRow());if(rows.length===1e5){console.warn(`[bedrock-sqlite] all() returned 100k rows, query: ${this._source.slice(0,200)}`)}if(rows.length>=1e7){sqlite3.reset(this._ptr);throw new SqliteError(`all() exceeded 10M row safety limit, likely infinite loop. query: ${this._source.slice(0,200)}`)}}sqlite3.reset(this._ptr);return rows}*iterate(...args){this._assertReady();const params=resolveBindParams(args);this._reset();if(params)this._bind(params);while(this._step()){yield this._getRow()}}pluck(toggle=true){this._pluck=toggle;this._raw=false;this._expand=false;return this}expand(toggle=true){this._expand=toggle;this._pluck=false;this._raw=false;return this}raw(toggle=true){this._raw=toggle;this._pluck=false;this._expand=false;return this}columns(){this._assertReady();const cols=[];for(let i=0;i<this._columnCount;i++){cols.push({name:sqlite3.column_name(this._ptr,i),column:sqlite3.column_origin_name(this._ptr,i),table:sqlite3.column_table_name(this._ptr,i),database:sqlite3.column_database_name(this._ptr,i),type:null})}return cols}scanStatusV2(){return[]}scanStatusReset(){}safeIntegers(){return this}bind(...args){this._assertReady();const params=resolveBindParams(args);this._reset();if(params)this._bind(params);this._bound=true;return this}_reset(){sqlite3.clear_bindings(this._ptr);sqlite3.reset(this._ptr)}_step(){const rc=sqlite3.step(this._ptr);if(rc===SQLITE_ROW)return true;if(rc===SQLITE_DONE)return false;sqlite3.reset(this._ptr);throw new SqliteError(sqlite3.errmsg(this._db._ptr),rc)}_getRow(){if(this._pluck){return this._getColumnValue(0)}if(this._raw){const row=[];for(let i=0;i<this._columnCount;i++){row.push(this._getColumnValue(i))}return row}if(this._expand){const row={};for(let i=0;i<this._columnCount;i++){let table=sqlite3.column_table_name(this._ptr,i);table=table===""||table===null?"$":table;const name=sqlite3.column_name(this._ptr,i);if(!row[table])row[table]={};row[table][name]=this._getColumnValue(i)}return row}const row={};for(let i=0;i<this._columnCount;i++){row[sqlite3.column_name(this._ptr,i)]=this._getColumnValue(i)}return row}_getColumnValue(i){const type=sqlite3.column_type(this._ptr,i);switch(type){case SQLITE_INTEGER:return toNumberOrNot(sqlite3.column_int64(this._ptr,i));case SQLITE_FLOAT:return sqlite3.column_double(this._ptr,i);case SQLITE_TEXT:return sqlite3.column_text(this._ptr,i);case SQLITE_BLOB:{const p=sqlite3.column_blob(this._ptr,i);if(p!==NULL){const nbytes=sqlite3.column_bytes(this._ptr,i);if(nbytes>104857600){throw new SqliteError(`blob column ${i} has unreasonable size: ${nbytes} bytes`)}return copyByteArray(HEAPU8.slice(p,p+nbytes))}return emptyByteArray()}case SQLITE_NULL:return null;default:return null}}_bind(params){if(Array.isArray(params)){for(let i=0;i<params.length;i++){this._bindValue(params[i],i+1)}}else if(typeof params==="object"){const count=sqlite3.bind_parameter_count(this._ptr);for(let i=1;i<=count;i++){const pname=sqlite3.bind_parameter_name(this._ptr,i);if(!pname)continue;const stripped=pname.slice(1);const value=pname in params?params[pname]:stripped in params?params[stripped]:undefined;if(value!==undefined){this._bindValue(value,i)}}}}_bindValue(value,position){let rc;switch(typeof value){case"string":{const tp=stringToHeap(value);rc=sqlite3.bind_text(this._ptr,position,tp,-1,SQLITE_TRANSIENT);_free(tp);break}case"number":if(!this._numbersAsDoubles&&Number.isSafeInteger(value)){if(value>=INT32_MIN&&value<=INT32_MAX){rc=sqlite3.bind_int(this._ptr,position,value)}else{rc=sqlite3.bind_int64(this._ptr,position,BigInt(value))}}else{rc=sqlite3.bind_double(this._ptr,position,value)}break;case"bigint":rc=sqlite3.bind_int64(this._ptr,position,value);break;case"boolean":rc=sqlite3.bind_int(this._ptr,position,value?1:0);break;case"object":if(value===null){rc=sqlite3.bind_null(this._ptr,position)}else if(isByteArray(value)){const tp=arrayToHeap(value);rc=sqlite3.bind_blob(this._ptr,position,tp,value.byteLength,SQLITE_TRANSIENT);_free(tp)}else{throw new SqliteError(`Unsupported binding type at position ${position}`)}break;default:if(value===undefined){rc=sqlite3.bind_null(this._ptr,position)}else{throw new SqliteError(`Unsupported binding type: ${typeof value}`)}}if(rc!==SQLITE_OK){throw new SqliteError(sqlite3.errmsg(this._db._ptr))}}_assertReady(){if(this._finalized)throw new SqliteError("This statement has been finalized");if(!this._db._open)throw new SqliteError("The database connection is not open")}}Module.Database=Database;Module.SqliteError=SqliteError};const SQLITE_CANTOPEN=14;const SQLITE_IOERR_READ=266;const SQLITE_IOERR_SHORT_READ=522;const SQLITE_IOERR_WRITE=778;const SQLITE_IOERR_TRUNCATE=1546;const SQLITE_IOERR_FSTAT=1802;const SQLITE_OPEN_EXCLUSIVE=16;const SQLITE_LOCK_NONE=0;const SQLITE_LOCK_SHARED=1;const SQLITE_LOCK_RESERVED=2;const SQLITE_LOCK_EXCLUSIVE=4;const SQLITE_BUSY=5;function _fd(fileInfo){return getValue(fileInfo+4,"i32")}function _setLocked(fileInfo,locked){setValue(fileInfo+8,locked?1:0,"i32")}function _path(fileInfo){return UTF8ToString(getValue(fileInfo+12,"i32"))}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 ABORT=false;var EXITSTATUS;var readyPromiseResolve,readyPromiseReject;var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;var HEAP64,HEAPU64;var runtimeInitialized=false;function updateMemoryViews(){var b=wasmMemory.buffer;HEAP8=new Int8Array(b);HEAP16=new Int16Array(b);HEAPU8=new Uint8Array(b);HEAPU16=new Uint16Array(b);HEAP32=new Int32Array(b);HEAPU32=new Uint32Array(b);HEAPF32=new Float32Array(b);HEAPF64=new Float64Array(b);HEAP64=new BigInt64Array(b);HEAPU64=new BigUint64Array(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;wasmExports["E"]()}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(onPostRuns)}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("sqlite3-browser.wasm")}return new URL("sqlite3-browser.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){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(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance,module){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();if(Module["instantiateWasm"]){return new Promise((resolve,reject)=>{Module["instantiateWasm"](info,(inst,mod)=>{resolve(receiveInstance(inst,mod))})})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}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":return HEAP64[ptr>>3];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":HEAP64[ptr>>3]=BigInt(value);break;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=globalThis.TextDecoder&&new TextDecoder;var findStringEnd=(heapOrArray,idx,maxBytesToRead,ignoreNul)=>{var maxIdx=idx+maxBytesToRead;if(ignoreNul)return maxIdx;while(heapOrArray[idx]&&!(idx>=maxIdx))++idx;return idx};var UTF8ArrayToString=(heapOrArray,idx=0,maxBytesToRead,ignoreNul)=>{var endPtr=findStringEnd(heapOrArray,idx,maxBytesToRead,ignoreNul);if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr))}var str="";while(idx<endPtr){var u0=heapOrArray[idx++];if(!(u0&128)){str+=String.fromCharCode(u0);continue}var u1=heapOrArray[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=heapOrArray[idx++]&63;if((u0&240)==224){u0=(u0&15)<<12|u1<<6|u2}else{u0=(u0&7)<<18|u1<<12|u2<<6|heapOrArray[idx++]&63}if(u0<65536){str+=String.fromCharCode(u0)}else{var ch=u0-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}return str};var UTF8ToString=(ptr,maxBytesToRead,ignoreNul)=>ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead,ignoreNul):"";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 __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};var INT53_MAX=9007199254740992;var INT53_MIN=-9007199254740992;var bigintToI53Checked=num=>num<INT53_MIN||num>INT53_MAX?NaN:Number(num);function __localtime_js(time,tmPtr){time=bigintToI53Checked(time);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}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{return func()}catch(e){handleException(e)}finally{maybeExit()}};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 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.codePointAt(i);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;i++}}heap[outIdx]=0;return outIdx-startIdx};var stringToUTF8=(str,outPtr,maxBytesToWrite)=>stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite);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=()=>536870912;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+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 _memfs={files:{},fds:{},nextFd:10};function _nodejsAccess(vfs,filePath,flags,outResult){var path=UTF8ToString(filePath);setValue(outResult,_memfs.files[path]?1:0,"i32");return SQLITE_OK}var _fileLocks={};function _nodejsCheckReservedLock(fi,outResult){var filePath=_path(fi);var holders=_fileLocks[filePath];var reserved=0;if(holders){for(var[other,otherLevel]of holders){if(other!==fi&&otherLevel>=SQLITE_LOCK_RESERVED){reserved=1;break}}}setValue(outResult,reserved,"i32");return SQLITE_OK}function _nodejsClose(fi){_nodejsUnlock(fi,SQLITE_LOCK_NONE);var fd=_fd(fi);delete _memfs.fds[fd];return SQLITE_OK}function _nodejsDelete(vfs,filePath,dirSync){var path=UTF8ToString(filePath);delete _memfs.files[path];return SQLITE_OK}function _nodejsFileSize(fi,outSize){var fdInfo=_memfs.fds[_fd(fi)];if(!fdInfo)return SQLITE_IOERR_FSTAT;var file=_memfs.files[fdInfo.path];if(!file)return SQLITE_IOERR_FSTAT;setValue(outSize,file.size,"i64");return SQLITE_OK}function _nodejsFullPathname(vfs,relPath,sizeFullPath,outFullPath){var full=UTF8ToString(relPath);if(full.startsWith("./"))full=full.substring(2);if(!full.startsWith("/"))full="/"+full;stringToUTF8(full,outFullPath,sizeFullPath);return full.length<sizeFullPath?SQLITE_OK:SQLITE_CANTOPEN}function _nodejsLock(fi,level){var filePath=_path(fi);if(!_fileLocks[filePath])_fileLocks[filePath]=new Map;var holders=_fileLocks[filePath];var myLevel=holders.get(fi)||SQLITE_LOCK_NONE;if(level>=SQLITE_LOCK_RESERVED&&myLevel<SQLITE_LOCK_RESERVED){for(var[other,otherLevel]of holders){if(other!==fi&&otherLevel>=SQLITE_LOCK_RESERVED){return SQLITE_BUSY}}}if(level>=SQLITE_LOCK_EXCLUSIVE&&myLevel<SQLITE_LOCK_EXCLUSIVE){for(var[other,otherLevel]of holders){if(other!==fi&&otherLevel>=SQLITE_LOCK_SHARED){return SQLITE_BUSY}}}holders.set(fi,level);if(level>SQLITE_LOCK_NONE)_setLocked(fi,true);return SQLITE_OK}function _nodejsRandomness(vfs,bytes,outBuffer){var buf=HEAPU8.subarray(outBuffer,outBuffer+bytes);if(typeof globalThis.crypto!=="undefined"&&globalThis.crypto.getRandomValues){globalThis.crypto.getRandomValues(buf)}else{for(var i=0;i<bytes;i++)buf[i]=Math.floor(Math.random()*256)}return bytes}function _nodejsRead(fi,outBuffer,bytes,offset){var fdInfo=_memfs.fds[_fd(fi)];if(!fdInfo)return SQLITE_IOERR_READ;var file=_memfs.files[fdInfo.path];if(!file)return SQLITE_IOERR_READ;var off=Number(offset);var buf=HEAPU8.subarray(outBuffer,outBuffer+bytes);if(off>=file.size){buf.fill(0);return SQLITE_IOERR_SHORT_READ}var available=Math.min(bytes,file.size-off);buf.set(file.data.subarray(off,off+available));if(available<bytes){buf.fill(0,available);return SQLITE_IOERR_SHORT_READ}return SQLITE_OK}function _nodejsShmBarrier(fi){}function _nodejsShmLock(fi,offset,n,flags){return SQLITE_OK}var _shmRegistry={};function _nodejsShmMap(fi,pgno,pgsz,isWrite,ppOut){const filePath=_path(fi);if(!_shmRegistry[filePath])_shmRegistry[filePath]={};const regions=_shmRegistry[filePath];if(!(pgno in regions)){if(!isWrite){setValue(ppOut,0,"*");return SQLITE_OK}const buf=_malloc(pgsz);HEAPU8.fill(0,buf,buf+pgsz);regions[pgno]=buf}setValue(ppOut,regions[pgno],"*");return SQLITE_OK}function _nodejsShmUnmap(fi,deleteFlag){if(deleteFlag){const filePath=_path(fi);const regions=_shmRegistry[filePath];if(regions){for(const pgno in regions)_free(regions[pgno]);delete _shmRegistry[filePath]}}return SQLITE_OK}function _nodejsSleep(vfs,nMicro){if(typeof SharedArrayBuffer==="undefined")return nMicro;try{var ms=Math.max(1,Math.floor(nMicro/1e3));var sab=new SharedArrayBuffer(4);Atomics.wait(new Int32Array(sab),0,0,ms)}catch{}return nMicro}function _nodejsSync(fi,flags){return SQLITE_OK}function _nodejsTruncate(fi,size){var fdInfo=_memfs.fds[_fd(fi)];if(!fdInfo)return SQLITE_IOERR_TRUNCATE;var file=_memfs.files[fdInfo.path];if(!file)return SQLITE_IOERR_TRUNCATE;var sz=Number(size);if(sz<file.size){file.data.fill(0,sz,file.size);file.size=sz}else if(sz>file.size){_memfsEnsureSize(file,sz);file.data.fill(0,file.size,sz);file.size=sz}return SQLITE_OK}function _nodejsUnlock(fi,level){var filePath=_path(fi);var holders=_fileLocks[filePath];if(holders){if(level==SQLITE_LOCK_NONE){holders.delete(fi);_setLocked(fi,false)}else{holders.set(fi,level)}}else{if(level==SQLITE_LOCK_NONE)_setLocked(fi,false)}return SQLITE_OK}function _memfsEnsureSize(file,needed){if(needed<=file.data.length)return;var newSize=Math.max(file.data.length*2,needed);var newData=new Uint8Array(newSize);newData.set(file.data.subarray(0,file.size));file.data=newData}function _nodejsWrite(fi,buffer,bytes,offset){var fdInfo=_memfs.fds[_fd(fi)];if(!fdInfo)return SQLITE_IOERR_WRITE;var file=_memfs.files[fdInfo.path];if(!file)return SQLITE_IOERR_WRITE;var off=Number(offset);_memfsEnsureSize(file,off+bytes);file.data.set(HEAPU8.subarray(buffer,buffer+bytes),off);if(off+bytes>file.size)file.size=off+bytes;return SQLITE_OK}function _nodejs_max_path_length(){return 4096}function _memfsGetOrCreate(path){if(!_memfs.files[path]){_memfs.files[path]={data:new Uint8Array(4096),size:0}}return _memfs.files[path]}function _nodejs_open(filePath,flags,mode){var path=UTF8ToString(filePath);var exclusive=flags&SQLITE_OPEN_EXCLUSIVE;if(exclusive&&_memfs.files[path])return-1;_memfsGetOrCreate(path);var fd=_memfs.nextFd++;_memfs.fds[fd]={path,pos:0};return fd}var getCFunc=ident=>{var func=Module["_"+ident];return func};var writeArrayToMemory=(array,buffer)=>{HEAP8.set(array,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 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 wasmTableMirror=[];var getWasmTableEntry=funcPtr=>{var func=wasmTableMirror[funcPtr];if(!func){wasmTableMirror[funcPtr]=func=wasmTable.get(funcPtr)}return func};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()}return wasmTable["grow"](1)};var setWasmTableEntry=(idx,func)=>{wasmTable.set(idx,func);wasmTableMirror[idx]=wasmTable.get(idx)};var uleb128EncodeWithLen=arr=>{const n=arr.length;return[n%128|128,n>>7,...arr]};var wasmTypeCodes={i:127,p:127,j:126,f:125,d:124,e:111};var generateTypePack=types=>uleb128EncodeWithLen(Array.from(types,type=>{var code=wasmTypeCodes[type];return code}));var convertJsFunctionToWasm=(func,sig)=>{var bytes=Uint8Array.of(0,97,115,109,1,0,0,0,1,...uleb128EncodeWithLen([1,96,...generateTypePack(sig.slice(1)),...generateTypePack(sig[0]==="v"?"":sig[0])]),2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0);var module=new WebAssembly.Module(bytes);var instance=new WebAssembly.Instance(module,{e:{f:func}});var wrappedFunc=instance.exports["f"];return wrappedFunc};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 removeFunction=index=>{functionsInTableMap.delete(getWasmTableEntry(index));setWasmTableEntry(index,null);freeTableIndexes.push(index)};Module["_memfs"]=_memfs;{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];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"];if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].shift()()}}}Module["cwrap"]=cwrap;Module["addFunction"]=addFunction;Module["removeFunction"]=removeFunction;Module["setValue"]=setValue;Module["getValue"]=getValue;var _sqlite3_prepare_v2,_sqlite3_step,_sqlite3_column_int64,_sqlite3_reset,_sqlite3_exec,_sqlite3_finalize,_sqlite3_clear_bindings,_sqlite3_value_blob,_sqlite3_value_text,_sqlite3_value_bytes,_sqlite3_value_double,_sqlite3_value_int64,_sqlite3_value_type,_sqlite3_result_blob,_sqlite3_result_double,_sqlite3_result_error,_sqlite3_result_int,_sqlite3_result_int64,_sqlite3_result_null,_sqlite3_result_text,_sqlite3_column_count,_sqlite3_data_count,_sqlite3_column_blob,_sqlite3_column_bytes,_sqlite3_column_double,_sqlite3_column_text,_sqlite3_column_type,_sqlite3_column_name,_sqlite3_column_database_name,_sqlite3_column_table_name,_sqlite3_column_origin_name,_sqlite3_bind_blob,_sqlite3_bind_double,_sqlite3_bind_int,_sqlite3_bind_int64,_sqlite3_bind_null,_sqlite3_bind_text,_sqlite3_bind_parameter_count,_sqlite3_bind_parameter_name,_sqlite3_bind_parameter_index,_sqlite3_stmt_readonly,_sqlite3_sql,_sqlite3_errmsg,_sqlite3_last_insert_rowid,_sqlite3_changes,_sqlite3_total_changes,_sqlite3_close_v2,_sqlite3_create_function_v2,_sqlite3_open_v2,_sqlite3_get_autocommit,_malloc,_free,__emscripten_timeout,__emscripten_stack_restore,__emscripten_stack_alloc,_emscripten_stack_get_current,memory,__indirect_function_table,wasmMemory,wasmTable;function assignWasmExports(wasmExports){_sqlite3_prepare_v2=Module["_sqlite3_prepare_v2"]=wasmExports["F"];_sqlite3_step=Module["_sqlite3_step"]=wasmExports["G"];_sqlite3_column_int64=Module["_sqlite3_column_int64"]=wasmExports["H"];_sqlite3_reset=Module["_sqlite3_reset"]=wasmExports["I"];_sqlite3_exec=Module["_sqlite3_exec"]=wasmExports["J"];_sqlite3_finalize=Module["_sqlite3_finalize"]=wasmExports["K"];_sqlite3_clear_bindings=Module["_sqlite3_clear_bindings"]=wasmExports["L"];_sqlite3_value_blob=Module["_sqlite3_value_blob"]=wasmExports["M"];_sqlite3_value_text=Module["_sqlite3_value_text"]=wasmExports["N"];_sqlite3_value_bytes=Module["_sqlite3_value_bytes"]=wasmExports["O"];_sqlite3_value_double=Module["_sqlite3_value_double"]=wasmExports["P"];_sqlite3_value_int64=Module["_sqlite3_value_int64"]=wasmExports["Q"];_sqlite3_value_type=Module["_sqlite3_value_type"]=wasmExports["R"];_sqlite3_result_blob=Module["_sqlite3_result_blob"]=wasmExports["S"];_sqlite3_result_double=Module["_sqlite3_result_double"]=wasmExports["T"];_sqlite3_result_error=Module["_sqlite3_result_error"]=wasmExports["U"];_sqlite3_result_int=Module["_sqlite3_result_int"]=wasmExports["V"];_sqlite3_result_int64=Module["_sqlite3_result_int64"]=wasmExports["W"];_sqlite3_result_null=Module["_sqlite3_result_null"]=wasmExports["X"];_sqlite3_result_text=Module["_sqlite3_result_text"]=wasmExports["Y"];_sqlite3_column_count=Module["_sqlite3_column_count"]=wasmExports["Z"];_sqlite3_data_count=Module["_sqlite3_data_count"]=wasmExports["_"];_sqlite3_column_blob=Module["_sqlite3_column_blob"]=wasmExports["$"];_sqlite3_column_bytes=Module["_sqlite3_column_bytes"]=wasmExports["aa"];_sqlite3_column_double=Module["_sqlite3_column_double"]=wasmExports["ba"];_sqlite3_column_text=Module["_sqlite3_column_text"]=wasmExports["ca"];_sqlite3_column_type=Module["_sqlite3_column_type"]=wasmExports["da"];_sqlite3_column_name=Module["_sqlite3_column_name"]=wasmExports["ea"];_sqlite3_column_database_name=Module["_sqlite3_column_database_name"]=wasmExports["fa"];_sqlite3_column_table_name=Module["_sqlite3_column_table_name"]=wasmExports["ga"];_sqlite3_column_origin_name=Module["_sqlite3_column_origin_name"]=wasmExports["ha"];_sqlite3_bind_blob=Module["_sqlite3_bind_blob"]=wasmExports["ia"];_sqlite3_bind_double=Module["_sqlite3_bind_double"]=wasmExports["ja"];_sqlite3_bind_int=Module["_sqlite3_bind_int"]=wasmExports["ka"];_sqlite3_bind_int64=Module["_sqlite3_bind_int64"]=wasmExports["la"];_sqlite3_bind_null=Module["_sqlite3_bind_null"]=wasmExports["ma"];_sqlite3_bind_text=Module["_sqlite3_bind_text"]=wasmExports["na"];_sqlite3_bind_parameter_count=Module["_sqlite3_bind_parameter_count"]=wasmExports["oa"];_sqlite3_bind_parameter_name=Module["_sqlite3_bind_parameter_name"]=wasmExports["pa"];_sqlite3_bind_parameter_index=Module["_sqlite3_bind_parameter_index"]=wasmExports["qa"];_sqlite3_stmt_readonly=Module["_sqlite3_stmt_readonly"]=wasmExports["ra"];_sqlite3_sql=Module["_sqlite3_sql"]=wasmExports["sa"];_sqlite3_errmsg=Module["_sqlite3_errmsg"]=wasmExports["ta"];_sqlite3_last_insert_rowid=Module["_sqlite3_last_insert_rowid"]=wasmExports["ua"];_sqlite3_changes=Module["_sqlite3_changes"]=wasmExports["va"];_sqlite3_total_changes=Module["_sqlite3_total_changes"]=wasmExports["wa"];_sqlite3_close_v2=Module["_sqlite3_close_v2"]=wasmExports["xa"];_sqlite3_create_function_v2=Module["_sqlite3_create_function_v2"]=wasmExports["ya"];_sqlite3_open_v2=Module["_sqlite3_open_v2"]=wasmExports["za"];_sqlite3_get_autocommit=Module["_sqlite3_get_autocommit"]=wasmExports["Aa"];_malloc=Module["_malloc"]=wasmExports["Ba"];_free=Module["_free"]=wasmExports["Ca"];__emscripten_timeout=wasmExports["Ea"];__emscripten_stack_restore=wasmExports["Fa"];__emscripten_stack_alloc=wasmExports["Ga"];_emscripten_stack_get_current=wasmExports["Ha"];memory=wasmMemory=wasmExports["D"];__indirect_function_table=wasmTable=wasmExports["Da"]}var wasmImports={a:___assert_fail,p:__abort_js,j:__emscripten_runtime_keepalive_clear,m:__localtime_js,k:__setitimer_js,n:__tzset_js,o:_emscripten_date_now,l:_emscripten_resize_heap,B:_nodejsAccess,w:_nodejsCheckReservedLock,e:_nodejsClose,C:_nodejsDelete,z:_nodejsFileSize,q:_nodejsFullPathname,y:_nodejsLock,h:_nodejsRandomness,d:_nodejsRead,t:_nodejsShmBarrier,u:_nodejsShmLock,v:_nodejsShmMap,s:_nodejsShmUnmap,g:_nodejsSleep,A:_nodejsSync,b:_nodejsTruncate,x:_nodejsUnlock,c:_nodejsWrite,f:_nodejs_max_path_length,r:_nodejs_open,i:_proc_exit};function run(){preRun();function doRun(){Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve?.(Module);Module["onRuntimeInitialized"]?.();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(()=>{setTimeout(()=>Module["setStatus"](""),1);doRun()},1)}else{doRun()}}var wasmExports;wasmExports=await (createWasm());run();if(runtimeInitialized){moduleRtn=Module}else{moduleRtn=new Promise((resolve,reject)=>{readyPromiseResolve=resolve;readyPromiseReject=reject})}
1
+ async function createSqliteModule(moduleArg={}){var moduleRtn;var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer";const SQLITE_OK=0;const SQLITE_ROW=100;const SQLITE_DONE=101;const SQLITE_INTEGER=1;const SQLITE_FLOAT=2;const SQLITE_TEXT=3;const SQLITE_BLOB=4;const SQLITE_NULL=5;const SQLITE_UTF8=1;const SQLITE_TRANSIENT=-1;const SQLITE_DETERMINISTIC=2048;const SQLITE_DIRECTONLY=524288;const INT32_MIN=-2147483648;const INT32_MAX=2147483647;const NULL=0;function isByteArray(value){return value instanceof Uint8Array}function copyByteArray(value){const NodeBuffer=globalThis.Buffer;return NodeBuffer?NodeBuffer.from(value):Uint8Array.from(value)}function emptyByteArray(){const NodeBuffer=globalThis.Buffer;return NodeBuffer?NodeBuffer.alloc(0):new Uint8Array}let temp;const sqlite3={};Module.onRuntimeInitialized=()=>{temp=stackAlloc(8);const v=null;const n="number";const s="string";const n1=[n];const n2=[n,...n1];const n3=[n,...n2];const n4=[n,...n3];const n5=[n,...n4];const signatures={open_v2:[n,[s,n,n,s]],exec:[n,n5],errmsg:[s,n1],prepare_v2:[n,n5],close_v2:[n,n1],finalize:[n,n1],reset:[n,n1],clear_bindings:[n,n1],bind_int:[n,n3],bind_int64:[n,n3],bind_double:[n,n3],bind_text:[n,n5],bind_blob:[n,n5],bind_null:[n,n2],bind_parameter_index:[n,[n,s]],bind_parameter_count:[n,n1],bind_parameter_name:[s,n2],step:[n,n1],column_int64:[n,n2],column_double:[n,n2],column_text:[s,n2],column_blob:[n,n2],column_type:[n,n2],column_name:[s,n2],column_count:[n,n1],column_bytes:[n,n2],column_table_name:[s,n2],column_origin_name:[s,n2],column_database_name:[s,n2],data_count:[n,n1],sql:[s,n1],stmt_readonly:[n,n1],last_insert_rowid:[n,n1],changes:[n,n1],total_changes:[n,n1],create_function_v2:[n,[n,s,n,n,n,n,n,n,n]],value_type:[n,n1],value_text:[s,n1],value_blob:[n,n1],value_int64:[n,n1],value_double:[n,n1],value_bytes:[n,n1],result_double:[v,n2],result_null:[v,n1],result_text:[v,n4],result_blob:[v,n4],result_int:[v,n2],result_int64:[v,n2],result_error:[v,n3],get_autocommit:[n,n1],free:[v,n1],db_filename:[s,[n,s]],backup_init:[n,[n,s,n,s]],backup_step:[n,n2],backup_finish:[n,n1],update_hook:[n,n3],commit_hook:[n,n3],rollback_hook:[n,n3],session_create:[n,[n,s,n]],session_attach:[n,[n,s]],session_enable:[n,n2],session_delete:[v,n1],session_changeset:[n,n3],changeset_apply:[n,[n,n,n,n,n,n]],changeset_invert:[n,n4]};for(const[name,sig]of Object.entries(signatures)){const prefix=/^(session|changeset)_/.test(name)?"sqlite3":"sqlite3_";sqlite3[name]=cwrap(`${prefix}${name}`,sig[0],sig[1])}function arrayToHeap(array){const ptr=_malloc(array.byteLength);HEAPU8.set(array instanceof ArrayBuffer?new Uint8Array(array):array,ptr);return ptr}function stringToHeap(str){const size=lengthBytesUTF8(str)+1;const ptr=_malloc(size);stringToUTF8(str,ptr,size);return ptr}function toNumberOrNot(val){if(typeof val==="bigint"){if(val>=Number.MIN_SAFE_INTEGER&&val<=Number.MAX_SAFE_INTEGER){return Number(val)}return val}return val}const SQLITE_ERROR_NAMES={1:"SQLITE_ERROR",2:"SQLITE_INTERNAL",3:"SQLITE_PERM",4:"SQLITE_ABORT",5:"SQLITE_BUSY",6:"SQLITE_LOCKED",7:"SQLITE_NOMEM",8:"SQLITE_READONLY",9:"SQLITE_INTERRUPT",10:"SQLITE_IOERR",11:"SQLITE_CORRUPT",12:"SQLITE_NOTFOUND",13:"SQLITE_FULL",14:"SQLITE_CANTOPEN",15:"SQLITE_PROTOCOL",16:"SQLITE_EMPTY",17:"SQLITE_SCHEMA",18:"SQLITE_TOOBIG",19:"SQLITE_CONSTRAINT",20:"SQLITE_MISMATCH",21:"SQLITE_MISUSE",23:"SQLITE_AUTH",24:"SQLITE_FORMAT",25:"SQLITE_RANGE",26:"SQLITE_NOTADB",100:"SQLITE_ROW",101:"SQLITE_DONE"};class SqliteError extends Error{constructor(message,code){super(message);this.name="SqliteError";if(typeof code==="number"){this.code=SQLITE_ERROR_NAMES[code&255]||SQLITE_ERROR_NAMES[code]||"SQLITE_ERROR"}else{this.code=code||"SQLITE_ERROR"}}}function resolveBindParams(args){if(args.length===0)return null;if(args.length===1){const arg=args[0];if(arg===undefined||arg===null)return null;if(Array.isArray(arg))return arg;if(typeof arg==="object"&&!isByteArray(arg))return arg;return[arg]}return Array.from(args)}function parseFunctionArgs(argc,argv){const args=[];for(let i=0;i<argc;i++){const ptr=getValue(argv+4*i,"i32");const type=sqlite3.value_type(ptr);switch(type){case SQLITE_INTEGER:args.push(toNumberOrNot(sqlite3.value_int64(ptr)));break;case SQLITE_FLOAT:args.push(sqlite3.value_double(ptr));break;case SQLITE_TEXT:args.push(sqlite3.value_text(ptr));break;case SQLITE_BLOB:{const p=sqlite3.value_blob(ptr);args.push(p!==NULL?copyByteArray(HEAPU8.slice(p,p+sqlite3.value_bytes(ptr))):emptyByteArray());break}case SQLITE_NULL:args.push(null);break}}return args}function setFunctionResult(cx,result){switch(typeof result){case"boolean":sqlite3.result_int(cx,result?1:0);break;case"number":if(Number.isSafeInteger(result)){if(result>=INT32_MIN&&result<=INT32_MAX){sqlite3.result_int(cx,result)}else{sqlite3.result_int64(cx,BigInt(result))}}else{sqlite3.result_double(cx,result)}break;case"bigint":sqlite3.result_int64(cx,result);break;case"string":{const tp=stringToHeap(result);sqlite3.result_text(cx,tp,-1,SQLITE_TRANSIENT);_free(tp);break}case"object":if(result===null){sqlite3.result_null(cx)}else if(isByteArray(result)){const tp=arrayToHeap(result);sqlite3.result_blob(cx,tp,result.byteLength,SQLITE_TRANSIENT);_free(tp)}else{sqlite3.result_error(cx,stringToHeap("unsupported return type"),-1)}break;default:sqlite3.result_null(cx);break}}class Database{constructor(filename,options={}){if(typeof filename!=="string"&&!isByteArray(filename)){throw new TypeError("Expected first argument to be a string")}filename=String(filename);const readonly=!!options.readonly;const fileMustExist=!!options.fileMustExist;let flags;if(readonly){flags=1}else{flags=2;if(!fileMustExist)flags|=4}const rc=sqlite3.open_v2(filename,temp,flags,NULL);this._ptr=getValue(temp,"i32");if(rc!==SQLITE_OK){const msg=this._ptr!==NULL?sqlite3.errmsg(this._ptr):"unable to open database";if(this._ptr!==NULL)sqlite3.close_v2(this._ptr);this._ptr=null;throw new SqliteError(msg)}this._open=true;this._readonly=readonly;this._unsafe=false;this._name=filename;this._statements=new Set;this._functions=new Map;this._sessions=new Set;this._updateHook=0;this._commitHook=0;this._rollbackHook=0;this.exec("PRAGMA busy_timeout = 5000")}unsafeMode(enabled){if(enabled===undefined)enabled=true;this._unsafe=!!enabled;return this}get open(){return this._open}get readonly(){return this._readonly}get name(){return this._name}get inTransaction(){return this._open&&sqlite3.get_autocommit(this._ptr)===0}prepare(source){this._assertOpen();if(typeof source!=="string"){throw new TypeError("Expected first argument to be a string")}const stmt=new Statement(this,source);this._statements.add(stmt);return stmt}exec(sql,{resetStatements=true}={}){this._assertOpen();if(resetStatements){for(const stmt of this._statements){if(!stmt._finalized)sqlite3.reset(stmt._ptr)}}const tp=stringToHeap(sql);try{const rc=sqlite3.exec(this._ptr,tp,NULL,NULL,NULL);if(rc!==SQLITE_OK){throw new SqliteError(sqlite3.errmsg(this._ptr),rc)}}finally{_free(tp)}return this}transaction(fn){if(typeof fn!=="function"){throw new TypeError("Expected first argument to be a function")}const db=this;const wrapTxn=begin=>{const beginStmt=db.prepare(begin);const commitStmt=db.prepare("COMMIT");const rollbackStmt=db.prepare("ROLLBACK");const runner=function(...args){let result;if(db.inTransaction){return fn.apply(this,args)}beginStmt.run();try{result=fn.apply(this,args);commitStmt.run()}catch(err){if(db.inTransaction){rollbackStmt.run()}throw err}return result};return runner};const result=wrapTxn("BEGIN");result.deferred=wrapTxn("BEGIN DEFERRED");result.immediate=wrapTxn("BEGIN IMMEDIATE");result.exclusive=wrapTxn("BEGIN EXCLUSIVE");result.database=db;return result}pragma(source,options){if(typeof source!=="string"){throw new TypeError("Expected first argument to be a string")}const simple=options&&options.simple;const sql=`PRAGMA ${source}`;const stmt=this.prepare(sql);try{if(stmt.reader){return simple?stmt.pluck().get():stmt.all()}else{return stmt.run()}}finally{stmt.finalize()}}function(name,fn,options={}){this._assertOpen();if(typeof name!=="string")throw new TypeError("Expected first argument to be a string");if(typeof fn!=="function")throw new TypeError("Expected second argument to be a function");const deterministic=!!options.deterministic;const directOnly=!!options.directOnly;const varargs=options.varargs||false;if(this._functions.has(name)){removeFunction(this._functions.get(name));this._functions.delete(name)}const wrappedFunc=(cx,argc,argv)=>{const args=parseFunctionArgs(argc,argv);try{const result=fn(...args);setFunctionResult(cx,result)}catch(err){const tp=stringToHeap(err.toString());sqlite3.result_error(cx,tp,-1);_free(tp)}};const funcPtr=addFunction(wrappedFunc,"viii");this._functions.set(name,funcPtr);let eTextRep=SQLITE_UTF8;if(deterministic)eTextRep|=SQLITE_DETERMINISTIC;if(directOnly)eTextRep|=SQLITE_DIRECTONLY;const rc=sqlite3.create_function_v2(this._ptr,name,varargs?-1:fn.length,eTextRep,NULL,funcPtr,NULL,NULL,NULL);if(rc!==SQLITE_OK)throw new SqliteError(sqlite3.errmsg(this._ptr));return this}aggregate(name,options){this._assertOpen();if(typeof name!=="string")throw new TypeError("Expected first argument to be a string");if(!options||typeof options!=="object")throw new TypeError("Expected second argument to be an options object");const step=options.step;const result=options.result||(acc=>acc);const start=options.start;const inverse=options.inverse;const deterministic=!!options.deterministic;const directOnly=!!options.directOnly;const varargs=!!options.varargs;if(typeof step!=="function")throw new TypeError("Expected options.step to be a function");let accumulator;const stepWrapper=(cx,argc,argv)=>{const args=parseFunctionArgs(argc,argv);try{accumulator=step(accumulator,...args)}catch(err){const tp=stringToHeap(err.toString());sqlite3.result_error(cx,tp,-1);_free(tp)}};const finalWrapper=cx=>{try{const val=result(accumulator);setFunctionResult(cx,val)}catch(err){const tp=stringToHeap(err.toString());sqlite3.result_error(cx,tp,-1);_free(tp)}accumulator=typeof start==="function"?start():start};accumulator=typeof start==="function"?start():start;if(this._functions.has(name+"_step")){removeFunction(this._functions.get(name+"_step"));this._functions.delete(name+"_step")}if(this._functions.has(name+"_final")){removeFunction(this._functions.get(name+"_final"));this._functions.delete(name+"_final")}const stepPtr=addFunction(stepWrapper,"viii");const finalPtr=addFunction(finalWrapper,"vi");this._functions.set(name+"_step",stepPtr);this._functions.set(name+"_final",finalPtr);let eTextRep=SQLITE_UTF8;if(deterministic)eTextRep|=SQLITE_DETERMINISTIC;if(directOnly)eTextRep|=SQLITE_DIRECTONLY;const argCount=varargs?-1:step.length-1;const rc=sqlite3.create_function_v2(this._ptr,name,argCount,eTextRep,NULL,NULL,stepPtr,finalPtr,NULL);if(rc!==SQLITE_OK)throw new SqliteError(sqlite3.errmsg(this._ptr));return this}updateHook(fn){this._assertOpen();if(fn!==null&&typeof fn!=="function")throw new TypeError("Expected first argument to be a function or null");const previous=this._updateHook;this._updateHook=fn===null?null:addFunction((_arg,op,databaseName,tableName,rowid)=>{fn(op,UTF8ToString(databaseName),UTF8ToString(tableName),toNumberOrNot(rowid))},"viiiij");sqlite3.update_hook(this._ptr,this._updateHook??NULL,NULL);if(previous)removeFunction(previous);return this}commitHook(fn){this._assertOpen();if(fn!==null&&typeof fn!=="function")throw new TypeError("Expected first argument to be a function or null");const previous=this._commitHook;this._commitHook=fn===null?null:addFunction(()=>fn(),"ii");sqlite3.commit_hook(this._ptr,this._commitHook??NULL,NULL);if(previous)removeFunction(previous);return this}rollbackHook(fn){this._assertOpen();if(fn!==null&&typeof fn!=="function")throw new TypeError("Expected first argument to be a function or null");const previous=this._rollbackHook;this._rollbackHook=fn===null?null:addFunction(()=>fn(),"vi");sqlite3.rollback_hook(this._ptr,this._rollbackHook??NULL,NULL);if(previous)removeFunction(previous);return this}filename(databaseName="main"){this._assertOpen();return sqlite3.db_filename(this._ptr,databaseName)}backupTo(destination,sourceName="main",destinationName="main"){this._assertOpen();destination._assertOpen();const backup=sqlite3.backup_init(destination._ptr,destinationName,this._ptr,sourceName);if(!backup)throw new SqliteError(sqlite3.errmsg(destination._ptr));sqlite3.backup_step(backup,-1);const finish=sqlite3.backup_finish(backup);if(finish!==SQLITE_OK){throw new SqliteError(sqlite3.errmsg(destination._ptr),finish)}}createSession(databaseName="main"){this._assertOpen();const rc=sqlite3.session_create(this._ptr,databaseName,temp);if(rc!==SQLITE_OK)throw new SqliteError(sqlite3.errmsg(this._ptr),rc);const pointer=getValue(temp,"i32");const database=this;let closed=false;const check=()=>{database._assertOpen();if(closed)throw new SqliteError("The session is closed",21)};const session={attach(table=null){check();const result=sqlite3.session_attach(pointer,table);if(result!==SQLITE_OK)throw new SqliteError(sqlite3.errmsg(database._ptr),result)},enable(enabled){check();sqlite3.session_enable(pointer,enabled?1:0)},changeset(){check();const output=_malloc(8);try{const result=sqlite3.session_changeset(pointer,output,output+4);if(result!==SQLITE_OK)throw new SqliteError(sqlite3.errmsg(database._ptr),result);const size=getValue(output,"i32");const buffer=getValue(output+4,"i32");try{return HEAPU8.slice(buffer,buffer+size)}finally{sqlite3.free(buffer)}}finally{_free(output)}},close(){if(closed)return;sqlite3.session_delete(pointer);closed=true;database._sessions.delete(session)}};this._sessions.add(session);return session}applyChangeset(changeset,onConflict=(()=>2)){this._assertOpen();const input=arrayToHeap(changeset);const conflict=addFunction((context,reason)=>onConflict(reason),"iiii");try{const rc=sqlite3.changeset_apply(this._ptr,changeset.byteLength,input,NULL,conflict,NULL);if(rc!==SQLITE_OK)throw new SqliteError(sqlite3.errmsg(this._ptr),rc)}finally{removeFunction(conflict);_free(input)}}invertChangeset(changeset){this._assertOpen();const input=arrayToHeap(changeset);const output=_malloc(8);try{const rc=sqlite3.changeset_invert(changeset.byteLength,input,output,output+4);if(rc!==SQLITE_OK)throw new SqliteError(sqlite3.errmsg(this._ptr),rc);const size=getValue(output,"i32");const buffer=getValue(output+4,"i32");try{return HEAPU8.slice(buffer,buffer+size)}finally{sqlite3.free(buffer)}}finally{_free(output);_free(input)}}close(){if(!this._open)return;for(const session of this._sessions)session.close();this.updateHook(null);this.commitHook(null);this.rollbackHook(null);for(const stmt of this._statements){if(!stmt._finalized){sqlite3.finalize(stmt._ptr);stmt._finalized=true}}this._statements.clear();for(const func of this._functions.values()){removeFunction(func)}this._functions.clear();if(this._updateHook){sqlite3.update_hook(this._ptr,NULL,NULL);removeFunction(this._updateHook);this._updateHook=null}const rc=sqlite3.close_v2(this._ptr);if(rc!==SQLITE_OK){throw new SqliteError(sqlite3.errmsg(this._ptr))}this._ptr=null;this._open=false}_assertOpen(){if(!this._open)throw new SqliteError("The database connection is not open")}_handleError(rc){if(rc!==SQLITE_OK){throw new SqliteError(sqlite3.errmsg(this._ptr),rc)}}}class Statement{constructor(db,source){this._db=db;this._source=source;this._finalized=false;this._pluck=false;this._expand=false;this._raw=false;this._bound=false;this._numbersAsDoubles=false;const tp=stringToHeap(source);try{const rc=sqlite3.prepare_v2(db._ptr,tp,-1,temp,NULL);if(rc!==SQLITE_OK){throw new SqliteError(sqlite3.errmsg(db._ptr),rc)}}finally{_free(tp)}this._ptr=getValue(temp,"i32");if(this._ptr===NULL){throw new SqliteError("Nothing to prepare")}this._columnCount=sqlite3.column_count(this._ptr);this._reader=this._columnCount>0;this._readonly=!!sqlite3.stmt_readonly(this._ptr)}get source(){return this._source}get reader(){return this._reader}get readonly(){return this._readonly}get parameterCount(){this._assertReady();return sqlite3.bind_parameter_count(this._ptr)}numbersAsDoubles(toggle=true){this._numbersAsDoubles=toggle;return this}finalize(){if(this._finalized)return;sqlite3.finalize(this._ptr);this._finalized=true;this._ptr=null;this._db._statements.delete(this)}run(...args){this._assertReady();const params=resolveBindParams(args);this._reset();if(params)this._bind(params);this._step();const result={changes:sqlite3.changes(this._db._ptr),lastInsertRowid:toNumberOrNot(sqlite3.last_insert_rowid(this._db._ptr))};sqlite3.reset(this._ptr);return result}get(...args){this._assertReady();const params=resolveBindParams(args);this._reset();if(params)this._bind(params);if(!this._step()){sqlite3.reset(this._ptr);return undefined}const row=this._getRow();sqlite3.reset(this._ptr);return row}all(...args){this._assertReady();const params=resolveBindParams(args);this._reset();if(params)this._bind(params);const rows=[];while(this._step()){rows.push(this._getRow());if(rows.length===1e5){console.warn(`[bedrock-sqlite] all() returned 100k rows, query: ${this._source.slice(0,200)}`)}if(rows.length>=1e7){sqlite3.reset(this._ptr);throw new SqliteError(`all() exceeded 10M row safety limit, likely infinite loop. query: ${this._source.slice(0,200)}`)}}sqlite3.reset(this._ptr);return rows}*iterate(...args){this._assertReady();const params=resolveBindParams(args);this._reset();if(params)this._bind(params);while(this._step()){yield this._getRow()}}pluck(toggle=true){this._pluck=toggle;this._raw=false;this._expand=false;return this}expand(toggle=true){this._expand=toggle;this._pluck=false;this._raw=false;return this}raw(toggle=true){this._raw=toggle;this._pluck=false;this._expand=false;return this}columns(){this._assertReady();const cols=[];for(let i=0;i<this._columnCount;i++){cols.push({name:sqlite3.column_name(this._ptr,i),column:sqlite3.column_origin_name(this._ptr,i),table:sqlite3.column_table_name(this._ptr,i),database:sqlite3.column_database_name(this._ptr,i),type:null})}return cols}scanStatusV2(){return[]}scanStatusReset(){}safeIntegers(){return this}bind(...args){this._assertReady();const params=resolveBindParams(args);this._reset();if(params)this._bind(params);this._bound=true;return this}_reset(){sqlite3.clear_bindings(this._ptr);sqlite3.reset(this._ptr)}_step(){const rc=sqlite3.step(this._ptr);if(rc===SQLITE_ROW)return true;if(rc===SQLITE_DONE)return false;sqlite3.reset(this._ptr);throw new SqliteError(sqlite3.errmsg(this._db._ptr),rc)}_getRow(){if(this._pluck){return this._getColumnValue(0)}if(this._raw){const row=[];for(let i=0;i<this._columnCount;i++){row.push(this._getColumnValue(i))}return row}if(this._expand){const row={};for(let i=0;i<this._columnCount;i++){let table=sqlite3.column_table_name(this._ptr,i);table=table===""||table===null?"$":table;const name=sqlite3.column_name(this._ptr,i);if(!row[table])row[table]={};row[table][name]=this._getColumnValue(i)}return row}const row={};for(let i=0;i<this._columnCount;i++){row[sqlite3.column_name(this._ptr,i)]=this._getColumnValue(i)}return row}_getColumnValue(i){const type=sqlite3.column_type(this._ptr,i);switch(type){case SQLITE_INTEGER:return toNumberOrNot(sqlite3.column_int64(this._ptr,i));case SQLITE_FLOAT:return sqlite3.column_double(this._ptr,i);case SQLITE_TEXT:return sqlite3.column_text(this._ptr,i);case SQLITE_BLOB:{const p=sqlite3.column_blob(this._ptr,i);if(p!==NULL){const nbytes=sqlite3.column_bytes(this._ptr,i);if(nbytes>104857600){throw new SqliteError(`blob column ${i} has unreasonable size: ${nbytes} bytes`)}return copyByteArray(HEAPU8.slice(p,p+nbytes))}return emptyByteArray()}case SQLITE_NULL:return null;default:return null}}_bind(params){if(Array.isArray(params)){for(let i=0;i<params.length;i++){this._bindValue(params[i],i+1)}}else if(typeof params==="object"){const count=sqlite3.bind_parameter_count(this._ptr);for(let i=1;i<=count;i++){const pname=sqlite3.bind_parameter_name(this._ptr,i);if(!pname)continue;const stripped=pname.slice(1);const value=pname in params?params[pname]:stripped in params?params[stripped]:undefined;if(value!==undefined){this._bindValue(value,i)}}}}_bindValue(value,position){let rc;switch(typeof value){case"string":{const tp=stringToHeap(value);rc=sqlite3.bind_text(this._ptr,position,tp,-1,SQLITE_TRANSIENT);_free(tp);break}case"number":if(!this._numbersAsDoubles&&Number.isSafeInteger(value)){if(value>=INT32_MIN&&value<=INT32_MAX){rc=sqlite3.bind_int(this._ptr,position,value)}else{rc=sqlite3.bind_int64(this._ptr,position,BigInt(value))}}else{rc=sqlite3.bind_double(this._ptr,position,value)}break;case"bigint":rc=sqlite3.bind_int64(this._ptr,position,value);break;case"boolean":rc=sqlite3.bind_int(this._ptr,position,value?1:0);break;case"object":if(value===null){rc=sqlite3.bind_null(this._ptr,position)}else if(isByteArray(value)){const tp=arrayToHeap(value);rc=sqlite3.bind_blob(this._ptr,position,tp,value.byteLength,SQLITE_TRANSIENT);_free(tp)}else{throw new SqliteError(`Unsupported binding type at position ${position}`)}break;default:if(value===undefined){rc=sqlite3.bind_null(this._ptr,position)}else{throw new SqliteError(`Unsupported binding type: ${typeof value}`)}}if(rc!==SQLITE_OK){throw new SqliteError(sqlite3.errmsg(this._db._ptr))}}_assertReady(){if(this._finalized)throw new SqliteError("This statement has been finalized");if(!this._db._open)throw new SqliteError("The database connection is not open")}}Module.Database=Database;Module.SqliteError=SqliteError};const SQLITE_CANTOPEN=14;const SQLITE_IOERR_READ=266;const SQLITE_IOERR_SHORT_READ=522;const SQLITE_IOERR_WRITE=778;const SQLITE_IOERR_TRUNCATE=1546;const SQLITE_IOERR_FSTAT=1802;const SQLITE_OPEN_EXCLUSIVE=16;const SQLITE_LOCK_NONE=0;const SQLITE_LOCK_SHARED=1;const SQLITE_LOCK_RESERVED=2;const SQLITE_LOCK_EXCLUSIVE=4;const SQLITE_BUSY=5;function _fd(fileInfo){return getValue(fileInfo+4,"i32")}function _setLocked(fileInfo,locked){setValue(fileInfo+8,locked?1:0,"i32")}function _path(fileInfo){return UTF8ToString(getValue(fileInfo+12,"i32"))}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 ABORT=false;var EXITSTATUS;var readyPromiseResolve,readyPromiseReject;var runtimeInitialized=false;function updateMemoryViews(){var b=wasmMemory.buffer;HEAP8=new Int8Array(b);HEAP16=new Int16Array(b);HEAPU8=new Uint8Array(b);HEAPU16=new Uint16Array(b);HEAP32=new Int32Array(b);HEAPU32=new Uint32Array(b);HEAPF32=new Float32Array(b);HEAPF64=new Float64Array(b);HEAP64=new BigInt64Array(b);HEAPU64=new BigUint64Array(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;wasmExports["E"]()}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(onPostRuns)}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("sqlite3-browser.wasm")}return new URL("sqlite3-browser.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){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(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance,module){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();if(Module["instantiateWasm"]){return new Promise((resolve,reject)=>{Module["instantiateWasm"](info,(inst,mod)=>{resolve(receiveInstance(inst,mod))})})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var HEAP16;var HEAP32;var HEAP64;var HEAP8;var HEAPF32;var HEAPF64;var HEAPU16;var HEAPU32;var HEAPU64;var HEAPU8;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":return HEAP64[ptr>>3];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":HEAP64[ptr>>3]=BigInt(value);break;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=globalThis.TextDecoder&&new TextDecoder;var findStringEnd=(heapOrArray,idx,maxBytesToRead,ignoreNul)=>{var maxIdx=idx+maxBytesToRead;if(ignoreNul)return maxIdx;while(heapOrArray[idx]&&!(idx>=maxIdx))++idx;return idx};var UTF8ArrayToString=(heapOrArray,idx=0,maxBytesToRead,ignoreNul)=>{var endPtr=findStringEnd(heapOrArray,idx,maxBytesToRead,ignoreNul);if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr))}var str="";while(idx<endPtr){var u0=heapOrArray[idx++];if(!(u0&128)){str+=String.fromCharCode(u0);continue}var u1=heapOrArray[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=heapOrArray[idx++]&63;if((u0&240)==224){u0=(u0&15)<<12|u1<<6|u2}else{u0=(u0&7)<<18|u1<<12|u2<<6|heapOrArray[idx++]&63}if(u0<65536){str+=String.fromCharCode(u0)}else{var ch=u0-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}return str};var UTF8ToString=(ptr,maxBytesToRead,ignoreNul)=>ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead,ignoreNul):"";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 __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};var INT53_MAX=9007199254740992;var INT53_MIN=-9007199254740992;var bigintToI53Checked=num=>num<INT53_MIN||num>INT53_MAX?NaN:Number(num);function __localtime_js(time,tmPtr){time=bigintToI53Checked(time);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}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{return func()}catch(e){handleException(e)}finally{maybeExit()}};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 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.codePointAt(i);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;i++}}heap[outIdx]=0;return outIdx-startIdx};var stringToUTF8=(str,outPtr,maxBytesToWrite)=>stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite);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=()=>536870912;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+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 _memfs={files:{},fds:{},nextFd:10};function _nodejsAccess(vfs,filePath,flags,outResult){var path=UTF8ToString(filePath);setValue(outResult,_memfs.files[path]?1:0,"i32");return SQLITE_OK}var _fileLocks={};function _nodejsCheckReservedLock(fi,outResult){var filePath=_path(fi);var holders=_fileLocks[filePath];var reserved=0;if(holders){for(var[other,otherLevel]of holders){if(other!==fi&&otherLevel>=SQLITE_LOCK_RESERVED){reserved=1;break}}}setValue(outResult,reserved,"i32");return SQLITE_OK}function _nodejsClose(fi){_nodejsUnlock(fi,SQLITE_LOCK_NONE);var fd=_fd(fi);delete _memfs.fds[fd];return SQLITE_OK}function _nodejsDelete(vfs,filePath,dirSync){var path=UTF8ToString(filePath);delete _memfs.files[path];return SQLITE_OK}function _nodejsFileSize(fi,outSize){var fdInfo=_memfs.fds[_fd(fi)];if(!fdInfo)return SQLITE_IOERR_FSTAT;var file=_memfs.files[fdInfo.path];if(!file)return SQLITE_IOERR_FSTAT;setValue(outSize,file.size,"i64");return SQLITE_OK}function _nodejsFullPathname(vfs,relPath,sizeFullPath,outFullPath){var full=UTF8ToString(relPath);if(full.startsWith("./"))full=full.substring(2);if(!full.startsWith("/"))full="/"+full;stringToUTF8(full,outFullPath,sizeFullPath);return full.length<sizeFullPath?SQLITE_OK:SQLITE_CANTOPEN}function _nodejsLock(fi,level){var filePath=_path(fi);if(!_fileLocks[filePath])_fileLocks[filePath]=new Map;var holders=_fileLocks[filePath];var myLevel=holders.get(fi)||SQLITE_LOCK_NONE;if(level>=SQLITE_LOCK_RESERVED&&myLevel<SQLITE_LOCK_RESERVED){for(var[other,otherLevel]of holders){if(other!==fi&&otherLevel>=SQLITE_LOCK_RESERVED){return SQLITE_BUSY}}}if(level>=SQLITE_LOCK_EXCLUSIVE&&myLevel<SQLITE_LOCK_EXCLUSIVE){for(var[other,otherLevel]of holders){if(other!==fi&&otherLevel>=SQLITE_LOCK_SHARED){return SQLITE_BUSY}}}holders.set(fi,level);if(level>SQLITE_LOCK_NONE)_setLocked(fi,true);return SQLITE_OK}function _nodejsRandomness(vfs,bytes,outBuffer){var buf=HEAPU8.subarray(outBuffer,outBuffer+bytes);if(typeof globalThis.crypto!=="undefined"&&globalThis.crypto.getRandomValues){globalThis.crypto.getRandomValues(buf)}else{for(var i=0;i<bytes;i++)buf[i]=Math.floor(Math.random()*256)}return bytes}function _nodejsRead(fi,outBuffer,bytes,offset){var fdInfo=_memfs.fds[_fd(fi)];if(!fdInfo)return SQLITE_IOERR_READ;var file=_memfs.files[fdInfo.path];if(!file)return SQLITE_IOERR_READ;var off=Number(offset);var buf=HEAPU8.subarray(outBuffer,outBuffer+bytes);if(off>=file.size){buf.fill(0);return SQLITE_IOERR_SHORT_READ}var available=Math.min(bytes,file.size-off);buf.set(file.data.subarray(off,off+available));if(available<bytes){buf.fill(0,available);return SQLITE_IOERR_SHORT_READ}return SQLITE_OK}function _nodejsShmBarrier(fi){}function _nodejsShmLock(fi,offset,n,flags){return SQLITE_OK}var _shmRegistry={};function _nodejsShmMap(fi,pgno,pgsz,isWrite,ppOut){const filePath=_path(fi);if(!_shmRegistry[filePath])_shmRegistry[filePath]={};const regions=_shmRegistry[filePath];if(!(pgno in regions)){if(!isWrite){setValue(ppOut,0,"*");return SQLITE_OK}const buf=_malloc(pgsz);HEAPU8.fill(0,buf,buf+pgsz);regions[pgno]=buf}setValue(ppOut,regions[pgno],"*");return SQLITE_OK}function _nodejsShmUnmap(fi,deleteFlag){if(deleteFlag){const filePath=_path(fi);const regions=_shmRegistry[filePath];if(regions){for(const pgno in regions)_free(regions[pgno]);delete _shmRegistry[filePath]}}return SQLITE_OK}function _nodejsSleep(vfs,nMicro){if(typeof SharedArrayBuffer==="undefined")return nMicro;try{var ms=Math.max(1,Math.floor(nMicro/1e3));var sab=new SharedArrayBuffer(4);Atomics.wait(new Int32Array(sab),0,0,ms)}catch{}return nMicro}function _nodejsSync(fi,flags){return SQLITE_OK}function _nodejsTruncate(fi,size){var fdInfo=_memfs.fds[_fd(fi)];if(!fdInfo)return SQLITE_IOERR_TRUNCATE;var file=_memfs.files[fdInfo.path];if(!file)return SQLITE_IOERR_TRUNCATE;var sz=Number(size);if(sz<file.size){file.data.fill(0,sz,file.size);file.size=sz}else if(sz>file.size){_memfsEnsureSize(file,sz);file.data.fill(0,file.size,sz);file.size=sz}return SQLITE_OK}function _nodejsUnlock(fi,level){var filePath=_path(fi);var holders=_fileLocks[filePath];if(holders){if(level==SQLITE_LOCK_NONE){holders.delete(fi);_setLocked(fi,false)}else{holders.set(fi,level)}}else{if(level==SQLITE_LOCK_NONE)_setLocked(fi,false)}return SQLITE_OK}function _memfsEnsureSize(file,needed){if(needed<=file.data.length)return;var newSize=Math.max(file.data.length*2,needed);var newData=new Uint8Array(newSize);newData.set(file.data.subarray(0,file.size));file.data=newData}function _nodejsWrite(fi,buffer,bytes,offset){var fdInfo=_memfs.fds[_fd(fi)];if(!fdInfo)return SQLITE_IOERR_WRITE;var file=_memfs.files[fdInfo.path];if(!file)return SQLITE_IOERR_WRITE;var off=Number(offset);_memfsEnsureSize(file,off+bytes);file.data.set(HEAPU8.subarray(buffer,buffer+bytes),off);if(off+bytes>file.size)file.size=off+bytes;return SQLITE_OK}function _nodejs_max_path_length(){return 4096}function _memfsGetOrCreate(path){if(!_memfs.files[path]){_memfs.files[path]={data:new Uint8Array(4096),size:0}}return _memfs.files[path]}function _nodejs_open(filePath,flags,mode){var path=UTF8ToString(filePath);var exclusive=flags&SQLITE_OPEN_EXCLUSIVE;if(exclusive&&_memfs.files[path])return-1;_memfsGetOrCreate(path);var fd=_memfs.nextFd++;_memfs.fds[fd]={path,pos:0};return fd}var getCFunc=ident=>{var func=Module["_"+ident];return func};var writeArrayToMemory=(array,buffer)=>{HEAP8.set(array,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 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 wasmTableMirror=[];var getWasmTableEntry=funcPtr=>{var func=wasmTableMirror[funcPtr];if(!func){wasmTableMirror[funcPtr]=func=wasmTable.get(funcPtr)}return func};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()}return wasmTable["grow"](1)};var setWasmTableEntry=(idx,func)=>{wasmTable.set(idx,func);wasmTableMirror[idx]=wasmTable.get(idx)};var uleb128EncodeWithLen=arr=>{const n=arr.length;return[n%128|128,n>>7,...arr]};var wasmTypeCodes={i:127,p:127,j:126,f:125,d:124,e:111};var generateTypePack=types=>uleb128EncodeWithLen(Array.from(types,type=>{var code=wasmTypeCodes[type];return code}));var convertJsFunctionToWasm=(func,sig)=>{var bytes=Uint8Array.of(0,97,115,109,1,0,0,0,1,...uleb128EncodeWithLen([1,96,...generateTypePack(sig.slice(1)),...generateTypePack(sig[0]==="v"?"":sig[0])]),2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0);var module=new WebAssembly.Module(bytes);var instance=new WebAssembly.Instance(module,{e:{f:func}});var wrappedFunc=instance.exports["f"];return wrappedFunc};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 removeFunction=index=>{functionsInTableMap.delete(getWasmTableEntry(index));setWasmTableEntry(index,null);freeTableIndexes.push(index)};Module["_memfs"]=_memfs;{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];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"];if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].shift()()}}}Module["cwrap"]=cwrap;Module["addFunction"]=addFunction;Module["removeFunction"]=removeFunction;Module["setValue"]=setValue;Module["getValue"]=getValue;var _sqlite3_free,_sqlite3_prepare_v2,_sqlite3_step,_sqlite3_column_int64,_sqlite3_reset,_sqlite3_exec,_sqlite3_finalize,_sqlite3_backup_init,_sqlite3_backup_step,_sqlite3_backup_finish,_sqlite3_clear_bindings,_sqlite3_value_blob,_sqlite3_value_text,_sqlite3_value_bytes,_sqlite3_value_double,_sqlite3_value_int64,_sqlite3_value_type,_sqlite3_result_blob,_sqlite3_result_double,_sqlite3_result_error,_sqlite3_result_int,_sqlite3_result_int64,_sqlite3_result_null,_sqlite3_result_text,_sqlite3_column_count,_sqlite3_data_count,_sqlite3_column_blob,_sqlite3_column_bytes,_sqlite3_column_double,_sqlite3_column_text,_sqlite3_column_type,_sqlite3_column_name,_sqlite3_column_database_name,_sqlite3_column_table_name,_sqlite3_column_origin_name,_sqlite3_bind_blob,_sqlite3_bind_double,_sqlite3_bind_int,_sqlite3_bind_int64,_sqlite3_bind_null,_sqlite3_bind_text,_sqlite3_bind_parameter_count,_sqlite3_bind_parameter_name,_sqlite3_bind_parameter_index,_sqlite3_stmt_readonly,_sqlite3_sql,_sqlite3_errmsg,_sqlite3_last_insert_rowid,_sqlite3_changes,_sqlite3_total_changes,_sqlite3_close_v2,_sqlite3_create_function_v2,_sqlite3_commit_hook,_sqlite3_update_hook,_sqlite3_rollback_hook,_sqlite3_open_v2,_sqlite3_get_autocommit,_sqlite3_db_filename,_sqlite3session_create,_sqlite3session_delete,_sqlite3session_attach,_sqlite3session_changeset,_sqlite3session_enable,_sqlite3changeset_invert,_sqlite3changeset_apply,_malloc,_free,__emscripten_timeout,__emscripten_stack_restore,__emscripten_stack_alloc,_emscripten_stack_get_current,memory,__indirect_function_table,wasmMemory,wasmTable;function assignWasmExports(wasmExports){_sqlite3_free=Module["_sqlite3_free"]=wasmExports["F"];_sqlite3_prepare_v2=Module["_sqlite3_prepare_v2"]=wasmExports["G"];_sqlite3_step=Module["_sqlite3_step"]=wasmExports["H"];_sqlite3_column_int64=Module["_sqlite3_column_int64"]=wasmExports["I"];_sqlite3_reset=Module["_sqlite3_reset"]=wasmExports["J"];_sqlite3_exec=Module["_sqlite3_exec"]=wasmExports["K"];_sqlite3_finalize=Module["_sqlite3_finalize"]=wasmExports["L"];_sqlite3_backup_init=Module["_sqlite3_backup_init"]=wasmExports["M"];_sqlite3_backup_step=Module["_sqlite3_backup_step"]=wasmExports["N"];_sqlite3_backup_finish=Module["_sqlite3_backup_finish"]=wasmExports["O"];_sqlite3_clear_bindings=Module["_sqlite3_clear_bindings"]=wasmExports["P"];_sqlite3_value_blob=Module["_sqlite3_value_blob"]=wasmExports["Q"];_sqlite3_value_text=Module["_sqlite3_value_text"]=wasmExports["R"];_sqlite3_value_bytes=Module["_sqlite3_value_bytes"]=wasmExports["S"];_sqlite3_value_double=Module["_sqlite3_value_double"]=wasmExports["T"];_sqlite3_value_int64=Module["_sqlite3_value_int64"]=wasmExports["U"];_sqlite3_value_type=Module["_sqlite3_value_type"]=wasmExports["V"];_sqlite3_result_blob=Module["_sqlite3_result_blob"]=wasmExports["W"];_sqlite3_result_double=Module["_sqlite3_result_double"]=wasmExports["X"];_sqlite3_result_error=Module["_sqlite3_result_error"]=wasmExports["Y"];_sqlite3_result_int=Module["_sqlite3_result_int"]=wasmExports["Z"];_sqlite3_result_int64=Module["_sqlite3_result_int64"]=wasmExports["_"];_sqlite3_result_null=Module["_sqlite3_result_null"]=wasmExports["$"];_sqlite3_result_text=Module["_sqlite3_result_text"]=wasmExports["aa"];_sqlite3_column_count=Module["_sqlite3_column_count"]=wasmExports["ba"];_sqlite3_data_count=Module["_sqlite3_data_count"]=wasmExports["ca"];_sqlite3_column_blob=Module["_sqlite3_column_blob"]=wasmExports["da"];_sqlite3_column_bytes=Module["_sqlite3_column_bytes"]=wasmExports["ea"];_sqlite3_column_double=Module["_sqlite3_column_double"]=wasmExports["fa"];_sqlite3_column_text=Module["_sqlite3_column_text"]=wasmExports["ga"];_sqlite3_column_type=Module["_sqlite3_column_type"]=wasmExports["ha"];_sqlite3_column_name=Module["_sqlite3_column_name"]=wasmExports["ia"];_sqlite3_column_database_name=Module["_sqlite3_column_database_name"]=wasmExports["ja"];_sqlite3_column_table_name=Module["_sqlite3_column_table_name"]=wasmExports["ka"];_sqlite3_column_origin_name=Module["_sqlite3_column_origin_name"]=wasmExports["la"];_sqlite3_bind_blob=Module["_sqlite3_bind_blob"]=wasmExports["ma"];_sqlite3_bind_double=Module["_sqlite3_bind_double"]=wasmExports["na"];_sqlite3_bind_int=Module["_sqlite3_bind_int"]=wasmExports["oa"];_sqlite3_bind_int64=Module["_sqlite3_bind_int64"]=wasmExports["pa"];_sqlite3_bind_null=Module["_sqlite3_bind_null"]=wasmExports["qa"];_sqlite3_bind_text=Module["_sqlite3_bind_text"]=wasmExports["ra"];_sqlite3_bind_parameter_count=Module["_sqlite3_bind_parameter_count"]=wasmExports["sa"];_sqlite3_bind_parameter_name=Module["_sqlite3_bind_parameter_name"]=wasmExports["ta"];_sqlite3_bind_parameter_index=Module["_sqlite3_bind_parameter_index"]=wasmExports["ua"];_sqlite3_stmt_readonly=Module["_sqlite3_stmt_readonly"]=wasmExports["va"];_sqlite3_sql=Module["_sqlite3_sql"]=wasmExports["wa"];_sqlite3_errmsg=Module["_sqlite3_errmsg"]=wasmExports["xa"];_sqlite3_last_insert_rowid=Module["_sqlite3_last_insert_rowid"]=wasmExports["ya"];_sqlite3_changes=Module["_sqlite3_changes"]=wasmExports["za"];_sqlite3_total_changes=Module["_sqlite3_total_changes"]=wasmExports["Aa"];_sqlite3_close_v2=Module["_sqlite3_close_v2"]=wasmExports["Ba"];_sqlite3_create_function_v2=Module["_sqlite3_create_function_v2"]=wasmExports["Ca"];_sqlite3_commit_hook=Module["_sqlite3_commit_hook"]=wasmExports["Da"];_sqlite3_update_hook=Module["_sqlite3_update_hook"]=wasmExports["Ea"];_sqlite3_rollback_hook=Module["_sqlite3_rollback_hook"]=wasmExports["Fa"];_sqlite3_open_v2=Module["_sqlite3_open_v2"]=wasmExports["Ga"];_sqlite3_get_autocommit=Module["_sqlite3_get_autocommit"]=wasmExports["Ha"];_sqlite3_db_filename=Module["_sqlite3_db_filename"]=wasmExports["Ia"];_sqlite3session_create=Module["_sqlite3session_create"]=wasmExports["Ja"];_sqlite3session_delete=Module["_sqlite3session_delete"]=wasmExports["Ka"];_sqlite3session_attach=Module["_sqlite3session_attach"]=wasmExports["La"];_sqlite3session_changeset=Module["_sqlite3session_changeset"]=wasmExports["Ma"];_sqlite3session_enable=Module["_sqlite3session_enable"]=wasmExports["Na"];_sqlite3changeset_invert=Module["_sqlite3changeset_invert"]=wasmExports["Oa"];_sqlite3changeset_apply=Module["_sqlite3changeset_apply"]=wasmExports["Pa"];_malloc=Module["_malloc"]=wasmExports["Qa"];_free=Module["_free"]=wasmExports["Ra"];__emscripten_timeout=wasmExports["Ta"];__emscripten_stack_restore=wasmExports["Ua"];__emscripten_stack_alloc=wasmExports["Va"];_emscripten_stack_get_current=wasmExports["Wa"];memory=wasmMemory=wasmExports["D"];__indirect_function_table=wasmTable=wasmExports["Sa"]}var wasmImports={a:___assert_fail,p:__abort_js,j:__emscripten_runtime_keepalive_clear,m:__localtime_js,k:__setitimer_js,n:__tzset_js,o:_emscripten_date_now,l:_emscripten_resize_heap,B:_nodejsAccess,w:_nodejsCheckReservedLock,e:_nodejsClose,C:_nodejsDelete,z:_nodejsFileSize,q:_nodejsFullPathname,y:_nodejsLock,h:_nodejsRandomness,d:_nodejsRead,t:_nodejsShmBarrier,u:_nodejsShmLock,v:_nodejsShmMap,s:_nodejsShmUnmap,g:_nodejsSleep,A:_nodejsSync,b:_nodejsTruncate,x:_nodejsUnlock,c:_nodejsWrite,f:_nodejs_max_path_length,r:_nodejs_open,i:_proc_exit};function run(){preRun();function doRun(){Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve?.(Module);Module["onRuntimeInitialized"]?.();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(()=>{setTimeout(()=>Module["setStatus"](""),1);doRun()},1)}else{doRun()}}var wasmExports;wasmExports=await (createWasm());run();if(runtimeInitialized){moduleRtn=Module}else{moduleRtn=new Promise((resolve,reject)=>{readyPromiseResolve=resolve;readyPromiseReject=reject})}
2
2
  ;return moduleRtn}export default createSqliteModule;
Binary file
package/dist/sqlite3.js CHANGED
@@ -1 +1 @@
1
- var Module=typeof Module!="undefined"?Module:{};var ENVIRONMENT_IS_NODE=true;const SQLITE_OK=0;const SQLITE_ROW=100;const SQLITE_DONE=101;const SQLITE_INTEGER=1;const SQLITE_FLOAT=2;const SQLITE_TEXT=3;const SQLITE_BLOB=4;const SQLITE_NULL=5;const SQLITE_UTF8=1;const SQLITE_TRANSIENT=-1;const SQLITE_DETERMINISTIC=2048;const SQLITE_DIRECTONLY=524288;const INT32_MIN=-2147483648;const INT32_MAX=2147483647;const NULL=0;function isByteArray(value){return value instanceof Uint8Array}function copyByteArray(value){const NodeBuffer=globalThis.Buffer;return NodeBuffer?NodeBuffer.from(value):Uint8Array.from(value)}function emptyByteArray(){const NodeBuffer=globalThis.Buffer;return NodeBuffer?NodeBuffer.alloc(0):new Uint8Array}let temp;const sqlite3={};Module.onRuntimeInitialized=()=>{temp=stackAlloc(8);const v=null;const n="number";const s="string";const n1=[n];const n2=[n,...n1];const n3=[n,...n2];const n4=[n,...n3];const n5=[n,...n4];const signatures={open_v2:[n,[s,n,n,s]],exec:[n,n5],errmsg:[s,n1],prepare_v2:[n,n5],close_v2:[n,n1],finalize:[n,n1],reset:[n,n1],clear_bindings:[n,n1],bind_int:[n,n3],bind_int64:[n,n3],bind_double:[n,n3],bind_text:[n,n5],bind_blob:[n,n5],bind_null:[n,n2],bind_parameter_index:[n,[n,s]],bind_parameter_count:[n,n1],bind_parameter_name:[s,n2],step:[n,n1],column_int64:[n,n2],column_double:[n,n2],column_text:[s,n2],column_blob:[n,n2],column_type:[n,n2],column_name:[s,n2],column_count:[n,n1],column_bytes:[n,n2],column_table_name:[s,n2],column_origin_name:[s,n2],column_database_name:[s,n2],data_count:[n,n1],sql:[s,n1],stmt_readonly:[n,n1],last_insert_rowid:[n,n1],changes:[n,n1],total_changes:[n,n1],create_function_v2:[n,[n,s,n,n,n,n,n,n,n]],value_type:[n,n1],value_text:[s,n1],value_blob:[n,n1],value_int64:[n,n1],value_double:[n,n1],value_bytes:[n,n1],result_double:[v,n2],result_null:[v,n1],result_text:[v,n4],result_blob:[v,n4],result_int:[v,n2],result_int64:[v,n2],result_error:[v,n3],get_autocommit:[n,n1]};for(const[name,sig]of Object.entries(signatures)){sqlite3[name]=cwrap(`sqlite3_${name}`,sig[0],sig[1])}function arrayToHeap(array){const ptr=_malloc(array.byteLength);HEAPU8.set(array,ptr);return ptr}function stringToHeap(str){const size=lengthBytesUTF8(str)+1;const ptr=_malloc(size);stringToUTF8(str,ptr,size);return ptr}function toNumberOrNot(val){if(typeof val==="bigint"){if(val>=Number.MIN_SAFE_INTEGER&&val<=Number.MAX_SAFE_INTEGER){return Number(val)}return val}return val}const SQLITE_ERROR_NAMES={1:"SQLITE_ERROR",2:"SQLITE_INTERNAL",3:"SQLITE_PERM",4:"SQLITE_ABORT",5:"SQLITE_BUSY",6:"SQLITE_LOCKED",7:"SQLITE_NOMEM",8:"SQLITE_READONLY",9:"SQLITE_INTERRUPT",10:"SQLITE_IOERR",11:"SQLITE_CORRUPT",12:"SQLITE_NOTFOUND",13:"SQLITE_FULL",14:"SQLITE_CANTOPEN",15:"SQLITE_PROTOCOL",16:"SQLITE_EMPTY",17:"SQLITE_SCHEMA",18:"SQLITE_TOOBIG",19:"SQLITE_CONSTRAINT",20:"SQLITE_MISMATCH",21:"SQLITE_MISUSE",23:"SQLITE_AUTH",24:"SQLITE_FORMAT",25:"SQLITE_RANGE",26:"SQLITE_NOTADB",100:"SQLITE_ROW",101:"SQLITE_DONE"};class SqliteError extends Error{constructor(message,code){super(message);this.name="SqliteError";if(typeof code==="number"){this.code=SQLITE_ERROR_NAMES[code&255]||SQLITE_ERROR_NAMES[code]||"SQLITE_ERROR"}else{this.code=code||"SQLITE_ERROR"}}}function resolveBindParams(args){if(args.length===0)return null;if(args.length===1){const arg=args[0];if(arg===undefined||arg===null)return null;if(Array.isArray(arg))return arg;if(typeof arg==="object"&&!isByteArray(arg))return arg;return[arg]}return Array.from(args)}function parseFunctionArgs(argc,argv){const args=[];for(let i=0;i<argc;i++){const ptr=getValue(argv+4*i,"i32");const type=sqlite3.value_type(ptr);switch(type){case SQLITE_INTEGER:args.push(toNumberOrNot(sqlite3.value_int64(ptr)));break;case SQLITE_FLOAT:args.push(sqlite3.value_double(ptr));break;case SQLITE_TEXT:args.push(sqlite3.value_text(ptr));break;case SQLITE_BLOB:{const p=sqlite3.value_blob(ptr);args.push(p!==NULL?copyByteArray(HEAPU8.slice(p,p+sqlite3.value_bytes(ptr))):emptyByteArray());break}case SQLITE_NULL:args.push(null);break}}return args}function setFunctionResult(cx,result){switch(typeof result){case"boolean":sqlite3.result_int(cx,result?1:0);break;case"number":if(Number.isSafeInteger(result)){if(result>=INT32_MIN&&result<=INT32_MAX){sqlite3.result_int(cx,result)}else{sqlite3.result_int64(cx,BigInt(result))}}else{sqlite3.result_double(cx,result)}break;case"bigint":sqlite3.result_int64(cx,result);break;case"string":{const tp=stringToHeap(result);sqlite3.result_text(cx,tp,-1,SQLITE_TRANSIENT);_free(tp);break}case"object":if(result===null){sqlite3.result_null(cx)}else if(isByteArray(result)){const tp=arrayToHeap(result);sqlite3.result_blob(cx,tp,result.byteLength,SQLITE_TRANSIENT);_free(tp)}else{sqlite3.result_error(cx,stringToHeap("unsupported return type"),-1)}break;default:sqlite3.result_null(cx);break}}class Database{constructor(filename,options={}){if(typeof filename!=="string"&&!isByteArray(filename)){throw new TypeError("Expected first argument to be a string")}filename=String(filename);const readonly=!!options.readonly;const fileMustExist=!!options.fileMustExist;let flags;if(readonly){flags=1}else{flags=2;if(!fileMustExist)flags|=4}const rc=sqlite3.open_v2(filename,temp,flags,NULL);this._ptr=getValue(temp,"i32");if(rc!==SQLITE_OK){const msg=this._ptr!==NULL?sqlite3.errmsg(this._ptr):"unable to open database";if(this._ptr!==NULL)sqlite3.close_v2(this._ptr);this._ptr=null;throw new SqliteError(msg)}this._open=true;this._readonly=readonly;this._unsafe=false;this._name=filename;this._statements=new Set;this._functions=new Map;this.exec("PRAGMA busy_timeout = 5000")}unsafeMode(enabled){if(enabled===undefined)enabled=true;this._unsafe=!!enabled;return this}get open(){return this._open}get readonly(){return this._readonly}get name(){return this._name}get inTransaction(){return this._open&&sqlite3.get_autocommit(this._ptr)===0}prepare(source){this._assertOpen();if(typeof source!=="string"){throw new TypeError("Expected first argument to be a string")}const stmt=new Statement(this,source);this._statements.add(stmt);return stmt}exec(sql,{resetStatements=true}={}){this._assertOpen();if(resetStatements){for(const stmt of this._statements){if(!stmt._finalized)sqlite3.reset(stmt._ptr)}}const tp=stringToHeap(sql);try{const rc=sqlite3.exec(this._ptr,tp,NULL,NULL,NULL);if(rc!==SQLITE_OK){throw new SqliteError(sqlite3.errmsg(this._ptr),rc)}}finally{_free(tp)}return this}transaction(fn){if(typeof fn!=="function"){throw new TypeError("Expected first argument to be a function")}const db=this;const wrapTxn=begin=>{const beginStmt=db.prepare(begin);const commitStmt=db.prepare("COMMIT");const rollbackStmt=db.prepare("ROLLBACK");const runner=function(...args){let result;if(db.inTransaction){return fn.apply(this,args)}beginStmt.run();try{result=fn.apply(this,args);commitStmt.run()}catch(err){if(db.inTransaction){rollbackStmt.run()}throw err}return result};return runner};const result=wrapTxn("BEGIN");result.deferred=wrapTxn("BEGIN DEFERRED");result.immediate=wrapTxn("BEGIN IMMEDIATE");result.exclusive=wrapTxn("BEGIN EXCLUSIVE");result.database=db;return result}pragma(source,options){if(typeof source!=="string"){throw new TypeError("Expected first argument to be a string")}const simple=options&&options.simple;const sql=`PRAGMA ${source}`;const stmt=this.prepare(sql);try{if(stmt.reader){return simple?stmt.pluck().get():stmt.all()}else{return stmt.run()}}finally{stmt.finalize()}}function(name,fn,options={}){this._assertOpen();if(typeof name!=="string")throw new TypeError("Expected first argument to be a string");if(typeof fn!=="function")throw new TypeError("Expected second argument to be a function");const deterministic=!!options.deterministic;const directOnly=!!options.directOnly;const varargs=options.varargs||false;if(this._functions.has(name)){removeFunction(this._functions.get(name));this._functions.delete(name)}const wrappedFunc=(cx,argc,argv)=>{const args=parseFunctionArgs(argc,argv);try{const result=fn(...args);setFunctionResult(cx,result)}catch(err){const tp=stringToHeap(err.toString());sqlite3.result_error(cx,tp,-1);_free(tp)}};const funcPtr=addFunction(wrappedFunc,"viii");this._functions.set(name,funcPtr);let eTextRep=SQLITE_UTF8;if(deterministic)eTextRep|=SQLITE_DETERMINISTIC;if(directOnly)eTextRep|=SQLITE_DIRECTONLY;const rc=sqlite3.create_function_v2(this._ptr,name,varargs?-1:fn.length,eTextRep,NULL,funcPtr,NULL,NULL,NULL);if(rc!==SQLITE_OK)throw new SqliteError(sqlite3.errmsg(this._ptr));return this}aggregate(name,options){this._assertOpen();if(typeof name!=="string")throw new TypeError("Expected first argument to be a string");if(!options||typeof options!=="object")throw new TypeError("Expected second argument to be an options object");const step=options.step;const result=options.result||(acc=>acc);const start=options.start;const inverse=options.inverse;const deterministic=!!options.deterministic;const directOnly=!!options.directOnly;const varargs=!!options.varargs;if(typeof step!=="function")throw new TypeError("Expected options.step to be a function");let accumulator;const stepWrapper=(cx,argc,argv)=>{const args=parseFunctionArgs(argc,argv);try{accumulator=step(accumulator,...args)}catch(err){const tp=stringToHeap(err.toString());sqlite3.result_error(cx,tp,-1);_free(tp)}};const finalWrapper=cx=>{try{const val=result(accumulator);setFunctionResult(cx,val)}catch(err){const tp=stringToHeap(err.toString());sqlite3.result_error(cx,tp,-1);_free(tp)}accumulator=typeof start==="function"?start():start};accumulator=typeof start==="function"?start():start;if(this._functions.has(name+"_step")){removeFunction(this._functions.get(name+"_step"));this._functions.delete(name+"_step")}if(this._functions.has(name+"_final")){removeFunction(this._functions.get(name+"_final"));this._functions.delete(name+"_final")}const stepPtr=addFunction(stepWrapper,"viii");const finalPtr=addFunction(finalWrapper,"vi");this._functions.set(name+"_step",stepPtr);this._functions.set(name+"_final",finalPtr);let eTextRep=SQLITE_UTF8;if(deterministic)eTextRep|=SQLITE_DETERMINISTIC;if(directOnly)eTextRep|=SQLITE_DIRECTONLY;const argCount=varargs?-1:step.length-1;const rc=sqlite3.create_function_v2(this._ptr,name,argCount,eTextRep,NULL,NULL,stepPtr,finalPtr,NULL);if(rc!==SQLITE_OK)throw new SqliteError(sqlite3.errmsg(this._ptr));return this}close(){if(!this._open)return;for(const stmt of this._statements){if(!stmt._finalized){sqlite3.finalize(stmt._ptr);stmt._finalized=true}}this._statements.clear();for(const func of this._functions.values()){removeFunction(func)}this._functions.clear();const rc=sqlite3.close_v2(this._ptr);if(rc!==SQLITE_OK){throw new SqliteError(sqlite3.errmsg(this._ptr))}this._ptr=null;this._open=false}_assertOpen(){if(!this._open)throw new SqliteError("The database connection is not open")}_handleError(rc){if(rc!==SQLITE_OK){throw new SqliteError(sqlite3.errmsg(this._ptr),rc)}}}class Statement{constructor(db,source){this._db=db;this._source=source;this._finalized=false;this._pluck=false;this._expand=false;this._raw=false;this._bound=false;this._numbersAsDoubles=false;const tp=stringToHeap(source);try{const rc=sqlite3.prepare_v2(db._ptr,tp,-1,temp,NULL);if(rc!==SQLITE_OK){throw new SqliteError(sqlite3.errmsg(db._ptr),rc)}}finally{_free(tp)}this._ptr=getValue(temp,"i32");if(this._ptr===NULL){throw new SqliteError("Nothing to prepare")}this._columnCount=sqlite3.column_count(this._ptr);this._reader=this._columnCount>0;this._readonly=!!sqlite3.stmt_readonly(this._ptr)}get source(){return this._source}get reader(){return this._reader}get readonly(){return this._readonly}get parameterCount(){this._assertReady();return sqlite3.bind_parameter_count(this._ptr)}numbersAsDoubles(toggle=true){this._numbersAsDoubles=toggle;return this}finalize(){if(this._finalized)return;sqlite3.finalize(this._ptr);this._finalized=true;this._ptr=null;this._db._statements.delete(this)}run(...args){this._assertReady();const params=resolveBindParams(args);this._reset();if(params)this._bind(params);this._step();const result={changes:sqlite3.changes(this._db._ptr),lastInsertRowid:toNumberOrNot(sqlite3.last_insert_rowid(this._db._ptr))};sqlite3.reset(this._ptr);return result}get(...args){this._assertReady();const params=resolveBindParams(args);this._reset();if(params)this._bind(params);if(!this._step()){sqlite3.reset(this._ptr);return undefined}const row=this._getRow();sqlite3.reset(this._ptr);return row}all(...args){this._assertReady();const params=resolveBindParams(args);this._reset();if(params)this._bind(params);const rows=[];while(this._step()){rows.push(this._getRow());if(rows.length===1e5){console.warn(`[bedrock-sqlite] all() returned 100k rows, query: ${this._source.slice(0,200)}`)}if(rows.length>=1e7){sqlite3.reset(this._ptr);throw new SqliteError(`all() exceeded 10M row safety limit, likely infinite loop. query: ${this._source.slice(0,200)}`)}}sqlite3.reset(this._ptr);return rows}*iterate(...args){this._assertReady();const params=resolveBindParams(args);this._reset();if(params)this._bind(params);while(this._step()){yield this._getRow()}}pluck(toggle=true){this._pluck=toggle;this._raw=false;this._expand=false;return this}expand(toggle=true){this._expand=toggle;this._pluck=false;this._raw=false;return this}raw(toggle=true){this._raw=toggle;this._pluck=false;this._expand=false;return this}columns(){this._assertReady();const cols=[];for(let i=0;i<this._columnCount;i++){cols.push({name:sqlite3.column_name(this._ptr,i),column:sqlite3.column_origin_name(this._ptr,i),table:sqlite3.column_table_name(this._ptr,i),database:sqlite3.column_database_name(this._ptr,i),type:null})}return cols}scanStatusV2(){return[]}scanStatusReset(){}safeIntegers(){return this}bind(...args){this._assertReady();const params=resolveBindParams(args);this._reset();if(params)this._bind(params);this._bound=true;return this}_reset(){sqlite3.clear_bindings(this._ptr);sqlite3.reset(this._ptr)}_step(){const rc=sqlite3.step(this._ptr);if(rc===SQLITE_ROW)return true;if(rc===SQLITE_DONE)return false;sqlite3.reset(this._ptr);throw new SqliteError(sqlite3.errmsg(this._db._ptr),rc)}_getRow(){if(this._pluck){return this._getColumnValue(0)}if(this._raw){const row=[];for(let i=0;i<this._columnCount;i++){row.push(this._getColumnValue(i))}return row}if(this._expand){const row={};for(let i=0;i<this._columnCount;i++){let table=sqlite3.column_table_name(this._ptr,i);table=table===""||table===null?"$":table;const name=sqlite3.column_name(this._ptr,i);if(!row[table])row[table]={};row[table][name]=this._getColumnValue(i)}return row}const row={};for(let i=0;i<this._columnCount;i++){row[sqlite3.column_name(this._ptr,i)]=this._getColumnValue(i)}return row}_getColumnValue(i){const type=sqlite3.column_type(this._ptr,i);switch(type){case SQLITE_INTEGER:return toNumberOrNot(sqlite3.column_int64(this._ptr,i));case SQLITE_FLOAT:return sqlite3.column_double(this._ptr,i);case SQLITE_TEXT:return sqlite3.column_text(this._ptr,i);case SQLITE_BLOB:{const p=sqlite3.column_blob(this._ptr,i);if(p!==NULL){const nbytes=sqlite3.column_bytes(this._ptr,i);if(nbytes>104857600){throw new SqliteError(`blob column ${i} has unreasonable size: ${nbytes} bytes`)}return copyByteArray(HEAPU8.slice(p,p+nbytes))}return emptyByteArray()}case SQLITE_NULL:return null;default:return null}}_bind(params){if(Array.isArray(params)){for(let i=0;i<params.length;i++){this._bindValue(params[i],i+1)}}else if(typeof params==="object"){const count=sqlite3.bind_parameter_count(this._ptr);for(let i=1;i<=count;i++){const pname=sqlite3.bind_parameter_name(this._ptr,i);if(!pname)continue;const stripped=pname.slice(1);const value=pname in params?params[pname]:stripped in params?params[stripped]:undefined;if(value!==undefined){this._bindValue(value,i)}}}}_bindValue(value,position){let rc;switch(typeof value){case"string":{const tp=stringToHeap(value);rc=sqlite3.bind_text(this._ptr,position,tp,-1,SQLITE_TRANSIENT);_free(tp);break}case"number":if(!this._numbersAsDoubles&&Number.isSafeInteger(value)){if(value>=INT32_MIN&&value<=INT32_MAX){rc=sqlite3.bind_int(this._ptr,position,value)}else{rc=sqlite3.bind_int64(this._ptr,position,BigInt(value))}}else{rc=sqlite3.bind_double(this._ptr,position,value)}break;case"bigint":rc=sqlite3.bind_int64(this._ptr,position,value);break;case"boolean":rc=sqlite3.bind_int(this._ptr,position,value?1:0);break;case"object":if(value===null){rc=sqlite3.bind_null(this._ptr,position)}else if(isByteArray(value)){const tp=arrayToHeap(value);rc=sqlite3.bind_blob(this._ptr,position,tp,value.byteLength,SQLITE_TRANSIENT);_free(tp)}else{throw new SqliteError(`Unsupported binding type at position ${position}`)}break;default:if(value===undefined){rc=sqlite3.bind_null(this._ptr,position)}else{throw new SqliteError(`Unsupported binding type: ${typeof value}`)}}if(rc!==SQLITE_OK){throw new SqliteError(sqlite3.errmsg(this._db._ptr))}}_assertReady(){if(this._finalized)throw new SqliteError("This statement has been finalized");if(!this._db._open)throw new SqliteError("The database connection is not open")}}Module.Database=Database;Module.SqliteError=SqliteError};const path=require("node:path");const crypto=require("node:crypto");const SQLITE_CANTOPEN=14;const SQLITE_IOERR_READ=266;const SQLITE_IOERR_SHORT_READ=522;const SQLITE_IOERR_FSYNC=1034;const SQLITE_IOERR_WRITE=778;const SQLITE_IOERR_DELETE=2570;const SQLITE_IOERR_CLOSE=4106;const SQLITE_IOERR_TRUNCATE=1546;const SQLITE_IOERR_FSTAT=1802;const SQLITE_OPEN_READONLY=1;const SQLITE_OPEN_READWRITE=2;const SQLITE_OPEN_CREATE=4;const SQLITE_OPEN_EXCLUSIVE=16;const SQLITE_ACCESS_READWRITE=1;const SQLITE_ACCESS_READ=2;const SQLITE_LOCK_NONE=0;const SQLITE_LOCK_SHARED=1;const SQLITE_LOCK_RESERVED=2;const SQLITE_LOCK_EXCLUSIVE=4;const SQLITE_BUSY=5;function _fd(fileInfo){return getValue(fileInfo+4,"i32")}function _setLocked(fileInfo,locked){setValue(fileInfo+8,locked?1:0,"i32")}function _path(fileInfo){return UTF8ToString(getValue(fileInfo+12,"i32"))}function _safeInt(bigInt){if(bigInt<Number.MIN_SAFE_INTEGER||bigInt>Number.MAX_SAFE_INTEGER)throw 0;return Number(bigInt)}var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var _scriptName;if(typeof __filename!="undefined"){_scriptName=__filename}else{}var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");scriptDirectory=__dirname+"/";readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(process.argv.length>1){thisProgram=process.argv[1].replace(/\\/g,"/")}arguments_=process.argv.slice(2);if(typeof module!="undefined"){module["exports"]=Module}quit_=(status,toThrow)=>{process.exitCode=status;throw toThrow}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var EXITSTATUS;var isFileURI=filename=>filename.startsWith("file://");var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;var HEAP64,HEAPU64;var runtimeInitialized=false;function updateMemoryViews(){var b=wasmMemory.buffer;HEAP8=new Int8Array(b);HEAP16=new Int16Array(b);HEAPU8=new Uint8Array(b);HEAPU16=new Uint16Array(b);HEAP32=new Int32Array(b);HEAPU32=new Uint32Array(b);HEAPF32=new Float32Array(b);HEAPF64=new Float64Array(b);HEAP64=new BigInt64Array(b);HEAPU64=new BigUint64Array(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;wasmExports["E"]()}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(onPostRuns)}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);throw e}var wasmBinaryFile;function findWasmBinary(){return locateFile("sqlite3.wasm")}function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw'sync fetching of the wasm failed: you can preload it to Module["wasmBinary"] manually, or emcc.py will do that for you when generating HTML (but not JS)'}function instantiateSync(file,info){var module;var binary=getBinarySync(file);module=new WebAssembly.Module(binary);var instance=new WebAssembly.Instance(module,info);return[instance,module]}function getWasmImports(){var imports={a:wasmImports};return imports}function createWasm(){function receiveInstance(instance,module){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}var info=getWasmImports();if(Module["instantiateWasm"]){return new Promise((resolve,reject)=>{Module["instantiateWasm"](info,(inst,mod)=>{resolve(receiveInstance(inst,mod))})})}wasmBinaryFile??=findWasmBinary();var result=instantiateSync(wasmBinaryFile,info);return receiveInstance(result[0])}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":return HEAP64[ptr>>3];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":HEAP64[ptr>>3]=BigInt(value);break;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=globalThis.TextDecoder&&new TextDecoder;var findStringEnd=(heapOrArray,idx,maxBytesToRead,ignoreNul)=>{var maxIdx=idx+maxBytesToRead;if(ignoreNul)return maxIdx;while(heapOrArray[idx]&&!(idx>=maxIdx))++idx;return idx};var UTF8ArrayToString=(heapOrArray,idx=0,maxBytesToRead,ignoreNul)=>{var endPtr=findStringEnd(heapOrArray,idx,maxBytesToRead,ignoreNul);if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr))}var str="";while(idx<endPtr){var u0=heapOrArray[idx++];if(!(u0&128)){str+=String.fromCharCode(u0);continue}var u1=heapOrArray[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=heapOrArray[idx++]&63;if((u0&240)==224){u0=(u0&15)<<12|u1<<6|u2}else{u0=(u0&7)<<18|u1<<12|u2<<6|heapOrArray[idx++]&63}if(u0<65536){str+=String.fromCharCode(u0)}else{var ch=u0-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}return str};var UTF8ToString=(ptr,maxBytesToRead,ignoreNul)=>ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead,ignoreNul):"";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 __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};var INT53_MAX=9007199254740992;var INT53_MIN=-9007199254740992;var bigintToI53Checked=num=>num<INT53_MIN||num>INT53_MAX?NaN:Number(num);function __localtime_js(time,tmPtr){time=bigintToI53Checked(time);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}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{return func()}catch(e){handleException(e)}finally{maybeExit()}};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 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.codePointAt(i);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;i++}}heap[outIdx]=0;return outIdx-startIdx};var stringToUTF8=(str,outPtr,maxBytesToWrite)=>stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite);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=()=>536870912;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+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};function _nodejsAccess(vfs,filePath,flags,outResult){let aflags=fs.constants.F_OK;if(flags==SQLITE_ACCESS_READWRITE)aflags=fs.constants.R_OK|fs.constants.W_OK;if(flags==SQLITE_ACCESS_READ)aflags=fs.constants.R_OK;try{fs.accessSync(UTF8ToString(filePath),aflags);setValue(outResult,1,"i32")}catch{setValue(outResult,0,"i32")}return SQLITE_OK}var _fileLocks={};function _nodejsCheckReservedLock(fi,outResult){var filePath=_path(fi);var holders=_fileLocks[filePath];var reserved=0;if(holders){for(var[other,otherLevel]of holders){if(other!==fi&&otherLevel>=SQLITE_LOCK_RESERVED){reserved=1;break}}}setValue(outResult,reserved,"i32");return SQLITE_OK}function _nodejsClose(fi){_nodejsUnlock(fi,SQLITE_LOCK_NONE);try{fs.closeSync(_fd(fi))}catch{return SQLITE_IOERR_CLOSE}return SQLITE_OK}function _nodejsDelete(vfs,filePath,dirSync){const pathStr=UTF8ToString(filePath);try{fs.unlinkSync(pathStr)}catch(err){if(err.code!="ENOENT")return SQLITE_IOERR_DELETE}if(dirSync){let fd=-1;try{fd=fs.openSync(path.dirname(pathStr),"r");fs.fsyncSync(fd)}catch{return SQLITE_IOERR_FSYNC}finally{try{fs.closeSync(fd)}catch{return SQLITE_IOERR_FSYNC}}}return SQLITE_OK}function _nodejsFileSize(fi,outSize){try{setValue(outSize,fs.fstatSync(_fd(fi)).size,"i64")}catch{return SQLITE_IOERR_FSTAT}return SQLITE_OK}function _nodejsFullPathname(vfs,relPath,sizeFullPath,outFullPath){const full=path.resolve(UTF8ToString(relPath));stringToUTF8(full,outFullPath,sizeFullPath);return full.length<sizeFullPath?SQLITE_OK:SQLITE_CANTOPEN}function _nodejsLock(fi,level){var filePath=_path(fi);if(!_fileLocks[filePath])_fileLocks[filePath]=new Map;var holders=_fileLocks[filePath];var myLevel=holders.get(fi)||SQLITE_LOCK_NONE;if(level>=SQLITE_LOCK_RESERVED&&myLevel<SQLITE_LOCK_RESERVED){for(var[other,otherLevel]of holders){if(other!==fi&&otherLevel>=SQLITE_LOCK_RESERVED){return SQLITE_BUSY}}}if(level>=SQLITE_LOCK_EXCLUSIVE&&myLevel<SQLITE_LOCK_EXCLUSIVE){for(var[other,otherLevel]of holders){if(other!==fi&&otherLevel>=SQLITE_LOCK_SHARED){return SQLITE_BUSY}}}holders.set(fi,level);if(level>SQLITE_LOCK_NONE)_setLocked(fi,true);return SQLITE_OK}function _nodejsRandomness(vfs,bytes,outBuffer){const buf=HEAPU8.subarray(outBuffer,outBuffer+bytes);crypto.randomFillSync(buf);return bytes}function _nodejsRead(fi,outBuffer,bytes,offset){const buf=HEAPU8.subarray(outBuffer,outBuffer+bytes);let bytesRead;try{bytesRead=fs.readSync(_fd(fi),buf,0,bytes,_safeInt(offset))}catch{return SQLITE_IOERR_READ}if(bytesRead==bytes){return SQLITE_OK}else if(bytesRead>=0){if(bytesRead<bytes){try{buf.fill(0,bytesRead)}catch{return SQLITE_IOERR_READ}}return SQLITE_IOERR_SHORT_READ}return SQLITE_IOERR_READ}function _nodejsShmBarrier(fi){var filePath=_path(fi);var reg=_shmRegistry[filePath];if(!reg||reg._hasExclusiveLock)return;var shmPath=filePath+"-shm";var stat;try{stat=fs.statSync(shmPath)}catch(e){return}if(reg._lastShmWrite&&stat.mtimeMs<=reg._lastShmWrite)return;var fd;try{fd=fs.openSync(shmPath,fs.constants.O_RDONLY)}catch(e){return}for(var pgno in reg){if(typeof reg[pgno]!=="object"||!reg[pgno].ptr)continue;var r=reg[pgno];try{fs.readSync(fd,HEAPU8.subarray(r.ptr,r.ptr+r.pgsz),0,r.pgsz,Number(pgno)*r.pgsz)}catch(e){}}fs.closeSync(fd);reg._lastShmWrite=stat.mtimeMs}function _nodejsShmLock(fi,offset,n,flags){var filePath=_path(fi);if(!_shmRegistry[filePath])_shmRegistry[filePath]={};var reg=_shmRegistry[filePath];if(flags&2&&flags&8){reg._hasExclusiveLock=true}if(flags&1&&flags&8&&reg._hasExclusiveLock){var shmPath=filePath+"-shm";var fd;try{fd=fs.openSync(shmPath,fs.constants.O_RDWR|fs.constants.O_CREAT,420)}catch(e){reg._hasExclusiveLock=false;return SQLITE_OK}for(var pgno in reg){if(typeof reg[pgno]!=="object"||!reg[pgno].ptr)continue;var r=reg[pgno];try{fs.writeSync(fd,HEAPU8.subarray(r.ptr,r.ptr+r.pgsz),0,r.pgsz,Number(pgno)*r.pgsz)}catch(e){}}try{fs.fsyncSync(fd)}catch(e){}try{reg._lastShmWrite=fs.fstatSync(fd).mtimeMs}catch(e){reg._lastShmWrite=Date.now()}fs.closeSync(fd);reg._hasExclusiveLock=false}return SQLITE_OK}var _shmRegistry={};function _nodejsShmMap(fi,pgno,pgsz,isWrite,ppOut){var filePath=_path(fi);if(!_shmRegistry[filePath])_shmRegistry[filePath]={};var regions=_shmRegistry[filePath];if(!(pgno in regions)||typeof regions[pgno]!=="object"){if(!isWrite){setValue(ppOut,0,"*");return SQLITE_OK}var buf=_malloc(pgsz);HEAPU8.fill(0,buf,buf+pgsz);regions[pgno]={ptr:buf,pgsz}}setValue(ppOut,regions[pgno].ptr,"*");return SQLITE_OK}function _nodejsShmUnmap(fi,deleteFlag){if(deleteFlag){var filePath=_path(fi);var regions=_shmRegistry[filePath];if(regions){for(var pgno in regions){if(typeof regions[pgno]==="object"&&regions[pgno].ptr)_free(regions[pgno].ptr)}delete _shmRegistry[filePath]}}return SQLITE_OK}function _nodejsSleep(vfs,nMicro){var ms=Math.max(1,Math.floor(nMicro/1e3));var sab=new SharedArrayBuffer(4);Atomics.wait(new Int32Array(sab),0,0,ms);return nMicro}function _nodejsSync(fi,flags){try{fs.fsyncSync(_fd(fi))}catch{return SQLITE_IOERR_FSYNC}return SQLITE_OK}function _nodejsTruncate(fi,size){try{fs.ftruncateSync(_fd(fi),_safeInt(size))}catch{return SQLITE_IOERR_TRUNCATE}return SQLITE_OK}function _nodejsUnlock(fi,level){var filePath=_path(fi);var holders=_fileLocks[filePath];if(holders){if(level==SQLITE_LOCK_NONE){holders.delete(fi);_setLocked(fi,false)}else{holders.set(fi,level)}}else{if(level==SQLITE_LOCK_NONE)_setLocked(fi,false)}return SQLITE_OK}function _nodejsWrite(fi,buffer,bytes,offset){try{const bytesWritten=fs.writeSync(_fd(fi),HEAPU8.subarray(buffer,buffer+bytes),0,bytes,_safeInt(offset));return bytesWritten!=bytes?SQLITE_IOERR_WRITE:SQLITE_OK}catch{return SQLITE_IOERR_WRITE}}function _nodejs_max_path_length(){return process.platform=="win32"?260:4096}function _nodejs_open(filePath,flags,mode){let oflags=0;if(flags&SQLITE_OPEN_EXCLUSIVE)oflags|=fs.constants.O_EXCL;if(flags&SQLITE_OPEN_CREATE)oflags|=fs.constants.O_CREAT;if(flags&SQLITE_OPEN_READONLY)oflags|=fs.constants.O_RDONLY;if(flags&SQLITE_OPEN_READWRITE)oflags|=fs.constants.O_RDWR;try{return fs.openSync(UTF8ToString(filePath),oflags,mode)}catch{return-1}}var getCFunc=ident=>{var func=Module["_"+ident];return func};var writeArrayToMemory=(array,buffer)=>{HEAP8.set(array,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 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 wasmTableMirror=[];var getWasmTableEntry=funcPtr=>{var func=wasmTableMirror[funcPtr];if(!func){wasmTableMirror[funcPtr]=func=wasmTable.get(funcPtr)}return func};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()}return wasmTable["grow"](1)};var setWasmTableEntry=(idx,func)=>{wasmTable.set(idx,func);wasmTableMirror[idx]=wasmTable.get(idx)};var uleb128EncodeWithLen=arr=>{const n=arr.length;return[n%128|128,n>>7,...arr]};var wasmTypeCodes={i:127,p:127,j:126,f:125,d:124,e:111};var generateTypePack=types=>uleb128EncodeWithLen(Array.from(types,type=>{var code=wasmTypeCodes[type];return code}));var convertJsFunctionToWasm=(func,sig)=>{var bytes=Uint8Array.of(0,97,115,109,1,0,0,0,1,...uleb128EncodeWithLen([1,96,...generateTypePack(sig.slice(1)),...generateTypePack(sig[0]==="v"?"":sig[0])]),2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0);var module=new WebAssembly.Module(bytes);var instance=new WebAssembly.Instance(module,{e:{f:func}});var wrappedFunc=instance.exports["f"];return wrappedFunc};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 removeFunction=index=>{functionsInTableMap.delete(getWasmTableEntry(index));setWasmTableEntry(index,null);freeTableIndexes.push(index)};{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];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"];if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].shift()()}}}Module["cwrap"]=cwrap;Module["addFunction"]=addFunction;Module["removeFunction"]=removeFunction;var _sqlite3_prepare_v2,_sqlite3_step,_sqlite3_column_int64,_sqlite3_reset,_sqlite3_exec,_sqlite3_finalize,_sqlite3_clear_bindings,_sqlite3_value_blob,_sqlite3_value_text,_sqlite3_value_bytes,_sqlite3_value_double,_sqlite3_value_int64,_sqlite3_value_type,_sqlite3_result_blob,_sqlite3_result_double,_sqlite3_result_error,_sqlite3_result_int,_sqlite3_result_int64,_sqlite3_result_null,_sqlite3_result_text,_sqlite3_column_count,_sqlite3_data_count,_sqlite3_column_blob,_sqlite3_column_bytes,_sqlite3_column_double,_sqlite3_column_text,_sqlite3_column_type,_sqlite3_column_name,_sqlite3_column_database_name,_sqlite3_column_table_name,_sqlite3_column_origin_name,_sqlite3_bind_blob,_sqlite3_bind_double,_sqlite3_bind_int,_sqlite3_bind_int64,_sqlite3_bind_null,_sqlite3_bind_text,_sqlite3_bind_parameter_count,_sqlite3_bind_parameter_name,_sqlite3_bind_parameter_index,_sqlite3_stmt_readonly,_sqlite3_sql,_sqlite3_errmsg,_sqlite3_last_insert_rowid,_sqlite3_changes,_sqlite3_total_changes,_sqlite3_close_v2,_sqlite3_create_function_v2,_sqlite3_open_v2,_sqlite3_get_autocommit,_malloc,_free,__emscripten_timeout,__emscripten_stack_restore,__emscripten_stack_alloc,_emscripten_stack_get_current,memory,__indirect_function_table,wasmMemory,wasmTable;function assignWasmExports(wasmExports){_sqlite3_prepare_v2=Module["_sqlite3_prepare_v2"]=wasmExports["F"];_sqlite3_step=Module["_sqlite3_step"]=wasmExports["G"];_sqlite3_column_int64=Module["_sqlite3_column_int64"]=wasmExports["H"];_sqlite3_reset=Module["_sqlite3_reset"]=wasmExports["I"];_sqlite3_exec=Module["_sqlite3_exec"]=wasmExports["J"];_sqlite3_finalize=Module["_sqlite3_finalize"]=wasmExports["K"];_sqlite3_clear_bindings=Module["_sqlite3_clear_bindings"]=wasmExports["L"];_sqlite3_value_blob=Module["_sqlite3_value_blob"]=wasmExports["M"];_sqlite3_value_text=Module["_sqlite3_value_text"]=wasmExports["N"];_sqlite3_value_bytes=Module["_sqlite3_value_bytes"]=wasmExports["O"];_sqlite3_value_double=Module["_sqlite3_value_double"]=wasmExports["P"];_sqlite3_value_int64=Module["_sqlite3_value_int64"]=wasmExports["Q"];_sqlite3_value_type=Module["_sqlite3_value_type"]=wasmExports["R"];_sqlite3_result_blob=Module["_sqlite3_result_blob"]=wasmExports["S"];_sqlite3_result_double=Module["_sqlite3_result_double"]=wasmExports["T"];_sqlite3_result_error=Module["_sqlite3_result_error"]=wasmExports["U"];_sqlite3_result_int=Module["_sqlite3_result_int"]=wasmExports["V"];_sqlite3_result_int64=Module["_sqlite3_result_int64"]=wasmExports["W"];_sqlite3_result_null=Module["_sqlite3_result_null"]=wasmExports["X"];_sqlite3_result_text=Module["_sqlite3_result_text"]=wasmExports["Y"];_sqlite3_column_count=Module["_sqlite3_column_count"]=wasmExports["Z"];_sqlite3_data_count=Module["_sqlite3_data_count"]=wasmExports["_"];_sqlite3_column_blob=Module["_sqlite3_column_blob"]=wasmExports["$"];_sqlite3_column_bytes=Module["_sqlite3_column_bytes"]=wasmExports["aa"];_sqlite3_column_double=Module["_sqlite3_column_double"]=wasmExports["ba"];_sqlite3_column_text=Module["_sqlite3_column_text"]=wasmExports["ca"];_sqlite3_column_type=Module["_sqlite3_column_type"]=wasmExports["da"];_sqlite3_column_name=Module["_sqlite3_column_name"]=wasmExports["ea"];_sqlite3_column_database_name=Module["_sqlite3_column_database_name"]=wasmExports["fa"];_sqlite3_column_table_name=Module["_sqlite3_column_table_name"]=wasmExports["ga"];_sqlite3_column_origin_name=Module["_sqlite3_column_origin_name"]=wasmExports["ha"];_sqlite3_bind_blob=Module["_sqlite3_bind_blob"]=wasmExports["ia"];_sqlite3_bind_double=Module["_sqlite3_bind_double"]=wasmExports["ja"];_sqlite3_bind_int=Module["_sqlite3_bind_int"]=wasmExports["ka"];_sqlite3_bind_int64=Module["_sqlite3_bind_int64"]=wasmExports["la"];_sqlite3_bind_null=Module["_sqlite3_bind_null"]=wasmExports["ma"];_sqlite3_bind_text=Module["_sqlite3_bind_text"]=wasmExports["na"];_sqlite3_bind_parameter_count=Module["_sqlite3_bind_parameter_count"]=wasmExports["oa"];_sqlite3_bind_parameter_name=Module["_sqlite3_bind_parameter_name"]=wasmExports["pa"];_sqlite3_bind_parameter_index=Module["_sqlite3_bind_parameter_index"]=wasmExports["qa"];_sqlite3_stmt_readonly=Module["_sqlite3_stmt_readonly"]=wasmExports["ra"];_sqlite3_sql=Module["_sqlite3_sql"]=wasmExports["sa"];_sqlite3_errmsg=Module["_sqlite3_errmsg"]=wasmExports["ta"];_sqlite3_last_insert_rowid=Module["_sqlite3_last_insert_rowid"]=wasmExports["ua"];_sqlite3_changes=Module["_sqlite3_changes"]=wasmExports["va"];_sqlite3_total_changes=Module["_sqlite3_total_changes"]=wasmExports["wa"];_sqlite3_close_v2=Module["_sqlite3_close_v2"]=wasmExports["xa"];_sqlite3_create_function_v2=Module["_sqlite3_create_function_v2"]=wasmExports["ya"];_sqlite3_open_v2=Module["_sqlite3_open_v2"]=wasmExports["za"];_sqlite3_get_autocommit=Module["_sqlite3_get_autocommit"]=wasmExports["Aa"];_malloc=Module["_malloc"]=wasmExports["Ba"];_free=Module["_free"]=wasmExports["Ca"];__emscripten_timeout=wasmExports["Ea"];__emscripten_stack_restore=wasmExports["Fa"];__emscripten_stack_alloc=wasmExports["Ga"];_emscripten_stack_get_current=wasmExports["Ha"];memory=wasmMemory=wasmExports["D"];__indirect_function_table=wasmTable=wasmExports["Da"]}var wasmImports={a:___assert_fail,p:__abort_js,j:__emscripten_runtime_keepalive_clear,m:__localtime_js,k:__setitimer_js,n:__tzset_js,o:_emscripten_date_now,l:_emscripten_resize_heap,B:_nodejsAccess,w:_nodejsCheckReservedLock,e:_nodejsClose,C:_nodejsDelete,z:_nodejsFileSize,q:_nodejsFullPathname,y:_nodejsLock,h:_nodejsRandomness,d:_nodejsRead,t:_nodejsShmBarrier,u:_nodejsShmLock,v:_nodejsShmMap,s:_nodejsShmUnmap,g:_nodejsSleep,A:_nodejsSync,b:_nodejsTruncate,x:_nodejsUnlock,c:_nodejsWrite,f:_nodejs_max_path_length,r:_nodejs_open,i:_proc_exit};function run(){preRun();function doRun(){Module["calledRun"]=true;if(ABORT)return;initRuntime();Module["onRuntimeInitialized"]?.();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(()=>{setTimeout(()=>Module["setStatus"](""),1);doRun()},1)}else{doRun()}}var wasmExports;wasmExports=createWasm();run();
1
+ var Module=typeof Module!="undefined"?Module:{};var ENVIRONMENT_IS_NODE=true;const SQLITE_OK=0;const SQLITE_ROW=100;const SQLITE_DONE=101;const SQLITE_INTEGER=1;const SQLITE_FLOAT=2;const SQLITE_TEXT=3;const SQLITE_BLOB=4;const SQLITE_NULL=5;const SQLITE_UTF8=1;const SQLITE_TRANSIENT=-1;const SQLITE_DETERMINISTIC=2048;const SQLITE_DIRECTONLY=524288;const INT32_MIN=-2147483648;const INT32_MAX=2147483647;const NULL=0;function isByteArray(value){return value instanceof Uint8Array}function copyByteArray(value){const NodeBuffer=globalThis.Buffer;return NodeBuffer?NodeBuffer.from(value):Uint8Array.from(value)}function emptyByteArray(){const NodeBuffer=globalThis.Buffer;return NodeBuffer?NodeBuffer.alloc(0):new Uint8Array}let temp;const sqlite3={};Module.onRuntimeInitialized=()=>{temp=stackAlloc(8);const v=null;const n="number";const s="string";const n1=[n];const n2=[n,...n1];const n3=[n,...n2];const n4=[n,...n3];const n5=[n,...n4];const signatures={open_v2:[n,[s,n,n,s]],exec:[n,n5],errmsg:[s,n1],prepare_v2:[n,n5],close_v2:[n,n1],finalize:[n,n1],reset:[n,n1],clear_bindings:[n,n1],bind_int:[n,n3],bind_int64:[n,n3],bind_double:[n,n3],bind_text:[n,n5],bind_blob:[n,n5],bind_null:[n,n2],bind_parameter_index:[n,[n,s]],bind_parameter_count:[n,n1],bind_parameter_name:[s,n2],step:[n,n1],column_int64:[n,n2],column_double:[n,n2],column_text:[s,n2],column_blob:[n,n2],column_type:[n,n2],column_name:[s,n2],column_count:[n,n1],column_bytes:[n,n2],column_table_name:[s,n2],column_origin_name:[s,n2],column_database_name:[s,n2],data_count:[n,n1],sql:[s,n1],stmt_readonly:[n,n1],last_insert_rowid:[n,n1],changes:[n,n1],total_changes:[n,n1],create_function_v2:[n,[n,s,n,n,n,n,n,n,n]],value_type:[n,n1],value_text:[s,n1],value_blob:[n,n1],value_int64:[n,n1],value_double:[n,n1],value_bytes:[n,n1],result_double:[v,n2],result_null:[v,n1],result_text:[v,n4],result_blob:[v,n4],result_int:[v,n2],result_int64:[v,n2],result_error:[v,n3],get_autocommit:[n,n1],free:[v,n1],db_filename:[s,[n,s]],backup_init:[n,[n,s,n,s]],backup_step:[n,n2],backup_finish:[n,n1],update_hook:[n,n3],commit_hook:[n,n3],rollback_hook:[n,n3],session_create:[n,[n,s,n]],session_attach:[n,[n,s]],session_enable:[n,n2],session_delete:[v,n1],session_changeset:[n,n3],changeset_apply:[n,[n,n,n,n,n,n]],changeset_invert:[n,n4]};for(const[name,sig]of Object.entries(signatures)){const prefix=/^(session|changeset)_/.test(name)?"sqlite3":"sqlite3_";sqlite3[name]=cwrap(`${prefix}${name}`,sig[0],sig[1])}function arrayToHeap(array){const ptr=_malloc(array.byteLength);HEAPU8.set(array instanceof ArrayBuffer?new Uint8Array(array):array,ptr);return ptr}function stringToHeap(str){const size=lengthBytesUTF8(str)+1;const ptr=_malloc(size);stringToUTF8(str,ptr,size);return ptr}function toNumberOrNot(val){if(typeof val==="bigint"){if(val>=Number.MIN_SAFE_INTEGER&&val<=Number.MAX_SAFE_INTEGER){return Number(val)}return val}return val}const SQLITE_ERROR_NAMES={1:"SQLITE_ERROR",2:"SQLITE_INTERNAL",3:"SQLITE_PERM",4:"SQLITE_ABORT",5:"SQLITE_BUSY",6:"SQLITE_LOCKED",7:"SQLITE_NOMEM",8:"SQLITE_READONLY",9:"SQLITE_INTERRUPT",10:"SQLITE_IOERR",11:"SQLITE_CORRUPT",12:"SQLITE_NOTFOUND",13:"SQLITE_FULL",14:"SQLITE_CANTOPEN",15:"SQLITE_PROTOCOL",16:"SQLITE_EMPTY",17:"SQLITE_SCHEMA",18:"SQLITE_TOOBIG",19:"SQLITE_CONSTRAINT",20:"SQLITE_MISMATCH",21:"SQLITE_MISUSE",23:"SQLITE_AUTH",24:"SQLITE_FORMAT",25:"SQLITE_RANGE",26:"SQLITE_NOTADB",100:"SQLITE_ROW",101:"SQLITE_DONE"};class SqliteError extends Error{constructor(message,code){super(message);this.name="SqliteError";if(typeof code==="number"){this.code=SQLITE_ERROR_NAMES[code&255]||SQLITE_ERROR_NAMES[code]||"SQLITE_ERROR"}else{this.code=code||"SQLITE_ERROR"}}}function resolveBindParams(args){if(args.length===0)return null;if(args.length===1){const arg=args[0];if(arg===undefined||arg===null)return null;if(Array.isArray(arg))return arg;if(typeof arg==="object"&&!isByteArray(arg))return arg;return[arg]}return Array.from(args)}function parseFunctionArgs(argc,argv){const args=[];for(let i=0;i<argc;i++){const ptr=getValue(argv+4*i,"i32");const type=sqlite3.value_type(ptr);switch(type){case SQLITE_INTEGER:args.push(toNumberOrNot(sqlite3.value_int64(ptr)));break;case SQLITE_FLOAT:args.push(sqlite3.value_double(ptr));break;case SQLITE_TEXT:args.push(sqlite3.value_text(ptr));break;case SQLITE_BLOB:{const p=sqlite3.value_blob(ptr);args.push(p!==NULL?copyByteArray(HEAPU8.slice(p,p+sqlite3.value_bytes(ptr))):emptyByteArray());break}case SQLITE_NULL:args.push(null);break}}return args}function setFunctionResult(cx,result){switch(typeof result){case"boolean":sqlite3.result_int(cx,result?1:0);break;case"number":if(Number.isSafeInteger(result)){if(result>=INT32_MIN&&result<=INT32_MAX){sqlite3.result_int(cx,result)}else{sqlite3.result_int64(cx,BigInt(result))}}else{sqlite3.result_double(cx,result)}break;case"bigint":sqlite3.result_int64(cx,result);break;case"string":{const tp=stringToHeap(result);sqlite3.result_text(cx,tp,-1,SQLITE_TRANSIENT);_free(tp);break}case"object":if(result===null){sqlite3.result_null(cx)}else if(isByteArray(result)){const tp=arrayToHeap(result);sqlite3.result_blob(cx,tp,result.byteLength,SQLITE_TRANSIENT);_free(tp)}else{sqlite3.result_error(cx,stringToHeap("unsupported return type"),-1)}break;default:sqlite3.result_null(cx);break}}class Database{constructor(filename,options={}){if(typeof filename!=="string"&&!isByteArray(filename)){throw new TypeError("Expected first argument to be a string")}filename=String(filename);const readonly=!!options.readonly;const fileMustExist=!!options.fileMustExist;let flags;if(readonly){flags=1}else{flags=2;if(!fileMustExist)flags|=4}const rc=sqlite3.open_v2(filename,temp,flags,NULL);this._ptr=getValue(temp,"i32");if(rc!==SQLITE_OK){const msg=this._ptr!==NULL?sqlite3.errmsg(this._ptr):"unable to open database";if(this._ptr!==NULL)sqlite3.close_v2(this._ptr);this._ptr=null;throw new SqliteError(msg)}this._open=true;this._readonly=readonly;this._unsafe=false;this._name=filename;this._statements=new Set;this._functions=new Map;this._sessions=new Set;this._updateHook=0;this._commitHook=0;this._rollbackHook=0;this.exec("PRAGMA busy_timeout = 5000")}unsafeMode(enabled){if(enabled===undefined)enabled=true;this._unsafe=!!enabled;return this}get open(){return this._open}get readonly(){return this._readonly}get name(){return this._name}get inTransaction(){return this._open&&sqlite3.get_autocommit(this._ptr)===0}prepare(source){this._assertOpen();if(typeof source!=="string"){throw new TypeError("Expected first argument to be a string")}const stmt=new Statement(this,source);this._statements.add(stmt);return stmt}exec(sql,{resetStatements=true}={}){this._assertOpen();if(resetStatements){for(const stmt of this._statements){if(!stmt._finalized)sqlite3.reset(stmt._ptr)}}const tp=stringToHeap(sql);try{const rc=sqlite3.exec(this._ptr,tp,NULL,NULL,NULL);if(rc!==SQLITE_OK){throw new SqliteError(sqlite3.errmsg(this._ptr),rc)}}finally{_free(tp)}return this}transaction(fn){if(typeof fn!=="function"){throw new TypeError("Expected first argument to be a function")}const db=this;const wrapTxn=begin=>{const beginStmt=db.prepare(begin);const commitStmt=db.prepare("COMMIT");const rollbackStmt=db.prepare("ROLLBACK");const runner=function(...args){let result;if(db.inTransaction){return fn.apply(this,args)}beginStmt.run();try{result=fn.apply(this,args);commitStmt.run()}catch(err){if(db.inTransaction){rollbackStmt.run()}throw err}return result};return runner};const result=wrapTxn("BEGIN");result.deferred=wrapTxn("BEGIN DEFERRED");result.immediate=wrapTxn("BEGIN IMMEDIATE");result.exclusive=wrapTxn("BEGIN EXCLUSIVE");result.database=db;return result}pragma(source,options){if(typeof source!=="string"){throw new TypeError("Expected first argument to be a string")}const simple=options&&options.simple;const sql=`PRAGMA ${source}`;const stmt=this.prepare(sql);try{if(stmt.reader){return simple?stmt.pluck().get():stmt.all()}else{return stmt.run()}}finally{stmt.finalize()}}function(name,fn,options={}){this._assertOpen();if(typeof name!=="string")throw new TypeError("Expected first argument to be a string");if(typeof fn!=="function")throw new TypeError("Expected second argument to be a function");const deterministic=!!options.deterministic;const directOnly=!!options.directOnly;const varargs=options.varargs||false;if(this._functions.has(name)){removeFunction(this._functions.get(name));this._functions.delete(name)}const wrappedFunc=(cx,argc,argv)=>{const args=parseFunctionArgs(argc,argv);try{const result=fn(...args);setFunctionResult(cx,result)}catch(err){const tp=stringToHeap(err.toString());sqlite3.result_error(cx,tp,-1);_free(tp)}};const funcPtr=addFunction(wrappedFunc,"viii");this._functions.set(name,funcPtr);let eTextRep=SQLITE_UTF8;if(deterministic)eTextRep|=SQLITE_DETERMINISTIC;if(directOnly)eTextRep|=SQLITE_DIRECTONLY;const rc=sqlite3.create_function_v2(this._ptr,name,varargs?-1:fn.length,eTextRep,NULL,funcPtr,NULL,NULL,NULL);if(rc!==SQLITE_OK)throw new SqliteError(sqlite3.errmsg(this._ptr));return this}aggregate(name,options){this._assertOpen();if(typeof name!=="string")throw new TypeError("Expected first argument to be a string");if(!options||typeof options!=="object")throw new TypeError("Expected second argument to be an options object");const step=options.step;const result=options.result||(acc=>acc);const start=options.start;const inverse=options.inverse;const deterministic=!!options.deterministic;const directOnly=!!options.directOnly;const varargs=!!options.varargs;if(typeof step!=="function")throw new TypeError("Expected options.step to be a function");let accumulator;const stepWrapper=(cx,argc,argv)=>{const args=parseFunctionArgs(argc,argv);try{accumulator=step(accumulator,...args)}catch(err){const tp=stringToHeap(err.toString());sqlite3.result_error(cx,tp,-1);_free(tp)}};const finalWrapper=cx=>{try{const val=result(accumulator);setFunctionResult(cx,val)}catch(err){const tp=stringToHeap(err.toString());sqlite3.result_error(cx,tp,-1);_free(tp)}accumulator=typeof start==="function"?start():start};accumulator=typeof start==="function"?start():start;if(this._functions.has(name+"_step")){removeFunction(this._functions.get(name+"_step"));this._functions.delete(name+"_step")}if(this._functions.has(name+"_final")){removeFunction(this._functions.get(name+"_final"));this._functions.delete(name+"_final")}const stepPtr=addFunction(stepWrapper,"viii");const finalPtr=addFunction(finalWrapper,"vi");this._functions.set(name+"_step",stepPtr);this._functions.set(name+"_final",finalPtr);let eTextRep=SQLITE_UTF8;if(deterministic)eTextRep|=SQLITE_DETERMINISTIC;if(directOnly)eTextRep|=SQLITE_DIRECTONLY;const argCount=varargs?-1:step.length-1;const rc=sqlite3.create_function_v2(this._ptr,name,argCount,eTextRep,NULL,NULL,stepPtr,finalPtr,NULL);if(rc!==SQLITE_OK)throw new SqliteError(sqlite3.errmsg(this._ptr));return this}updateHook(fn){this._assertOpen();if(fn!==null&&typeof fn!=="function")throw new TypeError("Expected first argument to be a function or null");const previous=this._updateHook;this._updateHook=fn===null?null:addFunction((_arg,op,databaseName,tableName,rowid)=>{fn(op,UTF8ToString(databaseName),UTF8ToString(tableName),toNumberOrNot(rowid))},"viiiij");sqlite3.update_hook(this._ptr,this._updateHook??NULL,NULL);if(previous)removeFunction(previous);return this}commitHook(fn){this._assertOpen();if(fn!==null&&typeof fn!=="function")throw new TypeError("Expected first argument to be a function or null");const previous=this._commitHook;this._commitHook=fn===null?null:addFunction(()=>fn(),"ii");sqlite3.commit_hook(this._ptr,this._commitHook??NULL,NULL);if(previous)removeFunction(previous);return this}rollbackHook(fn){this._assertOpen();if(fn!==null&&typeof fn!=="function")throw new TypeError("Expected first argument to be a function or null");const previous=this._rollbackHook;this._rollbackHook=fn===null?null:addFunction(()=>fn(),"vi");sqlite3.rollback_hook(this._ptr,this._rollbackHook??NULL,NULL);if(previous)removeFunction(previous);return this}filename(databaseName="main"){this._assertOpen();return sqlite3.db_filename(this._ptr,databaseName)}backupTo(destination,sourceName="main",destinationName="main"){this._assertOpen();destination._assertOpen();const backup=sqlite3.backup_init(destination._ptr,destinationName,this._ptr,sourceName);if(!backup)throw new SqliteError(sqlite3.errmsg(destination._ptr));sqlite3.backup_step(backup,-1);const finish=sqlite3.backup_finish(backup);if(finish!==SQLITE_OK){throw new SqliteError(sqlite3.errmsg(destination._ptr),finish)}}createSession(databaseName="main"){this._assertOpen();const rc=sqlite3.session_create(this._ptr,databaseName,temp);if(rc!==SQLITE_OK)throw new SqliteError(sqlite3.errmsg(this._ptr),rc);const pointer=getValue(temp,"i32");const database=this;let closed=false;const check=()=>{database._assertOpen();if(closed)throw new SqliteError("The session is closed",21)};const session={attach(table=null){check();const result=sqlite3.session_attach(pointer,table);if(result!==SQLITE_OK)throw new SqliteError(sqlite3.errmsg(database._ptr),result)},enable(enabled){check();sqlite3.session_enable(pointer,enabled?1:0)},changeset(){check();const output=_malloc(8);try{const result=sqlite3.session_changeset(pointer,output,output+4);if(result!==SQLITE_OK)throw new SqliteError(sqlite3.errmsg(database._ptr),result);const size=getValue(output,"i32");const buffer=getValue(output+4,"i32");try{return HEAPU8.slice(buffer,buffer+size)}finally{sqlite3.free(buffer)}}finally{_free(output)}},close(){if(closed)return;sqlite3.session_delete(pointer);closed=true;database._sessions.delete(session)}};this._sessions.add(session);return session}applyChangeset(changeset,onConflict=(()=>2)){this._assertOpen();const input=arrayToHeap(changeset);const conflict=addFunction((context,reason)=>onConflict(reason),"iiii");try{const rc=sqlite3.changeset_apply(this._ptr,changeset.byteLength,input,NULL,conflict,NULL);if(rc!==SQLITE_OK)throw new SqliteError(sqlite3.errmsg(this._ptr),rc)}finally{removeFunction(conflict);_free(input)}}invertChangeset(changeset){this._assertOpen();const input=arrayToHeap(changeset);const output=_malloc(8);try{const rc=sqlite3.changeset_invert(changeset.byteLength,input,output,output+4);if(rc!==SQLITE_OK)throw new SqliteError(sqlite3.errmsg(this._ptr),rc);const size=getValue(output,"i32");const buffer=getValue(output+4,"i32");try{return HEAPU8.slice(buffer,buffer+size)}finally{sqlite3.free(buffer)}}finally{_free(output);_free(input)}}close(){if(!this._open)return;for(const session of this._sessions)session.close();this.updateHook(null);this.commitHook(null);this.rollbackHook(null);for(const stmt of this._statements){if(!stmt._finalized){sqlite3.finalize(stmt._ptr);stmt._finalized=true}}this._statements.clear();for(const func of this._functions.values()){removeFunction(func)}this._functions.clear();if(this._updateHook){sqlite3.update_hook(this._ptr,NULL,NULL);removeFunction(this._updateHook);this._updateHook=null}const rc=sqlite3.close_v2(this._ptr);if(rc!==SQLITE_OK){throw new SqliteError(sqlite3.errmsg(this._ptr))}this._ptr=null;this._open=false}_assertOpen(){if(!this._open)throw new SqliteError("The database connection is not open")}_handleError(rc){if(rc!==SQLITE_OK){throw new SqliteError(sqlite3.errmsg(this._ptr),rc)}}}class Statement{constructor(db,source){this._db=db;this._source=source;this._finalized=false;this._pluck=false;this._expand=false;this._raw=false;this._bound=false;this._numbersAsDoubles=false;const tp=stringToHeap(source);try{const rc=sqlite3.prepare_v2(db._ptr,tp,-1,temp,NULL);if(rc!==SQLITE_OK){throw new SqliteError(sqlite3.errmsg(db._ptr),rc)}}finally{_free(tp)}this._ptr=getValue(temp,"i32");if(this._ptr===NULL){throw new SqliteError("Nothing to prepare")}this._columnCount=sqlite3.column_count(this._ptr);this._reader=this._columnCount>0;this._readonly=!!sqlite3.stmt_readonly(this._ptr)}get source(){return this._source}get reader(){return this._reader}get readonly(){return this._readonly}get parameterCount(){this._assertReady();return sqlite3.bind_parameter_count(this._ptr)}numbersAsDoubles(toggle=true){this._numbersAsDoubles=toggle;return this}finalize(){if(this._finalized)return;sqlite3.finalize(this._ptr);this._finalized=true;this._ptr=null;this._db._statements.delete(this)}run(...args){this._assertReady();const params=resolveBindParams(args);this._reset();if(params)this._bind(params);this._step();const result={changes:sqlite3.changes(this._db._ptr),lastInsertRowid:toNumberOrNot(sqlite3.last_insert_rowid(this._db._ptr))};sqlite3.reset(this._ptr);return result}get(...args){this._assertReady();const params=resolveBindParams(args);this._reset();if(params)this._bind(params);if(!this._step()){sqlite3.reset(this._ptr);return undefined}const row=this._getRow();sqlite3.reset(this._ptr);return row}all(...args){this._assertReady();const params=resolveBindParams(args);this._reset();if(params)this._bind(params);const rows=[];while(this._step()){rows.push(this._getRow());if(rows.length===1e5){console.warn(`[bedrock-sqlite] all() returned 100k rows, query: ${this._source.slice(0,200)}`)}if(rows.length>=1e7){sqlite3.reset(this._ptr);throw new SqliteError(`all() exceeded 10M row safety limit, likely infinite loop. query: ${this._source.slice(0,200)}`)}}sqlite3.reset(this._ptr);return rows}*iterate(...args){this._assertReady();const params=resolveBindParams(args);this._reset();if(params)this._bind(params);while(this._step()){yield this._getRow()}}pluck(toggle=true){this._pluck=toggle;this._raw=false;this._expand=false;return this}expand(toggle=true){this._expand=toggle;this._pluck=false;this._raw=false;return this}raw(toggle=true){this._raw=toggle;this._pluck=false;this._expand=false;return this}columns(){this._assertReady();const cols=[];for(let i=0;i<this._columnCount;i++){cols.push({name:sqlite3.column_name(this._ptr,i),column:sqlite3.column_origin_name(this._ptr,i),table:sqlite3.column_table_name(this._ptr,i),database:sqlite3.column_database_name(this._ptr,i),type:null})}return cols}scanStatusV2(){return[]}scanStatusReset(){}safeIntegers(){return this}bind(...args){this._assertReady();const params=resolveBindParams(args);this._reset();if(params)this._bind(params);this._bound=true;return this}_reset(){sqlite3.clear_bindings(this._ptr);sqlite3.reset(this._ptr)}_step(){const rc=sqlite3.step(this._ptr);if(rc===SQLITE_ROW)return true;if(rc===SQLITE_DONE)return false;sqlite3.reset(this._ptr);throw new SqliteError(sqlite3.errmsg(this._db._ptr),rc)}_getRow(){if(this._pluck){return this._getColumnValue(0)}if(this._raw){const row=[];for(let i=0;i<this._columnCount;i++){row.push(this._getColumnValue(i))}return row}if(this._expand){const row={};for(let i=0;i<this._columnCount;i++){let table=sqlite3.column_table_name(this._ptr,i);table=table===""||table===null?"$":table;const name=sqlite3.column_name(this._ptr,i);if(!row[table])row[table]={};row[table][name]=this._getColumnValue(i)}return row}const row={};for(let i=0;i<this._columnCount;i++){row[sqlite3.column_name(this._ptr,i)]=this._getColumnValue(i)}return row}_getColumnValue(i){const type=sqlite3.column_type(this._ptr,i);switch(type){case SQLITE_INTEGER:return toNumberOrNot(sqlite3.column_int64(this._ptr,i));case SQLITE_FLOAT:return sqlite3.column_double(this._ptr,i);case SQLITE_TEXT:return sqlite3.column_text(this._ptr,i);case SQLITE_BLOB:{const p=sqlite3.column_blob(this._ptr,i);if(p!==NULL){const nbytes=sqlite3.column_bytes(this._ptr,i);if(nbytes>104857600){throw new SqliteError(`blob column ${i} has unreasonable size: ${nbytes} bytes`)}return copyByteArray(HEAPU8.slice(p,p+nbytes))}return emptyByteArray()}case SQLITE_NULL:return null;default:return null}}_bind(params){if(Array.isArray(params)){for(let i=0;i<params.length;i++){this._bindValue(params[i],i+1)}}else if(typeof params==="object"){const count=sqlite3.bind_parameter_count(this._ptr);for(let i=1;i<=count;i++){const pname=sqlite3.bind_parameter_name(this._ptr,i);if(!pname)continue;const stripped=pname.slice(1);const value=pname in params?params[pname]:stripped in params?params[stripped]:undefined;if(value!==undefined){this._bindValue(value,i)}}}}_bindValue(value,position){let rc;switch(typeof value){case"string":{const tp=stringToHeap(value);rc=sqlite3.bind_text(this._ptr,position,tp,-1,SQLITE_TRANSIENT);_free(tp);break}case"number":if(!this._numbersAsDoubles&&Number.isSafeInteger(value)){if(value>=INT32_MIN&&value<=INT32_MAX){rc=sqlite3.bind_int(this._ptr,position,value)}else{rc=sqlite3.bind_int64(this._ptr,position,BigInt(value))}}else{rc=sqlite3.bind_double(this._ptr,position,value)}break;case"bigint":rc=sqlite3.bind_int64(this._ptr,position,value);break;case"boolean":rc=sqlite3.bind_int(this._ptr,position,value?1:0);break;case"object":if(value===null){rc=sqlite3.bind_null(this._ptr,position)}else if(isByteArray(value)){const tp=arrayToHeap(value);rc=sqlite3.bind_blob(this._ptr,position,tp,value.byteLength,SQLITE_TRANSIENT);_free(tp)}else{throw new SqliteError(`Unsupported binding type at position ${position}`)}break;default:if(value===undefined){rc=sqlite3.bind_null(this._ptr,position)}else{throw new SqliteError(`Unsupported binding type: ${typeof value}`)}}if(rc!==SQLITE_OK){throw new SqliteError(sqlite3.errmsg(this._db._ptr))}}_assertReady(){if(this._finalized)throw new SqliteError("This statement has been finalized");if(!this._db._open)throw new SqliteError("The database connection is not open")}}Module.Database=Database;Module.SqliteError=SqliteError};const path=require("node:path");const crypto=require("node:crypto");const SQLITE_CANTOPEN=14;const SQLITE_IOERR_READ=266;const SQLITE_IOERR_SHORT_READ=522;const SQLITE_IOERR_FSYNC=1034;const SQLITE_IOERR_WRITE=778;const SQLITE_IOERR_DELETE=2570;const SQLITE_IOERR_CLOSE=4106;const SQLITE_IOERR_TRUNCATE=1546;const SQLITE_IOERR_FSTAT=1802;const SQLITE_OPEN_READONLY=1;const SQLITE_OPEN_READWRITE=2;const SQLITE_OPEN_CREATE=4;const SQLITE_OPEN_EXCLUSIVE=16;const SQLITE_ACCESS_READWRITE=1;const SQLITE_ACCESS_READ=2;const SQLITE_LOCK_NONE=0;const SQLITE_LOCK_SHARED=1;const SQLITE_LOCK_RESERVED=2;const SQLITE_LOCK_EXCLUSIVE=4;const SQLITE_BUSY=5;function _fd(fileInfo){return getValue(fileInfo+4,"i32")}function _setLocked(fileInfo,locked){setValue(fileInfo+8,locked?1:0,"i32")}function _path(fileInfo){return UTF8ToString(getValue(fileInfo+12,"i32"))}function _safeInt(bigInt){if(bigInt<Number.MIN_SAFE_INTEGER||bigInt>Number.MAX_SAFE_INTEGER)throw 0;return Number(bigInt)}var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var _scriptName;if(typeof __filename!="undefined"){_scriptName=__filename}else{}var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");scriptDirectory=__dirname+"/";readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(process.argv.length>1){thisProgram=process.argv[1].replace(/\\/g,"/")}arguments_=process.argv.slice(2);if(typeof module!="undefined"){module["exports"]=Module}quit_=(status,toThrow)=>{process.exitCode=status;throw toThrow}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var EXITSTATUS;var isFileURI=filename=>filename.startsWith("file://");var runtimeInitialized=false;function updateMemoryViews(){var b=wasmMemory.buffer;HEAP8=new Int8Array(b);HEAP16=new Int16Array(b);HEAPU8=new Uint8Array(b);HEAPU16=new Uint16Array(b);HEAP32=new Int32Array(b);HEAPU32=new Uint32Array(b);HEAPF32=new Float32Array(b);HEAPF64=new Float64Array(b);HEAP64=new BigInt64Array(b);HEAPU64=new BigUint64Array(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;wasmExports["E"]()}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(onPostRuns)}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);throw e}var wasmBinaryFile;function findWasmBinary(){return locateFile("sqlite3.wasm")}function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw'sync fetching of the wasm failed: you can preload it to Module["wasmBinary"] manually, or emcc.py will do that for you when generating HTML (but not JS)'}function instantiateSync(file,info){var module;var binary=getBinarySync(file);module=new WebAssembly.Module(binary);var instance=new WebAssembly.Instance(module,info);return[instance,module]}function getWasmImports(){var imports={a:wasmImports};return imports}function createWasm(){function receiveInstance(instance,module){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}var info=getWasmImports();if(Module["instantiateWasm"]){return new Promise((resolve,reject)=>{Module["instantiateWasm"](info,(inst,mod)=>{resolve(receiveInstance(inst,mod))})})}wasmBinaryFile??=findWasmBinary();var result=instantiateSync(wasmBinaryFile,info);return receiveInstance(result[0])}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var HEAP16;var HEAP32;var HEAP64;var HEAP8;var HEAPF32;var HEAPF64;var HEAPU16;var HEAPU32;var HEAPU64;var HEAPU8;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":return HEAP64[ptr>>3];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":HEAP64[ptr>>3]=BigInt(value);break;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=globalThis.TextDecoder&&new TextDecoder;var findStringEnd=(heapOrArray,idx,maxBytesToRead,ignoreNul)=>{var maxIdx=idx+maxBytesToRead;if(ignoreNul)return maxIdx;while(heapOrArray[idx]&&!(idx>=maxIdx))++idx;return idx};var UTF8ArrayToString=(heapOrArray,idx=0,maxBytesToRead,ignoreNul)=>{var endPtr=findStringEnd(heapOrArray,idx,maxBytesToRead,ignoreNul);if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr))}var str="";while(idx<endPtr){var u0=heapOrArray[idx++];if(!(u0&128)){str+=String.fromCharCode(u0);continue}var u1=heapOrArray[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=heapOrArray[idx++]&63;if((u0&240)==224){u0=(u0&15)<<12|u1<<6|u2}else{u0=(u0&7)<<18|u1<<12|u2<<6|heapOrArray[idx++]&63}if(u0<65536){str+=String.fromCharCode(u0)}else{var ch=u0-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}return str};var UTF8ToString=(ptr,maxBytesToRead,ignoreNul)=>ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead,ignoreNul):"";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 __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};var INT53_MAX=9007199254740992;var INT53_MIN=-9007199254740992;var bigintToI53Checked=num=>num<INT53_MIN||num>INT53_MAX?NaN:Number(num);function __localtime_js(time,tmPtr){time=bigintToI53Checked(time);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}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{return func()}catch(e){handleException(e)}finally{maybeExit()}};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 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.codePointAt(i);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;i++}}heap[outIdx]=0;return outIdx-startIdx};var stringToUTF8=(str,outPtr,maxBytesToWrite)=>stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite);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=()=>536870912;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+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};function _nodejsAccess(vfs,filePath,flags,outResult){let aflags=fs.constants.F_OK;if(flags==SQLITE_ACCESS_READWRITE)aflags=fs.constants.R_OK|fs.constants.W_OK;if(flags==SQLITE_ACCESS_READ)aflags=fs.constants.R_OK;try{fs.accessSync(UTF8ToString(filePath),aflags);setValue(outResult,1,"i32")}catch{setValue(outResult,0,"i32")}return SQLITE_OK}var _fileLocks={};function _nodejsCheckReservedLock(fi,outResult){var filePath=_path(fi);var holders=_fileLocks[filePath];var reserved=0;if(holders){for(var[other,otherLevel]of holders){if(other!==fi&&otherLevel>=SQLITE_LOCK_RESERVED){reserved=1;break}}}setValue(outResult,reserved,"i32");return SQLITE_OK}function _nodejsClose(fi){_nodejsUnlock(fi,SQLITE_LOCK_NONE);try{fs.closeSync(_fd(fi))}catch{return SQLITE_IOERR_CLOSE}return SQLITE_OK}function _nodejsDelete(vfs,filePath,dirSync){const pathStr=UTF8ToString(filePath);try{fs.unlinkSync(pathStr)}catch(err){if(err.code!="ENOENT")return SQLITE_IOERR_DELETE}if(dirSync){let fd=-1;try{fd=fs.openSync(path.dirname(pathStr),"r");fs.fsyncSync(fd)}catch{return SQLITE_IOERR_FSYNC}finally{try{fs.closeSync(fd)}catch{return SQLITE_IOERR_FSYNC}}}return SQLITE_OK}function _nodejsFileSize(fi,outSize){try{setValue(outSize,fs.fstatSync(_fd(fi)).size,"i64")}catch{return SQLITE_IOERR_FSTAT}return SQLITE_OK}function _nodejsFullPathname(vfs,relPath,sizeFullPath,outFullPath){const full=path.resolve(UTF8ToString(relPath));stringToUTF8(full,outFullPath,sizeFullPath);return full.length<sizeFullPath?SQLITE_OK:SQLITE_CANTOPEN}function _nodejsLock(fi,level){var filePath=_path(fi);if(!_fileLocks[filePath])_fileLocks[filePath]=new Map;var holders=_fileLocks[filePath];var myLevel=holders.get(fi)||SQLITE_LOCK_NONE;if(level>=SQLITE_LOCK_RESERVED&&myLevel<SQLITE_LOCK_RESERVED){for(var[other,otherLevel]of holders){if(other!==fi&&otherLevel>=SQLITE_LOCK_RESERVED){return SQLITE_BUSY}}}if(level>=SQLITE_LOCK_EXCLUSIVE&&myLevel<SQLITE_LOCK_EXCLUSIVE){for(var[other,otherLevel]of holders){if(other!==fi&&otherLevel>=SQLITE_LOCK_SHARED){return SQLITE_BUSY}}}holders.set(fi,level);if(level>SQLITE_LOCK_NONE)_setLocked(fi,true);return SQLITE_OK}function _nodejsRandomness(vfs,bytes,outBuffer){const buf=HEAPU8.subarray(outBuffer,outBuffer+bytes);crypto.randomFillSync(buf);return bytes}function _nodejsRead(fi,outBuffer,bytes,offset){const buf=HEAPU8.subarray(outBuffer,outBuffer+bytes);let bytesRead;try{bytesRead=fs.readSync(_fd(fi),buf,0,bytes,_safeInt(offset))}catch{return SQLITE_IOERR_READ}if(bytesRead==bytes){return SQLITE_OK}else if(bytesRead>=0){if(bytesRead<bytes){try{buf.fill(0,bytesRead)}catch{return SQLITE_IOERR_READ}}return SQLITE_IOERR_SHORT_READ}return SQLITE_IOERR_READ}function _nodejsShmBarrier(fi){var filePath=_path(fi);var reg=_shmRegistry[filePath];if(!reg||reg._hasExclusiveLock)return;var shmPath=filePath+"-shm";var stat;try{stat=fs.statSync(shmPath)}catch(e){return}if(reg._lastShmWrite&&stat.mtimeMs<=reg._lastShmWrite)return;var fd;try{fd=fs.openSync(shmPath,fs.constants.O_RDONLY)}catch(e){return}for(var pgno in reg){if(typeof reg[pgno]!=="object"||!reg[pgno].ptr)continue;var r=reg[pgno];try{fs.readSync(fd,HEAPU8.subarray(r.ptr,r.ptr+r.pgsz),0,r.pgsz,Number(pgno)*r.pgsz)}catch(e){}}fs.closeSync(fd);reg._lastShmWrite=stat.mtimeMs}function _nodejsShmLock(fi,offset,n,flags){var filePath=_path(fi);if(!_shmRegistry[filePath])_shmRegistry[filePath]={};var reg=_shmRegistry[filePath];if(flags&2&&flags&8){reg._hasExclusiveLock=true}if(flags&1&&flags&8&&reg._hasExclusiveLock){var shmPath=filePath+"-shm";var fd;try{fd=fs.openSync(shmPath,fs.constants.O_RDWR|fs.constants.O_CREAT,420)}catch(e){reg._hasExclusiveLock=false;return SQLITE_OK}for(var pgno in reg){if(typeof reg[pgno]!=="object"||!reg[pgno].ptr)continue;var r=reg[pgno];try{fs.writeSync(fd,HEAPU8.subarray(r.ptr,r.ptr+r.pgsz),0,r.pgsz,Number(pgno)*r.pgsz)}catch(e){}}try{fs.fsyncSync(fd)}catch(e){}try{reg._lastShmWrite=fs.fstatSync(fd).mtimeMs}catch(e){reg._lastShmWrite=Date.now()}fs.closeSync(fd);reg._hasExclusiveLock=false}return SQLITE_OK}var _shmRegistry={};function _nodejsShmMap(fi,pgno,pgsz,isWrite,ppOut){var filePath=_path(fi);if(!_shmRegistry[filePath])_shmRegistry[filePath]={};var regions=_shmRegistry[filePath];if(!(pgno in regions)||typeof regions[pgno]!=="object"){if(!isWrite){setValue(ppOut,0,"*");return SQLITE_OK}var buf=_malloc(pgsz);HEAPU8.fill(0,buf,buf+pgsz);regions[pgno]={ptr:buf,pgsz}}setValue(ppOut,regions[pgno].ptr,"*");return SQLITE_OK}function _nodejsShmUnmap(fi,deleteFlag){if(deleteFlag){var filePath=_path(fi);var regions=_shmRegistry[filePath];if(regions){for(var pgno in regions){if(typeof regions[pgno]==="object"&&regions[pgno].ptr)_free(regions[pgno].ptr)}delete _shmRegistry[filePath]}}return SQLITE_OK}function _nodejsSleep(vfs,nMicro){var ms=Math.max(1,Math.floor(nMicro/1e3));var sab=new SharedArrayBuffer(4);Atomics.wait(new Int32Array(sab),0,0,ms);return nMicro}function _nodejsSync(fi,flags){try{fs.fsyncSync(_fd(fi))}catch{return SQLITE_IOERR_FSYNC}return SQLITE_OK}function _nodejsTruncate(fi,size){try{fs.ftruncateSync(_fd(fi),_safeInt(size))}catch{return SQLITE_IOERR_TRUNCATE}return SQLITE_OK}function _nodejsUnlock(fi,level){var filePath=_path(fi);var holders=_fileLocks[filePath];if(holders){if(level==SQLITE_LOCK_NONE){holders.delete(fi);_setLocked(fi,false)}else{holders.set(fi,level)}}else{if(level==SQLITE_LOCK_NONE)_setLocked(fi,false)}return SQLITE_OK}function _nodejsWrite(fi,buffer,bytes,offset){try{const bytesWritten=fs.writeSync(_fd(fi),HEAPU8.subarray(buffer,buffer+bytes),0,bytes,_safeInt(offset));return bytesWritten!=bytes?SQLITE_IOERR_WRITE:SQLITE_OK}catch{return SQLITE_IOERR_WRITE}}function _nodejs_max_path_length(){return process.platform=="win32"?260:4096}function _nodejs_open(filePath,flags,mode){let oflags=0;if(flags&SQLITE_OPEN_EXCLUSIVE)oflags|=fs.constants.O_EXCL;if(flags&SQLITE_OPEN_CREATE)oflags|=fs.constants.O_CREAT;if(flags&SQLITE_OPEN_READONLY)oflags|=fs.constants.O_RDONLY;if(flags&SQLITE_OPEN_READWRITE)oflags|=fs.constants.O_RDWR;try{return fs.openSync(UTF8ToString(filePath),oflags,mode)}catch{return-1}}var getCFunc=ident=>{var func=Module["_"+ident];return func};var writeArrayToMemory=(array,buffer)=>{HEAP8.set(array,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 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 wasmTableMirror=[];var getWasmTableEntry=funcPtr=>{var func=wasmTableMirror[funcPtr];if(!func){wasmTableMirror[funcPtr]=func=wasmTable.get(funcPtr)}return func};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()}return wasmTable["grow"](1)};var setWasmTableEntry=(idx,func)=>{wasmTable.set(idx,func);wasmTableMirror[idx]=wasmTable.get(idx)};var uleb128EncodeWithLen=arr=>{const n=arr.length;return[n%128|128,n>>7,...arr]};var wasmTypeCodes={i:127,p:127,j:126,f:125,d:124,e:111};var generateTypePack=types=>uleb128EncodeWithLen(Array.from(types,type=>{var code=wasmTypeCodes[type];return code}));var convertJsFunctionToWasm=(func,sig)=>{var bytes=Uint8Array.of(0,97,115,109,1,0,0,0,1,...uleb128EncodeWithLen([1,96,...generateTypePack(sig.slice(1)),...generateTypePack(sig[0]==="v"?"":sig[0])]),2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0);var module=new WebAssembly.Module(bytes);var instance=new WebAssembly.Instance(module,{e:{f:func}});var wrappedFunc=instance.exports["f"];return wrappedFunc};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 removeFunction=index=>{functionsInTableMap.delete(getWasmTableEntry(index));setWasmTableEntry(index,null);freeTableIndexes.push(index)};{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];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"];if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].shift()()}}}Module["cwrap"]=cwrap;Module["addFunction"]=addFunction;Module["removeFunction"]=removeFunction;var _sqlite3_free,_sqlite3_prepare_v2,_sqlite3_step,_sqlite3_column_int64,_sqlite3_reset,_sqlite3_exec,_sqlite3_finalize,_sqlite3_backup_init,_sqlite3_backup_step,_sqlite3_backup_finish,_sqlite3_clear_bindings,_sqlite3_value_blob,_sqlite3_value_text,_sqlite3_value_bytes,_sqlite3_value_double,_sqlite3_value_int64,_sqlite3_value_type,_sqlite3_result_blob,_sqlite3_result_double,_sqlite3_result_error,_sqlite3_result_int,_sqlite3_result_int64,_sqlite3_result_null,_sqlite3_result_text,_sqlite3_column_count,_sqlite3_data_count,_sqlite3_column_blob,_sqlite3_column_bytes,_sqlite3_column_double,_sqlite3_column_text,_sqlite3_column_type,_sqlite3_column_name,_sqlite3_column_database_name,_sqlite3_column_table_name,_sqlite3_column_origin_name,_sqlite3_bind_blob,_sqlite3_bind_double,_sqlite3_bind_int,_sqlite3_bind_int64,_sqlite3_bind_null,_sqlite3_bind_text,_sqlite3_bind_parameter_count,_sqlite3_bind_parameter_name,_sqlite3_bind_parameter_index,_sqlite3_stmt_readonly,_sqlite3_sql,_sqlite3_errmsg,_sqlite3_last_insert_rowid,_sqlite3_changes,_sqlite3_total_changes,_sqlite3_close_v2,_sqlite3_create_function_v2,_sqlite3_commit_hook,_sqlite3_update_hook,_sqlite3_rollback_hook,_sqlite3_open_v2,_sqlite3_get_autocommit,_sqlite3_db_filename,_sqlite3session_create,_sqlite3session_delete,_sqlite3session_attach,_sqlite3session_changeset,_sqlite3session_enable,_sqlite3changeset_invert,_sqlite3changeset_apply,_malloc,_free,__emscripten_timeout,__emscripten_stack_restore,__emscripten_stack_alloc,_emscripten_stack_get_current,memory,__indirect_function_table,wasmMemory,wasmTable;function assignWasmExports(wasmExports){_sqlite3_free=Module["_sqlite3_free"]=wasmExports["F"];_sqlite3_prepare_v2=Module["_sqlite3_prepare_v2"]=wasmExports["G"];_sqlite3_step=Module["_sqlite3_step"]=wasmExports["H"];_sqlite3_column_int64=Module["_sqlite3_column_int64"]=wasmExports["I"];_sqlite3_reset=Module["_sqlite3_reset"]=wasmExports["J"];_sqlite3_exec=Module["_sqlite3_exec"]=wasmExports["K"];_sqlite3_finalize=Module["_sqlite3_finalize"]=wasmExports["L"];_sqlite3_backup_init=Module["_sqlite3_backup_init"]=wasmExports["M"];_sqlite3_backup_step=Module["_sqlite3_backup_step"]=wasmExports["N"];_sqlite3_backup_finish=Module["_sqlite3_backup_finish"]=wasmExports["O"];_sqlite3_clear_bindings=Module["_sqlite3_clear_bindings"]=wasmExports["P"];_sqlite3_value_blob=Module["_sqlite3_value_blob"]=wasmExports["Q"];_sqlite3_value_text=Module["_sqlite3_value_text"]=wasmExports["R"];_sqlite3_value_bytes=Module["_sqlite3_value_bytes"]=wasmExports["S"];_sqlite3_value_double=Module["_sqlite3_value_double"]=wasmExports["T"];_sqlite3_value_int64=Module["_sqlite3_value_int64"]=wasmExports["U"];_sqlite3_value_type=Module["_sqlite3_value_type"]=wasmExports["V"];_sqlite3_result_blob=Module["_sqlite3_result_blob"]=wasmExports["W"];_sqlite3_result_double=Module["_sqlite3_result_double"]=wasmExports["X"];_sqlite3_result_error=Module["_sqlite3_result_error"]=wasmExports["Y"];_sqlite3_result_int=Module["_sqlite3_result_int"]=wasmExports["Z"];_sqlite3_result_int64=Module["_sqlite3_result_int64"]=wasmExports["_"];_sqlite3_result_null=Module["_sqlite3_result_null"]=wasmExports["$"];_sqlite3_result_text=Module["_sqlite3_result_text"]=wasmExports["aa"];_sqlite3_column_count=Module["_sqlite3_column_count"]=wasmExports["ba"];_sqlite3_data_count=Module["_sqlite3_data_count"]=wasmExports["ca"];_sqlite3_column_blob=Module["_sqlite3_column_blob"]=wasmExports["da"];_sqlite3_column_bytes=Module["_sqlite3_column_bytes"]=wasmExports["ea"];_sqlite3_column_double=Module["_sqlite3_column_double"]=wasmExports["fa"];_sqlite3_column_text=Module["_sqlite3_column_text"]=wasmExports["ga"];_sqlite3_column_type=Module["_sqlite3_column_type"]=wasmExports["ha"];_sqlite3_column_name=Module["_sqlite3_column_name"]=wasmExports["ia"];_sqlite3_column_database_name=Module["_sqlite3_column_database_name"]=wasmExports["ja"];_sqlite3_column_table_name=Module["_sqlite3_column_table_name"]=wasmExports["ka"];_sqlite3_column_origin_name=Module["_sqlite3_column_origin_name"]=wasmExports["la"];_sqlite3_bind_blob=Module["_sqlite3_bind_blob"]=wasmExports["ma"];_sqlite3_bind_double=Module["_sqlite3_bind_double"]=wasmExports["na"];_sqlite3_bind_int=Module["_sqlite3_bind_int"]=wasmExports["oa"];_sqlite3_bind_int64=Module["_sqlite3_bind_int64"]=wasmExports["pa"];_sqlite3_bind_null=Module["_sqlite3_bind_null"]=wasmExports["qa"];_sqlite3_bind_text=Module["_sqlite3_bind_text"]=wasmExports["ra"];_sqlite3_bind_parameter_count=Module["_sqlite3_bind_parameter_count"]=wasmExports["sa"];_sqlite3_bind_parameter_name=Module["_sqlite3_bind_parameter_name"]=wasmExports["ta"];_sqlite3_bind_parameter_index=Module["_sqlite3_bind_parameter_index"]=wasmExports["ua"];_sqlite3_stmt_readonly=Module["_sqlite3_stmt_readonly"]=wasmExports["va"];_sqlite3_sql=Module["_sqlite3_sql"]=wasmExports["wa"];_sqlite3_errmsg=Module["_sqlite3_errmsg"]=wasmExports["xa"];_sqlite3_last_insert_rowid=Module["_sqlite3_last_insert_rowid"]=wasmExports["ya"];_sqlite3_changes=Module["_sqlite3_changes"]=wasmExports["za"];_sqlite3_total_changes=Module["_sqlite3_total_changes"]=wasmExports["Aa"];_sqlite3_close_v2=Module["_sqlite3_close_v2"]=wasmExports["Ba"];_sqlite3_create_function_v2=Module["_sqlite3_create_function_v2"]=wasmExports["Ca"];_sqlite3_commit_hook=Module["_sqlite3_commit_hook"]=wasmExports["Da"];_sqlite3_update_hook=Module["_sqlite3_update_hook"]=wasmExports["Ea"];_sqlite3_rollback_hook=Module["_sqlite3_rollback_hook"]=wasmExports["Fa"];_sqlite3_open_v2=Module["_sqlite3_open_v2"]=wasmExports["Ga"];_sqlite3_get_autocommit=Module["_sqlite3_get_autocommit"]=wasmExports["Ha"];_sqlite3_db_filename=Module["_sqlite3_db_filename"]=wasmExports["Ia"];_sqlite3session_create=Module["_sqlite3session_create"]=wasmExports["Ja"];_sqlite3session_delete=Module["_sqlite3session_delete"]=wasmExports["Ka"];_sqlite3session_attach=Module["_sqlite3session_attach"]=wasmExports["La"];_sqlite3session_changeset=Module["_sqlite3session_changeset"]=wasmExports["Ma"];_sqlite3session_enable=Module["_sqlite3session_enable"]=wasmExports["Na"];_sqlite3changeset_invert=Module["_sqlite3changeset_invert"]=wasmExports["Oa"];_sqlite3changeset_apply=Module["_sqlite3changeset_apply"]=wasmExports["Pa"];_malloc=Module["_malloc"]=wasmExports["Qa"];_free=Module["_free"]=wasmExports["Ra"];__emscripten_timeout=wasmExports["Ta"];__emscripten_stack_restore=wasmExports["Ua"];__emscripten_stack_alloc=wasmExports["Va"];_emscripten_stack_get_current=wasmExports["Wa"];memory=wasmMemory=wasmExports["D"];__indirect_function_table=wasmTable=wasmExports["Sa"]}var wasmImports={a:___assert_fail,p:__abort_js,j:__emscripten_runtime_keepalive_clear,m:__localtime_js,k:__setitimer_js,n:__tzset_js,o:_emscripten_date_now,l:_emscripten_resize_heap,B:_nodejsAccess,w:_nodejsCheckReservedLock,e:_nodejsClose,C:_nodejsDelete,z:_nodejsFileSize,q:_nodejsFullPathname,y:_nodejsLock,h:_nodejsRandomness,d:_nodejsRead,t:_nodejsShmBarrier,u:_nodejsShmLock,v:_nodejsShmMap,s:_nodejsShmUnmap,g:_nodejsSleep,A:_nodejsSync,b:_nodejsTruncate,x:_nodejsUnlock,c:_nodejsWrite,f:_nodejs_max_path_length,r:_nodejs_open,i:_proc_exit};function run(){preRun();function doRun(){Module["calledRun"]=true;if(ABORT)return;initRuntime();Module["onRuntimeInitialized"]?.();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(()=>{setTimeout(()=>Module["setStatus"](""),1);doRun()},1)}else{doRun()}}var wasmExports;wasmExports=createWasm();run();
package/dist/sqlite3.wasm CHANGED
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bedrock-sqlite",
3
- "version": "0.16.20",
3
+ "version": "0.16.21",
4
4
  "description": "WASM build of SQLite (bedrock branch) with better-sqlite3 compatible API. Supports BEGIN CONCURRENT and WAL2.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -30,7 +30,10 @@
30
30
  "bedrock-sqlite.d.ts",
31
31
  "bedrock-sqlite-async.d.ts",
32
32
  "bedrock-sqlite-browser.d.ts",
33
- "LICENSE.sqlite-vec"
33
+ "LICENSE.sqlite-vec",
34
+ "LICENSE.lexbor",
35
+ "LICENSE.fts5-tokenizers",
36
+ "FTS5-SOURCES.md"
34
37
  ],
35
38
  "repository": {
36
39
  "type": "git",
@@ -55,8 +58,8 @@
55
58
  "prepublishOnly": "test -f dist/sqlite3.wasm || (echo 'Run build:wasm first' && exit 1)"
56
59
  },
57
60
  "devDependencies": {
58
- "vitest": "^3.0.0",
61
+ "vitest": "^3.2.7",
59
62
  "typescript": "^5.7.0"
60
63
  },
61
- "releaseSourceCommit": "ea248201d35f2c30b74a6401eda49b9bdd3d2287"
64
+ "releaseSourceCommit": "692d233ff502256274f2ff23036a5d17c0936b5a"
62
65
  }