viborm 1.0.0 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -3
- package/dist/adapters.d.mts +1 -1
- package/dist/adapters.mjs +1 -1
- package/dist/{array-literal-D9FexFqy.mjs → array-literal-DcEm5tt_.mjs} +1 -1
- package/dist/{array-literal-D9FexFqy.mjs.map → array-literal-DcEm5tt_.mjs.map} +1 -1
- package/dist/batch-refs-Op1fx9Bo.mjs +6 -0
- package/dist/batch-refs-Op1fx9Bo.mjs.map +1 -0
- package/dist/builder-DkWfNHEV.mjs +2 -0
- package/dist/builder-DkWfNHEV.mjs.map +1 -0
- package/dist/bun-sql.d.mts +1 -1
- package/dist/bun-sql.mjs +1 -1
- package/dist/bun-sqlite.d.mts +1 -1
- package/dist/bun-sqlite.mjs +1 -1
- package/dist/bun-sqlite.mjs.map +1 -1
- package/dist/cache/cloudflare-kv.d.mts +1 -1
- package/dist/cache/cloudflare-kv.mjs +1 -1
- package/dist/cache/memory.d.mts +1 -1
- package/dist/cache/memory.mjs +1 -1
- package/dist/cache.d.mts +1 -1
- package/dist/cache.mjs +1 -1
- package/dist/cli.mjs +6 -6
- package/dist/cli.mjs.map +1 -1
- package/dist/client-C8gXvWIA.mjs +2 -0
- package/dist/client-C8gXvWIA.mjs.map +1 -0
- package/dist/client-z9mcpRtA.mjs +435 -0
- package/dist/client-z9mcpRtA.mjs.map +1 -0
- package/dist/client.d.mts +1 -1
- package/dist/client.mjs +1 -1
- package/dist/config.d.mts +1 -1
- package/dist/config.mjs +1 -1
- package/dist/d1.d.mts +1 -1
- package/dist/d1.mjs +1 -1
- package/dist/{identifiers-By-JRCb5.mjs → datetime-physical-codec-BK93pJGW.mjs} +2 -2
- package/dist/datetime-physical-codec-BK93pJGW.mjs.map +1 -0
- package/dist/driver-CHclfK3q.mjs +2 -0
- package/dist/driver-CHclfK3q.mjs.map +1 -0
- package/dist/{driver-CRaDT4B7.mjs → driver-ZIbkciaz.mjs} +2 -2
- package/dist/{driver-CRaDT4B7.mjs.map → driver-ZIbkciaz.mjs.map} +1 -1
- package/dist/{driver-options-DxlB1tms.mjs → driver-options-DVxWlZ0s.mjs} +1 -1
- package/dist/{driver-options-DxlB1tms.mjs.map → driver-options-DVxWlZ0s.mjs.map} +1 -1
- package/dist/driver.d.mts +1 -1
- package/dist/driver.mjs +1 -1
- package/dist/error-mapping-LKqxnw-b.mjs +2 -0
- package/dist/error-mapping-LKqxnw-b.mjs.map +1 -0
- package/dist/execution-context-Bm_qTp1i.mjs +2 -0
- package/dist/execution-context-Bm_qTp1i.mjs.map +1 -0
- package/dist/{fs-estate-BcjgY4iY.mjs → fs-estate-BLqNdigQ.mjs} +1 -1
- package/dist/{fs-estate-BcjgY4iY.mjs.map → fs-estate-BLqNdigQ.mjs.map} +1 -1
- package/dist/{index-T0YKKw66.d.mts → index-BbcE-gyl.d.mts} +109 -59
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +1 -1
- package/dist/instrumentation.d.mts +1 -1
- package/dist/instrumentation.mjs +1 -1
- package/dist/{json-number-C10HFiy6.mjs → json-number-TpD-pfqt.mjs} +1 -1
- package/dist/{json-number-C10HFiy6.mjs.map → json-number-TpD-pfqt.mjs.map} +1 -1
- package/dist/libsql.d.mts +8 -3
- package/dist/libsql.mjs +1 -1
- package/dist/libsql.mjs.map +1 -1
- package/dist/migrations/storage/fs.mjs +1 -1
- package/dist/migrations.d.mts +6 -4
- package/dist/migrations.mjs +1 -1
- package/dist/migrations.mjs.map +1 -1
- package/dist/mysql-adapter-DtZdwqzc.mjs +2 -0
- package/dist/{mysql-adapter-D9FoHlWE.mjs.map → mysql-adapter-DtZdwqzc.mjs.map} +1 -1
- package/dist/mysql2.d.mts +1 -1
- package/dist/mysql2.mjs +1 -1
- package/dist/neon-http.d.mts +1 -1
- package/dist/neon-http.mjs +1 -1
- package/dist/pg.d.mts +1 -1
- package/dist/pg.mjs +1 -1
- package/dist/pglite.d.mts +1 -1
- package/dist/pglite.mjs +1 -1
- package/dist/{pinned-session-Ca7C9yxY.mjs → pinned-session-CNANv7bv.mjs} +2 -2
- package/dist/{pinned-session-Ca7C9yxY.mjs.map → pinned-session-CNANv7bv.mjs.map} +1 -1
- package/dist/planetscale.d.mts +1 -1
- package/dist/planetscale.mjs +1 -1
- package/dist/{planner-B11VjIin.d.mts → planner-Bbw8W81b.d.mts} +1 -1
- package/dist/postgres-adapter-ButxrmEa.mjs +2 -0
- package/dist/{postgres-adapter-T2Iko-vt.mjs.map → postgres-adapter-ButxrmEa.mjs.map} +1 -1
- package/dist/postgres.d.mts +1 -1
- package/dist/postgres.mjs +1 -1
- package/dist/postgres.mjs.map +1 -1
- package/dist/provider-limits-DXj_pOT0.mjs +2 -0
- package/dist/provider-limits-DXj_pOT0.mjs.map +1 -0
- package/dist/{result-shape-DKTu8yre.mjs → result-shape-CKLOBSKl.mjs} +2 -2
- package/dist/result-shape-CKLOBSKl.mjs.map +1 -0
- package/dist/scalar-BTktMqvO.mjs.map +1 -1
- package/dist/schema/json.d.mts +1 -1
- package/dist/{schema-introspection-DsXPfCst.mjs → schema-introspection-C7P7lwIs.mjs} +2 -2
- package/dist/{schema-introspection-DsXPfCst.mjs.map → schema-introspection-C7P7lwIs.mjs.map} +1 -1
- package/dist/schema.d.mts +1 -1
- package/dist/soft-delete.d.mts +1 -1
- package/dist/sqlite-adapter-1krz0OXw.mjs +2 -0
- package/dist/{sqlite-adapter-HqO3GpAK.mjs.map → sqlite-adapter-1krz0OXw.mjs.map} +1 -1
- package/dist/sqlite3.d.mts +1 -1
- package/dist/sqlite3.mjs +1 -1
- package/dist/transaction-operation-BC7aua5V.mjs.map +1 -1
- package/dist/{utils-DfztpPvR.mjs → utils-CRFUUfNn.mjs} +1 -1
- package/dist/{utils-DfztpPvR.mjs.map → utils-CRFUUfNn.mjs.map} +1 -1
- package/dist/v-B2WwtcRz.mjs.map +1 -1
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/version-De1l_ZMF.mjs +2 -0
- package/dist/{version-Cr80LFvx.mjs.map → version-De1l_ZMF.mjs.map} +1 -1
- package/package.json +1 -2
- package/dist/batch-refs-BY51FIXm.mjs +0 -6
- package/dist/batch-refs-BY51FIXm.mjs.map +0 -1
- package/dist/builder-bPfagDQV.mjs +0 -2
- package/dist/builder-bPfagDQV.mjs.map +0 -1
- package/dist/client-NleI4Nm-.mjs +0 -434
- package/dist/client-NleI4Nm-.mjs.map +0 -1
- package/dist/client-tjSMPjeZ.mjs +0 -2
- package/dist/client-tjSMPjeZ.mjs.map +0 -1
- package/dist/decimal-12NERGYZ.mjs +0 -3
- package/dist/decimal-12NERGYZ.mjs.map +0 -1
- package/dist/driver-yCYqzIQg.mjs +0 -2
- package/dist/driver-yCYqzIQg.mjs.map +0 -1
- package/dist/error-mapping-BWzb-l02.mjs +0 -2
- package/dist/error-mapping-BWzb-l02.mjs.map +0 -1
- package/dist/execution-context-BPk0YLhd.mjs +0 -2
- package/dist/execution-context-BPk0YLhd.mjs.map +0 -1
- package/dist/identifiers-By-JRCb5.mjs.map +0 -1
- package/dist/mysql-adapter-D9FoHlWE.mjs +0 -2
- package/dist/postgres-adapter-T2Iko-vt.mjs +0 -2
- package/dist/result-shape-DKTu8yre.mjs.map +0 -1
- package/dist/sqlite-adapter-HqO3GpAK.mjs +0 -2
- package/dist/version-Cr80LFvx.mjs +0 -2
package/dist/bun-sql.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { D as Schema, Dn as QueryExecutionContext, Ft as NoExtraDriverConfigKeys, Ht as TransactionOptionSupport, It as VibORMClient, L as LinkedClientConfig, On as QueryResult, d as PinnedSessionReservation, f as DriverResultParser, jt as DriverConfig, s as DatabaseAdapter, u as Driver } from "./index-
|
|
1
|
+
import { D as Schema, Dn as QueryExecutionContext, Ft as NoExtraDriverConfigKeys, Ht as TransactionOptionSupport, It as VibORMClient, L as LinkedClientConfig, On as QueryResult, d as PinnedSessionReservation, f as DriverResultParser, jt as DriverConfig, s as DatabaseAdapter, u as Driver } from "./index-BbcE-gyl.mjs";
|
|
2
2
|
|
|
3
3
|
//#region src/drivers/bun-sql/index.d.ts
|
|
4
4
|
|
package/dist/bun-sql.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{y as t}from"./validation-Du6j0Q38.mjs";import{c as n}from"./bind-parameter-capacity-DzMcIB95.mjs";import{a as r,r as i}from"./transactions-gjmrWN5W.mjs";import{s as a}from"./execution-context-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{y as t}from"./validation-Du6j0Q38.mjs";import{c as n}from"./bind-parameter-capacity-DzMcIB95.mjs";import{a as r,r as i}from"./transactions-gjmrWN5W.mjs";import{s as a}from"./execution-context-Bm_qTp1i.mjs";import{n as o}from"./client-C8gXvWIA.mjs";import{i as s,t as c}from"./driver-options-DVxWlZ0s.mjs";import{r as l}from"./pinned-session-CNANv7bv.mjs";import{t as u}from"./driver-CHclfK3q.mjs";import{t as d}from"./postgres-adapter-ButxrmEa.mjs";function normalizeBunSQLParams(e,t){let n;for(let r=0;r<t.length;r+=1){let i=t[r];Array.isArray(i)&&(n??=[...t],n[r]=e.array(i,`TEXT`).serializedValues)}return n??t}const f={parseField:(e,t,n)=>t===`int`&&e instanceof Int32Array?n(Array.from(e),t):n(e,t)};var BunSQLDriver=class extends u{result=f;maxBindParametersPerStatement=65535;driverOptions;suppliedClient;constructor(e={}){super(`postgresql`,`bun-sql`);let n=s(e);this.driverOptions=e,this.suppliedClient=e.client,this.suppliedClient&&(this.client=this.suppliedClient);let r=new d(n,e.postgis===!0);r.capabilities.supportsVector=e.pgvector===!0,e.pgvector||(r.vector=t),c(this,`adapter`,r)}async initClient(){if(this.suppliedClient!==void 0)return this.suppliedClient;let{SQL:e}=await import(`bun`);return this.driverOptions.databaseUrl?new e({...this.driverOptions.options,url:this.driverOptions.databaseUrl}):new e(this.driverOptions.options??{})}async closeClient(e){e!==this.suppliedClient&&await e.close()}async execute(e,t,r,i){let a=i?.operation??`execute`,o=await e.unsafe(t,normalizeBunSQLParams(e,r));return{rows:o,rowCount:n(o.count,{provider:`bun-sql`,operation:a})}}async executeRaw(e,t,r,i){let a=i?.operation??`executeRaw`,o=await e.unsafe(t,r);return{rows:o,rowCount:n(o.count,{provider:`bun-sql`,operation:a})}}transactionOptionSupport(){return{isolationLevel:`post-begin`,timeout:!0,maxWait:`unsupported`,maxWaitReason:`Bun SQL acquires the connection inside sql.begin(), which VibORM cannot observe or bound — the wait would be unbounded no matter what maxWait said`}}async transaction(e,t,n){if(`savepoint`in e)throw i(this.driverName);return r({run:t=>e.begin(t),callback:t,phases:a(n),close:async()=>void 0})}async pinnedSession(){let e=await this.getClient({operation:`pinnedSession`});if(`savepoint`in e)throw i(this.driverName);let t=await e.reserve();return{session:t,release:n=>l({driverName:this.driverName,discard:n,reset:()=>t.unsafe(`SELECT pg_advisory_unlock_all()`),release:()=>t.release(),closeOwnedTransport:e===this.suppliedClient?void 0:async()=>{this.client=null,this.initPromise=null,await e.close()}})}}};function createClient(e){let{client:t,databaseUrl:n,options:r,pgvector:i,postgis:a}=e;return o(e,new BunSQLDriver({client:t,databaseUrl:n,options:r,pgvector:i,postgis:a,namespace:s(e)}))}export{BunSQLDriver,createClient};
|
|
2
2
|
//# sourceMappingURL=bun-sql.mjs.map
|
package/dist/bun-sqlite.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { D as Schema, Dn as QueryExecutionContext, Ft as NoExtraDriverConfigKeys, Ht as TransactionOptionSupport, It as VibORMClient, L as LinkedClientConfig, On as QueryResult, f as DriverResultParser, jt as DriverConfig, s as DatabaseAdapter, u as Driver } from "./index-
|
|
1
|
+
import { D as Schema, Dn as QueryExecutionContext, Ft as NoExtraDriverConfigKeys, Ht as TransactionOptionSupport, It as VibORMClient, L as LinkedClientConfig, On as QueryResult, f as DriverResultParser, jt as DriverConfig, s as DatabaseAdapter, u as Driver } from "./index-BbcE-gyl.mjs";
|
|
2
2
|
|
|
3
3
|
//#region src/drivers/bun-sqlite/index.d.ts
|
|
4
4
|
|
package/dist/bun-sqlite.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{a as t,r as n}from"./validation-Du6j0Q38.mjs";import{s as r}from"./transactions-gjmrWN5W.mjs";import{s as i}from"./execution-context-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{a as t,r as n}from"./validation-Du6j0Q38.mjs";import{s as r}from"./transactions-gjmrWN5W.mjs";import{s as i}from"./execution-context-Bm_qTp1i.mjs";import{n as a}from"./client-C8gXvWIA.mjs";import{n as o,t as s}from"./driver-CHclfK3q.mjs";import{i as c,o as l,r as u,s as d,t as f}from"./sqlite-utils-D26BFuJJ.mjs";import{t as p}from"./sqlite-adapter-1krz0OXw.mjs";function requireSafeIntegers(e){if(typeof e.safeIntegers!=`function`)throw new t(`bun:sqlite`,`Statement.safeIntegers`,`This Bun build cannot read INTEGER columns as BigInt, so any value past 2^53 would come back silently rounded. Upgrade to Bun 1.1.14 or newer.`);return e}function reusesStatements(e){let t;for(let n=Object.getPrototypeOf(e);n;n=Object.getPrototypeOf(n))Object.hasOwn(n,`prepare`)&&(t=n.prepare);return e.prepare===t}const m=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u;function convertValuesForBunSQLite(e){return e.map(e=>{let t=f(e);if(typeof t==`string`&&m.test(t))throw TypeError(`bun:sqlite cannot preserve unpaired UTF-16 surrogates; the parameter was refused before dispatch.`);return t instanceof Uint8Array||!u(t)?t:l(t)})}var BunSQLiteDriver=class extends s{adapter=new p;maxBindParametersPerStatement=32766;result=d;serializeTransactions=!0;driverOptions;suppliedClient;constructor(e={}){if(super(`sqlite`,`bun-sqlite`),this.driverOptions=e,this.suppliedClient=e.client,this.suppliedClient){let e=this.suppliedClient.query(`PRAGMA foreign_keys`).get();if(!e||typeof e!=`object`||Reflect.get(e,`foreign_keys`)!==1)throw new n(`A supplied bun:sqlite Database must enable PRAGMA foreign_keys = ON before wrapping.`,{meta:{driver:`bun-sqlite`}});this.client=this.suppliedClient,Object.defineProperty(this,`connectionQueue`,{value:o(this.suppliedClient)})}}async initClient(){if(this.suppliedClient)return this.suppliedClient;let{Database:e}=await import(`bun:sqlite`),t=this.driverOptions.dataDir??`:memory:`,n=this.driverOptions.options,r=n===void 0||Object.keys(n).length===0?new e(t):new e(t,n);return r.exec(`PRAGMA foreign_keys = ON`),r.exec(`PRAGMA busy_timeout = 5000`),r}async closeClient(e){e!==this.suppliedClient&&e.close()}async execute(e,t,n,r){let i=convertValuesForBunSQLite(n);return this.runStatement(e,t,i,r?.model!==`$raw`)}async executeRaw(e,t,n){let r=n?convertValuesForBunSQLite(n):void 0;return this.runStatement(e,t,r,!1)}runStatement(e,t,n,r){let i=r&&reusesStatements(e)?e.query(t):e.prepare(t);if(i.columnNames.length>0){requireSafeIntegers(i).safeIntegers(!0);let e=n?i.all(...n):i.all();return{rows:r?e:c(e),rowCount:e.length}}return{rows:[],rowCount:(n?i.run(...n):i.run()).changes}}transactionOptionSupport(){return{isolationLevel:`serializable-only`,isolationLevelReason:`SQLite serializes transactions on a single connection and has no statement to weaken isolation, so only Serializable can be honored truthfully`,timeout:!0,maxWait:`queue`}}async transaction(e,t,n){return r({begin:()=>e.exec(`BEGIN IMMEDIATE`),callback:()=>t(e),commit:()=>e.exec(`COMMIT`),rollback:()=>{e.inTransaction&&e.exec(`ROLLBACK`)},phases:i(n)})}};function createClient(e){let{client:t,dataDir:n,options:r}=e;return a(e,new BunSQLiteDriver({client:t,dataDir:n,options:r}))}export{BunSQLiteDriver,createClient};
|
|
2
2
|
//# sourceMappingURL=bun-sqlite.mjs.map
|
package/dist/bun-sqlite.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bun-sqlite.mjs","names":[],"sources":["../src/drivers/bun-sqlite/index.ts"],"sourcesContent":["import { physicalConnectionQueue } from \"../connection-scope\";\nimport { normalizeSQLiteRawRows } from \"../shared/sqlite-utils\";\n/**\n * Bun SQLite Driver\n *\n * Driver implementation for Bun's built-in SQLite (bun:sqlite).\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport { SQLiteAdapter } from \"@adapters/databases/sqlite/sqlite-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport { ClientInitializationError, FeatureNotSupportedError } from \"@errors\";\nimport {\n Driver,\n type DriverResultParser,\n type QueryExecutionContext,\n} from \"../driver\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport {\n convertValueForSQLite,\n isSQLiteBinaryValue,\n runTransactionLifecycle,\n sqliteBinaryToUint8Array,\n sqliteResultParser,\n type TransactionOptionSupport,\n} from \"../shared\";\nimport type { QueryResult } from \"../types\";\n\n// ============================================================\n// TYPE DECLARATIONS FOR BUN:SQLITE\n// ============================================================\n\n// Bun's Database type - we define inline to avoid requiring bun types at compile time\ninterface BunSQLiteDatabase {\n query<T = unknown>(sql: string): BunSQLiteStatement<T>;\n prepare<T = unknown>(sql: string): BunSQLiteStatement<T>;\n run(sql: string, ...params: unknown[]): void;\n exec(sql: string): void;\n readonly inTransaction: boolean;\n close(): void;\n transaction<T>(fn: () => T): () => T;\n}\n\ninterface BunSQLiteStatement<T = unknown> {\n readonly columnNames: string[];\n all(...params: unknown[]): T[];\n get(...params: unknown[]): T | null;\n run(...params: unknown[]): {\n changes: number;\n lastInsertRowid: number | bigint;\n };\n /**\n * Reads INTEGER columns as BigInt instead of lossy JS numbers. Present on\n * `bun:sqlite` statements since Bun 1.1.14; the driver refuses to read\n * rather than return corrupted values when it is missing.\n */\n safeIntegers(safe: boolean): BunSQLiteStatement<T>;\n values(...params: unknown[]): unknown[][];\n}\n\n/**\n * `safeIntegers()` is what keeps an INTEGER past 2^53 from being rounded on\n * the way out of SQLite. A `bun:sqlite` old enough to lack it cannot answer\n * the query truthfully, so the read is refused instead of silently returning\n * a corrupted number — the one outcome that must never ship.\n */\nfunction requireSafeIntegers<T>(\n stmt: BunSQLiteStatement<T>\n): BunSQLiteStatement<T> {\n if (typeof stmt.safeIntegers !== \"function\") {\n throw new FeatureNotSupportedError(\n \"bun:sqlite\",\n \"Statement.safeIntegers\",\n \"This Bun build cannot read INTEGER columns as BigInt, so any value past 2^53 would come back silently rounded. Upgrade to Bun 1.1.14 or newer.\"\n );\n }\n return stmt;\n}\n\nconst UNPAIRED_SURROGATE_PATTERN =\n /[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]/u;\n\nfunction convertValuesForBunSQLite(values: unknown[]): unknown[] {\n return values.map((parameter) => {\n const value = convertValueForSQLite(parameter);\n if (typeof value === \"string\" && UNPAIRED_SURROGATE_PATTERN.test(value)) {\n throw new TypeError(\n \"bun:sqlite cannot preserve unpaired UTF-16 surrogates; the parameter was refused before dispatch.\"\n );\n }\n if (value instanceof Uint8Array || !isSQLiteBinaryValue(value)) {\n return value;\n }\n return sqliteBinaryToUint8Array(value);\n });\n}\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport interface BunSQLiteOptions {\n readonly?: boolean;\n create?: boolean;\n readwrite?: boolean;\n strict?: boolean;\n}\n\nexport interface BunSQLiteDriverOptions {\n client?: BunSQLiteDatabase;\n dataDir?: string;\n options?: BunSQLiteOptions;\n}\n\nexport type BunSQLiteClientConfig<C extends DriverConfig> =\n BunSQLiteDriverOptions & C;\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class BunSQLiteDriver extends Driver<\n BunSQLiteDatabase,\n BunSQLiteDatabase\n> {\n readonly adapter: DatabaseAdapter = new SQLiteAdapter();\n readonly maxBindParametersPerStatement: number | undefined = 32_766;\n readonly result: DriverResultParser = sqliteResultParser;\n protected override readonly serializeTransactions = true;\n\n private readonly driverOptions: BunSQLiteDriverOptions;\n private readonly suppliedClient: BunSQLiteDatabase | undefined;\n\n constructor(options: BunSQLiteDriverOptions = {}) {\n super(\"sqlite\", \"bun-sqlite\");\n this.driverOptions = options;\n\n this.suppliedClient = options.client;\n if (this.suppliedClient) {\n const enabled = this.suppliedClient.query(\"PRAGMA foreign_keys\").get();\n if (\n !enabled ||\n typeof enabled !== \"object\" ||\n Reflect.get(enabled, \"foreign_keys\") !== 1\n ) {\n throw new ClientInitializationError(\n \"A supplied bun:sqlite Database must enable PRAGMA foreign_keys = ON before wrapping.\",\n { meta: { driver: \"bun-sqlite\" } }\n );\n }\n this.client = this.suppliedClient;\n Object.defineProperty(this, \"connectionQueue\", {\n value: physicalConnectionQueue(this.suppliedClient),\n });\n }\n }\n\n protected async initClient(): Promise<BunSQLiteDatabase> {\n if (this.suppliedClient) return this.suppliedClient;\n // Dynamic import for bun:sqlite\n const { Database } = await import(\"bun:sqlite\");\n\n const dataDir = this.driverOptions.dataDir ?? \":memory:\";\n const options = this.driverOptions.options;\n\n // bun:sqlite derives its open flags from this object and rejects one that\n // names no access mode: `new Database(path, {})` throws SQLITE_MISUSE\n // (\"flags must include SQLITE_OPEN_READONLY or SQLITE_OPEN_READWRITE\").\n // An options bag that says nothing must mean nothing, so the argument is\n // omitted entirely and Bun applies its own default (readwrite + create).\n const db = (options === undefined || Object.keys(options).length === 0\n ? new Database(dataDir)\n : new Database(dataDir, options)) as unknown as BunSQLiteDatabase;\n\n // bun:sqlite leaves SQLite's foreign_keys default (OFF), which would let a\n // dangling FK write report success while sqlite3 and libsql refuse it.\n // Enforcement is a viborm guarantee, not an inherited library default.\n db.exec(\"PRAGMA foreign_keys = ON\");\n db.exec(\"PRAGMA busy_timeout = 5000\");\n\n return db;\n }\n\n protected async closeClient(db: BunSQLiteDatabase): Promise<void> {\n if (db !== this.suppliedClient) db.close();\n }\n\n protected async execute<T>(\n client: BunSQLiteDatabase,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const values = convertValuesForBunSQLite(params);\n return this.runStatement<T>(client, sql, values, context?.model !== \"$raw\");\n }\n\n protected async executeRaw<T>(\n client: BunSQLiteDatabase,\n sql: string,\n params?: unknown[]\n ): Promise<QueryResult<T>> {\n const values = params ? convertValuesForBunSQLite(params) : undefined;\n return this.runStatement<T>(client, sql, values, false);\n }\n\n private runStatement<T>(\n db: BunSQLiteDatabase,\n sql: string,\n values: unknown[] | undefined,\n typed: boolean\n ): QueryResult<T> {\n const stmt = db.prepare(sql);\n\n if (stmt.columnNames.length > 0) {\n // Read once without precision loss, including unsafe raw queries.\n requireSafeIntegers(stmt).safeIntegers(true);\n const rows = (values ? stmt.all(...values) : stmt.all()) as T[];\n return {\n rows: typed ? rows : normalizeSQLiteRawRows(rows),\n rowCount: rows.length,\n };\n }\n\n const result = values ? stmt.run(...values) : stmt.run();\n return { rows: [] as T[], rowCount: result.changes };\n }\n\n /**\n * SQLite has no isolation-level statement: one writer at a time on one\n * connection makes every transaction serializable already. `Serializable` is\n * therefore honored by construction, with no SQL to emit; the three weaker\n * levels are refused because pretending to relax isolation we cannot relax\n * would misreport what the transaction actually guarantees.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"serializable-only\",\n isolationLevelReason:\n \"SQLite serializes transactions on a single connection and has no statement to weaken isolation, so only Serializable can be honored truthfully\",\n timeout: true,\n maxWait: \"queue\",\n };\n }\n\n protected async transaction<T>(\n client: BunSQLiteDatabase,\n fn: (tx: BunSQLiteDatabase) => Promise<T>,\n context?: QueryExecutionContext\n ): Promise<T> {\n return runTransactionLifecycle({\n begin: () => client.exec(\"BEGIN IMMEDIATE\"),\n callback: () => fn(client),\n commit: () => client.exec(\"COMMIT\"),\n // A failed BEGIN never grants rollback ownership. After a failed COMMIT,\n // successful rollback restores this same database, including :memory:.\n rollback: () => {\n if (client.inTransaction) client.exec(\"ROLLBACK\");\n },\n phases: getExecutionTransactionPhases(context),\n });\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: BunSQLiteClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, BunSQLiteDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: BunSQLiteDriver }\n >]: LinkedClientConfig<C & { driver: BunSQLiteDriver }>[P];\n}> {\n const { client, dataDir, options } = config;\n\n const driver = new BunSQLiteDriver({ client, dataDir, options });\n\n return createClientFromDriverConfig<S, C, BunSQLiteDriver>(config, driver);\n}\n"],"mappings":"4ZAyEA,SAAS,oBACP,EACuB,CACvB,GAAI,OAAO,EAAK,cAAiB,WAC/B,MAAM,IAAI,EACR,aACA,yBACA,iJACD,CAEH,OAAO,EAGT,MAAM,EACJ,0EAEF,SAAS,0BAA0B,EAA8B,CAC/D,OAAO,EAAO,IAAK,GAAc,CAC/B,IAAM,EAAQ,EAAsB,EAAU,CAC9C,GAAI,OAAO,GAAU,UAAY,EAA2B,KAAK,EAAM,CACrE,MAAU,UACR,oGACD,CAKH,OAHI,aAAiB,YAAc,CAAC,EAAoB,EAAM,CACrD,EAEF,EAAyB,EAAM,EACtC,CA2BJ,IAAa,gBAAb,cAAqC,CAGnC,CACA,QAAoC,IAAI,EACxC,8BAA6D,MAC7D,OAAsC,EACtC,sBAAoD,GAEpD,cACA,eAEA,YAAY,EAAkC,EAAE,CAAE,CAKhD,GAJA,MAAM,SAAU,aAAa,CAC7B,KAAK,cAAgB,EAErB,KAAK,eAAiB,EAAQ,OAC1B,KAAK,eAAgB,CACvB,IAAM,EAAU,KAAK,eAAe,MAAM,sBAAsB,CAAC,KAAK,CACtE,GACE,CAAC,GACD,OAAO,GAAY,UACnB,QAAQ,IAAI,EAAS,e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,KAAK,EACb,QAAS,CAUtD,0BAAwE,CACtE,MAAO,CACL,eAAgB,oBAChB,qBACE,iJACF,QAAS,GACT,QAAS,QACV,CAGH,MAAgB,YACd,EACA,EACA,EACY,CACZ,OAAO,EAAwB,CAC7B,UAAa,EAAO,KAAK,kBAAkB,CAC3C,aAAgB,EAAG,EAAO,CAC1B,WAAc,EAAO,KAAK,SAAS,CAGnC,aAAgB,CACV,EAAO,eAAe,EAAO,KAAK,WAAW,EAEnD,OAAQ,EAA8B,EAAQ,CAC/C,CAAC,GAQN,SAAgB,aACd,EAOC,CACD,GAAM,CAAE,SAAQ,UAAS,WAAY,EAIrC,OAAO,EAAoD,EAF5C,IAAI,gBAAgB,CAAE,SAAQ,UAAS,UAAS,CAAC,CAEU"}
|
|
1
|
+
{"version":3,"file":"bun-sqlite.mjs","names":[],"sources":["../src/drivers/bun-sqlite/index.ts"],"sourcesContent":["import { physicalConnectionQueue } from \"../connection-scope\";\nimport { normalizeSQLiteRawRows } from \"../shared/sqlite-utils\";\n/**\n * Bun SQLite Driver\n *\n * Driver implementation for Bun's built-in SQLite (bun:sqlite).\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport { SQLiteAdapter } from \"@adapters/databases/sqlite/sqlite-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport { ClientInitializationError, FeatureNotSupportedError } from \"@errors\";\nimport {\n Driver,\n type DriverResultParser,\n type QueryExecutionContext,\n} from \"../driver\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport {\n convertValueForSQLite,\n isSQLiteBinaryValue,\n runTransactionLifecycle,\n sqliteBinaryToUint8Array,\n sqliteResultParser,\n type TransactionOptionSupport,\n} from \"../shared\";\nimport type { QueryResult } from \"../types\";\n\n// ============================================================\n// TYPE DECLARATIONS FOR BUN:SQLITE\n// ============================================================\n\n// Bun's Database type - we define inline to avoid requiring bun types at compile time\ninterface BunSQLiteDatabase {\n query<T = unknown>(sql: string): BunSQLiteStatement<T>;\n prepare<T = unknown>(sql: string): BunSQLiteStatement<T>;\n run(sql: string, ...params: unknown[]): void;\n exec(sql: string): void;\n readonly inTransaction: boolean;\n close(): void;\n transaction<T>(fn: () => T): () => T;\n}\n\ninterface BunSQLiteStatement<T = unknown> {\n readonly columnNames: string[];\n all(...params: unknown[]): T[];\n get(...params: unknown[]): T | null;\n run(...params: unknown[]): {\n changes: number;\n lastInsertRowid: number | bigint;\n };\n /**\n * Reads INTEGER columns as BigInt instead of lossy JS numbers. Present on\n * `bun:sqlite` statements since Bun 1.1.14; the driver refuses to read\n * rather than return corrupted values when it is missing.\n */\n safeIntegers(safe: boolean): BunSQLiteStatement<T>;\n values(...params: unknown[]): unknown[][];\n}\n\n/**\n * `safeIntegers()` is what keeps an INTEGER past 2^53 from being rounded on\n * the way out of SQLite. A `bun:sqlite` old enough to lack it cannot answer\n * the query truthfully, so the read is refused instead of silently returning\n * a corrupted number — the one outcome that must never ship.\n */\nfunction requireSafeIntegers<T>(\n stmt: BunSQLiteStatement<T>\n): BunSQLiteStatement<T> {\n if (typeof stmt.safeIntegers !== \"function\") {\n throw new FeatureNotSupportedError(\n \"bun:sqlite\",\n \"Statement.safeIntegers\",\n \"This Bun build cannot read INTEGER columns as BigInt, so any value past 2^53 would come back silently rounded. Upgrade to Bun 1.1.14 or newer.\"\n );\n }\n return stmt;\n}\n\n/**\n * Typed statements come from `bun:sqlite`'s own bounded statement cache\n * (`query`), which dies with the database: `close()` finalizes it, and a closed\n * database refuses instead of answering. The cache is reused only while\n * `prepare` is the one `bun:sqlite` defines at the base of the class chain; a\n * database whose `prepare` was replaced or overridden sees every call.\n */\nfunction reusesStatements(db: BunSQLiteDatabase): boolean {\n let stock: unknown;\n for (\n let proto = Object.getPrototypeOf(db);\n proto;\n proto = Object.getPrototypeOf(proto)\n )\n if (Object.hasOwn(proto, \"prepare\")) stock = proto.prepare;\n return db.prepare === stock;\n}\n\nconst UNPAIRED_SURROGATE_PATTERN =\n /[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]/u;\n\nfunction convertValuesForBunSQLite(values: unknown[]): unknown[] {\n return values.map((parameter) => {\n const value = convertValueForSQLite(parameter);\n if (typeof value === \"string\" && UNPAIRED_SURROGATE_PATTERN.test(value)) {\n throw new TypeError(\n \"bun:sqlite cannot preserve unpaired UTF-16 surrogates; the parameter was refused before dispatch.\"\n );\n }\n if (value instanceof Uint8Array || !isSQLiteBinaryValue(value)) {\n return value;\n }\n return sqliteBinaryToUint8Array(value);\n });\n}\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport interface BunSQLiteOptions {\n readonly?: boolean;\n create?: boolean;\n readwrite?: boolean;\n strict?: boolean;\n}\n\nexport interface BunSQLiteDriverOptions {\n client?: BunSQLiteDatabase;\n dataDir?: string;\n options?: BunSQLiteOptions;\n}\n\nexport type BunSQLiteClientConfig<C extends DriverConfig> =\n BunSQLiteDriverOptions & C;\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class BunSQLiteDriver extends Driver<\n BunSQLiteDatabase,\n BunSQLiteDatabase\n> {\n readonly adapter: DatabaseAdapter = new SQLiteAdapter();\n readonly maxBindParametersPerStatement: number | undefined = 32_766;\n readonly result: DriverResultParser = sqliteResultParser;\n protected override readonly serializeTransactions = true;\n\n private readonly driverOptions: BunSQLiteDriverOptions;\n private readonly suppliedClient: BunSQLiteDatabase | undefined;\n\n constructor(options: BunSQLiteDriverOptions = {}) {\n super(\"sqlite\", \"bun-sqlite\");\n this.driverOptions = options;\n\n this.suppliedClient = options.client;\n if (this.suppliedClient) {\n const enabled = this.suppliedClient.query(\"PRAGMA foreign_keys\").get();\n if (\n !enabled ||\n typeof enabled !== \"object\" ||\n Reflect.get(enabled, \"foreign_keys\") !== 1\n ) {\n throw new ClientInitializationError(\n \"A supplied bun:sqlite Database must enable PRAGMA foreign_keys = ON before wrapping.\",\n { meta: { driver: \"bun-sqlite\" } }\n );\n }\n this.client = this.suppliedClient;\n Object.defineProperty(this, \"connectionQueue\", {\n value: physicalConnectionQueue(this.suppliedClient),\n });\n }\n }\n\n protected async initClient(): Promise<BunSQLiteDatabase> {\n if (this.suppliedClient) return this.suppliedClient;\n // Dynamic import for bun:sqlite\n const { Database } = await import(\"bun:sqlite\");\n\n const dataDir = this.driverOptions.dataDir ?? \":memory:\";\n const options = this.driverOptions.options;\n\n // bun:sqlite derives its open flags from this object and rejects one that\n // names no access mode: `new Database(path, {})` throws SQLITE_MISUSE\n // (\"flags must include SQLITE_OPEN_READONLY or SQLITE_OPEN_READWRITE\").\n // An options bag that says nothing must mean nothing, so the argument is\n // omitted entirely and Bun applies its own default (readwrite + create).\n const db = (options === undefined || Object.keys(options).length === 0\n ? new Database(dataDir)\n : new Database(dataDir, options)) as unknown as BunSQLiteDatabase;\n\n // bun:sqlite leaves SQLite's foreign_keys default (OFF), which would let a\n // dangling FK write report success while sqlite3 and libsql refuse it.\n // Enforcement is a viborm guarantee, not an inherited library default.\n db.exec(\"PRAGMA foreign_keys = ON\");\n db.exec(\"PRAGMA busy_timeout = 5000\");\n\n return db;\n }\n\n protected async closeClient(db: BunSQLiteDatabase): Promise<void> {\n if (db !== this.suppliedClient) db.close();\n }\n\n protected async execute<T>(\n client: BunSQLiteDatabase,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const values = convertValuesForBunSQLite(params);\n return this.runStatement<T>(client, sql, values, context?.model !== \"$raw\");\n }\n\n protected async executeRaw<T>(\n client: BunSQLiteDatabase,\n sql: string,\n params?: unknown[]\n ): Promise<QueryResult<T>> {\n const values = params ? convertValuesForBunSQLite(params) : undefined;\n return this.runStatement<T>(client, sql, values, false);\n }\n\n private runStatement<T>(\n db: BunSQLiteDatabase,\n sql: string,\n values: unknown[] | undefined,\n typed: boolean\n ): QueryResult<T> {\n const stmt =\n typed && reusesStatements(db) ? db.query(sql) : db.prepare(sql);\n\n if (stmt.columnNames.length > 0) {\n // Read once without precision loss, including unsafe raw queries.\n requireSafeIntegers(stmt).safeIntegers(true);\n const rows = (values ? stmt.all(...values) : stmt.all()) as T[];\n return {\n rows: typed ? rows : normalizeSQLiteRawRows(rows),\n rowCount: rows.length,\n };\n }\n\n const result = values ? stmt.run(...values) : stmt.run();\n return { rows: [] as T[], rowCount: result.changes };\n }\n\n /**\n * SQLite has no isolation-level statement: one writer at a time on one\n * connection makes every transaction serializable already. `Serializable` is\n * therefore honored by construction, with no SQL to emit; the three weaker\n * levels are refused because pretending to relax isolation we cannot relax\n * would misreport what the transaction actually guarantees.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"serializable-only\",\n isolationLevelReason:\n \"SQLite serializes transactions on a single connection and has no statement to weaken isolation, so only Serializable can be honored truthfully\",\n timeout: true,\n maxWait: \"queue\",\n };\n }\n\n protected async transaction<T>(\n client: BunSQLiteDatabase,\n fn: (tx: BunSQLiteDatabase) => Promise<T>,\n context?: QueryExecutionContext\n ): Promise<T> {\n return runTransactionLifecycle({\n begin: () => client.exec(\"BEGIN IMMEDIATE\"),\n callback: () => fn(client),\n commit: () => client.exec(\"COMMIT\"),\n // A failed BEGIN never grants rollback ownership. After a failed COMMIT,\n // successful rollback restores this same database, including :memory:.\n rollback: () => {\n if (client.inTransaction) client.exec(\"ROLLBACK\");\n },\n phases: getExecutionTransactionPhases(context),\n });\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: BunSQLiteClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, BunSQLiteDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: BunSQLiteDriver }\n >]: LinkedClientConfig<C & { driver: BunSQLiteDriver }>[P];\n}> {\n const { client, dataDir, options } = config;\n\n const driver = new BunSQLiteDriver({ client, dataDir, options });\n\n return createClientFromDriverConfig<S, C, BunSQLiteDriver>(config, driver);\n}\n"],"mappings":"4ZAyEA,SAAS,oBACP,EACuB,CACvB,GAAI,OAAO,EAAK,cAAiB,WAC/B,MAAM,IAAI,EACR,aACA,yBACA,iJACD,CAEH,OAAO,EAUT,SAAS,iBAAiB,EAAgC,CACxD,IAAI,EACJ,IACE,IAAI,EAAQ,OAAO,eAAe,EAAG,CACrC,EACA,EAAQ,OAAO,eAAe,EAAM,CAEhC,OAAO,OAAO,EAAO,UAAU,GAAE,EAAQ,EAAM,SACrD,OAAO,EAAG,UAAY,EAGxB,MAAM,EACJ,0EAEF,SAAS,0BAA0B,EAA8B,CAC/D,OAAO,EAAO,IAAK,GAAc,CAC/B,IAAM,EAAQ,EAAsB,EAAU,CAC9C,GAAI,OAAO,GAAU,UAAY,EAA2B,KAAK,EAAM,CACrE,MAAU,UACR,oGACD,CAKH,OAHI,aAAiB,YAAc,CAAC,EAAoB,EAAM,CACrD,EAEF,EAAyB,EAAM,EACtC,CA2BJ,IAAa,gBAAb,cAAqC,CAGnC,CACA,QAAoC,IAAI,EACxC,8BAA6D,MAC7D,OAAsC,EACtC,sBAAoD,GAEpD,cACA,eAEA,YAAY,EAAkC,EAAE,CAAE,CAKhD,GAJA,MAAM,SAAU,aAAa,CAC7B,KAAK,cAAgB,EAErB,KAAK,eAAiB,EAAQ,OAC1B,KAAK,eAAgB,CACvB,IAAM,EAAU,KAAK,eAAe,MAAM,sBAAsB,CAAC,KAAK,CACtE,GACE,CAAC,GACD,OAAO,GAAY,UACnB,QAAQ,IAAI,EAAS,eAAe,GAAK,EAEzC,MAAM,IAAI,EACR,uFACA,CAAE,KAAM,CAAE,OAAQ,aAAc,CAAE,CACnC,CAEH,KAAK,OAAS,KAAK,eACnB,OAAO,eAAe,KAAM,kBAAmB,CAC7C,MAAO,EAAwB,KAAK,eAAe,CACpD,C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,CACZ,OAAO,EAAwB,CAC7B,UAAa,EAAO,KAAK,kBAAkB,CAC3C,aAAgB,EAAG,EAAO,CAC1B,WAAc,EAAO,KAAK,SAAS,CAGnC,aAAgB,CACV,EAAO,eAAe,EAAO,KAAK,WAAW,EAEnD,OAAQ,EAA8B,EAAQ,CAC/C,CAAC,GAQN,SAAgB,aACd,EAOC,CACD,GAAM,CAAE,SAAQ,UAAS,WAAY,EAIrC,OAAO,EAAoD,EAF5C,IAAI,gBAAgB,CAAE,SAAQ,UAAS,UAAS,CAAC,CAEU"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"../chunk-BuuaeEvq.mjs";import{t}from"../driver-
|
|
1
|
+
import{n as e}from"../chunk-BuuaeEvq.mjs";import{t}from"../driver-ZIbkciaz.mjs";var CloudflareKVCache=class extends t{#e;constructor(e){super(`cloudflare-kv`),this.#e=e}async get(e){return await this.#e.get(e,`json`)||null}async set(e,t,n){let r=Math.max(60,Math.ceil(t/1e3));await this.#e.put(e,JSON.stringify(n),{expirationTtl:r})}async delete(e){await Promise.all(e.map(e=>this.#e.delete(e)))}async clear(e){let t;do{let n=await this.#e.list({prefix:e,cursor:t});await Promise.all(n.keys.map(e=>this.#e.delete(e.name))),t=n.list_complete?void 0:n.cursor}while(t)}};export{CloudflareKVCache};
|
|
2
2
|
//# sourceMappingURL=cloudflare-kv.mjs.map
|
package/dist/cache/memory.d.mts
CHANGED
package/dist/cache/memory.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"../chunk-BuuaeEvq.mjs";import{p as t}from"../observation-CLp8ylmL.mjs";import{t as n}from"../driver-
|
|
1
|
+
import{n as e}from"../chunk-BuuaeEvq.mjs";import{p as t}from"../observation-CLp8ylmL.mjs";import{t as n}from"../driver-ZIbkciaz.mjs";var MemoryCache=class extends n{#e=new Map;#t;#n;constructor(e,...n){if(super(`memory`),n.length)throw new t(`MemoryCache received extra construction arguments.`);let r=1024;if(e!==void 0){let n;try{n=Object.getOwnPropertyDescriptors(e)}catch{throw new t(`MemoryCache options could not be inspected.`)}let i=n.maxEntries,a=i&&`value`in i?i.value:void 0;if(Reflect.ownKeys(n).length!==1||!i||!(`value`in i)||typeof a!=`number`||!Number.isSafeInteger(a)||a<1)throw new t(`MemoryCache options must contain a positive safe-integer maxEntries only.`);r=a}this.#t=r}async get(e){let t=this.#e.get(e);return t?(this.#e.delete(e),this.clock.now()>=t.expiresAt?(this.#r(),null):(this.#e.set(e,t),t.entry)):null}async set(e,t,n){for(this.#e.delete(e),this.#e.set(e,{entry:n,expiresAt:this.clock.now()+t});this.#e.size>this.#t;){let e=this.#e.keys().next().value;e!==void 0&&this.#e.delete(e)}this.#i(t)}async delete(e){for(let t of e)this.#e.delete(t);this.#r()}async clear(e){for(let t of this.#e.keys())t.startsWith(e)&&this.#e.delete(t);this.#r()}#r(){this.#e.size||(this.#n?.cancel(),this.#n=void 0)}#i(e=6e4){this.#n||!this.#e.size||(this.#n=this.clock.setTimeout(()=>{this.#n=void 0;let e=this.clock.now();for(let[t,n]of this.#e)e>=n.expiresAt&&this.#e.delete(t);this.#i()},Math.min(e,6e4)),this.#n.unref?.())}async disconnect(){this.#e.clear(),this.#r()}};export{MemoryCache};
|
|
2
2
|
//# sourceMappingURL=memory.mjs.map
|
package/dist/cache.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Cn as WithCacheOptions, Sn as CacheInvalidationOptions, Ut as OfficialCacheExtension, bn as CacheSetOptions, vn as CacheDriver, xn as WaitUntilFn, yn as CacheEntry } from "./index-
|
|
1
|
+
import { Cn as WithCacheOptions, Sn as CacheInvalidationOptions, Ut as OfficialCacheExtension, bn as CacheSetOptions, vn as CacheDriver, xn as WaitUntilFn, yn as CacheEntry } from "./index-BbcE-gyl.mjs";
|
|
2
2
|
|
|
3
3
|
//#region src/cache/extension.d.ts
|
|
4
4
|
interface CacheExtensionConfig {
|
package/dist/cache.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{C as t,E as n,T as r,w as i}from"./validation-Du6j0Q38.mjs";import{b as a,c as o,f as s,g as c,l,m as u,r as d,y as f}from"./controls-BhxRnPYS.mjs";import{b as p}from"./base-vfur-DaU.mjs";import{g as m,p as h}from"./observation-CLp8ylmL.mjs";import{i as g}from"./key-DKaqPb8w.mjs";import{t as _}from"./invariant-DCsftyml.mjs";import{r as v}from"./builder-bPfagDQV.mjs";import{F as y,St as b,T as x,_ as S,r as C,x as w}from"./geo-point-codec-DUTTtlav.mjs";import{t as T}from"./validation-tgjL_9n8.mjs";import{a as E,i as D,n as O,o as k,r as A,s as j,t as M}from"./driver-CRaDT4B7.mjs";const N=new Set([`findFirst`,`findMany`,`findUnique`,`findUniqueOrThrow`,`findFirstOrThrow`,`count`,`aggregate`,`groupBy`,`exist`]),P=new WeakMap;function admitMutationCacheOptions(e){let t=T(k,e);if(t.issues)throw new h(`Invalid mutation cache options: ${t.issues.map(e=>e.message).join(`, `)}`,{cause:b(t)});let n=t.value.invalidate===void 0?void 0:[...t.value.invalidate];n&&Object.freeze(n);let r=Object.freeze({autoInvalidate:t.value.autoInvalidate,...n===void 0?{}:{invalidate:n}});return P.set(r,r),r}function readMutationCacheOptions(e){let t=e?.cache;return r(t)?P.get(t):void 0}function cacheKeyOf(e,t,n){if(t===void 0)return e;if(Object.values(t).every(d))return n===void 0?[e,t]:[e,t,n]}function prepareMutationCacheWriteOutcome(e,t,n,r,i,a){if(o(n))return Object.freeze({extension:`viborm.cache`,failurePolicy:`boundary-owned`,listener:async o=>{try{await D(e,t,r,i,a)}catch(e){throw new h(`Cache invalidation failed after mutation '${n}' on model '${t}'.`,{cause:p(e)?e:Error(`A non-Error value was thrown.`,{cause:e}),meta:{method:`invalidate`,model:t,operation:n,commitCertainty:o.certainty}})}}})}function validateCacheableOperation(e){if(!N.has(e))throw new m(e,[...N])}function createCacheExecutionOptions(e,t,n){let r=T(j,e);if(r.issues)throw new h(`Invalid cache options: ${r.issues.map(e=>e.message).join(`, `)}`,{cause:b(r)});let{bypass:i,key:a,ttl:o,swr:s}=r.value;return{ttlMs:o,swr:resolveSwr(s,o),bypass:i,key:a,waitUntil:t,driverIdentity:n}}function executeCachedResultOperation(e,t,n,r,i,a,o,s){return A(e,t,n,r,i,a,o,s)}async function invalidateManualCache(e,t,n,r){let i=[...t];await D(e,`manual`,Object.freeze({invalidate:i}),n,r)}function resolveSwr(e,t){return e===void 0||e===!1?!1:e===!0?t*2:t+e}var CacheSnapshotFailure=class extends Error{};function failCacheSnapshot(){throw new CacheSnapshotFailure}function readSnapshotArray(e){if(!Array.isArray(e)||Object.getPrototypeOf(e)!==Array.prototype)return failCacheSnapshot();let t=Reflect.ownKeys(e),n=Reflect.getOwnPropertyDescriptor(e,`length`)?.value;if(typeof n!=`number`||!Number.isSafeInteger(n)||n<0||t.length!==n+1||t[n]!==`length`)return failCacheSnapshot();let r=Array(n);for(let i=0;i<n;i+=1){let n=String(i);if(t[i]!==n)return failCacheSnapshot();let a=Reflect.getOwnPropertyDescriptor(e,n);if(!(a&&`value`in a&&a.enumerable))return failCacheSnapshot();r[i]=a.value}return r}function readSnapshotRecord(e,t=!1){if(typeof e!=`object`||!e||Array.isArray(e))return failCacheSnapshot();let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&!(t&&n===null))return failCacheSnapshot();let r=Reflect.ownKeys(e),i=Array(r.length);for(let t=0;t<r.length;t+=1){let n=r[t];if(typeof n!=`string`)return failCacheSnapshot();let a=Reflect.getOwnPropertyDescriptor(e,n);if(!(a&&`value`in a&&a.enumerable))return failCacheSnapshot();i[t]=[n,a.value]}return i}function defineSnapshotProperty(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,value:n,writable:!0})}function enterSnapshotObject(e,t){e.has(t)&&failCacheSnapshot(),e.add(t)}function withSnapshotObject(e,t,n){enterSnapshotObject(e,t);try{return n()}finally{e.delete(t)}}function encodeSnapshotNumber(e){return typeof e!=`number`||!Number.isFinite(e)?failCacheSnapshot():Object.is(e,-0)?`-0`:String(e)}function decodeSnapshotNumber(e){if(typeof e!=`string`)return failCacheSnapshot();let t=Number(e);return!Number.isFinite(t)||encodeSnapshotNumber(t)!==e?failCacheSnapshot():t}function encodeSnapshotCount(e){return typeof e!=`number`||!Number.isSafeInteger(e)||e<0?failCacheSnapshot():String(e)}function decodeSnapshotCount(e){let t=decodeSnapshotNumber(e);return!Number.isSafeInteger(t)||t<0?failCacheSnapshot():t}const F=`null`,I=`string`,L=`boolean`,R=`number`,z=`array`,B=`object`;function snapshotJsonValue(e,t){return e===null?[F]:typeof e==`string`?[I,e]:typeof e==`boolean`?[L,e]:typeof e==`number`?[R,encodeSnapshotNumber(e)]:Array.isArray(e)?withSnapshotObject(t,e,()=>[z,readSnapshotArray(e).map(e=>snapshotJsonValue(e,t))]):typeof e==`object`&&e?withSnapshotObject(t,e,()=>[B,readSnapshotRecord(e,!0).map(([e,n])=>[e,snapshotJsonValue(n,t)])]):failCacheSnapshot()}function materializeJsonValue(e,t){return typeof e!=`object`||!e?failCacheSnapshot():withSnapshotObject(t,e,()=>{let n=readSnapshotArray(e),r=n[0];return r===F&&n.length===1?null:r===I&&n.length===2&&typeof n[1]==`string`||r===L&&n.length===2&&typeof n[1]==`boolean`?n[1]:r===R&&n.length===2?decodeSnapshotNumber(n[1]):r===z&&n.length===2?materializeJsonArray(n[1],t):r===B&&n.length===2?materializeJsonObject(n[1],t):failCacheSnapshot()})}function materializeJsonArray(e,t){return typeof e!=`object`||!e?failCacheSnapshot():withSnapshotObject(t,e,()=>readSnapshotArray(e).map(e=>materializeJsonValue(e,t)))}function materializeJsonObject(e,t){return typeof e!=`object`||!e?failCacheSnapshot():withSnapshotObject(t,e,()=>{let n=readSnapshotArray(e),r={},i=new Set;for(let e of n){if(typeof e!=`object`||!e)return failCacheSnapshot();let n=withSnapshotObject(t,e,()=>readSnapshotArray(e)),a=n[0];if(n.length!==2||typeof a!=`string`||i.has(a))return failCacheSnapshot();i.add(a),defineSnapshotProperty(r,a,materializeJsonValue(n[1],t))}return r})}const V=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d{1,3})?$/;function compileScalarCodec(e,t=!0){let n;if(`enumValues`in e)n=enumCodec(new Set(e.enumValues));else{let t=e[`~`].state;switch(t.type){case`string`:n=stringCodec();break;case`time`:n=timeCodec();break;case`int`:n=integerCodec();break;case`number`:n=numberCodec();break;case`decimal`:n=decimalCodec(t.decimal);break;case`boolean`:n=booleanCodec();break;case`bigint`:n=bigintCodec();break;case`datetime`:n=dateCodec(!1);break;case`date`:n=dateCodec(!0);break;case`json`:n=jsonCodec();break;case`vector`:n=vectorCodec(t.dimension);break;case`blob`:n=bytesCodec();break;case`point`:n=pointCodec();break}}let r=e[`~`].state,i=r.array?arrayCodec(n):n;return t&&r.nullable?nullableCodec(i):i}function taggedRelationCodec(e){return{snapshot(t,n){return typeof t!=`object`||!t?failCacheSnapshot():withSnapshotObject(n,t,()=>{let r=readSnapshotRecord(t);if(r.length!==2)return failCacheSnapshot();let i,a;for(let[e,t]of r)if(e===`type`&&typeof t==`string`)i=t;else if(e===`data`)a=t;else return failCacheSnapshot();let o=i===void 0?void 0:e.get(i);return!o||a==null?failCacheSnapshot():r.map(([e,t])=>[e,e===`type`?i:o.snapshot(t,n)])})},materialize(t,n){return materializeArray(t,n,t=>{if(t.length!==2)return failCacheSnapshot();let r=readEncodedEntries(t,n),i,a;for(let[e,t]of r)if(e===`type`&&typeof t==`string`)i=t;else if(e===`data`)a=t;else return failCacheSnapshot();let o=i===void 0?void 0:e.get(i);if(!o||a==null)return failCacheSnapshot();let s={};for(let[e]of r)defineSnapshotProperty(s,e,e===`type`?i:o.materialize(a,n));return s})}}}function recordCodec(e){return{snapshot(t,n){return typeof t!=`object`||!t?failCacheSnapshot():withSnapshotObject(n,t,()=>{let r=readSnapshotRecord(t);if(r.length!==e.size)return failCacheSnapshot();let i=new Set;return r.map(([t,r])=>{let a=e.get(t);return!a||i.has(t)?failCacheSnapshot():(i.add(t),[t,a.snapshot(r,n)])})})},materialize(t,n){return materializeArray(t,n,t=>{if(t.length!==e.size)return failCacheSnapshot();let r=readEncodedEntries(t,n),i=new Set,a={};for(let[t,o]of r){let r=e.get(t);if(!r||i.has(t))return failCacheSnapshot();i.add(t),defineSnapshotProperty(a,t,r.materialize(o,n))}return a})}}}function arrayCodec(e){return{snapshot(t,n){return Array.isArray(t)?withSnapshotObject(n,t,()=>readSnapshotArray(t).map(t=>e.snapshot(t,n))):failCacheSnapshot()},materialize(t,n){return materializeArray(t,n,t=>t.map(t=>e.materialize(t,n)))}}}function nullableCodec(e){return{snapshot(t,n){return t===null?null:e.snapshot(t,n)},materialize(t,n){return t===null?null:e.materialize(t,n)}}}function recursiveRelationCodec(e,t){return{snapshot:(n,r)=>walkRecursiveSlot(n,r,e,{read(n){let i={},a=[];for(let[t,r]of readSnapshotRecord(n))t===e.relation?a.push(r):defineSnapshotProperty(i,t,r);return[t.snapshot(i,r),a]},write:(e,t)=>[e,...t]}),materialize:(n,r)=>walkRecursiveSlot(n,r,e,{read(e){let[n,...i]=readSnapshotArray(e);return[t.materialize(n,r),i]},write(t,n){return n.length>0&&defineSnapshotProperty(t,e.relation,n[0]),t}})}}function walkRecursiveSlot(e,t,n,r){let open=(e,t,r,i)=>{let a;return a=n.many?readSnapshotArray(e):e===null?n.optional?[]:failCacheSnapshot():[e],{level:t,occurrences:a,outputs:[],owner:r,node:i,next:0}},i=[open(e,1)],a;for(;i.length>0;){let e=i.at(-1);if(e.next<e.occurrences.length){let a=e.occurrences[e.next];if(e.next+=1,typeof a!=`object`||!a)return failCacheSnapshot();enterSnapshotObject(t,a);let o=v(n.depth,e.level),[s,c]=r.read(a);if(c.length!==(o?1:0))return failCacheSnapshot();if(o){i.push(open(c[0],e.level+1,a,s));continue}t.delete(a),e.outputs.push(r.write(s,c));continue}i.pop();let o=n.many?e.outputs:e.outputs[0]??null;if(e.owner===void 0){a=o;continue}let s=i.at(-1);t.delete(e.owner),s.outputs.push(r.write(e.node,[o]))}return a}function booleanCodec(){return primitiveCodec(e=>typeof e==`boolean`?e:failCacheSnapshot(),e=>typeof e==`boolean`?e:failCacheSnapshot())}function numberCodec(){return primitiveCodec(encodeSnapshotNumber,decodeSnapshotNumber)}function countCodec(){return primitiveCodec(encodeSnapshotCount,decodeSnapshotCount)}function readEncodedEntries(e,t){let n=Array(e.length);for(let r=0;r<e.length;r+=1)n[r]=materializeArray(e[r],t,e=>e.length!==2||typeof e[0]!=`string`?failCacheSnapshot():[e[0],e[1]]);return n}function stringCodec(){return primitiveCodec(e=>typeof e==`string`?e:failCacheSnapshot(),e=>typeof e==`string`?e:failCacheSnapshot())}function timeCodec(){return primitiveCodec(e=>typeof e==`string`&&V.test(e)?e:failCacheSnapshot(),e=>typeof e==`string`&&V.test(e)?e:failCacheSnapshot())}function enumCodec(e){return primitiveCodec(t=>typeof t==`string`&&e.has(t)?t:failCacheSnapshot(),t=>typeof t==`string`&&e.has(t)?t:failCacheSnapshot())}function integerCodec(){return primitiveCodec(e=>typeof e!=`number`||!Number.isSafeInteger(e)?failCacheSnapshot():encodeSnapshotNumber(e),e=>{let t=decodeSnapshotNumber(e);return Number.isSafeInteger(t)?t:failCacheSnapshot()})}function decimalCodec(e){return primitiveCodec(t=>e?w(S(t),e)??failCacheSnapshot():failCacheSnapshot(),t=>{if(!e)return failCacheSnapshot();let n=w(t,e);return n!==void 0&&n===t?y(n):failCacheSnapshot()})}function compileWidenedSumCodec(e){let t=e[`~`].state.decimal;return primitiveCodec(e=>t?x(S(e),t.scale)??failCacheSnapshot():failCacheSnapshot(),e=>{if(!t)return failCacheSnapshot();let n=x(e,t.scale);return n!==void 0&&n===e?y(n):failCacheSnapshot()})}function bigintCodec(){return primitiveCodec(e=>typeof e==`bigint`?e.toString():failCacheSnapshot(),e=>{if(typeof e!=`string`)return failCacheSnapshot();try{let t=BigInt(e);return t.toString()===e?t:failCacheSnapshot()}catch{return failCacheSnapshot()}})}function dateCodec(e){return primitiveCodec(t=>{if(!(t instanceof Date)||Object.getPrototypeOf(t)!==Date.prototype||Reflect.ownKeys(t).length!==0)return failCacheSnapshot();let n=Date.prototype.getTime.call(t);if(!Number.isFinite(n))return failCacheSnapshot();let r=Date.prototype.toISOString.call(t);return e&&!r.endsWith(`T00:00:00.000Z`)?failCacheSnapshot():r},t=>{if(typeof t!=`string`)return failCacheSnapshot();let n=new Date(t);return!Number.isFinite(n.getTime())||n.toISOString()!==t||e&&!t.endsWith(`T00:00:00.000Z`)?failCacheSnapshot():n})}function jsonCodec(){return{snapshot:snapshotJsonValue,materialize:materializeJsonValue}}function vectorCodec(e){return{snapshot(t,n){return Array.isArray(t)?withSnapshotObject(n,t,()=>{let n=readSnapshotArray(t);return e!==void 0&&n.length!==e?failCacheSnapshot():n.map(encodeSnapshotNumber)}):failCacheSnapshot()},materialize(t,n){return materializeArray(t,n,t=>e!==void 0&&t.length!==e?failCacheSnapshot():t.map(decodeSnapshotNumber))}}}function bytesCodec(){return{snapshot(e){if(!(e instanceof Uint8Array)||Object.getPrototypeOf(e)!==Uint8Array.prototype||Reflect.ownKeys(e).length!==e.byteLength)return failCacheSnapshot();let t=Array(e.byteLength);for(let n=0;n<e.byteLength;n+=1)t[n]=e[n];return t},materialize(e){let t=readSnapshotArray(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e+=1){let r=t[e];if(typeof r!=`number`||!Number.isInteger(r)||r<0||r>255)return failCacheSnapshot();n[e]=r}return n}}}function pointCodec(){let e=recordCodec(new Map([[`longitude`,numberCodec()],[`latitude`,numberCodec()]]));return{snapshot(t,n){let r=C(t);return r.issues?failCacheSnapshot():e.snapshot(r.value,n)},materialize(t,n){let r=C(e.materialize(t,n));return r.issues?failCacheSnapshot():r.value}}}function primitiveCodec(e,t){return{snapshot:e,materialize:t}}function materializeArray(e,t,n){return typeof e!=`object`||!e?failCacheSnapshot():withSnapshotObject(t,e,()=>n(readSnapshotArray(e)))}function cacheCodec(e,t){let n=shapeCodec(e.value,t),r=e.empty===null?nullableCodec(n):n;return Object.freeze({snapshot(e){try{return r.snapshot(e,new WeakSet)}catch(e){throw new h(`The operation result cannot be represented by the cache result codec.`,{cause:e instanceof Error?e:void 0,meta:{method:`snapshot`,operation:t}})}},materialize(e){try{return r.materialize(e,new WeakSet)}catch(e){throw new h(`The cached result snapshot is malformed.`,{cause:e instanceof Error?e:void 0,meta:{method:`materialize`,operation:t}})}}})}function shapeCodec(e,t){switch(e.kind){case`scalar`:return leafCodec(e,t);case`object`:{let n=new Map;for(let[r,i]of Object.entries(e.fields))n.set(r,shapeCodec(i,t));let r=recordCodec(n);return e.nullable===!1?r:nullableCodec(r)}case`collection`:return arrayCodec(shapeCodec(e.row,t));case`variants`:{let n=new Map;for(let[r,i]of Object.entries(e.arms))n.set(r,shapeCodec(e.many&&i.kind===`collection`?i.row:i,t));let r=taggedRelationCodec(n);return e.many?arrayCodec(r):nullableCodec(r)}case`recursive`:return recursiveRelationCodec({relation:e.relation,many:e.many,optional:e.optional,depth:e.recurrence.depth},shapeCodec(e.row,t))}}function leafCodec(e,t){let n=e.scalar,r;if(n)r=e.widened?compileWidenedSumCodec(n):compileScalarCodec(n,!1);else if(e.type===`boolean`)r=booleanCodec();else if(e.type===`int`)r=countCodec();else if(e.type===`number`)r=numberCodec();else throw new _(`Cannot cache a '${e.type}' result for '${t}': its scalar declaration is missing.`);return e.nullable?nullableCodec(r):r}function bindChain(e,t){let n=s(e);n!==void 0&&a(e,Object.freeze({driver:n.driver,version:n.version,waitUntil:n.waitUntil,scope:O(g({version:n.version,dialect:t.dialect,namespace:t.adapter.namespace}))}))}const H=Object.freeze({admitMutationCacheOptions,bindChain,cacheCodec,cacheKeyOf,createCacheExecutionOptions,executeCachedResultOperation,invalidateManualCache,prepareMutationCacheWriteOutcome,readCacheExecutionOutcomes:E,readMutationCacheOptions,validateCacheableOperation});u(H);function configurationCause(e){return p(e)?e:Error(`A non-Error value was thrown.`,{cause:e})}function configurationError(e,t){throw new h(e,{cause:t===void 0?void 0:configurationCause(t)})}function isCacheDriver(e){try{return e instanceof M}catch(e){configurationError(`Cache extension driver capability could not be inspected.`,e)}}function snapshotConfig(e){r(e)||configurationError(`Cache extension configuration must be an object.`);let a;try{a=Reflect.ownKeys(e)}catch(e){configurationError(`Cache extension configuration could not be inspected.`,e)}for(let e of a)(typeof e!=`string`||e!==`driver`&&e!==`version`&&e!==`waitUntil`)&&configurationError(`Cache extension configuration has unknown member "${String(e)}".`);let read=t=>{if(a.includes(t))try{return e[t]}catch(e){configurationError(`Cache extension configuration member "${t}" could not be read.`,e)}},o=read(`driver`),s=read(`version`),c=read(`waitUntil`);return isCacheDriver(o)||configurationError(`Cache extension configuration requires a CacheDriver instance.`),s!==void 0&&!(n(s)||i(s)&&Number.isFinite(s))&&configurationError(`Cache extension configuration "version" must be a string or finite number.`),c!==void 0&&!t(c)&&configurationError(`Cache extension configuration "waitUntil" must be a function.`),Object.freeze({driver:o,version:s,waitUntil:c})}function cache(e){let t=snapshotConfig(e),query=({proceed:e})=>e();return f(query,t,H),Object.freeze({name:l,query,controls:c})}export{M as CacheDriver,cache};
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{C as t,E as n,T as r,w as i}from"./validation-Du6j0Q38.mjs";import{b as a,c as o,f as s,g as c,l,m as u,r as d,y as f}from"./controls-BhxRnPYS.mjs";import{b as p}from"./base-vfur-DaU.mjs";import{g as m,p as h}from"./observation-CLp8ylmL.mjs";import{i as g}from"./key-DKaqPb8w.mjs";import{t as _}from"./invariant-DCsftyml.mjs";import{r as v}from"./builder-DkWfNHEV.mjs";import{F as y,St as b,T as x,_ as S,r as C,x as w}from"./geo-point-codec-DUTTtlav.mjs";import{t as T}from"./validation-tgjL_9n8.mjs";import{a as E,i as D,n as O,o as k,r as A,s as j,t as M}from"./driver-ZIbkciaz.mjs";const N=new Set([`findFirst`,`findMany`,`findUnique`,`findUniqueOrThrow`,`findFirstOrThrow`,`count`,`aggregate`,`groupBy`,`exist`]),P=new WeakMap;function admitMutationCacheOptions(e){let t=T(k,e);if(t.issues)throw new h(`Invalid mutation cache options: ${t.issues.map(e=>e.message).join(`, `)}`,{cause:b(t)});let n=t.value.invalidate===void 0?void 0:[...t.value.invalidate];n&&Object.freeze(n);let r=Object.freeze({autoInvalidate:t.value.autoInvalidate,...n===void 0?{}:{invalidate:n}});return P.set(r,r),r}function readMutationCacheOptions(e){let t=e?.cache;return r(t)?P.get(t):void 0}function cacheKeyOf(e,t,n){if(t===void 0)return e;if(Object.values(t).every(d))return n===void 0?[e,t]:[e,t,n]}function prepareMutationCacheWriteOutcome(e,t,n,r,i,a){if(o(n))return Object.freeze({extension:`viborm.cache`,failurePolicy:`boundary-owned`,listener:async o=>{try{await D(e,t,r,i,a)}catch(e){throw new h(`Cache invalidation failed after mutation '${n}' on model '${t}'.`,{cause:p(e)?e:Error(`A non-Error value was thrown.`,{cause:e}),meta:{method:`invalidate`,model:t,operation:n,commitCertainty:o.certainty}})}}})}function validateCacheableOperation(e){if(!N.has(e))throw new m(e,[...N])}function createCacheExecutionOptions(e,t,n){let r=T(j,e);if(r.issues)throw new h(`Invalid cache options: ${r.issues.map(e=>e.message).join(`, `)}`,{cause:b(r)});let{bypass:i,key:a,ttl:o,swr:s}=r.value;return{ttlMs:o,swr:resolveSwr(s,o),bypass:i,key:a,waitUntil:t,driverIdentity:n}}function executeCachedResultOperation(e,t,n,r,i,a,o,s){return A(e,t,n,r,i,a,o,s)}async function invalidateManualCache(e,t,n,r){let i=[...t];await D(e,`manual`,Object.freeze({invalidate:i}),n,r)}function resolveSwr(e,t){return e===void 0||e===!1?!1:e===!0?t*2:t+e}var CacheSnapshotFailure=class extends Error{};function failCacheSnapshot(){throw new CacheSnapshotFailure}function readSnapshotArray(e){if(!Array.isArray(e)||Object.getPrototypeOf(e)!==Array.prototype)return failCacheSnapshot();let t=Reflect.ownKeys(e),n=Reflect.getOwnPropertyDescriptor(e,`length`)?.value;if(typeof n!=`number`||!Number.isSafeInteger(n)||n<0||t.length!==n+1||t[n]!==`length`)return failCacheSnapshot();let r=Array(n);for(let i=0;i<n;i+=1){let n=String(i);if(t[i]!==n)return failCacheSnapshot();let a=Reflect.getOwnPropertyDescriptor(e,n);if(!(a&&`value`in a&&a.enumerable))return failCacheSnapshot();r[i]=a.value}return r}function readSnapshotRecord(e,t=!1){if(typeof e!=`object`||!e||Array.isArray(e))return failCacheSnapshot();let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&!(t&&n===null))return failCacheSnapshot();let r=Reflect.ownKeys(e),i=Array(r.length);for(let t=0;t<r.length;t+=1){let n=r[t];if(typeof n!=`string`)return failCacheSnapshot();let a=Reflect.getOwnPropertyDescriptor(e,n);if(!(a&&`value`in a&&a.enumerable))return failCacheSnapshot();i[t]=[n,a.value]}return i}function defineSnapshotProperty(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,value:n,writable:!0})}function enterSnapshotObject(e,t){e.has(t)&&failCacheSnapshot(),e.add(t)}function withSnapshotObject(e,t,n){enterSnapshotObject(e,t);try{return n()}finally{e.delete(t)}}function encodeSnapshotNumber(e){return typeof e!=`number`||!Number.isFinite(e)?failCacheSnapshot():Object.is(e,-0)?`-0`:String(e)}function decodeSnapshotNumber(e){if(typeof e!=`string`)return failCacheSnapshot();let t=Number(e);return!Number.isFinite(t)||encodeSnapshotNumber(t)!==e?failCacheSnapshot():t}function encodeSnapshotCount(e){return typeof e!=`number`||!Number.isSafeInteger(e)||e<0?failCacheSnapshot():String(e)}function decodeSnapshotCount(e){let t=decodeSnapshotNumber(e);return!Number.isSafeInteger(t)||t<0?failCacheSnapshot():t}const F=`null`,I=`string`,L=`boolean`,R=`number`,z=`array`,B=`object`;function snapshotJsonValue(e,t){return e===null?[F]:typeof e==`string`?[I,e]:typeof e==`boolean`?[L,e]:typeof e==`number`?[R,encodeSnapshotNumber(e)]:Array.isArray(e)?withSnapshotObject(t,e,()=>[z,readSnapshotArray(e).map(e=>snapshotJsonValue(e,t))]):typeof e==`object`&&e?withSnapshotObject(t,e,()=>[B,readSnapshotRecord(e,!0).map(([e,n])=>[e,snapshotJsonValue(n,t)])]):failCacheSnapshot()}function materializeJsonValue(e,t){return typeof e!=`object`||!e?failCacheSnapshot():withSnapshotObject(t,e,()=>{let n=readSnapshotArray(e),r=n[0];return r===F&&n.length===1?null:r===I&&n.length===2&&typeof n[1]==`string`||r===L&&n.length===2&&typeof n[1]==`boolean`?n[1]:r===R&&n.length===2?decodeSnapshotNumber(n[1]):r===z&&n.length===2?materializeJsonArray(n[1],t):r===B&&n.length===2?materializeJsonObject(n[1],t):failCacheSnapshot()})}function materializeJsonArray(e,t){return typeof e!=`object`||!e?failCacheSnapshot():withSnapshotObject(t,e,()=>readSnapshotArray(e).map(e=>materializeJsonValue(e,t)))}function materializeJsonObject(e,t){return typeof e!=`object`||!e?failCacheSnapshot():withSnapshotObject(t,e,()=>{let n=readSnapshotArray(e),r={},i=new Set;for(let e of n){if(typeof e!=`object`||!e)return failCacheSnapshot();let n=withSnapshotObject(t,e,()=>readSnapshotArray(e)),a=n[0];if(n.length!==2||typeof a!=`string`||i.has(a))return failCacheSnapshot();i.add(a),defineSnapshotProperty(r,a,materializeJsonValue(n[1],t))}return r})}const V=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d{1,3})?$/;function compileScalarCodec(e,t=!0){let n;if(`enumValues`in e)n=enumCodec(new Set(e.enumValues));else{let t=e[`~`].state;switch(t.type){case`string`:n=stringCodec();break;case`time`:n=timeCodec();break;case`int`:n=integerCodec();break;case`number`:n=numberCodec();break;case`decimal`:n=decimalCodec(t.decimal);break;case`boolean`:n=booleanCodec();break;case`bigint`:n=bigintCodec();break;case`datetime`:n=dateCodec(!1);break;case`date`:n=dateCodec(!0);break;case`json`:n=jsonCodec();break;case`vector`:n=vectorCodec(t.dimension);break;case`blob`:n=bytesCodec();break;case`point`:n=pointCodec();break}}let r=e[`~`].state,i=r.array?arrayCodec(n):n;return t&&r.nullable?nullableCodec(i):i}function taggedRelationCodec(e){return{snapshot(t,n){return typeof t!=`object`||!t?failCacheSnapshot():withSnapshotObject(n,t,()=>{let r=readSnapshotRecord(t);if(r.length!==2)return failCacheSnapshot();let i,a;for(let[e,t]of r)if(e===`type`&&typeof t==`string`)i=t;else if(e===`data`)a=t;else return failCacheSnapshot();let o=i===void 0?void 0:e.get(i);return!o||a==null?failCacheSnapshot():r.map(([e,t])=>[e,e===`type`?i:o.snapshot(t,n)])})},materialize(t,n){return materializeArray(t,n,t=>{if(t.length!==2)return failCacheSnapshot();let r=readEncodedEntries(t,n),i,a;for(let[e,t]of r)if(e===`type`&&typeof t==`string`)i=t;else if(e===`data`)a=t;else return failCacheSnapshot();let o=i===void 0?void 0:e.get(i);if(!o||a==null)return failCacheSnapshot();let s={};for(let[e]of r)defineSnapshotProperty(s,e,e===`type`?i:o.materialize(a,n));return s})}}}function recordCodec(e){return{snapshot(t,n){return typeof t!=`object`||!t?failCacheSnapshot():withSnapshotObject(n,t,()=>{let r=readSnapshotRecord(t);if(r.length!==e.size)return failCacheSnapshot();let i=new Set;return r.map(([t,r])=>{let a=e.get(t);return!a||i.has(t)?failCacheSnapshot():(i.add(t),[t,a.snapshot(r,n)])})})},materialize(t,n){return materializeArray(t,n,t=>{if(t.length!==e.size)return failCacheSnapshot();let r=readEncodedEntries(t,n),i=new Set,a={};for(let[t,o]of r){let r=e.get(t);if(!r||i.has(t))return failCacheSnapshot();i.add(t),defineSnapshotProperty(a,t,r.materialize(o,n))}return a})}}}function arrayCodec(e){return{snapshot(t,n){return Array.isArray(t)?withSnapshotObject(n,t,()=>readSnapshotArray(t).map(t=>e.snapshot(t,n))):failCacheSnapshot()},materialize(t,n){return materializeArray(t,n,t=>t.map(t=>e.materialize(t,n)))}}}function nullableCodec(e){return{snapshot(t,n){return t===null?null:e.snapshot(t,n)},materialize(t,n){return t===null?null:e.materialize(t,n)}}}function recursiveRelationCodec(e,t){return{snapshot:(n,r)=>walkRecursiveSlot(n,r,e,{read(n){let i={},a=[];for(let[t,r]of readSnapshotRecord(n))t===e.relation?a.push(r):defineSnapshotProperty(i,t,r);return[t.snapshot(i,r),a]},write:(e,t)=>[e,...t]}),materialize:(n,r)=>walkRecursiveSlot(n,r,e,{read(e){let[n,...i]=readSnapshotArray(e);return[t.materialize(n,r),i]},write(t,n){return n.length>0&&defineSnapshotProperty(t,e.relation,n[0]),t}})}}function walkRecursiveSlot(e,t,n,r){let open=(e,t,r,i)=>{let a;return a=n.many?readSnapshotArray(e):e===null?n.optional?[]:failCacheSnapshot():[e],{level:t,occurrences:a,outputs:[],owner:r,node:i,next:0}},i=[open(e,1)],a;for(;i.length>0;){let e=i.at(-1);if(e.next<e.occurrences.length){let a=e.occurrences[e.next];if(e.next+=1,typeof a!=`object`||!a)return failCacheSnapshot();enterSnapshotObject(t,a);let o=v(n.depth,e.level),[s,c]=r.read(a);if(c.length!==(o?1:0))return failCacheSnapshot();if(o){i.push(open(c[0],e.level+1,a,s));continue}t.delete(a),e.outputs.push(r.write(s,c));continue}i.pop();let o=n.many?e.outputs:e.outputs[0]??null;if(e.owner===void 0){a=o;continue}let s=i.at(-1);t.delete(e.owner),s.outputs.push(r.write(e.node,[o]))}return a}function booleanCodec(){return primitiveCodec(e=>typeof e==`boolean`?e:failCacheSnapshot(),e=>typeof e==`boolean`?e:failCacheSnapshot())}function numberCodec(){return primitiveCodec(encodeSnapshotNumber,decodeSnapshotNumber)}function countCodec(){return primitiveCodec(encodeSnapshotCount,decodeSnapshotCount)}function readEncodedEntries(e,t){let n=Array(e.length);for(let r=0;r<e.length;r+=1)n[r]=materializeArray(e[r],t,e=>e.length!==2||typeof e[0]!=`string`?failCacheSnapshot():[e[0],e[1]]);return n}function stringCodec(){return primitiveCodec(e=>typeof e==`string`?e:failCacheSnapshot(),e=>typeof e==`string`?e:failCacheSnapshot())}function timeCodec(){return primitiveCodec(e=>typeof e==`string`&&V.test(e)?e:failCacheSnapshot(),e=>typeof e==`string`&&V.test(e)?e:failCacheSnapshot())}function enumCodec(e){return primitiveCodec(t=>typeof t==`string`&&e.has(t)?t:failCacheSnapshot(),t=>typeof t==`string`&&e.has(t)?t:failCacheSnapshot())}function integerCodec(){return primitiveCodec(e=>typeof e!=`number`||!Number.isSafeInteger(e)?failCacheSnapshot():encodeSnapshotNumber(e),e=>{let t=decodeSnapshotNumber(e);return Number.isSafeInteger(t)?t:failCacheSnapshot()})}function decimalCodec(e){return primitiveCodec(t=>e?w(S(t),e)??failCacheSnapshot():failCacheSnapshot(),t=>{if(!e)return failCacheSnapshot();let n=w(t,e);return n!==void 0&&n===t?y(n):failCacheSnapshot()})}function compileWidenedSumCodec(e){let t=e[`~`].state.decimal;return primitiveCodec(e=>t?x(S(e),t.scale)??failCacheSnapshot():failCacheSnapshot(),e=>{if(!t)return failCacheSnapshot();let n=x(e,t.scale);return n!==void 0&&n===e?y(n):failCacheSnapshot()})}function bigintCodec(){return primitiveCodec(e=>typeof e==`bigint`?e.toString():failCacheSnapshot(),e=>{if(typeof e!=`string`)return failCacheSnapshot();try{let t=BigInt(e);return t.toString()===e?t:failCacheSnapshot()}catch{return failCacheSnapshot()}})}function dateCodec(e){return primitiveCodec(t=>{if(!(t instanceof Date)||Object.getPrototypeOf(t)!==Date.prototype||Reflect.ownKeys(t).length!==0)return failCacheSnapshot();let n=Date.prototype.getTime.call(t);if(!Number.isFinite(n))return failCacheSnapshot();let r=Date.prototype.toISOString.call(t);return e&&!r.endsWith(`T00:00:00.000Z`)?failCacheSnapshot():r},t=>{if(typeof t!=`string`)return failCacheSnapshot();let n=new Date(t);return!Number.isFinite(n.getTime())||n.toISOString()!==t||e&&!t.endsWith(`T00:00:00.000Z`)?failCacheSnapshot():n})}function jsonCodec(){return{snapshot:snapshotJsonValue,materialize:materializeJsonValue}}function vectorCodec(e){return{snapshot(t,n){return Array.isArray(t)?withSnapshotObject(n,t,()=>{let n=readSnapshotArray(t);return e!==void 0&&n.length!==e?failCacheSnapshot():n.map(encodeSnapshotNumber)}):failCacheSnapshot()},materialize(t,n){return materializeArray(t,n,t=>e!==void 0&&t.length!==e?failCacheSnapshot():t.map(decodeSnapshotNumber))}}}function bytesCodec(){return{snapshot(e){if(!(e instanceof Uint8Array)||Object.getPrototypeOf(e)!==Uint8Array.prototype||Reflect.ownKeys(e).length!==e.byteLength)return failCacheSnapshot();let t=Array(e.byteLength);for(let n=0;n<e.byteLength;n+=1)t[n]=e[n];return t},materialize(e){let t=readSnapshotArray(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e+=1){let r=t[e];if(typeof r!=`number`||!Number.isInteger(r)||r<0||r>255)return failCacheSnapshot();n[e]=r}return n}}}function pointCodec(){let e=recordCodec(new Map([[`longitude`,numberCodec()],[`latitude`,numberCodec()]]));return{snapshot(t,n){let r=C(t);return r.issues?failCacheSnapshot():e.snapshot(r.value,n)},materialize(t,n){let r=C(e.materialize(t,n));return r.issues?failCacheSnapshot():r.value}}}function primitiveCodec(e,t){return{snapshot:e,materialize:t}}function materializeArray(e,t,n){return typeof e!=`object`||!e?failCacheSnapshot():withSnapshotObject(t,e,()=>n(readSnapshotArray(e)))}function cacheCodec(e,t){let n=shapeCodec(e.value,t),r=e.empty===null?nullableCodec(n):n;return Object.freeze({snapshot(e){try{return r.snapshot(e,new WeakSet)}catch(e){throw new h(`The operation result cannot be represented by the cache result codec.`,{cause:e instanceof Error?e:void 0,meta:{method:`snapshot`,operation:t}})}},materialize(e){try{return r.materialize(e,new WeakSet)}catch(e){throw new h(`The cached result snapshot is malformed.`,{cause:e instanceof Error?e:void 0,meta:{method:`materialize`,operation:t}})}}})}function shapeCodec(e,t){switch(e.kind){case`scalar`:return leafCodec(e,t);case`object`:{let n=new Map;for(let[r,i]of Object.entries(e.fields))n.set(r,shapeCodec(i,t));let r=recordCodec(n);return e.nullable===!1?r:nullableCodec(r)}case`collection`:return arrayCodec(shapeCodec(e.row,t));case`variants`:{let n=new Map;for(let[r,i]of Object.entries(e.arms))n.set(r,shapeCodec(e.many&&i.kind===`collection`?i.row:i,t));let r=taggedRelationCodec(n);return e.many?arrayCodec(r):nullableCodec(r)}case`recursive`:return recursiveRelationCodec({relation:e.relation,many:e.many,optional:e.optional,depth:e.recurrence.depth},shapeCodec(e.row,t))}}function leafCodec(e,t){let n=e.scalar,r;if(n)r=e.widened?compileWidenedSumCodec(n):compileScalarCodec(n,!1);else if(e.type===`boolean`)r=booleanCodec();else if(e.type===`int`)r=countCodec();else if(e.type===`number`)r=numberCodec();else throw new _(`Cannot cache a '${e.type}' result for '${t}': its scalar declaration is missing.`);return e.nullable?nullableCodec(r):r}function bindChain(e,t){let n=s(e);n!==void 0&&a(e,Object.freeze({driver:n.driver,version:n.version,waitUntil:n.waitUntil,scope:O(g({version:n.version,dialect:t.dialect,namespace:t.adapter.namespace}))}))}const H=Object.freeze({admitMutationCacheOptions,bindChain,cacheCodec,cacheKeyOf,createCacheExecutionOptions,executeCachedResultOperation,invalidateManualCache,prepareMutationCacheWriteOutcome,readCacheExecutionOutcomes:E,readMutationCacheOptions,validateCacheableOperation});u(H);function configurationCause(e){return p(e)?e:Error(`A non-Error value was thrown.`,{cause:e})}function configurationError(e,t){throw new h(e,{cause:t===void 0?void 0:configurationCause(t)})}function isCacheDriver(e){try{return e instanceof M}catch(e){configurationError(`Cache extension driver capability could not be inspected.`,e)}}function snapshotConfig(e){r(e)||configurationError(`Cache extension configuration must be an object.`);let a;try{a=Reflect.ownKeys(e)}catch(e){configurationError(`Cache extension configuration could not be inspected.`,e)}for(let e of a)(typeof e!=`string`||e!==`driver`&&e!==`version`&&e!==`waitUntil`)&&configurationError(`Cache extension configuration has unknown member "${String(e)}".`);let read=t=>{if(a.includes(t))try{return e[t]}catch(e){configurationError(`Cache extension configuration member "${t}" could not be read.`,e)}},o=read(`driver`),s=read(`version`),c=read(`waitUntil`);return isCacheDriver(o)||configurationError(`Cache extension configuration requires a CacheDriver instance.`),s!==void 0&&!(n(s)||i(s)&&Number.isFinite(s))&&configurationError(`Cache extension configuration "version" must be a string or finite number.`),c!==void 0&&!t(c)&&configurationError(`Cache extension configuration "waitUntil" must be a function.`),Object.freeze({driver:o,version:s,waitUntil:c})}function cache(e){let t=snapshotConfig(e),query=({proceed:e})=>e();return f(query,t,H),Object.freeze({name:l,query,controls:c})}export{M as CacheDriver,cache};
|
|
2
2
|
//# sourceMappingURL=cache.mjs.map
|
package/dist/cli.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t}from"./validator-DMlEScV3.mjs";import{
|
|
3
|
-
`);async function runCheck(e){let r
|
|
4
|
-
`)}\n`)}e(printJson$1,`printJson`);async function withMigrations(e,t){let n,r;try{let r=await
|
|
5
|
-
`)}\n`);for(let e of a.warnings??[])process.stderr.write(`warning: ${e}\n`);(a.reviewSql||a.sql)&&process.stdout.write(`${a.reviewSql||a.sql}\n`)}t.review&&a.reviewSql&&await
|
|
6
|
-
`),`Push plan`)}async function runPush(e){let t,n;try{let n=await
|
|
7
|
-
`),e.dryRun){e.json?printJson(
|
|
2
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t}from"./validator-DMlEScV3.mjs";import{_ as n}from"./registration-preflight-BrA3EWvq.mjs";import{t as r}from"./physical-BkelResN.mjs";import{t as i}from"./hydration-D6JICBQG.mjs";import{t as a}from"./version-De1l_ZMF.mjs";import{F as o}from"./batch-refs-Op1fx9Bo.mjs";import{a as s,d as c,m as l,n as u,r as d,t as f}from"./client-z9mcpRtA.mjs";import{i as p,n as m,r as h}from"./utils-CRFUUfNn.mjs";import{o as g,t as _}from"./fs-estate-BLqNdigQ.mjs";import{Command as v,InvalidArgumentError as y}from"commander";import{resolve as b}from"node:path";import{writeFile as x}from"node:fs/promises";import{cancel as S,confirm as C,isCancel as w,note as T,outro as E}from"@clack/prompts";const D=o(`"`);async function readCatalog(e,t){let{rows:n}=await e._executeRaw(`SELECT s.sql AS definition, p.name, p.type, p."notnull", p.pk FROM sqlite_schema AS s JOIN pragma_table_info(s.name) AS p WHERE s.type = 'table' AND s.name = ?`,[t]);return n.map(({notnull:e,pk:t,...n})=>({...n,nullable:Number(e)===0&&Number(t)===0}))}async function auditStorage(e,t){if(e.dialect!==`sqlite`)return[];let i=[];for(let[a,o]of Object.entries(t)){let t=n(o,a),s=o[`~`].state,u,find=async n=>(await(u??=readCatalog(e,t))).find(e=>e.name===n);for(let[n,a]of Object.entries(s.scalars)){let s=a[`~`].state,{type:u,array:d=!1}=s,f=o[`~`].getFieldName(n).sql;if(s.type===`decimal`){let e=await find(f);i.push({table:t,column:f,type:`decimal`,declared:e?.type??null,checked:e!==void 0&&c(e.definition,e,s.decimal,d?`list`:`scalar`,D)});continue}if(!(u===`time`||u===`datetime`&&(d||r(a[`~`].nativeType)===`text`)))continue;let p=await find(f)&&await e._executeRaw(l(t,f,u,d));i.push({table:t,column:f,type:u,list:d,noncanonical:p?Number(p.rows[0]?.noncanonical):null})}}return i}const needsRepair=e=>e.type===`decimal`?!e.checked:e.noncanonical!==0,describeAudit=e=>{let t=`[storage] "${e.table}"."${e.column}"`;if((e.type===`decimal`?e.declared:e.noncanonical)===null)return`${t}: the column is missing; typed queries that use it fail.\n Create it through viborm push or migrate.`;if(e.type===`decimal`)return`${t}: declared ${e.declared}, not the checked scaled-integer decimal storage VibORM writes; typed reads, filters and writes are not checked against it.\n Adopt the table through viborm push, migrate or baseline: https://viborm.dev/docs/migration/drivers/sqlite#adopting-decimal-columns-from-another-tool`;let n=e.type===`time`?`Time`:`DateTime`,r=e.list?"Rewrite each row through the typed client (`update`), which stores canonical members":`Repair with sqliteCanonical${n}Expression from viborm/migrations`;return`${t}: ${e.noncanonical} row(s) of noncanonical ${n} text compare and sort wrongly.\n ${r}: https://viborm.dev/docs/migration/drivers/sqlite#repairing-foreign-timestamp-and-time-text`},describe=e=>[`[${e.code}] ${e.message}`,e.repair].filter(Boolean).join(`
|
|
3
|
+
`);async function runCheck(e){let n,r;try{let r=await p({config:e.config,skipValidation:!0});n=r.client;let{models:a}=r;i(a);let o=t(a),s=e.db?await auditStorage(r.driver,a):void 0,c=s?.filter(needsRepair)??[];if(e.json)process.stdout.write(`${JSON.stringify(s?{...o,storage:s}:o,null,2)}\n`);else{for(let e of o.errors)process.stderr.write(`error ${describe(e)}\n`);for(let e of o.warnings)process.stderr.write(`warning ${describe(e)}\n`);for(let e of c)process.stderr.write(`error ${describeAudit(e)}\n`);process.stdout.write(o.valid?`Schema valid (${Object.keys(a).length} models).\n`:`Schema invalid: ${o.errors.length} error(s).\n`),s&&process.stdout.write(`Storage audited: ${s.length} column(s), ${c.length} need repair.\n`)}(!o.valid||c.length>0)&&(process.exitCode=1)}catch(e){r={value:e}}finally{await m(n,r,e.json)}}function createCheckCommand(){return new v(`check`).description(`Validate the schema, so clients can be created with skipSchemaValidation`).option(`--config <path>`,`Path to viborm.config.ts`).option(`--json`,`Print machine-readable JSON`).option(`--db`,`Also audit SQLite storage: DateTime/Time text and decimal columns`).action(runCheck)}const O=createCheckCommand(),k=/^[0-9a-f]{8,63}$/;function positiveInteger(e){let t=Number(e);if(!Number.isSafeInteger(t)||t<=0)throw new y(`must be a positive safe integer`);return t}function selector(e){if(e)return g(e)?{id:e}:k.test(e)?{prefix:e}:{name:e}}function printJson$1(e,t){if(t){process.stdout.write(`${JSON.stringify(e,null,2)}\n`);return}let n=[],render=(e,t=``)=>{if(Array.isArray(e)){for(let r of e)n.push(`${t}-`),render(r,`${t} `);e.length===0&&n.push(`${t}(none)`)}else if(typeof e==`object`&&e)for(let[r,i]of Object.entries(e))typeof i==`object`&&i?(n.push(`${t}${r}:`),render(i,`${t} `)):n.push(`${t}${r}: ${String(i)}`);else n.push(`${t}${String(e)}`)};render(e),process.stdout.write(`${n.join(`
|
|
4
|
+
`)}\n`)}e(printJson$1,`printJson`);async function withMigrations(e,t){let n,r;try{let r=await p({config:e.config});n=r.client;let i=b(e.dir??r.migrations?.dir??`./migrations`),a=r.migrations?.storage??_(i);await t(f(r.client,{storage:a,...r.migrations?.tables===void 0?{}:{tables:r.migrations.tables}}),r,a)}catch(e){r={value:e}}finally{await m(n,r,e.json)}}function createMigrateCommand(){let e=new v(`migrate`).description(`Manage the authenticated migration estate`).option(`--config <path>`,`Path to viborm.config.ts`);return e.command(`generate`).description(`Publish a new estate state from the current schema`).option(`-n, --name <name>`,`Human-readable state label`).option(`-d, --dir <dir>`,`Estate directory`).option(`--from <stateId>`,`Parent state id, or empty for the virtual root`).option(`--custom <path>`,`Compile a TypeScript manual migration author`).option(`--review <path>`,`Write labelled forward/check/rollback review SQL`).option(`--dry-run`,`Preview without publishing`).option(`--json`,`Print machine-readable output`).action(async t=>{await withMigrations({...t,config:e.opts().config},async(e,n)=>{let r=t.from===void 0?void 0:t.from===``||t.from===`empty`?null:g(t.from)?t.from:(await e.show(selector(t.from))).stateId,i;if(t.custom){let n=await h(b(t.custom)),a=(Object.hasOwn(n,`default`)?n.default:void 0)??n.migration;if(!a)throw Error(`A custom migration module must export a default migration or author function`);let o=await e.graph(),s=Object.freeze(r===void 0?o.leaves.length===0?[null]:[...o.leaves]:[r]);i=typeof a==`function`?await a(s):a}let a=await e.generate({name:t.name,from:r,dryRun:t.dryRun,...n.migrations?.resolve?{resolve:n.migrations.resolve}:{},...i?{manualMigration:i}:{}});if(t.json)printJson$1(a,!0);else{process.stdout.write(`${a.outcome}: ${a.name??`No schema changes`}${a.stateId?` (${a.stateId})`:``}\n`);for(let e of a.operationsByParent??[])process.stdout.write(`Parent ${e.fromState??`empty`}:\n${e.operations.map(d).join(`
|
|
5
|
+
`)}\n`);for(let e of a.warnings??[])process.stderr.write(`warning: ${e}\n`);(a.reviewSql||a.sql)&&process.stdout.write(`${a.reviewSql||a.sql}\n`)}t.review&&a.reviewSql&&await x(b(t.review),a.reviewSql,`utf8`)})}),e.command(`check`).description(`Validate estate artifacts without touching the database`).option(`-d, --dir <dir>`,`Estate directory`).option(`--json`,`Print machine-readable output`).action(async t=>{await withMigrations({...t,config:e.opts().config},async e=>{let n=await e.check();printJson$1(n,!!t.json),n.ok||(process.exitCode=1)})}),e.command(`list`).description(`List estate states`).option(`-d, --dir <dir>`,`Estate directory`).option(`--json`,`Print machine-readable output`).action(async t=>{await withMigrations({...t,config:e.opts().config},async e=>{printJson$1(await e.list(),!!t.json)})}),e.command(`show`).description(`Show one estate state`).argument(`<state>`,`State id, unambiguous prefix, or name`).option(`-d, --dir <dir>`,`Estate directory`).option(`--sql`,`Print labelled forward/check/rollback review SQL`).option(`--review <path>`,`Write review SQL to this file`).option(`--json`,`Print machine-readable output`).action(async(t,n)=>{await withMigrations({...n,config:e.opts().config},async(e,r,i)=>{let a=await e.show(selector(t));if(!(n.sql||n.review)){printJson$1(a,!!n.json);return}let o=await s(i),c=o.states.get(a.stateId),l=c&&o.sql.get(c.sqlHash);if(!(c&&l))throw Error(`The authenticated state SQL is unavailable`);let d=u(c.parents,c.destinationChecks,l);n.json?printJson$1({...a,reviewSql:d},!0):(printJson$1(a,!1),process.stdout.write(d)),n.review&&await x(b(n.review),d,`utf8`)})}),e.command(`graph`).description(`Print estate roots and leaves`).option(`-d, --dir <dir>`,`Estate directory`).option(`--json`,`Print machine-readable output`).action(async t=>{await withMigrations({...t,config:e.opts().config},async e=>{printJson$1(await e.graph(),!!t.json)})}),e.command(`status`).description(`Show marker, pending path, and unfinished attempts`).option(`-d, --dir <dir>`,`Estate directory`).option(`--json`,`Print machine-readable output`).action(async t=>{await withMigrations({...t,config:e.opts().config},async e=>{printJson$1(await e.status(),!!t.json)})}),e.command(`verify`).description(`Lock and compare the live schema to the marker`).option(`-d, --dir <dir>`,`Estate directory`).option(`--json`,`Print machine-readable output`).action(async t=>{await withMigrations({...t,config:e.opts().config},async e=>{let n=await e.verify();printJson$1(n,!!t.json),n.ok||(process.exitCode=1)})}),e.command(`log`).description(`Print the append-only ledger`).option(`-d, --dir <dir>`,`Estate directory`).option(`--limit <n>`,`Maximum events`,positiveInteger).option(`--json`,`Print machine-readable output`).action(async t=>{await withMigrations({...t,config:e.opts().config},async e=>{let n=await e.log();printJson$1(t.limit?n.slice(-t.limit):n,!!t.json)})}),e.command(`apply`).description(`Apply estate states to the target`).option(`-d, --dir <dir>`,`Estate directory`).option(`--to <selector>`,`Target state id, prefix, or name`).option(`--via <stateId...>`,`Force a path through these states`).option(`--dry-run`,`Plan without executing`).option(`--json`,`Print machine-readable output`).action(async t=>{await withMigrations({...t,config:e.opts().config},async e=>{printJson$1(await e.apply({to:selector(t.to),via:t.via,dryRun:t.dryRun}),!!t.json)})}),e.command(`down`).description(`Roll back along the recorded arrival path`).option(`-d, --dir <dir>`,`Estate directory`).option(`--to <selector>`,`Roll back to this state`).option(`--steps <n>`,`Number of states to roll back`,positiveInteger).option(`--dry-run`,`Plan without executing`).option(`--json`,`Print machine-readable output`).action(async t=>{await withMigrations({...t,config:e.opts().config},async e=>{if(t.to!==void 0&&t.steps!==void 0)throw Error(`down accepts --to or --steps, not both`);printJson$1(await e.down(t.to?{to:selector(t.to),dryRun:t.dryRun}:{steps:t.steps,dryRun:t.dryRun}),!!t.json)})}),e.command(`baseline`).description(`Adopt an existing database as a known estate state`).requiredOption(`--to <selector>`,`Existing estate state to adopt`).option(`--via <stateId...>`,`Force the recorded root path`).option(`-d, --dir <dir>`,`Estate directory`).option(`--json`,`Print machine-readable output`).action(async t=>{await withMigrations({...t,config:e.opts().config},async e=>{printJson$1(await e.baseline({to:selector(t.to),via:t.via}),!!t.json)})}),e.command(`resolve`).description(`Resolve an unfinished attempt after live proof`).option(`-d, --dir <dir>`,`Estate directory`).option(`--complete`,`Mark complete when destination proof holds`).option(`--rolled-back`,`Mark rolled back when origin proof holds`).option(`--retry`,`Retry from the first proven incomplete step`).option(`--json`,`Print machine-readable output`).action(async t=>{await withMigrations({...t,config:e.opts().config},async e=>{if([t.complete,t.rolledBack,t.retry].filter(Boolean).length!==1)throw Error(`resolve requires exactly one of --complete, --rolled-back, or --retry`);let n=t.complete?`complete`:t.rolledBack?`rolled-back`:`retry`;printJson$1(await e.resolve({outcome:n}),!!t.json)})}),e.command(`reset`).description(`Clear managed objects and replay from empty to a selected state`).option(`-d, --dir <dir>`,`Estate directory`).option(`--to <selector>`,`Target state after rebuild`).option(`--via <stateId...>`,`Force a rebuild path`).option(`--confirm`,`Confirm destructive reset (not required for dry-run)`).option(`--dry-run`,`Plan without executing`).option(`--json`,`Print machine-readable output`).action(async t=>{await withMigrations({...t,config:e.opts().config},async e=>{if(!(t.dryRun||t.confirm))throw Error(`Reset requires --confirm; inspect --dry-run first`);printJson$1(await e.reset({to:selector(t.to),via:t.via,dryRun:t.dryRun}),!!t.json)})}),e}const A=createMigrateCommand();function printJson(e){process.stdout.write(`${JSON.stringify(e,null,2)}\n`)}function printPlan(e){let t=e.operations.length===0?[`No schema changes.`]:e.operations.map(e=>`[${e.risk}] ${e.label} (${e.id})`),n=e.statements.map((e,t)=>`${t+1}. ${e.sql}${e.parameters.length===0?``:`\n parameters: ${JSON.stringify(e.parameters)}`}`);T([`Target: ${JSON.stringify(e.target)}`,`Plan: ${e.planHash}`,...t,...n.length===0?[]:[``,`SQL:`,...n]].join(`
|
|
6
|
+
`),`Push plan`)}async function runPush(e){let t,n;try{let n=await p({config:e.config});t=n.client;let r=n.migrations?.tables===void 0?f(n.client):f(n.client,{tables:n.migrations.tables}),i=await r.push({dryRun:!0,...e.forceReset===!0?{forceReset:!0}:{},...n.migrations?.resolve?{resolve:n.migrations.resolve}:{}});if(!e.json&&n.driver?.dialect===`sqlite`&&[`sqlite3`,`bun-sqlite`,`bun-sql`].includes(n.driver.driverName)&&(await n.driver._executeRaw(`PRAGMA database_list`)).rows.some(e=>e.name===`main`&&e.file===``)&&process.stderr.write(`warning: SQLite reports an in-memory main database. Use a persistent target for durable schema changes.
|
|
7
|
+
`),e.dryRun){e.json?printJson(i):printPlan(i);return}if(e.json||printPlan(i),i.destructive&&!e.acceptDataLoss&&(e.yes||e.json||!process.stdin.isTTY))throw Error(`Destructive push requires --accept-data-loss; --yes does not authorize data loss. Inspect --dry-run first.`);if(i.outcome!==`noop`&&!e.yes&&!e.acceptDataLoss&&!e.json&&process.stdin.isTTY){let e=await C({message:i.destructive?`Apply this destructive push plan?`:`Apply this push plan?`,initialValue:!i.destructive});if(w(e)||!e){S(`Push cancelled.`);return}}let a=await r.push({consent:i.consent});e.json?printJson(a):E(a.outcome===`noop`?`Schema is up to date.`:`Push applied.`)}catch(e){n={value:e}}finally{await m(t,n,e.json)}}function createPushCommand(){return new v(`push`).description(`Synchronize the schema directly without migration history`).option(`--config <path>`,`Path to viborm.config.ts`).option(`--dry-run`,`Preview without changing the database`).option(`--force-reset`,`Plan a rebuild from an empty database`).option(`-y, --yes`,`Skip prompts for non-destructive plans`).option(`--accept-data-loss`,`Explicitly accept the previewed destructive plan`).option(`--json`,`Print machine-readable JSON`).action(runPush)}const j=createPushCommand(),M=new v;M.name(`viborm`).description(`VibORM - Type-safe ORM for PostgreSQL, MySQL and SQLite`).version(a),M.addCommand(O),M.addCommand(j),M.addCommand(A);try{await M.parseAsync()}catch(e){process.stderr.write(`${e instanceof Error?e.message:`CLI failed`}\n`),process.exitCode=1}export{};
|
|
8
8
|
//# sourceMappingURL=cli.mjs.map
|
package/dist/cli.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.mjs","names":["printJson"],"sources":["../src/cli/commands/check.ts","../src/cli/commands/migrate.ts","../src/cli/commands/push.ts","../src/cli/index.ts"],"sourcesContent":["/**\n * Schema check CLI.\n *\n * Runs every check a client runs when it is created (identifiers, model\n * identity, relation resolution, selector names), plus the advisory rules,\n * against the schema of the configured client. Run it in a build or CI step to\n * create clients with `skipSchemaValidation: true` at runtime.\n */\n\nimport { Command } from \"commander\";\nimport { hydrateSchemaNames } from \"../../schema/hydration\";\nimport type { SchemaValidationIssue } from \"../../schema/validation/types\";\nimport { validateSchema } from \"../../schema/validation/validator\";\nimport { finishCli, loadConfig } from \"../utils\";\n\ninterface CheckCliOptions {\n readonly config?: string;\n readonly json?: boolean;\n}\n\n// The repair hint, when the issue has one, goes on its own indented line.\nconst describe = (issue: SchemaValidationIssue): string =>\n [`[${issue.code}] ${issue.message}`, issue.repair]\n .filter(Boolean)\n .join(\"\\n \");\n\nasync function runCheck(options: CheckCliOptions): Promise<void> {\n let client: { $disconnect(): Promise<void> } | undefined;\n let failure: { value: unknown } | undefined;\n try {\n const config = await loadConfig({\n config: options.config,\n skipValidation: true,\n });\n client = config.client;\n const { models } = config;\n // The identifier and identity checks hydration runs, whatever the\n // configured client skipped.\n hydrateSchemaNames(models);\n const result = validateSchema(models);\n if (options.json) {\n process.stdout.write(`${JSON.stringify(result, null, 2)}\\n`);\n } else {\n for (const issue of result.errors)\n process.stderr.write(`error ${describe(issue)}\\n`);\n for (const issue of result.warnings)\n process.stderr.write(`warning ${describe(issue)}\\n`);\n process.stdout.write(\n result.valid\n ? `Schema valid (${Object.keys(models).length} models).\\n`\n : `Schema invalid: ${result.errors.length} error(s).\\n`\n );\n }\n if (!result.valid) process.exitCode = 1;\n } catch (error) {\n failure = { value: error };\n } finally {\n await finishCli(client, failure, options.json);\n }\n}\n\nexport function createCheckCommand(): Command {\n return new Command(\"check\")\n .description(\n \"Validate the schema, so clients can be created with skipSchemaValidation\"\n )\n .option(\"--config <path>\", \"Path to viborm.config.ts\")\n .option(\"--json\", \"Print machine-readable JSON\")\n .action(runCheck);\n}\n\nexport const checkCommand = createCheckCommand();\n","/**\n * Migration CLI. Composition root is createMigrationClient + loadConfig.\n */\n\nimport { writeFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { Command, InvalidArgumentError } from \"commander\";\nimport {\n createMigrationClient,\n type WritableMigrations,\n} from \"../../migrations/client\";\nimport { loadMigrationGraph } from \"../../migrations/graph\";\nimport { isSha256 } from \"../../migrations/identity\";\nimport { renderMigrationReview } from \"../../migrations/public-view\";\nimport { formatOperation } from \"../../migrations/push/format\";\nimport type { MigrationStorageWriter } from \"../../migrations/storage/contract\";\nimport { createFsStorageWriter } from \"../../migrations/storage/fs-estate\";\nimport type {\n ManualMigrationInput,\n StateSelector,\n} from \"../../migrations/v1-types\";\nimport {\n finishCli,\n type LoadedConfig,\n loadCliModule,\n loadConfig,\n} from \"../utils\";\n\nconst STATE_ID_PREFIX = /^[0-9a-f]{8,63}$/;\n\nfunction positiveInteger(value: string): number {\n const parsed = Number(value);\n if (!Number.isSafeInteger(parsed) || parsed <= 0) {\n throw new InvalidArgumentError(\"must be a positive safe integer\");\n }\n return parsed;\n}\n\nfunction selector(value: string | undefined): StateSelector | undefined {\n if (!value) return undefined;\n if (isSha256(value)) return { id: value };\n if (STATE_ID_PREFIX.test(value)) return { prefix: value };\n return { name: value };\n}\n\nfunction printJson(value: unknown, json: boolean): void {\n if (json) {\n process.stdout.write(`${JSON.stringify(value, null, 2)}\\n`);\n return;\n }\n const lines: string[] = [];\n const render = (item: unknown, indent = \"\") => {\n if (Array.isArray(item)) {\n for (const entry of item) {\n lines.push(`${indent}-`);\n render(entry, `${indent} `);\n }\n if (item.length === 0) lines.push(`${indent}(none)`);\n } else if (item !== null && typeof item === \"object\") {\n for (const [key, entry] of Object.entries(item)) {\n if (entry !== null && typeof entry === \"object\") {\n lines.push(`${indent}${key}:`);\n render(entry, `${indent} `);\n } else lines.push(`${indent}${key}: ${String(entry)}`);\n }\n } else lines.push(`${indent}${String(item)}`);\n };\n render(value);\n process.stdout.write(`${lines.join(\"\\n\")}\\n`);\n}\n\nasync function withMigrations(\n options: { dir?: string; config?: string; json?: boolean },\n run: (\n migrations: WritableMigrations,\n config: LoadedConfig,\n storage: MigrationStorageWriter\n ) => Promise<void>\n): Promise<void> {\n let client: { $disconnect(): Promise<void> } | undefined;\n let failure: { value: unknown } | undefined;\n try {\n const config = await loadConfig({ config: options.config });\n client = config.client;\n const directory = resolve(\n options.dir ?? config.migrations?.dir ?? \"./migrations\"\n );\n const storage =\n config.migrations?.storage ?? createFsStorageWriter(directory);\n const migrations = createMigrationClient(config.client, {\n storage,\n ...(config.migrations?.tables === undefined\n ? {}\n : { tables: config.migrations.tables }),\n });\n await run(migrations, config, storage);\n } catch (error) {\n failure = { value: error };\n } finally {\n await finishCli(client, failure, options.json);\n }\n}\n\nexport function createMigrateCommand(): Command {\n const migrate = new Command(\"migrate\")\n .description(\"Manage the authenticated migration estate\")\n .option(\"--config <path>\", \"Path to viborm.config.ts\");\n\n migrate\n .command(\"generate\")\n .description(\"Publish a new estate state from the current schema\")\n .option(\"-n, --name <name>\", \"Human-readable state label\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\n \"--from <stateId>\",\n \"Parent state id, or empty for the virtual root\"\n )\n .option(\"--custom <path>\", \"Compile a TypeScript manual migration author\")\n .option(\n \"--review <path>\",\n \"Write labelled forward/check/rollback review SQL\"\n )\n .option(\"--dry-run\", \"Preview without publishing\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(\n async (opts: {\n name?: string;\n dir?: string;\n from?: string;\n dryRun?: boolean;\n custom?: string;\n review?: string;\n json?: boolean;\n }) => {\n await withMigrations(\n { ...opts, config: migrate.opts<{ config?: string }>().config },\n async (migrations, config) => {\n const from =\n opts.from === undefined\n ? undefined\n : opts.from === \"\" || opts.from === \"empty\"\n ? null\n : isSha256(opts.from)\n ? opts.from\n : (await migrations.show(selector(opts.from)!)).stateId;\n let manualMigration: ManualMigrationInput | undefined;\n if (opts.custom) {\n type Author =\n | ManualMigrationInput\n | ((\n parents: readonly (string | null)[]\n ) => ManualMigrationInput | Promise<ManualMigrationInput>);\n const module = await loadCliModule<{\n default?: Author;\n migration?: Author;\n }>(resolve(opts.custom));\n const author =\n (Object.hasOwn(module, \"default\")\n ? module.default\n : undefined) ?? module.migration;\n if (!author)\n throw new Error(\n \"A custom migration module must export a default migration or author function\"\n );\n const graph = await migrations.graph();\n const parents = Object.freeze(\n from === undefined\n ? graph.leaves.length === 0\n ? [null]\n : [...graph.leaves]\n : [from]\n );\n manualMigration =\n typeof author === \"function\" ? await author(parents) : author;\n }\n const result = await migrations.generate({\n name: opts.name,\n from,\n dryRun: opts.dryRun,\n ...(config.migrations?.resolve\n ? { resolve: config.migrations.resolve }\n : {}),\n ...(manualMigration ? { manualMigration } : {}),\n });\n if (opts.json) printJson(result, true);\n else {\n process.stdout.write(\n `${result.outcome}: ${result.name ?? \"No schema changes\"}${result.stateId ? ` (${result.stateId})` : \"\"}\\n`\n );\n for (const parent of result.operationsByParent ?? []) {\n process.stdout.write(\n `Parent ${parent.fromState ?? \"empty\"}:\\n${parent.operations.map(formatOperation).join(\"\\n\")}\\n`\n );\n }\n for (const warning of result.warnings ?? [])\n process.stderr.write(`warning: ${warning}\\n`);\n if (result.reviewSql || result.sql)\n process.stdout.write(`${result.reviewSql || result.sql}\\n`);\n }\n if (opts.review && result.reviewSql)\n await writeFile(resolve(opts.review), result.reviewSql, \"utf8\");\n }\n );\n }\n );\n\n migrate\n .command(\"check\")\n .description(\"Validate estate artifacts without touching the database\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(async (opts: { dir?: string; json?: boolean }) => {\n await withMigrations(\n { ...opts, config: migrate.opts<{ config?: string }>().config },\n async (migrations) => {\n const result = await migrations.check();\n printJson(result, Boolean(opts.json));\n if (!result.ok) process.exitCode = 1;\n }\n );\n });\n\n migrate\n .command(\"list\")\n .description(\"List estate states\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(async (opts: { dir?: string; json?: boolean }) => {\n await withMigrations(\n { ...opts, config: migrate.opts<{ config?: string }>().config },\n async (migrations) => {\n printJson(await migrations.list(), Boolean(opts.json));\n }\n );\n });\n\n migrate\n .command(\"show\")\n .description(\"Show one estate state\")\n .argument(\"<state>\", \"State id, unambiguous prefix, or name\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--sql\", \"Print labelled forward/check/rollback review SQL\")\n .option(\"--review <path>\", \"Write review SQL to this file\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(\n async (\n state: string,\n opts: { dir?: string; sql?: boolean; review?: string; json?: boolean }\n ) => {\n await withMigrations(\n { ...opts, config: migrate.opts<{ config?: string }>().config },\n async (migrations, _config, storage) => {\n const details = await migrations.show(selector(state)!);\n if (!(opts.sql || opts.review)) {\n printJson(details, Boolean(opts.json));\n return;\n }\n const graph = await loadMigrationGraph(storage);\n const manifest = graph.states.get(details.stateId);\n const blob = manifest && graph.sql.get(manifest.sqlHash);\n if (!(manifest && blob))\n throw new Error(\"The authenticated state SQL is unavailable\");\n const reviewSql = renderMigrationReview(\n manifest.parents,\n manifest.destinationChecks,\n blob\n );\n if (opts.json) printJson({ ...details, reviewSql }, true);\n else {\n printJson(details, false);\n process.stdout.write(reviewSql);\n }\n if (opts.review)\n await writeFile(resolve(opts.review), reviewSql, \"utf8\");\n }\n );\n }\n );\n\n migrate\n .command(\"graph\")\n .description(\"Print estate roots and leaves\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(async (opts: { dir?: string; json?: boolean }) => {\n await withMigrations(\n { ...opts, config: migrate.opts<{ config?: string }>().config },\n async (migrations) => {\n printJson(await migrations.graph(), Boolean(opts.json));\n }\n );\n });\n\n migrate\n .command(\"status\")\n .description(\"Show marker, pending path, and unfinished attempts\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(async (opts: { dir?: string; json?: boolean }) => {\n await withMigrations(\n { ...opts, config: migrate.opts<{ config?: string }>().config },\n async (migrations) => {\n printJson(await migrations.status(), Boolean(opts.json));\n }\n );\n });\n\n migrate\n .command(\"verify\")\n .description(\"Lock and compare the live schema to the marker\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(async (opts: { dir?: string; json?: boolean }) => {\n await withMigrations(\n { ...opts, config: migrate.opts<{ config?: string }>().config },\n async (migrations) => {\n const result = await migrations.verify();\n printJson(result, Boolean(opts.json));\n if (!result.ok) process.exitCode = 1;\n }\n );\n });\n\n migrate\n .command(\"log\")\n .description(\"Print the append-only ledger\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--limit <n>\", \"Maximum events\", positiveInteger)\n .option(\"--json\", \"Print machine-readable output\")\n .action(async (opts: { dir?: string; limit?: number; json?: boolean }) => {\n await withMigrations(\n { ...opts, config: migrate.opts<{ config?: string }>().config },\n async (migrations) => {\n const events = await migrations.log();\n printJson(\n opts.limit ? events.slice(-opts.limit) : events,\n Boolean(opts.json)\n );\n }\n );\n });\n\n migrate\n .command(\"apply\")\n .description(\"Apply estate states to the target\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--to <selector>\", \"Target state id, prefix, or name\")\n .option(\"--via <stateId...>\", \"Force a path through these states\")\n .option(\"--dry-run\", \"Plan without executing\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(\n async (opts: {\n dir?: string;\n to?: string;\n via?: string[];\n dryRun?: boolean;\n json?: boolean;\n }) => {\n await withMigrations(\n { ...opts, config: migrate.opts<{ config?: string }>().config },\n async (migrations) => {\n printJson(\n await migrations.apply({\n to: selector(opts.to),\n via: opts.via,\n dryRun: opts.dryRun,\n }),\n Boolean(opts.json)\n );\n }\n );\n }\n );\n\n migrate\n .command(\"down\")\n .description(\"Roll back along the recorded arrival path\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--to <selector>\", \"Roll back to this state\")\n .option(\"--steps <n>\", \"Number of states to roll back\", positiveInteger)\n .option(\"--dry-run\", \"Plan without executing\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(\n async (opts: {\n dir?: string;\n to?: string;\n steps?: number;\n dryRun?: boolean;\n json?: boolean;\n }) => {\n await withMigrations(\n { ...opts, config: migrate.opts<{ config?: string }>().config },\n async (migrations) => {\n if (opts.to !== undefined && opts.steps !== undefined)\n throw new Error(\"down accepts --to or --steps, not both\");\n printJson(\n await migrations.down(\n opts.to\n ? { to: selector(opts.to)!, dryRun: opts.dryRun }\n : { steps: opts.steps, dryRun: opts.dryRun }\n ),\n Boolean(opts.json)\n );\n }\n );\n }\n );\n\n migrate\n .command(\"baseline\")\n .description(\"Adopt an existing database as a known estate state\")\n .requiredOption(\"--to <selector>\", \"Existing estate state to adopt\")\n .option(\"--via <stateId...>\", \"Force the recorded root path\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(\n async (opts: {\n to: string;\n via?: string[];\n dir?: string;\n json?: boolean;\n }) => {\n await withMigrations(\n { ...opts, config: migrate.opts<{ config?: string }>().config },\n async (migrations) => {\n printJson(\n await migrations.baseline({\n to: selector(opts.to)!,\n via: opts.via,\n }),\n Boolean(opts.json)\n );\n }\n );\n }\n );\n\n migrate\n .command(\"resolve\")\n .description(\"Resolve an unfinished attempt after live proof\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--complete\", \"Mark complete when destination proof holds\")\n .option(\"--rolled-back\", \"Mark rolled back when origin proof holds\")\n .option(\"--retry\", \"Retry from the first proven incomplete step\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(\n async (opts: {\n dir?: string;\n complete?: boolean;\n rolledBack?: boolean;\n retry?: boolean;\n json?: boolean;\n }) => {\n await withMigrations(\n { ...opts, config: migrate.opts<{ config?: string }>().config },\n async (migrations) => {\n if (\n [opts.complete, opts.rolledBack, opts.retry].filter(Boolean)\n .length !== 1\n )\n throw new Error(\n \"resolve requires exactly one of --complete, --rolled-back, or --retry\"\n );\n const outcome = opts.complete\n ? \"complete\"\n : opts.rolledBack\n ? \"rolled-back\"\n : \"retry\";\n printJson(\n await migrations.resolve({ outcome }),\n Boolean(opts.json)\n );\n }\n );\n }\n );\n\n migrate\n .command(\"reset\")\n .description(\n \"Clear managed objects and replay from empty to a selected state\"\n )\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--to <selector>\", \"Target state after rebuild\")\n .option(\"--via <stateId...>\", \"Force a rebuild path\")\n .option(\"--confirm\", \"Confirm destructive reset (not required for dry-run)\")\n .option(\"--dry-run\", \"Plan without executing\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(\n async (opts: {\n dir?: string;\n to?: string;\n via?: string[];\n confirm?: boolean;\n dryRun?: boolean;\n json?: boolean;\n }) => {\n await withMigrations(\n { ...opts, config: migrate.opts<{ config?: string }>().config },\n async (migrations) => {\n if (!(opts.dryRun || opts.confirm))\n throw new Error(\n \"Reset requires --confirm; inspect --dry-run first\"\n );\n printJson(\n await migrations.reset({\n to: selector(opts.to),\n via: opts.via,\n dryRun: opts.dryRun,\n }),\n Boolean(opts.json)\n );\n }\n );\n }\n );\n\n return migrate;\n}\n\nexport const migrateCommand = createMigrateCommand();\n","/**\n * History-free, authenticated schema push CLI.\n *\n * The preview is inert. Effectful execution receives only the consent emitted\n * by that preview; no generic force authorization reaches the apply call.\n */\n\nimport { cancel, confirm, isCancel, note, outro } from \"@clack/prompts\";\nimport { Command } from \"commander\";\nimport { createMigrationClient } from \"../../migrations/client\";\nimport type { PushPreview } from \"../../migrations/push-v1\";\nimport { finishCli, loadConfig } from \"../utils\";\n\ninterface PushCliOptions {\n readonly config?: string;\n readonly dryRun?: boolean;\n readonly forceReset?: boolean;\n readonly yes?: boolean;\n readonly acceptDataLoss?: boolean;\n readonly json?: boolean;\n}\n\nfunction printJson(value: unknown): void {\n process.stdout.write(`${JSON.stringify(value, null, 2)}\\n`);\n}\n\nfunction printPlan(preview: PushPreview): void {\n const operations =\n preview.operations.length === 0\n ? [\"No schema changes.\"]\n : preview.operations.map(\n (operation) =>\n `[${operation.risk}] ${operation.label} (${operation.id})`\n );\n const statements = preview.statements.map(\n (statement, index) =>\n `${index + 1}. ${statement.sql}${\n statement.parameters.length === 0\n ? \"\"\n : `\\n parameters: ${JSON.stringify(statement.parameters)}`\n }`\n );\n const lines = [\n `Target: ${JSON.stringify(preview.target)}`,\n `Plan: ${preview.planHash}`,\n ...operations,\n ...(statements.length === 0 ? [] : [\"\", \"SQL:\", ...statements]),\n ];\n note(lines.join(\"\\n\"), \"Push plan\");\n}\n\nasync function runPush(options: PushCliOptions): Promise<void> {\n let orm: { $disconnect(): Promise<void> } | undefined;\n let failure: { value: unknown } | undefined;\n try {\n const config = await loadConfig({ config: options.config });\n orm = config.client;\n const migrations =\n config.migrations?.tables === undefined\n ? createMigrationClient(config.client)\n : createMigrationClient(config.client, {\n tables: config.migrations.tables,\n });\n // `force` is confined to the inert planning arm. The authenticated apply\n // arm below receives only the consent bound to this exact preview.\n const preview = await migrations.push({\n dryRun: true,\n ...(options.forceReset === true ? { forceReset: true } : {}),\n ...(config.migrations?.resolve\n ? { resolve: config.migrations.resolve }\n : {}),\n });\n\n if (\n !options.json &&\n config.driver?.dialect === \"sqlite\" &&\n [\"sqlite3\", \"bun-sqlite\", \"bun-sql\"].includes(config.driver.driverName)\n ) {\n const databases = await config.driver._executeRaw<{\n name: string;\n file: string;\n }>(\"PRAGMA database_list\");\n if (\n databases.rows.some(\n (database) => database.name === \"main\" && database.file === \"\"\n )\n )\n process.stderr.write(\n \"warning: SQLite reports an in-memory main database. Use a persistent target for durable schema changes.\\n\"\n );\n }\n\n if (options.dryRun) {\n if (options.json) printJson(preview);\n else printPlan(preview);\n return;\n }\n\n if (!options.json) printPlan(preview);\n\n if (\n preview.destructive &&\n !options.acceptDataLoss &&\n (options.yes || options.json || !process.stdin.isTTY)\n ) {\n throw new Error(\n \"Destructive push requires --accept-data-loss; --yes does not authorize data loss. Inspect --dry-run first.\"\n );\n }\n if (\n preview.outcome !== \"noop\" &&\n !options.yes &&\n !options.acceptDataLoss &&\n !options.json &&\n process.stdin.isTTY\n ) {\n const accepted = await confirm({\n message: preview.destructive\n ? \"Apply this destructive push plan?\"\n : \"Apply this push plan?\",\n initialValue: !preview.destructive,\n });\n if (isCancel(accepted) || !accepted) {\n cancel(\"Push cancelled.\");\n return;\n }\n }\n\n const result = await migrations.push({ consent: preview.consent });\n if (options.json) printJson(result);\n else\n outro(\n result.outcome === \"noop\" ? \"Schema is up to date.\" : \"Push applied.\"\n );\n } catch (error) {\n failure = { value: error };\n } finally {\n await finishCli(orm, failure, options.json);\n }\n}\n\nexport function createPushCommand(): Command {\n return new Command(\"push\")\n .description(\"Synchronize the schema directly without migration history\")\n .option(\"--config <path>\", \"Path to viborm.config.ts\")\n .option(\"--dry-run\", \"Preview without changing the database\")\n .option(\"--force-reset\", \"Plan a rebuild from an empty database\")\n .option(\"-y, --yes\", \"Skip prompts for non-destructive plans\")\n .option(\n \"--accept-data-loss\",\n \"Explicitly accept the previewed destructive plan\"\n )\n .option(\"--json\", \"Print machine-readable JSON\")\n .action(runPush);\n}\n\nexport const pushCommand = createPushCommand();\n","#!/usr/bin/env node\n/**\n * VibORM CLI\n *\n * Command-line interface for VibORM database operations.\n */\n\nimport { Command } from \"commander\";\nimport { VIBORM_VERSION } from \"../version\";\nimport { checkCommand } from \"./commands/check\";\nimport { migrateCommand } from \"./commands/migrate\";\nimport { pushCommand } from \"./commands/push\";\n\nconst program = new Command();\n\nprogram\n .name(\"viborm\")\n .description(\"VibORM - Type-safe ORM for PostgreSQL, MySQL and SQLite\")\n .version(VIBORM_VERSION);\n\n// Register commands\nprogram.addCommand(checkCommand);\nprogram.addCommand(pushCommand);\nprogram.addCommand(migrateCommand);\n\n// Parse arguments\ntry {\n await program.parseAsync();\n} catch (error: unknown) {\n process.stderr.write(\n `${error instanceof Error ? error.message : \"CLI failed\"}\\n`\n );\n process.exitCode = 1;\n}\n"],"mappings":";0jBAqBA,MAAM,SAAY,GAChB,CAAC,IAAI,EAAM,KAAK,IAAI,EAAM,UAAW,EAAM,OAAO,CAC/C,OAAO,QAAQ,CACf,KAAK;MAAS,CAEnB,eAAe,SAAS,EAAyC,CAC/D,IAAI,EACA,EACJ,GAAI,CACF,IAAM,EAAS,MAAM,EAAW,CAC9B,OAAQ,EAAQ,OAChB,eAAgB,GACjB,CAAC,CACF,EAAS,EAAO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AAY,QACpB,CAAC,EAAQ,KACT,CAAC,EAAQ,gBACT,CAAC,EAAQ,MACT,QAAQ,MAAM,MACd,CACA,IAAM,EAAW,MAAM,EAAQ,CAC7B,QAAS,EAAQ,YACb,oCACA,wBACJ,aAAc,CAAC,EAAQ,YACxB,CAAC,CACF,GAAI,EAAS,EAAS,EAAI,CAAC,EAAU,CACnC,EAAO,kBAAkB,CACzB,QAIJ,IAAM,EAAS,MAAM,EAAW,KAAK,CAAE,QAAS,EAAQ,QAAS,CAAC,CAC9D,EAAQ,KAAM,UAAU,EAAO,CAEjC,EACE,EAAO,UAAY,OAAS,wBAA0B,gBACvD,OACI,EAAO,CACd,EAAU,CAAE,MAAO,EAAO,QAClB,CACR,MAAM,EAAU,EAAK,EAAS,EAAQ,KAAK,EAI/C,SAAgB,mBAA6B,CAC3C,OAAO,IAAI,EAAQ,OAAO,CACvB,YAAY,4DAA4D,CACxE,OAAO,kBAAmB,2BAA2B,CACrD,OAAO,YAAa,wCAAwC,CAC5D,OAAO,gBAAiB,wCAAwC,CAChE,OAAO,YAAa,yCAAyC,CAC7D,OACC,qBACA,mDACD,CACA,OAAO,SAAU,8BAA8B,CAC/C,OAAO,QAAQ,CAGpB,MAAa,EAAc,mBAAmB,CC/IxC,EAAU,IAAI,EAEpB,EACG,KAAK,SAAS,CACd,YAAY,0DAA0D,CACtE,QAAQ,EAAe,CAG1B,EAAQ,WAAW,EAAa,CAChC,EAAQ,WAAW,EAAY,CAC/B,EAAQ,WAAW,EAAe,CAGlC,GAAI,CACF,MAAM,EAAQ,YAAY,OACnB,EAAgB,CACvB,QAAQ,OAAO,MACb,GAAG,aAAiB,MAAQ,EAAM,QAAU,aAAa,IAC1D,CACD,QAAQ,SAAW"}
|
|
1
|
+
{"version":3,"file":"cli.mjs","names":["printJson"],"sources":["../src/cli/commands/check.ts","../src/cli/commands/migrate.ts","../src/cli/commands/push.ts","../src/cli/index.ts"],"sourcesContent":["/**\n * Schema check CLI.\n *\n * Runs every check a client runs when it is created (identifiers, model\n * identity, relation resolution, selector names), plus the advisory rules,\n * against the schema of the configured client. Run it in a build or CI step to\n * create clients with `skipSchemaValidation: true` at runtime.\n */\n\nimport { Command } from \"commander\";\nimport { sqliteNoncanonicalTemporalCount } from \"../../adapters/databases/sqlite/storage/datetime\";\nimport { isSqliteDecimalStorage } from \"../../adapters/databases/sqlite/storage/decimal\";\nimport type { AnyDriver } from \"../../drivers/driver\";\nimport { hydrateSchemaNames } from \"../../schema/hydration\";\nimport {\n type AnyModel,\n getTableName,\n type ModelState,\n} from \"../../schema/model\";\nimport { sqliteDateTimePhysicalForm } from \"../../schema/scalars/datetime/physical\";\nimport type { SchemaValidationIssue } from \"../../schema/validation/types\";\nimport { validateSchema } from \"../../schema/validation/validator\";\nimport { createIdentifierQuoter } from \"../../sql/identifiers\";\nimport { finishCli, loadConfig } from \"../utils\";\n\ninterface CheckCliOptions {\n readonly config?: string;\n readonly json?: boolean;\n readonly db?: boolean;\n}\n\ntype ColumnAudit = { readonly table: string; readonly column: string } & (\n | {\n readonly type: \"datetime\" | \"time\";\n readonly list: boolean;\n /** `null` when the column is missing. */\n readonly noncanonical: number | null;\n }\n | {\n readonly type: \"decimal\";\n /** The catalog's declared type; `null` when the column is missing. */\n readonly declared: string | null;\n readonly checked: boolean;\n }\n);\n\ninterface CatalogColumn {\n readonly definition: string | null;\n readonly name: string;\n readonly type: string;\n readonly nullable: boolean;\n}\n\nconst quote = createIdentifierQuoter('\"');\n\n/** One SQLite table's declared columns, each beside the table's stored definition. */\nasync function readCatalog(\n driver: AnyDriver,\n table: string\n): Promise<CatalogColumn[]> {\n const { rows } = await driver._executeRaw<\n Omit<CatalogColumn, \"nullable\"> & { notnull: number; pk: number }\n >(\n `SELECT s.sql AS definition, p.name, p.type, p.\"notnull\", p.pk FROM sqlite_schema AS s JOIN pragma_table_info(s.name) AS p WHERE s.type = 'table' AND s.name = ?`,\n [table]\n );\n // SQLite reports a primary key nullable; VibORM writes it NOT NULL.\n return rows.map(({ notnull, pk, ...column }) => ({\n ...column,\n nullable: Number(notnull) === 0 && Number(pk) === 0,\n }));\n}\n\n/**\n * Audit SQLite storage typed queries assume but never inspect: one catalog\n * read per table decides which audited columns exist; each existing text\n * DateTime/Time column's noncanonical rows are counted (one scan each), and\n * each decimal column is checked against the scaled-integer storage of its\n * descriptor. Other dialects store native types.\n */\nasync function auditStorage(\n driver: AnyDriver,\n models: Record<string, AnyModel>\n): Promise<ColumnAudit[]> {\n if (driver.dialect !== \"sqlite\") return [];\n const audits: ColumnAudit[] = [];\n for (const [name, model] of Object.entries(models)) {\n const table = getTableName(model, name);\n const state: ModelState = model[\"~\"].state;\n // A missing table has no catalog rows: each audited column is missing.\n let catalog: Promise<CatalogColumn[]> | undefined;\n const find = async (column: string) =>\n (await (catalog ??= readCatalog(driver, table))).find(\n (entry) => entry.name === column\n );\n for (const [field, scalar] of Object.entries(state.scalars)) {\n const definition = scalar[\"~\"].state;\n const { type, array = false } = definition;\n const column = model[\"~\"].getFieldName(field).sql;\n if (definition.type === \"decimal\") {\n const row = await find(column);\n audits.push({\n table,\n column,\n type: \"decimal\",\n declared: row?.type ?? null,\n checked:\n row !== undefined &&\n isSqliteDecimalStorage(\n row.definition,\n row,\n definition.decimal,\n array ? \"list\" : \"scalar\",\n quote\n ),\n });\n continue;\n }\n const text =\n type === \"time\" ||\n (type === \"datetime\" &&\n (array ||\n sqliteDateTimePhysicalForm(scalar[\"~\"].nativeType) === \"text\"));\n if (!text) continue;\n // Never scan a missing column: SQLite may read its quoted name as text.\n const scan =\n (await find(column)) &&\n (await driver._executeRaw<{ noncanonical: number }>(\n sqliteNoncanonicalTemporalCount(table, column, type, array)\n ));\n audits.push({\n table,\n column,\n type,\n list: array,\n noncanonical: scan ? Number(scan.rows[0]?.noncanonical) : null,\n });\n }\n }\n return audits;\n}\n\nconst needsRepair = (audit: ColumnAudit): boolean =>\n audit.type === \"decimal\" ? !audit.checked : audit.noncanonical !== 0;\n\nconst describeAudit = (audit: ColumnAudit): string => {\n const column = `[storage] \"${audit.table}\".\"${audit.column}\"`;\n if ((audit.type === \"decimal\" ? audit.declared : audit.noncanonical) === null)\n return `${column}: the column is missing; typed queries that use it fail.\\n Create it through viborm push or migrate.`;\n if (audit.type === \"decimal\")\n return `${column}: declared ${audit.declared}, not the checked scaled-integer decimal storage VibORM writes; typed reads, filters and writes are not checked against it.\\n Adopt the table through viborm push, migrate or baseline: https://viborm.dev/docs/migration/drivers/sqlite#adopting-decimal-columns-from-another-tool`;\n const kind = audit.type === \"time\" ? \"Time\" : \"DateTime\";\n const repair = audit.list\n ? \"Rewrite each row through the typed client (`update`), which stores canonical members\"\n : `Repair with sqliteCanonical${kind}Expression from viborm/migrations`;\n return `${column}: ${audit.noncanonical} row(s) of noncanonical ${kind} text compare and sort wrongly.\\n ${repair}: https://viborm.dev/docs/migration/drivers/sqlite#repairing-foreign-timestamp-and-time-text`;\n};\n\n// The repair hint, when the issue has one, goes on its own indented line.\nconst describe = (issue: SchemaValidationIssue): string =>\n [`[${issue.code}] ${issue.message}`, issue.repair]\n .filter(Boolean)\n .join(\"\\n \");\n\nasync function runCheck(options: CheckCliOptions): Promise<void> {\n let client: { $disconnect(): Promise<void> } | undefined;\n let failure: { value: unknown } | undefined;\n try {\n const config = await loadConfig({\n config: options.config,\n skipValidation: true,\n });\n client = config.client;\n const { models } = config;\n // The identifier and identity checks hydration runs, whatever the\n // configured client skipped.\n hydrateSchemaNames(models);\n const result = validateSchema(models);\n const storage = options.db\n ? await auditStorage(config.driver, models)\n : undefined;\n const dirty = storage?.filter(needsRepair) ?? [];\n if (options.json) {\n process.stdout.write(\n `${JSON.stringify(storage ? { ...result, storage } : result, null, 2)}\\n`\n );\n } else {\n for (const issue of result.errors)\n process.stderr.write(`error ${describe(issue)}\\n`);\n for (const issue of result.warnings)\n process.stderr.write(`warning ${describe(issue)}\\n`);\n for (const audit of dirty)\n process.stderr.write(`error ${describeAudit(audit)}\\n`);\n process.stdout.write(\n result.valid\n ? `Schema valid (${Object.keys(models).length} models).\\n`\n : `Schema invalid: ${result.errors.length} error(s).\\n`\n );\n if (storage)\n process.stdout.write(\n `Storage audited: ${storage.length} column(s), ${dirty.length} need repair.\\n`\n );\n }\n if (!result.valid || dirty.length > 0) process.exitCode = 1;\n } catch (error) {\n failure = { value: error };\n } finally {\n await finishCli(client, failure, options.json);\n }\n}\n\nexport function createCheckCommand(): Command {\n return new Command(\"check\")\n .description(\n \"Validate the schema, so clients can be created with skipSchemaValidation\"\n )\n .option(\"--config <path>\", \"Path to viborm.config.ts\")\n .option(\"--json\", \"Print machine-readable JSON\")\n .option(\n \"--db\",\n \"Also audit SQLite storage: DateTime/Time text and decimal columns\"\n )\n .action(runCheck);\n}\n\nexport const checkCommand = createCheckCommand();\n","/**\n * Migration CLI. Composition root is createMigrationClient + loadConfig.\n */\n\nimport { writeFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { Command, InvalidArgumentError } from \"commander\";\nimport {\n createMigrationClient,\n type WritableMigrations,\n} from \"../../migrations/client\";\nimport { loadMigrationGraph } from \"../../migrations/graph\";\nimport { isSha256 } from \"../../migrations/identity\";\nimport { renderMigrationReview } from \"../../migrations/public-view\";\nimport { formatOperation } from \"../../migrations/push/format\";\nimport type { MigrationStorageWriter } from \"../../migrations/storage/contract\";\nimport { createFsStorageWriter } from \"../../migrations/storage/fs-estate\";\nimport type {\n ManualMigrationInput,\n StateSelector,\n} from \"../../migrations/v1-types\";\nimport {\n finishCli,\n type LoadedConfig,\n loadCliModule,\n loadConfig,\n} from \"../utils\";\n\nconst STATE_ID_PREFIX = /^[0-9a-f]{8,63}$/;\n\nfunction positiveInteger(value: string): number {\n const parsed = Number(value);\n if (!Number.isSafeInteger(parsed) || parsed <= 0) {\n throw new InvalidArgumentError(\"must be a positive safe integer\");\n }\n return parsed;\n}\n\nfunction selector(value: string | undefined): StateSelector | undefined {\n if (!value) return undefined;\n if (isSha256(value)) return { id: value };\n if (STATE_ID_PREFIX.test(value)) return { prefix: value };\n return { name: value };\n}\n\nfunction printJson(value: unknown, json: boolean): void {\n if (json) {\n process.stdout.write(`${JSON.stringify(value, null, 2)}\\n`);\n return;\n }\n const lines: string[] = [];\n const render = (item: unknown, indent = \"\") => {\n if (Array.isArray(item)) {\n for (const entry of item) {\n lines.push(`${indent}-`);\n render(entry, `${indent} `);\n }\n if (item.length === 0) lines.push(`${indent}(none)`);\n } else if (item !== null && typeof item === \"object\") {\n for (const [key, entry] of Object.entries(item)) {\n if (entry !== null && typeof entry === \"object\") {\n lines.push(`${indent}${key}:`);\n render(entry, `${indent} `);\n } else lines.push(`${indent}${key}: ${String(entry)}`);\n }\n } else lines.push(`${indent}${String(item)}`);\n };\n render(value);\n process.stdout.write(`${lines.join(\"\\n\")}\\n`);\n}\n\nasync function withMigrations(\n options: { dir?: string; config?: string; json?: boolean },\n run: (\n migrations: WritableMigrations,\n config: LoadedConfig,\n storage: MigrationStorageWriter\n ) => Promise<void>\n): Promise<void> {\n let client: { $disconnect(): Promise<void> } | undefined;\n let failure: { value: unknown } | undefined;\n try {\n const config = await loadConfig({ config: options.config });\n client = config.client;\n const directory = resolve(\n options.dir ?? config.migrations?.dir ?? \"./migrations\"\n );\n const storage =\n config.migrations?.storage ?? createFsStorageWriter(directory);\n const migrations = createMigrationClient(config.client, {\n storage,\n ...(config.migrations?.tables === undefined\n ? {}\n : { tables: config.migrations.tables }),\n });\n await run(migrations, config, storage);\n } catch (error) {\n failure = { value: error };\n } finally {\n await finishCli(client, failure, options.json);\n }\n}\n\nexport function createMigrateCommand(): Command {\n const migrate = new Command(\"migrate\")\n .description(\"Manage the authenticated migration estate\")\n .option(\"--config <path>\", \"Path to viborm.config.ts\");\n\n migrate\n .command(\"generate\")\n .description(\"Publish a new estate state from the current schema\")\n .option(\"-n, --name <name>\", \"Human-readable state label\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\n \"--from <stateId>\",\n \"Parent state id, or empty for the virtual root\"\n )\n .option(\"--custom <path>\", \"Compile a TypeScript manual migration author\")\n .option(\n \"--review <path>\",\n \"Write labelled forward/check/rollback review SQL\"\n )\n .option(\"--dry-run\", \"Preview without publishing\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(\n async (opts: {\n name?: string;\n dir?: string;\n from?: string;\n dryRun?: boolean;\n custom?: string;\n review?: string;\n json?: boolean;\n }) => {\n await withMigrations(\n { ...opts, config: migrate.opts<{ config?: string }>().config },\n async (migrations, config) => {\n const from =\n opts.from === undefined\n ? undefined\n : opts.from === \"\" || opts.from === \"empty\"\n ? null\n : isSha256(opts.from)\n ? opts.from\n : (await migrations.show(selector(opts.from)!)).stateId;\n let manualMigration: ManualMigrationInput | undefined;\n if (opts.custom) {\n type Author =\n | ManualMigrationInput\n | ((\n parents: readonly (string | null)[]\n ) => ManualMigrationInput | Promise<ManualMigrationInput>);\n const module = await loadCliModule<{\n default?: Author;\n migration?: Author;\n }>(resolve(opts.custom));\n const author =\n (Object.hasOwn(module, \"default\")\n ? module.default\n : undefined) ?? module.migration;\n if (!author)\n throw new Error(\n \"A custom migration module must export a default migration or author function\"\n );\n const graph = await migrations.graph();\n const parents = Object.freeze(\n from === undefined\n ? graph.leaves.length === 0\n ? [null]\n : [...graph.leaves]\n : [from]\n );\n manualMigration =\n typeof author === \"function\" ? await author(parents) : author;\n }\n const result = await migrations.generate({\n name: opts.name,\n from,\n dryRun: opts.dryRun,\n ...(config.migrations?.resolve\n ? { resolve: config.migrations.resolve }\n : {}),\n ...(manualMigration ? { manualMigration } : {}),\n });\n if (opts.json) printJson(result, true);\n else {\n process.stdout.write(\n `${result.outcome}: ${result.name ?? \"No schema changes\"}${result.stateId ? ` (${result.stateId})` : \"\"}\\n`\n );\n for (const parent of result.operationsByParent ?? []) {\n process.stdout.write(\n `Parent ${parent.fromState ?? \"empty\"}:\\n${parent.operations.map(formatOperation).join(\"\\n\")}\\n`\n );\n }\n for (const warning of result.warnings ?? [])\n process.stderr.write(`warning: ${warning}\\n`);\n if (result.reviewSql || result.sql)\n process.stdout.write(`${result.reviewSql || result.sql}\\n`);\n }\n if (opts.review && result.reviewSql)\n await writeFile(resolve(opts.review), result.reviewSql, \"utf8\");\n }\n );\n }\n );\n\n migrate\n .command(\"check\")\n .description(\"Validate estate artifacts without touching the database\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(async (opts: { dir?: string; json?: boolean }) => {\n await withMigrations(\n { ...opts, config: migrate.opts<{ config?: string }>().config },\n async (migrations) => {\n const result = await migrations.check();\n printJson(result, Boolean(opts.json));\n if (!result.ok) process.exitCode = 1;\n }\n );\n });\n\n migrate\n .command(\"list\")\n .description(\"List estate states\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(async (opts: { dir?: string; json?: boolean }) => {\n await withMigrations(\n { ...opts, config: migrate.opts<{ config?: string }>().config },\n async (migrations) => {\n printJson(await migrations.list(), Boolean(opts.json));\n }\n );\n });\n\n migrate\n .command(\"show\")\n .description(\"Show one estate state\")\n .argument(\"<state>\", \"State id, unambiguous prefix, or name\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--sql\", \"Print labelled forward/check/rollback review SQL\")\n .option(\"--review <path>\", \"Write review SQL to this file\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(\n async (\n state: string,\n opts: { dir?: string; sql?: boolean; review?: string; json?: boolean }\n ) => {\n await withMigrations(\n { ...opts, config: migrate.opts<{ config?: string }>().config },\n async (migrations, _config, storage) => {\n const details = await migrations.show(selector(state)!);\n if (!(opts.sql || opts.review)) {\n printJson(details, Boolean(opts.json));\n return;\n }\n const graph = await loadMigrationGraph(storage);\n const manifest = graph.states.get(details.stateId);\n const blob = manifest && graph.sql.get(manifest.sqlHash);\n if (!(manifest && blob))\n throw new Error(\"The authenticated state SQL is unavailable\");\n const reviewSql = renderMigrationReview(\n manifest.parents,\n manifest.destinationChecks,\n blob\n );\n if (opts.json) printJson({ ...details, reviewSql }, true);\n else {\n printJson(details, false);\n process.stdout.write(reviewSql);\n }\n if (opts.review)\n await writeFile(resolve(opts.review), reviewSql, \"utf8\");\n }\n );\n }\n );\n\n migrate\n .command(\"graph\")\n .description(\"Print estate roots and leaves\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(async (opts: { dir?: string; json?: boolean }) => {\n await withMigrations(\n { ...opts, config: migrate.opts<{ config?: string }>().config },\n async (migrations) => {\n printJson(await migrations.graph(), Boolean(opts.json));\n }\n );\n });\n\n migrate\n .command(\"status\")\n .description(\"Show marker, pending path, and unfinished attempts\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(async (opts: { dir?: string; json?: boolean }) => {\n await withMigrations(\n { ...opts, config: migrate.opts<{ config?: string }>().config },\n async (migrations) => {\n printJson(await migrations.status(), Boolean(opts.json));\n }\n );\n });\n\n migrate\n .command(\"verify\")\n .description(\"Lock and compare the live schema to the marker\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(async (opts: { dir?: string; json?: boolean }) => {\n await withMigrations(\n { ...opts, config: migrate.opts<{ config?: string }>().config },\n async (migrations) => {\n const result = await migrations.verify();\n printJson(result, Boolean(opts.json));\n if (!result.ok) process.exitCode = 1;\n }\n );\n });\n\n migrate\n .command(\"log\")\n .description(\"Print the append-only ledger\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--limit <n>\", \"Maximum events\", positiveInteger)\n .option(\"--json\", \"Print machine-readable output\")\n .action(async (opts: { dir?: string; limit?: number; json?: boolean }) => {\n await withMigrations(\n { ...opts, config: migrate.opts<{ config?: string }>().config },\n async (migrations) => {\n const events = await migrations.log();\n printJson(\n opts.limit ? events.slice(-opts.limit) : events,\n Boolean(opts.json)\n );\n }\n );\n });\n\n migrate\n .command(\"apply\")\n .description(\"Apply estate states to the target\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--to <selector>\", \"Target state id, prefix, or name\")\n .option(\"--via <stateId...>\", \"Force a path through these states\")\n .option(\"--dry-run\", \"Plan without executing\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(\n async (opts: {\n dir?: string;\n to?: string;\n via?: string[];\n dryRun?: boolean;\n json?: boolean;\n }) => {\n await withMigrations(\n { ...opts, config: migrate.opts<{ config?: string }>().config },\n async (migrations) => {\n printJson(\n await migrations.apply({\n to: selector(opts.to),\n via: opts.via,\n dryRun: opts.dryRun,\n }),\n Boolean(opts.json)\n );\n }\n );\n }\n );\n\n migrate\n .command(\"down\")\n .description(\"Roll back along the recorded arrival path\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--to <selector>\", \"Roll back to this state\")\n .option(\"--steps <n>\", \"Number of states to roll back\", positiveInteger)\n .option(\"--dry-run\", \"Plan without executing\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(\n async (opts: {\n dir?: string;\n to?: string;\n steps?: number;\n dryRun?: boolean;\n json?: boolean;\n }) => {\n await withMigrations(\n { ...opts, config: migrate.opts<{ config?: string }>().config },\n async (migrations) => {\n if (opts.to !== undefined && opts.steps !== undefined)\n throw new Error(\"down accepts --to or --steps, not both\");\n printJson(\n await migrations.down(\n opts.to\n ? { to: selector(opts.to)!, dryRun: opts.dryRun }\n : { steps: opts.steps, dryRun: opts.dryRun }\n ),\n Boolean(opts.json)\n );\n }\n );\n }\n );\n\n migrate\n .command(\"baseline\")\n .description(\"Adopt an existing database as a known estate state\")\n .requiredOption(\"--to <selector>\", \"Existing estate state to adopt\")\n .option(\"--via <stateId...>\", \"Force the recorded root path\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(\n async (opts: {\n to: string;\n via?: string[];\n dir?: string;\n json?: boolean;\n }) => {\n await withMigrations(\n { ...opts, config: migrate.opts<{ config?: string }>().config },\n async (migrations) => {\n printJson(\n await migrations.baseline({\n to: selector(opts.to)!,\n via: opts.via,\n }),\n Boolean(opts.json)\n );\n }\n );\n }\n );\n\n migrate\n .command(\"resolve\")\n .description(\"Resolve an unfinished attempt after live proof\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--complete\", \"Mark complete when destination proof holds\")\n .option(\"--rolled-back\", \"Mark rolled back when origin proof holds\")\n .option(\"--retry\", \"Retry from the first proven incomplete step\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(\n async (opts: {\n dir?: string;\n complete?: boolean;\n rolledBack?: boolean;\n retry?: boolean;\n json?: boolean;\n }) => {\n await withMigrations(\n { ...opts, config: migrate.opts<{ config?: string }>().config },\n async (migrations) => {\n if (\n [opts.complete, opts.rolledBack, opts.retry].filter(Boolean)\n .length !== 1\n )\n throw new Error(\n \"resolve requires exactly one of --complete, --rolled-back, or --retry\"\n );\n const outcome = opts.complete\n ? \"complete\"\n : opts.rolledBack\n ? \"rolled-back\"\n : \"retry\";\n printJson(\n await migrations.resolve({ outcome }),\n Boolean(opts.json)\n );\n }\n );\n }\n );\n\n migrate\n .command(\"reset\")\n .description(\n \"Clear managed objects and replay from empty to a selected state\"\n )\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--to <selector>\", \"Target state after rebuild\")\n .option(\"--via <stateId...>\", \"Force a rebuild path\")\n .option(\"--confirm\", \"Confirm destructive reset (not required for dry-run)\")\n .option(\"--dry-run\", \"Plan without executing\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(\n async (opts: {\n dir?: string;\n to?: string;\n via?: string[];\n confirm?: boolean;\n dryRun?: boolean;\n json?: boolean;\n }) => {\n await withMigrations(\n { ...opts, config: migrate.opts<{ config?: string }>().config },\n async (migrations) => {\n if (!(opts.dryRun || opts.confirm))\n throw new Error(\n \"Reset requires --confirm; inspect --dry-run first\"\n );\n printJson(\n await migrations.reset({\n to: selector(opts.to),\n via: opts.via,\n dryRun: opts.dryRun,\n }),\n Boolean(opts.json)\n );\n }\n );\n }\n );\n\n return migrate;\n}\n\nexport const migrateCommand = createMigrateCommand();\n","/**\n * History-free, authenticated schema push CLI.\n *\n * The preview is inert. Effectful execution receives only the consent emitted\n * by that preview; no generic force authorization reaches the apply call.\n */\n\nimport { cancel, confirm, isCancel, note, outro } from \"@clack/prompts\";\nimport { Command } from \"commander\";\nimport { createMigrationClient } from \"../../migrations/client\";\nimport type { PushPreview } from \"../../migrations/push-v1\";\nimport { finishCli, loadConfig } from \"../utils\";\n\ninterface PushCliOptions {\n readonly config?: string;\n readonly dryRun?: boolean;\n readonly forceReset?: boolean;\n readonly yes?: boolean;\n readonly acceptDataLoss?: boolean;\n readonly json?: boolean;\n}\n\nfunction printJson(value: unknown): void {\n process.stdout.write(`${JSON.stringify(value, null, 2)}\\n`);\n}\n\nfunction printPlan(preview: PushPreview): void {\n const operations =\n preview.operations.length === 0\n ? [\"No schema changes.\"]\n : preview.operations.map(\n (operation) =>\n `[${operation.risk}] ${operation.label} (${operation.id})`\n );\n const statements = preview.statements.map(\n (statement, index) =>\n `${index + 1}. ${statement.sql}${\n statement.parameters.length === 0\n ? \"\"\n : `\\n parameters: ${JSON.stringify(statement.parameters)}`\n }`\n );\n const lines = [\n `Target: ${JSON.stringify(preview.target)}`,\n `Plan: ${preview.planHash}`,\n ...operations,\n ...(statements.length === 0 ? [] : [\"\", \"SQL:\", ...statements]),\n ];\n note(lines.join(\"\\n\"), \"Push plan\");\n}\n\nasync function runPush(options: PushCliOptions): Promise<void> {\n let orm: { $disconnect(): Promise<void> } | undefined;\n let failure: { value: unknown } | undefined;\n try {\n const config = await loadConfig({ config: options.config });\n orm = config.client;\n const migrations =\n config.migrations?.tables === undefined\n ? createMigrationClient(config.client)\n : createMigrationClient(config.client, {\n tables: config.migrations.tables,\n });\n // `force` is confined to the inert planning arm. The authenticated apply\n // arm below receives only the consent bound to this exact preview.\n const preview = await migrations.push({\n dryRun: true,\n ...(options.forceReset === true ? { forceReset: true } : {}),\n ...(config.migrations?.resolve\n ? { resolve: config.migrations.resolve }\n : {}),\n });\n\n if (\n !options.json &&\n config.driver?.dialect === \"sqlite\" &&\n [\"sqlite3\", \"bun-sqlite\", \"bun-sql\"].includes(config.driver.driverName)\n ) {\n const databases = await config.driver._executeRaw<{\n name: string;\n file: string;\n }>(\"PRAGMA database_list\");\n if (\n databases.rows.some(\n (database) => database.name === \"main\" && database.file === \"\"\n )\n )\n process.stderr.write(\n \"warning: SQLite reports an in-memory main database. Use a persistent target for durable schema changes.\\n\"\n );\n }\n\n if (options.dryRun) {\n if (options.json) printJson(preview);\n else printPlan(preview);\n return;\n }\n\n if (!options.json) printPlan(preview);\n\n if (\n preview.destructive &&\n !options.acceptDataLoss &&\n (options.yes || options.json || !process.stdin.isTTY)\n ) {\n throw new Error(\n \"Destructive push requires --accept-data-loss; --yes does not authorize data loss. Inspect --dry-run first.\"\n );\n }\n if (\n preview.outcome !== \"noop\" &&\n !options.yes &&\n !options.acceptDataLoss &&\n !options.json &&\n process.stdin.isTTY\n ) {\n const accepted = await confirm({\n message: preview.destructive\n ? \"Apply this destructive push plan?\"\n : \"Apply this push plan?\",\n initialValue: !preview.destructive,\n });\n if (isCancel(accepted) || !accepted) {\n cancel(\"Push cancelled.\");\n return;\n }\n }\n\n const result = await migrations.push({ consent: preview.consent });\n if (options.json) printJson(result);\n else\n outro(\n result.outcome === \"noop\" ? \"Schema is up to date.\" : \"Push applied.\"\n );\n } catch (error) {\n failure = { value: error };\n } finally {\n await finishCli(orm, failure, options.json);\n }\n}\n\nexport function createPushCommand(): Command {\n return new Command(\"push\")\n .description(\"Synchronize the schema directly without migration history\")\n .option(\"--config <path>\", \"Path to viborm.config.ts\")\n .option(\"--dry-run\", \"Preview without changing the database\")\n .option(\"--force-reset\", \"Plan a rebuild from an empty database\")\n .option(\"-y, --yes\", \"Skip prompts for non-destructive plans\")\n .option(\n \"--accept-data-loss\",\n \"Explicitly accept the previewed destructive plan\"\n )\n .option(\"--json\", \"Print machine-readable JSON\")\n .action(runPush);\n}\n\nexport const pushCommand = createPushCommand();\n","#!/usr/bin/env node\n/**\n * VibORM CLI\n *\n * Command-line interface for VibORM database operations.\n */\n\nimport { Command } from \"commander\";\nimport { VIBORM_VERSION } from \"../version\";\nimport { checkCommand } from \"./commands/check\";\nimport { migrateCommand } from \"./commands/migrate\";\nimport { pushCommand } from \"./commands/push\";\n\nconst program = new Command();\n\nprogram\n .name(\"viborm\")\n .description(\"VibORM - Type-safe ORM for PostgreSQL, MySQL and SQLite\")\n .version(VIBORM_VERSION);\n\n// Register commands\nprogram.addCommand(checkCommand);\nprogram.addCommand(pushCommand);\nprogram.addCommand(migrateCommand);\n\n// Parse arguments\ntry {\n await program.parseAsync();\n} catch (error: unknown) {\n process.stderr.write(\n `${error instanceof Error ? error.message : \"CLI failed\"}\\n`\n );\n process.exitCode = 1;\n}\n"],"mappings":";iuBAqDA,MAAM,EAAQ,EAAuB,IAAI,CAGzC,eAAe,YACb,EACA,EAC0B,CAC1B,GAAM,CAAE,QAAS,MAAM,EAAO,YAG5B,kKACA,CAAC,EAAM,CACR,CAED,OAAO,EAAK,KAAK,CAAE,UAAS,KAAI,GAAG,MAAc,CAC/C,GAAG,EACH,SAAU,OAAO,EAAQ,GAAK,GAAK,OAAO,EAAG,GAAK,EACnD,EAAE,CAUL,eAAe,aACb,EACA,EACwB,CACxB,GAAI,EAAO,UAAY,SAAU,MAAO,EAAE,CAC1C,IAAM,EAAwB,EAAE,CAChC,IAAK,GAAM,CAAC,EAAM,KAAU,OAAO,QAAQ,EAAO,CAAE,CAClD,IAAM,EAAQ,EAAa,EAAO,EAAK,CACjC,EAAoB,EAAM,KAAK,MAEjC,EACE,KAAO,KAAO,KACjB,MAAO,IAAY,YAAY,EAAQ,EAAM,GAAG,KAC9C,GAAU,EAAM,OAAS,EAC3B,CACH,IAAK,GAAM,CAAC,EAAO,KAAW,OAAO,QAAQ,EAAM,QAAQ,CAAE,CAC3D,IAAM,EAAa,EAAO,KAAK,MACzB,CAAE,OAAM,Q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