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
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-vfur-DaU.mjs";import{t as n}from"./migrations-BWZSBMZh.mjs";import{closeSync as r,constants as i,existsSync as a,fsyncSync as o,linkSync as s,lstatSync as c,mkdirSync as l,openSync as u,readFileSync as d,readdirSync as f,unlinkSync as p,writeSync as m}from"node:fs";import{dirname as h,join as g,resolve as _}from"node:path";import{createHash as v}from"node:crypto";const y=`sha256`,b={estate:`viborm.migration.estate.v1`,snapshot:`viborm.migration.snapshot.v1`,sql:`viborm.migration.sql.v1`,dispatch:`viborm.migration.dispatch.v1`,transition:`viborm.migration.transition.v1`,state:`viborm.migration.state.v1`,path:`viborm.migration.path.v1`,plan:`viborm.migration.plan.v1`,resetPlan:`viborm.migration.reset-plan.v1`,event:`viborm.migration.event.v1`},x=/^[0-9a-f]{64}$/,S=new TextEncoder;function isSha256(e){return typeof e==`string`&&x.test(e)}function parseSha256(e,r){if(!isSha256(e))throw new n(`${r} is not a lowercase 64-hex SHA-256 digest`,t.MIGRATION_INVALID_ESTATE);return e}function sha256Hex(e){return v(`sha256`).update(e).digest(`hex`)}function domainHash(e,t){let n=S.encode(e),r=new Uint8Array(n.length+1+t.length);return r.set(n,0),r[n.length]=0,r.set(t,n.length+1),sha256Hex(r)}function utf8Bytes(e){return S.encode(e)}function decodeUtf8(e){return new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0}).decode(e)}const C=`estate.json`;var FsEstateStorage=class{baseDir;constructor(e){this.baseDir=_(e)}async readEstate(){return readOptional(g(this.baseDir,C))}async listStates(){return listHexFiles(g(this.baseDir,`states`),`.json`)}async listSnapshots(){return listHexFiles(g(this.baseDir,`snapshots`),`.json`)}async listSql(){return listHexFiles(g(this.baseDir,`sql`),`.sql`)}async readState(e){return readOptional(g(this.baseDir,`states`,`${e}.json`))}async readSnapshot(e){return readOptional(g(this.baseDir,`snapshots`,`${e}.json`))}async readSql(e){return readOptional(g(this.baseDir,`sql`,`${e}.sql`))}async publishEstate(e){return publishNoReplace(this.baseDir,g(this.baseDir,C),e)}async publishSnapshot(e,t){return publishNoReplace(this.baseDir,g(this.baseDir,`snapshots`,`${e}.json`),t)}async publishSql(e,t){return publishNoReplace(this.baseDir,g(this.baseDir,`sql`,`${e}.sql`),t)}async publishState(e,t){return publishNoReplace(this.baseDir,g(this.baseDir,`states`,`${e}.json`),t)}};function createFsStorageWriter(e){return new FsEstateStorage(e)}function readOptional(e){return a(e)?(refuseSymlink(e),new Uint8Array(d(e))):null}function listHexFiles(e,t){if(!a(e))return[];refuseSymlink(e);let n=f(e),r=[];for(let e of n){if(e.startsWith(`.`)||e.endsWith(`.tmp`)||!e.endsWith(t))continue;let n=e.slice(0,-t.length);isSha256(n)&&r.push(n)}return r.sort()}function publishNoReplace(e,c,f){assertInsideBase(e,c);let _=h(c);if(l(_,{recursive:!0}),refuseSymlink(_),a(c))return refuseSymlink(c),compareExisting(c,f);let v=g(_,`.${randomSuffix()}.tmp`),y=u(v,i.O_CREAT|i.O_EXCL|i.O_WRONLY,420);try{m(y,f),o(y)}finally{r(y)}if(sha256Hex(d(v))!==sha256Hex(f))throw p(v),new n(`Temporary estate write did not round-trip`,t.MIGRATION_CORRUPTION);try{s(v,c)}catch(e){if(unlinkQuiet(v),isErrno(e,`EEXIST`))return compareExisting(c,f);throw isErrno(e,`EXDEV`)||isErrno(e,`ENOSYS`)||isErrno(e,`EPERM`)?new n(`Filesystem cannot atomically publish with a no-replace hard link`,t.MIGRATION_STORAGE_REQUIRED,{cause:e instanceof Error?e:void 0}):e}return unlinkQuiet(v),fsyncDirectory(_),{outcome:`created`}}function compareExisting(e,r){if(sha256Hex(d(e))!==sha256Hex(r))throw new n(`Content-addressed path ${e} already holds different bytes`,t.MIGRATION_CORRUPTION);return fsyncDirectory(h(e)),{outcome:`identical`}}function refuseSymlink(e){if(c(e).isSymbolicLink())throw new n(`Estate storage refuses to follow symlinks`,t.MIGRATION_INVALID_ESTATE)}function fsyncDirectory(e){let t=u(e,i.O_RDONLY|i.O_DIRECTORY);try{o(t)}finally{r(t)}}function unlinkQuiet(e){try{p(e)}catch{}}function isErrno(e,t){return!!(e&&typeof e==`object`&&`code`in e&&e.code===t)}function randomSuffix(){return`${Date.now().toString(16)}-${Math.random().toString(16).slice(2)}`}function assertInsideBase(e,r){let i=_(r),a=e.endsWith(`/`)?e:`${e}/`;if(i!==_(e)&&!i.startsWith(a))throw new n(`Estate path escapes the storage root`,t.MIGRATION_INVALID_ESTATE)}export{domainHash as a,utf8Bytes as c,decodeUtf8 as i,y as n,isSha256 as o,b as r,parseSha256 as s,createFsStorageWriter as t};
|
|
2
|
-
//# sourceMappingURL=fs-estate-
|
|
2
|
+
//# sourceMappingURL=fs-estate-BLqNdigQ.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fs-estate-BcjgY4iY.mjs","names":[],"sources":["../src/migrations/identity.ts","../src/migrations/storage/fs-estate.ts"],"sourcesContent":["/**\n * Content-addressed identity for Migration V1.\n *\n * One hash owner: SHA-256 over a frozen ASCII domain label, 0x00, then the\n * exact bytes being authenticated. Filenames and stored hex digests are the\n * lowercase 64-hex form of that digest. There is no self-referential checksum\n * header and no second hasher.\n */\n\nimport { createHash } from \"node:crypto\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\n\nexport type Sha256 = string;\n\nexport const HASH_ALGORITHM = \"sha256\";\n\nexport const HASH_DOMAIN = {\n estate: \"viborm.migration.estate.v1\",\n snapshot: \"viborm.migration.snapshot.v1\",\n sql: \"viborm.migration.sql.v1\",\n dispatch: \"viborm.migration.dispatch.v1\",\n transition: \"viborm.migration.transition.v1\",\n state: \"viborm.migration.state.v1\",\n path: \"viborm.migration.path.v1\",\n plan: \"viborm.migration.plan.v1\",\n resetPlan: \"viborm.migration.reset-plan.v1\",\n event: \"viborm.migration.event.v1\",\n} as const;\n\nexport type HashDomain = (typeof HASH_DOMAIN)[keyof typeof HASH_DOMAIN];\n\nconst HEX64 = /^[0-9a-f]{64}$/;\nconst UTF8 = new TextEncoder();\n\nexport function isSha256(value: unknown): value is Sha256 {\n return typeof value === \"string\" && HEX64.test(value);\n}\n\nexport function parseSha256(value: unknown, label: string): Sha256 {\n if (!isSha256(value)) {\n throw new MigrationError(\n `${label} is not a lowercase 64-hex SHA-256 digest`,\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n return value;\n}\n\nexport function sha256Hex(bytes: Uint8Array): Sha256 {\n return createHash(\"sha256\").update(bytes).digest(\"hex\");\n}\n\nexport function domainHash(domain: HashDomain, bytes: Uint8Array): Sha256 {\n const prefix = UTF8.encode(domain);\n const input = new Uint8Array(prefix.length + 1 + bytes.length);\n input.set(prefix, 0);\n input[prefix.length] = 0;\n input.set(bytes, prefix.length + 1);\n return sha256Hex(input);\n}\n\nexport function utf8Bytes(text: string): Uint8Array {\n return UTF8.encode(text);\n}\n\n/**\n * Exactly the characters the bytes encode — a leading U+FEFF among them.\n *\n * These bytes are a VALUE (a catalog default, a blob's text), not a document\n * with a byte-order mark: the decoder's default of swallowing a leading U+FEFF\n * would report a value its source does not hold. A caller that refuses a BOM\n * refuses it as a byte, before this (`validateSqlRanges`).\n */\nexport function decodeUtf8(bytes: Uint8Array): string {\n return new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true }).decode(\n bytes\n );\n}\n","/**\n * Filesystem estate writer.\n *\n * Publication is write-temp → fsync → rehash → hard-link no-replace →\n * verify EEXIST bytes → unlink temp → fsync directory. Check-then-rename\n * is forbidden.\n */\n\nimport {\n closeSync,\n constants,\n existsSync,\n fsyncSync,\n linkSync,\n lstatSync,\n mkdirSync,\n openSync,\n readdirSync,\n readFileSync,\n unlinkSync,\n writeSync,\n} from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { MigrationError, VibORMErrorCode } from \"../../errors\";\nimport { isSha256, type Sha256, sha256Hex } from \"../identity\";\nimport type { MigrationStorageWriter, PublishResult } from \"./contract\";\n\nconst ESTATE_NAME = \"estate.json\";\n\nclass FsEstateStorage implements MigrationStorageWriter {\n readonly baseDir: string;\n\n constructor(baseDir: string) {\n this.baseDir = resolve(baseDir);\n }\n\n async readEstate(): Promise<Uint8Array | null> {\n return readOptional(join(this.baseDir, ESTATE_NAME));\n }\n\n async listStates(): Promise<readonly Sha256[]> {\n return listHexFiles(join(this.baseDir, \"states\"), \".json\");\n }\n\n async listSnapshots(): Promise<readonly Sha256[]> {\n return listHexFiles(join(this.baseDir, \"snapshots\"), \".json\");\n }\n\n async listSql(): Promise<readonly Sha256[]> {\n return listHexFiles(join(this.baseDir, \"sql\"), \".sql\");\n }\n\n async readState(id: Sha256): Promise<Uint8Array | null> {\n return readOptional(join(this.baseDir, \"states\", `${id}.json`));\n }\n\n async readSnapshot(hash: Sha256): Promise<Uint8Array | null> {\n return readOptional(join(this.baseDir, \"snapshots\", `${hash}.json`));\n }\n\n async readSql(hash: Sha256): Promise<Uint8Array | null> {\n return readOptional(join(this.baseDir, \"sql\", `${hash}.sql`));\n }\n\n async publishEstate(bytes: Uint8Array): Promise<PublishResult> {\n return publishNoReplace(\n this.baseDir,\n join(this.baseDir, ESTATE_NAME),\n bytes\n );\n }\n\n async publishSnapshot(\n hash: Sha256,\n bytes: Uint8Array\n ): Promise<PublishResult> {\n return publishNoReplace(\n this.baseDir,\n join(this.baseDir, \"snapshots\", `${hash}.json`),\n bytes\n );\n }\n\n async publishSql(hash: Sha256, bytes: Uint8Array): Promise<PublishResult> {\n return publishNoReplace(\n this.baseDir,\n join(this.baseDir, \"sql\", `${hash}.sql`),\n bytes\n );\n }\n\n async publishState(id: Sha256, bytes: Uint8Array): Promise<PublishResult> {\n return publishNoReplace(\n this.baseDir,\n join(this.baseDir, \"states\", `${id}.json`),\n bytes\n );\n }\n}\n\nexport function createFsStorageWriter(baseDir: string): MigrationStorageWriter {\n return new FsEstateStorage(baseDir);\n}\n\nfunction readOptional(path: string): Uint8Array | null {\n if (!existsSync(path)) return null;\n refuseSymlink(path);\n return new Uint8Array(readFileSync(path));\n}\n\nfunction listHexFiles(directory: string, suffix: string): Sha256[] {\n if (!existsSync(directory)) return [];\n refuseSymlink(directory);\n const names = readdirSync(directory);\n const hashes: Sha256[] = [];\n for (const name of names) {\n if (name.startsWith(\".\") || name.endsWith(\".tmp\")) continue;\n if (!name.endsWith(suffix)) continue;\n const hex = name.slice(0, -suffix.length);\n if (!isSha256(hex)) continue;\n hashes.push(hex);\n }\n return hashes.sort();\n}\n\nfunction publishNoReplace(\n baseDir: string,\n finalPath: string,\n bytes: Uint8Array\n): PublishResult {\n assertInsideBase(baseDir, finalPath);\n const directory = dirname(finalPath);\n mkdirSync(directory, { recursive: true });\n refuseSymlink(directory);\n if (existsSync(finalPath)) {\n refuseSymlink(finalPath);\n return compareExisting(finalPath, bytes);\n }\n\n const tempPath = join(directory, `.${randomSuffix()}.tmp`);\n const fd = openSync(\n tempPath,\n // biome-ignore lint/suspicious/noBitwiseOperators: POSIX open flags are one mask\n constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY,\n 0o644\n );\n try {\n writeSync(fd, bytes);\n fsyncSync(fd);\n } finally {\n closeSync(fd);\n }\n\n const reread = readFileSync(tempPath);\n if (sha256Hex(reread) !== sha256Hex(bytes)) {\n unlinkSync(tempPath);\n throw new MigrationError(\n \"Temporary estate write did not round-trip\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n\n try {\n linkSync(tempPath, finalPath);\n } catch (error) {\n unlinkQuiet(tempPath);\n if (isErrno(error, \"EEXIST\")) {\n return compareExisting(finalPath, bytes);\n }\n if (\n isErrno(error, \"EXDEV\") ||\n isErrno(error, \"ENOSYS\") ||\n isErrno(error, \"EPERM\")\n ) {\n throw new MigrationError(\n \"Filesystem cannot atomically publish with a no-replace hard link\",\n VibORMErrorCode.MIGRATION_STORAGE_REQUIRED,\n { cause: error instanceof Error ? error : undefined }\n );\n }\n throw error;\n }\n\n unlinkQuiet(tempPath);\n fsyncDirectory(directory);\n return { outcome: \"created\" };\n}\n\nfunction compareExisting(path: string, bytes: Uint8Array): PublishResult {\n const existing = readFileSync(path);\n if (sha256Hex(existing) !== sha256Hex(bytes)) {\n throw new MigrationError(\n `Content-addressed path ${path} already holds different bytes`,\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n fsyncDirectory(dirname(path));\n return { outcome: \"identical\" };\n}\n\nfunction refuseSymlink(path: string): void {\n const stat = lstatSync(path);\n if (stat.isSymbolicLink()) {\n throw new MigrationError(\n \"Estate storage refuses to follow symlinks\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n}\n\nfunction fsyncDirectory(directory: string): void {\n const fd = openSync(\n directory,\n // biome-ignore lint/suspicious/noBitwiseOperators: POSIX open flags are one mask\n constants.O_RDONLY | constants.O_DIRECTORY\n );\n try {\n fsyncSync(fd);\n } finally {\n closeSync(fd);\n }\n}\n\nfunction unlinkQuiet(path: string): void {\n try {\n unlinkSync(path);\n } catch {\n // temp cleanup is best-effort after the final name is visible\n }\n}\n\nfunction isErrno(error: unknown, code: string): boolean {\n return Boolean(\n error && typeof error === \"object\" && \"code\" in error && error.code === code\n );\n}\n\nfunction randomSuffix(): string {\n return `${Date.now().toString(16)}-${Math.random().toString(16).slice(2)}`;\n}\n\nfunction assertInsideBase(baseDir: string, path: string): void {\n const resolved = resolve(path);\n const root = baseDir.endsWith(\"/\") ? baseDir : `${baseDir}/`;\n if (resolved !== resolve(baseDir) && !resolved.startsWith(root)) {\n throw new MigrationError(\n \"Estate path escapes the storage root\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n}\n"],"mappings":"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"}
|
|
1
|
+
{"version":3,"file":"fs-estate-BLqNdigQ.mjs","names":[],"sources":["../src/migrations/identity.ts","../src/migrations/storage/fs-estate.ts"],"sourcesContent":["/**\n * Content-addressed identity for Migration V1.\n *\n * One hash owner: SHA-256 over a frozen ASCII domain label, 0x00, then the\n * exact bytes being authenticated. Filenames and stored hex digests are the\n * lowercase 64-hex form of that digest. There is no self-referential checksum\n * header and no second hasher.\n */\n\nimport { createHash } from \"node:crypto\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\n\nexport type Sha256 = string;\n\nexport const HASH_ALGORITHM = \"sha256\";\n\nexport const HASH_DOMAIN = {\n estate: \"viborm.migration.estate.v1\",\n snapshot: \"viborm.migration.snapshot.v1\",\n sql: \"viborm.migration.sql.v1\",\n dispatch: \"viborm.migration.dispatch.v1\",\n transition: \"viborm.migration.transition.v1\",\n state: \"viborm.migration.state.v1\",\n path: \"viborm.migration.path.v1\",\n plan: \"viborm.migration.plan.v1\",\n resetPlan: \"viborm.migration.reset-plan.v1\",\n event: \"viborm.migration.event.v1\",\n} as const;\n\nexport type HashDomain = (typeof HASH_DOMAIN)[keyof typeof HASH_DOMAIN];\n\nconst HEX64 = /^[0-9a-f]{64}$/;\nconst UTF8 = new TextEncoder();\n\nexport function isSha256(value: unknown): value is Sha256 {\n return typeof value === \"string\" && HEX64.test(value);\n}\n\nexport function parseSha256(value: unknown, label: string): Sha256 {\n if (!isSha256(value)) {\n throw new MigrationError(\n `${label} is not a lowercase 64-hex SHA-256 digest`,\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n return value;\n}\n\nexport function sha256Hex(bytes: Uint8Array): Sha256 {\n return createHash(\"sha256\").update(bytes).digest(\"hex\");\n}\n\nexport function domainHash(domain: HashDomain, bytes: Uint8Array): Sha256 {\n const prefix = UTF8.encode(domain);\n const input = new Uint8Array(prefix.length + 1 + bytes.length);\n input.set(prefix, 0);\n input[prefix.length] = 0;\n input.set(bytes, prefix.length + 1);\n return sha256Hex(input);\n}\n\nexport function utf8Bytes(text: string): Uint8Array {\n return UTF8.encode(text);\n}\n\n/**\n * Exactly the characters the bytes encode — a leading U+FEFF among them.\n *\n * These bytes are a VALUE (a catalog default, a blob's text), not a document\n * with a byte-order mark: the decoder's default of swallowing a leading U+FEFF\n * would report a value its source does not hold. A caller that refuses a BOM\n * refuses it as a byte, before this (`validateSqlRanges`).\n */\nexport function decodeUtf8(bytes: Uint8Array): string {\n return new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true }).decode(\n bytes\n );\n}\n","/**\n * Filesystem estate writer.\n *\n * Publication is write-temp → fsync → rehash → hard-link no-replace →\n * verify EEXIST bytes → unlink temp → fsync directory. Check-then-rename\n * is forbidden.\n */\n\nimport {\n closeSync,\n constants,\n existsSync,\n fsyncSync,\n linkSync,\n lstatSync,\n mkdirSync,\n openSync,\n readdirSync,\n readFileSync,\n unlinkSync,\n writeSync,\n} from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { MigrationError, VibORMErrorCode } from \"../../errors\";\nimport { isSha256, type Sha256, sha256Hex } from \"../identity\";\nimport type { MigrationStorageWriter, PublishResult } from \"./contract\";\n\nconst ESTATE_NAME = \"estate.json\";\n\nclass FsEstateStorage implements MigrationStorageWriter {\n readonly baseDir: string;\n\n constructor(baseDir: string) {\n this.baseDir = resolve(baseDir);\n }\n\n async readEstate(): Promise<Uint8Array | null> {\n return readOptional(join(this.baseDir, ESTATE_NAME));\n }\n\n async listStates(): Promise<readonly Sha256[]> {\n return listHexFiles(join(this.baseDir, \"states\"), \".json\");\n }\n\n async listSnapshots(): Promise<readonly Sha256[]> {\n return listHexFiles(join(this.baseDir, \"snapshots\"), \".json\");\n }\n\n async listSql(): Promise<readonly Sha256[]> {\n return listHexFiles(join(this.baseDir, \"sql\"), \".sql\");\n }\n\n async readState(id: Sha256): Promise<Uint8Array | null> {\n return readOptional(join(this.baseDir, \"states\", `${id}.json`));\n }\n\n async readSnapshot(hash: Sha256): Promise<Uint8Array | null> {\n return readOptional(join(this.baseDir, \"snapshots\", `${hash}.json`));\n }\n\n async readSql(hash: Sha256): Promise<Uint8Array | null> {\n return readOptional(join(this.baseDir, \"sql\", `${hash}.sql`));\n }\n\n async publishEstate(bytes: Uint8Array): Promise<PublishResult> {\n return publishNoReplace(\n this.baseDir,\n join(this.baseDir, ESTATE_NAME),\n bytes\n );\n }\n\n async publishSnapshot(\n hash: Sha256,\n bytes: Uint8Array\n ): Promise<PublishResult> {\n return publishNoReplace(\n this.baseDir,\n join(this.baseDir, \"snapshots\", `${hash}.json`),\n bytes\n );\n }\n\n async publishSql(hash: Sha256, bytes: Uint8Array): Promise<PublishResult> {\n return publishNoReplace(\n this.baseDir,\n join(this.baseDir, \"sql\", `${hash}.sql`),\n bytes\n );\n }\n\n async publishState(id: Sha256, bytes: Uint8Array): Promise<PublishResult> {\n return publishNoReplace(\n this.baseDir,\n join(this.baseDir, \"states\", `${id}.json`),\n bytes\n );\n }\n}\n\nexport function createFsStorageWriter(baseDir: string): MigrationStorageWriter {\n return new FsEstateStorage(baseDir);\n}\n\nfunction readOptional(path: string): Uint8Array | null {\n if (!existsSync(path)) return null;\n refuseSymlink(path);\n return new Uint8Array(readFileSync(path));\n}\n\nfunction listHexFiles(directory: string, suffix: string): Sha256[] {\n if (!existsSync(directory)) return [];\n refuseSymlink(directory);\n const names = readdirSync(directory);\n const hashes: Sha256[] = [];\n for (const name of names) {\n if (name.startsWith(\".\") || name.endsWith(\".tmp\")) continue;\n if (!name.endsWith(suffix)) continue;\n const hex = name.slice(0, -suffix.length);\n if (!isSha256(hex)) continue;\n hashes.push(hex);\n }\n return hashes.sort();\n}\n\nfunction publishNoReplace(\n baseDir: string,\n finalPath: string,\n bytes: Uint8Array\n): PublishResult {\n assertInsideBase(baseDir, finalPath);\n const directory = dirname(finalPath);\n mkdirSync(directory, { recursive: true });\n refuseSymlink(directory);\n if (existsSync(finalPath)) {\n refuseSymlink(finalPath);\n return compareExisting(finalPath, bytes);\n }\n\n const tempPath = join(directory, `.${randomSuffix()}.tmp`);\n const fd = openSync(\n tempPath,\n // biome-ignore lint/suspicious/noBitwiseOperators: POSIX open flags are one mask\n constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY,\n 0o644\n );\n try {\n writeSync(fd, bytes);\n fsyncSync(fd);\n } finally {\n closeSync(fd);\n }\n\n const reread = readFileSync(tempPath);\n if (sha256Hex(reread) !== sha256Hex(bytes)) {\n unlinkSync(tempPath);\n throw new MigrationError(\n \"Temporary estate write did not round-trip\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n\n try {\n linkSync(tempPath, finalPath);\n } catch (error) {\n unlinkQuiet(tempPath);\n if (isErrno(error, \"EEXIST\")) {\n return compareExisting(finalPath, bytes);\n }\n if (\n isErrno(error, \"EXDEV\") ||\n isErrno(error, \"ENOSYS\") ||\n isErrno(error, \"EPERM\")\n ) {\n throw new MigrationError(\n \"Filesystem cannot atomically publish with a no-replace hard link\",\n VibORMErrorCode.MIGRATION_STORAGE_REQUIRED,\n { cause: error instanceof Error ? error : undefined }\n );\n }\n throw error;\n }\n\n unlinkQuiet(tempPath);\n fsyncDirectory(directory);\n return { outcome: \"created\" };\n}\n\nfunction compareExisting(path: string, bytes: Uint8Array): PublishResult {\n const existing = readFileSync(path);\n if (sha256Hex(existing) !== sha256Hex(bytes)) {\n throw new MigrationError(\n `Content-addressed path ${path} already holds different bytes`,\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n fsyncDirectory(dirname(path));\n return { outcome: \"identical\" };\n}\n\nfunction refuseSymlink(path: string): void {\n const stat = lstatSync(path);\n if (stat.isSymbolicLink()) {\n throw new MigrationError(\n \"Estate storage refuses to follow symlinks\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n}\n\nfunction fsyncDirectory(directory: string): void {\n const fd = openSync(\n directory,\n // biome-ignore lint/suspicious/noBitwiseOperators: POSIX open flags are one mask\n constants.O_RDONLY | constants.O_DIRECTORY\n );\n try {\n fsyncSync(fd);\n } finally {\n closeSync(fd);\n }\n}\n\nfunction unlinkQuiet(path: string): void {\n try {\n unlinkSync(path);\n } catch {\n // temp cleanup is best-effort after the final name is visible\n }\n}\n\nfunction isErrno(error: unknown, code: string): boolean {\n return Boolean(\n error && typeof error === \"object\" && \"code\" in error && error.code === code\n );\n}\n\nfunction randomSuffix(): string {\n return `${Date.now().toString(16)}-${Math.random().toString(16).slice(2)}`;\n}\n\nfunction assertInsideBase(baseDir: string, path: string): void {\n const resolved = resolve(path);\n const root = baseDir.endsWith(\"/\") ? baseDir : `${baseDir}/`;\n if (resolved !== resolve(baseDir) && !resolved.startsWith(root)) {\n throw new MigrationError(\n \"Estate path escapes the storage root\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n}\n"],"mappings":"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"}
|
|
@@ -1844,23 +1844,22 @@ declare function boolean<const Opts extends ScalarOptions<boolean, any>>(options
|
|
|
1844
1844
|
//#endregion
|
|
1845
1845
|
//#region src/validation/primitives/enum.d.ts
|
|
1846
1846
|
type EnumValues<S$1 extends VibSchema> = S$1 extends EnumSchema<infer TValues, any, any> ? TValues : never;
|
|
1847
|
-
type BaseEnumSchema<TValues extends string[], Opts extends ScalarOptions<TValues[number], any> | undefined = undefined> = EnumSchema<TValues, ComputeInput<TValues[number], Opts>, ComputeOutput<TValues[number], Opts>>;
|
|
1848
|
-
interface EnumSchema<TValues extends string[], TInput = TValues[number], TOutput = TValues[number]> extends VibSchema<TInput, TOutput> {
|
|
1847
|
+
type BaseEnumSchema<TValues extends readonly string[], Opts extends ScalarOptions<TValues[number], any> | undefined = undefined> = EnumSchema<TValues, ComputeInput<TValues[number], Opts>, ComputeOutput<TValues[number], Opts>>;
|
|
1848
|
+
interface EnumSchema<TValues extends readonly string[], TInput = TValues[number], TOutput = TValues[number]> extends VibSchema<TInput, TOutput> {
|
|
1849
1849
|
readonly type: "enum";
|
|
1850
1850
|
readonly values: TValues;
|
|
1851
1851
|
}
|
|
1852
1852
|
/**
|
|
1853
|
-
* Create an enum schema that validates a value is one of the allowed
|
|
1853
|
+
* Create an enum schema that validates a value is one of the allowed strings.
|
|
1854
1854
|
*
|
|
1855
|
-
*
|
|
1856
|
-
*
|
|
1855
|
+
* The values may be a readonly tuple (`["a", "b"] as const`). The mutable arm
|
|
1856
|
+
* of the constraint keeps an inline literal inferred as a mutable tuple, so
|
|
1857
|
+
* the types of existing schemas do not change.
|
|
1857
1858
|
*
|
|
1858
1859
|
* @example
|
|
1859
1860
|
* const status = v.enum_(["active", "inactive", "pending"]);
|
|
1860
|
-
* const level = v.enum_([1, 2, 3]);
|
|
1861
|
-
* const mixed = v.enum_(["a", 1, "b", 2]);
|
|
1862
1861
|
*/
|
|
1863
|
-
declare function enum_<const TValues extends string[], const Opts extends ScalarOptions<TValues[number], any> | undefined = undefined>(values: TValues, options?: Opts): EnumSchema<TValues, ComputeInput<TValues[number], Opts>, ComputeOutput<TValues[number], Opts>>;
|
|
1862
|
+
declare function enum_<const TValues extends string[] | readonly string[], const Opts extends ScalarOptions<TValues[number], any> | undefined = undefined>(values: TValues, options?: Opts): EnumSchema<TValues, ComputeInput<TValues[number], Opts>, ComputeOutput<TValues[number], Opts>>;
|
|
1864
1863
|
//#endregion
|
|
1865
1864
|
//#region src/validation/primitives/geo-area-codec.d.ts
|
|
1866
1865
|
declare function geoAreaSchema(): VibSchema<GeoArea, GeoArea>;
|
|
@@ -3491,7 +3490,7 @@ declare namespace V$1 {
|
|
|
3491
3490
|
* Type-level enum schema.
|
|
3492
3491
|
* @example V.Enum<["active", "inactive", "pending"]>
|
|
3493
3492
|
*/
|
|
3494
|
-
type Enum<TValues extends string[], Opts extends ScalarOptions<TValues[number], any> | undefined = undefined> = EnumSchema<TValues, ComputeInput<TValues[number], Opts>, ComputeOutput<TValues[number], Opts>>;
|
|
3493
|
+
type Enum<TValues extends readonly string[], Opts extends ScalarOptions<TValues[number], any> | undefined = undefined> = EnumSchema<TValues, ComputeInput<TValues[number], Opts>, ComputeOutput<TValues[number], Opts>>;
|
|
3495
3494
|
/**
|
|
3496
3495
|
* Type-level literal schema.
|
|
3497
3496
|
* @example V.Literal<"active">
|
|
@@ -4034,6 +4033,40 @@ type ToManyCreateSchema<Source extends AnyModel, Key$1, S$1 extends RelationStat
|
|
|
4034
4033
|
optional: true;
|
|
4035
4034
|
}>;
|
|
4036
4035
|
//#endregion
|
|
4036
|
+
//#region src/validation/relations/recurrence.d.ts
|
|
4037
|
+
interface NormalizedRecurrence {
|
|
4038
|
+
readonly depth: number | false;
|
|
4039
|
+
readonly cycles: "reject" | "prevent" | "allow";
|
|
4040
|
+
}
|
|
4041
|
+
/**
|
|
4042
|
+
* A foreign-key traversal has no cycle policy to choose: it rejects every
|
|
4043
|
+
* cycle it reaches. `preventCycles` is therefore refused by the bag's own type,
|
|
4044
|
+
* so no downstream guard has to know which topology a nested bag belongs to.
|
|
4045
|
+
*/
|
|
4046
|
+
type ForeignKeyRecurse = true | {
|
|
4047
|
+
readonly depth?: number | false;
|
|
4048
|
+
readonly preventCycles?: undefined;
|
|
4049
|
+
};
|
|
4050
|
+
type GraphRecurse = true | {
|
|
4051
|
+
readonly depth?: number;
|
|
4052
|
+
readonly preventCycles?: boolean;
|
|
4053
|
+
} | {
|
|
4054
|
+
readonly depth: false;
|
|
4055
|
+
readonly preventCycles?: true;
|
|
4056
|
+
};
|
|
4057
|
+
type ForeignKeyRecurrenceSchema = V$1.Schema<ForeignKeyRecurse, NormalizedRecurrence>;
|
|
4058
|
+
type GraphRecurrenceSchema = V$1.Schema<GraphRecurse, NormalizedRecurrence>;
|
|
4059
|
+
declare const unavailableRecurrence: () => OptionalSchema<VibSchema<never, never>, undefined, undefined, undefined>;
|
|
4060
|
+
type UnavailableRecurrenceSchema = ReturnType<typeof unavailableRecurrence>;
|
|
4061
|
+
declare const unavailableRecursiveClause: (clause: string) => OptionalSchema<VibSchema<never, never>, undefined, undefined, undefined>;
|
|
4062
|
+
type UnavailableRecursiveClauseSchema = ReturnType<typeof unavailableRecursiveClause>;
|
|
4063
|
+
/**
|
|
4064
|
+
* The static eligibility reader: the recurrence language a slot admits, or
|
|
4065
|
+
* `never` when it cannot recurse, so a recursive form whose `recurse` is
|
|
4066
|
+
* required is uninhabitable there.
|
|
4067
|
+
*/
|
|
4068
|
+
type RecurrenceFor<Source extends AnyModel, Key$1, S$1 extends RelationState> = StaticRecursiveMembership<Source, Key$1, S$1> extends StaticForeignKeyMembership ? ForeignKeyRecurrenceSchema : StaticRecursiveMembership<Source, Key$1, S$1> extends StaticJunctionMembership ? GraphRecurrenceSchema : never;
|
|
4069
|
+
//#endregion
|
|
4037
4070
|
//#region src/validation/relations/filter.d.ts
|
|
4038
4071
|
/**
|
|
4039
4072
|
* To-one filter. Two spellings are accepted (Prisma parity):
|
|
@@ -4055,6 +4088,13 @@ type ToManyCreateSchema<Source extends AnyModel, Key$1, S$1 extends RelationStat
|
|
|
4055
4088
|
* input type marks `is`/`isNot` as `never` (Prisma spells this `XOR<…>`), so a
|
|
4056
4089
|
* collision is a type error rather than a silent reinterpretation.
|
|
4057
4090
|
*
|
|
4091
|
+
* `recurse` collides the same way, one step earlier: an object that spells
|
|
4092
|
+
* `recurse` (not `undefined`) IS the recursive filter, on every relation slot,
|
|
4093
|
+
* and never reaches the shorthand. A target field literally named `recurse` is
|
|
4094
|
+
* reached through `{ parent: { is: { recurse: … } } }`; one named `self` is
|
|
4095
|
+
* unaffected, because only `recurse` selects the form. Both spelled
|
|
4096
|
+
* `undefined` read as absent, like every undefined key of an object.
|
|
4097
|
+
*
|
|
4058
4098
|
* For optional relations, `is` can also be null, and the bare `null`
|
|
4059
4099
|
* shorthand normalizes to `{ is: null }` (unchanged by the object shorthand).
|
|
4060
4100
|
*
|
|
@@ -4075,8 +4115,42 @@ type MayBeEmpty<Source extends AnyModel, Key$1, S$1 extends RelationState> = Slo
|
|
|
4075
4115
|
type ToOneFilterObjectSchema<Source extends AnyModel, Key$1, S$1 extends RelationState> = V$1.Object<{
|
|
4076
4116
|
is: () => V$1.MaybeNullable<GetTargetSchemas<S$1>["core"]["where"], MayBeEmpty<Source, Key$1, S$1>>;
|
|
4077
4117
|
isNot: () => V$1.MaybeNullable<GetTargetSchemas<S$1>["core"]["where"], MayBeEmpty<Source, Key$1, S$1>>;
|
|
4078
|
-
}>;
|
|
4118
|
+
} & NoClosure>;
|
|
4079
4119
|
type TargetWhereSchema<S$1 extends RelationState> = GetTargetSchemas<S$1>["core"]["where"];
|
|
4120
|
+
/** `some`/`every`/`none`, each the target's full `where`. */
|
|
4121
|
+
type Quantifiers<S$1 extends RelationState> = {
|
|
4122
|
+
some: () => TargetWhereSchema<S$1>;
|
|
4123
|
+
every: () => TargetWhereSchema<S$1>;
|
|
4124
|
+
none: () => TargetWhereSchema<S$1>;
|
|
4125
|
+
};
|
|
4126
|
+
/**
|
|
4127
|
+
* The recursive filter: a quantifier over the slot's transitive closure from
|
|
4128
|
+
* the filtered row, `self` adding that row itself. `recurse` is the very
|
|
4129
|
+
* language `select`/`include` admit on the slot, so eligibility, bounds and
|
|
4130
|
+
* normalization have one owner. Where the slot cannot recurse the required
|
|
4131
|
+
* `recurse` is `never` and the form is uninhabitable; eligibility stays inside
|
|
4132
|
+
* the required key, as on the select side, so no ordinary filter compares the
|
|
4133
|
+
* cyclic model graph eagerly.
|
|
4134
|
+
*/
|
|
4135
|
+
type RecursiveFilterSchema<Source extends AnyModel, Key$1, S$1 extends RelationState> = V$1.Object<{
|
|
4136
|
+
recurse: RecurrenceFor<Source, Key$1, S$1>;
|
|
4137
|
+
self: V$1.Boolean;
|
|
4138
|
+
is: UnavailableRecursiveClauseSchema;
|
|
4139
|
+
isNot: UnavailableRecursiveClauseSchema;
|
|
4140
|
+
} & Quantifiers<S$1>, {
|
|
4141
|
+
atLeast: ["recurse"];
|
|
4142
|
+
}>;
|
|
4143
|
+
/**
|
|
4144
|
+
* The ordinary forms' statement of the dispatcher's invariant: they never see
|
|
4145
|
+
* `recurse`, nor a `self` spelled `undefined`, so neither is theirs to accept.
|
|
4146
|
+
* Types only, like the shorthand's `is?: never`; the runtime objects carry no
|
|
4147
|
+
* entry, because `withRecursiveNode` routes a spelled `recurse` away and drops
|
|
4148
|
+
* both keys spelled `undefined`.
|
|
4149
|
+
*/
|
|
4150
|
+
type NoClosure = {
|
|
4151
|
+
recurse: UnavailableRecurrenceSchema;
|
|
4152
|
+
self: UnavailableRecurrenceSchema;
|
|
4153
|
+
};
|
|
4080
4154
|
/**
|
|
4081
4155
|
* The shorthand member: a target-model `where` whose parsed value is wrapped
|
|
4082
4156
|
* into the explicit `{ is }` shape. Its input type excludes `is`/`isNot` so the
|
|
@@ -4086,19 +4160,16 @@ type TargetWhereSchema<S$1 extends RelationState> = GetTargetSchemas<S$1>["core"
|
|
|
4086
4160
|
type ToOneShorthandFilterSchema<Source extends AnyModel, Key$1, S$1 extends RelationState> = V$1.Transform<V$1.Input<TargetWhereSchema<S$1>> & {
|
|
4087
4161
|
is?: never;
|
|
4088
4162
|
isNot?: never;
|
|
4163
|
+
recurse?: never;
|
|
4089
4164
|
}, V$1.Output<ToOneFilterObjectSchema<Source, Key$1, S$1>>> & {
|
|
4090
4165
|
wrapped: TargetWhereSchema<S$1>;
|
|
4091
4166
|
};
|
|
4092
|
-
type ToOneFilterSchema<Source extends AnyModel, Key$1, S$1 extends RelationState> = MayBeEmpty<Source, Key$1, S$1> extends true ? V$1.Union<readonly [NullToIsNull, ToOneFilterObjectSchema<Source, Key$1, S$1>, ToOneShorthandFilterSchema<Source, Key$1, S$1>]> : V$1.Union<readonly [ToOneFilterObjectSchema<Source, Key$1, S$1>, ToOneShorthandFilterSchema<Source, Key$1, S$1>]>;
|
|
4167
|
+
type ToOneFilterSchema<Source extends AnyModel, Key$1, S$1 extends RelationState> = MayBeEmpty<Source, Key$1, S$1> extends true ? V$1.Union<readonly [NullToIsNull, ToOneFilterObjectSchema<Source, Key$1, S$1>, ToOneShorthandFilterSchema<Source, Key$1, S$1>, RecursiveFilterSchema<Source, Key$1, S$1>]> : V$1.Union<readonly [ToOneFilterObjectSchema<Source, Key$1, S$1>, ToOneShorthandFilterSchema<Source, Key$1, S$1>, RecursiveFilterSchema<Source, Key$1, S$1>]>;
|
|
4093
4168
|
/**
|
|
4094
|
-
* To-many filter: { some?, every?, none? }
|
|
4169
|
+
* To-many filter: { some?, every?, none? }, or the recursive filter.
|
|
4095
4170
|
* Uses thunks for lazy evaluation - getTargetWhereSchema already returns thunk
|
|
4096
4171
|
*/
|
|
4097
|
-
type ToManyFilterSchema<S$1 extends RelationState> = V$1.Object<
|
|
4098
|
-
some: () => GetTargetSchemas<S$1>["core"]["where"];
|
|
4099
|
-
every: () => GetTargetSchemas<S$1>["core"]["where"];
|
|
4100
|
-
none: () => GetTargetSchemas<S$1>["core"]["where"];
|
|
4101
|
-
}>;
|
|
4172
|
+
type ToManyFilterSchema<Source extends AnyModel, Key$1, S$1 extends RelationState> = V$1.Union<readonly [V$1.Object<Quantifiers<S$1> & NoClosure>, RecursiveFilterSchema<Source, Key$1, S$1>]>;
|
|
4102
4173
|
//#endregion
|
|
4103
4174
|
//#region src/drivers/shared/sqlite-utils.d.ts
|
|
4104
4175
|
/**
|
|
@@ -4453,30 +4524,6 @@ type Schema$3 = Record<string, Model$1<any>>;
|
|
|
4453
4524
|
*/
|
|
4454
4525
|
type DateTimePhysicalForm = "text" | "epochMillis" | "julianDay";
|
|
4455
4526
|
//#endregion
|
|
4456
|
-
//#region src/validation/relations/recurrence.d.ts
|
|
4457
|
-
interface NormalizedRecurrence {
|
|
4458
|
-
readonly depth: number | false;
|
|
4459
|
-
readonly cycles: "reject" | "prevent" | "allow";
|
|
4460
|
-
}
|
|
4461
|
-
/**
|
|
4462
|
-
* A foreign-key traversal has no cycle policy to choose: it rejects every
|
|
4463
|
-
* cycle it reaches. `preventCycles` is therefore refused by the bag's own type,
|
|
4464
|
-
* so no downstream guard has to know which topology a nested bag belongs to.
|
|
4465
|
-
*/
|
|
4466
|
-
type ForeignKeyRecurse = true | {
|
|
4467
|
-
readonly depth?: number | false;
|
|
4468
|
-
readonly preventCycles?: undefined;
|
|
4469
|
-
};
|
|
4470
|
-
type GraphRecurse = true | {
|
|
4471
|
-
readonly depth?: number;
|
|
4472
|
-
readonly preventCycles?: boolean;
|
|
4473
|
-
} | {
|
|
4474
|
-
readonly depth: false;
|
|
4475
|
-
readonly preventCycles?: true;
|
|
4476
|
-
};
|
|
4477
|
-
type ForeignKeyRecurrenceSchema = V$1.Schema<ForeignKeyRecurse, NormalizedRecurrence>;
|
|
4478
|
-
type GraphRecurrenceSchema = V$1.Schema<GraphRecurse, NormalizedRecurrence>;
|
|
4479
|
-
//#endregion
|
|
4480
4527
|
//#region src/schema/validation/types.d.ts
|
|
4481
4528
|
type Severity = "error" | "warning";
|
|
4482
4529
|
interface SchemaValidationIssue {
|
|
@@ -5582,7 +5629,7 @@ declare const s: {
|
|
|
5582
5629
|
}>;
|
|
5583
5630
|
json: <Db extends NativeDialect = never, const Given extends ExactNativeTypeMap<Given> = never>(nativeType?: NativeTypeArgument<Db, Given>) => JsonScalar<InitialScalarState<"json", JsonSchema<JsonInput, JsonValue>>>;
|
|
5584
5631
|
blob: <Db extends NativeDialect = never, const Given extends ExactNativeTypeMap<Given> = never>(nativeType?: NativeTypeArgument<Db, Given>) => BlobScalar<InitialScalarState<"blob", BlobSchema<Uint8Array<ArrayBufferLike>, Uint8Array<ArrayBufferLike>>>>;
|
|
5585
|
-
enum: <const T$1 extends string[], Db extends NativeDialect = never, const Given extends ExactNativeTypeMap<Given> = never>(values: T$1, nativeType?: NativeTypeArgument<Db, Given>) => EnumScalar<InitialScalarState<"enum", EnumSchema<T$1, T$1[number], T$1[number]>>>;
|
|
5632
|
+
enum: <const T$1 extends string[] | readonly string[], Db extends NativeDialect = never, const Given extends ExactNativeTypeMap<Given> = never>(values: T$1, nativeType?: NativeTypeArgument<Db, Given>) => EnumScalar<InitialScalarState<"enum", EnumSchema<T$1, T$1[number], T$1[number]>>>;
|
|
5586
5633
|
point: typeof point;
|
|
5587
5634
|
vector: <Db extends NativeDialect = never, const Given extends ExactNativeTypeMap<Given> = never>(nativeType?: NativeTypeArgument<Db, Given>) => VectorScalar<InitialScalarState<"vector", VectorSchema<number[], number[]> & {
|
|
5588
5635
|
dimensions?: number;
|
|
@@ -6973,12 +7020,8 @@ type PaginationSkipSchema = V$1.Schema<number, number>;
|
|
|
6973
7020
|
type BulkWriteLimitSchema = V$1.Schema<number, number>;
|
|
6974
7021
|
//#endregion
|
|
6975
7022
|
//#region src/validation/relations/select-include.d.ts
|
|
6976
|
-
declare const unavailableRecurrence: () => OptionalSchema<VibSchema<never, never>, undefined, undefined, undefined>;
|
|
6977
|
-
declare const unavailableRecursiveClause: (clause: string) => OptionalSchema<VibSchema<never, never>, undefined, undefined, undefined>;
|
|
6978
7023
|
/** The asking key cannot have a second producer inside its own repeated node. */
|
|
6979
7024
|
declare const askingKeyRefusal: (key: string) => OptionalSchema<VibSchema<never, never>, undefined, undefined, undefined>;
|
|
6980
|
-
type UnavailableRecurrenceSchema = ReturnType<typeof unavailableRecurrence>;
|
|
6981
|
-
type RecurrenceFor<Source extends AnyModel, Key$1, S$1 extends RelationState> = StaticRecursiveMembership<Source, Key$1, S$1> extends StaticForeignKeyMembership ? ForeignKeyRecurrenceSchema : StaticRecursiveMembership<Source, Key$1, S$1> extends StaticJunctionMembership ? GraphRecurrenceSchema : never;
|
|
6982
7025
|
/** A target projection whose asking key is refused, keeping its options. */
|
|
6983
7026
|
type ProjectionWithoutAsking<Schema$4 extends V$1.Object<any, any>, Key$1> = V$1.Object<Omit<Schema$4["entries"], Extract<Key$1, keyof Schema$4["entries"]>> & Record<Extract<Key$1, string>, ReturnType<typeof askingKeyRefusal>>>;
|
|
6984
7027
|
type RecursiveProjectionSchemas<S$1 extends RelationState, Key$1> = {
|
|
@@ -6987,8 +7030,8 @@ type RecursiveProjectionSchemas<S$1 extends RelationState, Key$1> = {
|
|
|
6987
7030
|
};
|
|
6988
7031
|
type ToOneRecursiveNodeSchema<Source extends AnyModel, Key$1, S$1 extends RelationState> = IncludeToField<V$1.Object<{
|
|
6989
7032
|
recurse: RecurrenceFor<Source, Key$1, S$1>;
|
|
6990
|
-
where:
|
|
6991
|
-
orderBy:
|
|
7033
|
+
where: UnavailableRecursiveClauseSchema;
|
|
7034
|
+
orderBy: UnavailableRecursiveClauseSchema;
|
|
6992
7035
|
select: () => RecursiveProjectionSchemas<S$1, Key$1>["select"];
|
|
6993
7036
|
include: () => RecursiveProjectionSchemas<S$1, Key$1>["include"];
|
|
6994
7037
|
omit: () => GetTargetSchemas<S$1>["core"]["omit"];
|
|
@@ -7077,10 +7120,10 @@ type ToManyNestedNodeSchema<Core$1 extends ToManyNestedTargetCore, Distinct> = I
|
|
|
7077
7120
|
type ToManyRecursiveNodeSchema<Source extends AnyModel, Key$1, S$1 extends RelationState> = IncludeToField<V$1.Object<{
|
|
7078
7121
|
where: () => GetTargetSchemas<S$1>["core"]["where"];
|
|
7079
7122
|
orderBy: () => V$1.Union<readonly [GetTargetSchemas<S$1>["core"]["orderBy"], V$1.Array<GetTargetSchemas<S$1>["core"]["orderBy"]>]>;
|
|
7080
|
-
take:
|
|
7081
|
-
skip:
|
|
7082
|
-
cursor:
|
|
7083
|
-
distinct:
|
|
7123
|
+
take: UnavailableRecursiveClauseSchema;
|
|
7124
|
+
skip: UnavailableRecursiveClauseSchema;
|
|
7125
|
+
cursor: UnavailableRecursiveClauseSchema;
|
|
7126
|
+
distinct: UnavailableRecursiveClauseSchema;
|
|
7084
7127
|
select: () => RecursiveProjectionSchemas<S$1, Key$1>["select"];
|
|
7085
7128
|
include: () => RecursiveProjectionSchemas<S$1, Key$1>["include"];
|
|
7086
7129
|
omit: () => GetTargetSchemas<S$1>["core"]["omit"];
|
|
@@ -7233,7 +7276,7 @@ type ToOneSchemas<Source extends AnyModel, Key$1, S$1 extends RelationState> = {
|
|
|
7233
7276
|
countFilter: CountFilterSchema<S$1>;
|
|
7234
7277
|
};
|
|
7235
7278
|
type ToManySchemas<Source extends AnyModel, Key$1, S$1 extends RelationState> = {
|
|
7236
|
-
filter: ToManyFilterSchema<S$1>;
|
|
7279
|
+
filter: ToManyFilterSchema<Source, Key$1, S$1>;
|
|
7237
7280
|
create: ToManyCreateSchema<Source, Key$1, S$1>;
|
|
7238
7281
|
update: ToManyUpdateSchema<Source, Key$1, S$1>;
|
|
7239
7282
|
select: ToManySelectSchema<Source, Key$1, S$1>;
|
|
@@ -8203,7 +8246,7 @@ type DecimalCreateSchema<F$1 extends ScalarState<"decimal">> = F$1["hasDefault"]
|
|
|
8203
8246
|
* fragment, or a callback returning one of the latter two.
|
|
8204
8247
|
*/
|
|
8205
8248
|
type EnumOperand<S$1 extends V$1.Schema, C$1 extends V$1.Operand<any>> = V$1.ComparisonOperand<"enum", S$1, C$1>;
|
|
8206
|
-
type EnumFilterBase<S$1 extends V$1.Schema, Values extends string[], C$1 extends V$1.Operand<any>> = {
|
|
8249
|
+
type EnumFilterBase<S$1 extends V$1.Schema, Values extends readonly string[], C$1 extends V$1.Operand<any>> = {
|
|
8207
8250
|
equals: EnumOperand<S$1, C$1>;
|
|
8208
8251
|
in: V$1.Enum<Values, {
|
|
8209
8252
|
array: true;
|
|
@@ -8216,20 +8259,20 @@ type EnumFilterBase<S$1 extends V$1.Schema, Values extends string[], C$1 extends
|
|
|
8216
8259
|
gt: V$1.Schema<never, never>;
|
|
8217
8260
|
gte: V$1.Schema<never, never>;
|
|
8218
8261
|
};
|
|
8219
|
-
type EnumFilterSchema<S$1 extends V$1.Schema, Values extends string[], C$1 extends V$1.Operand<any>> = NegatableFilterSchema<EnumOperand<S$1, C$1>, EnumFilterBase<S$1, Values, C$1>>;
|
|
8262
|
+
type EnumFilterSchema<S$1 extends V$1.Schema, Values extends readonly string[], C$1 extends V$1.Operand<any>> = NegatableFilterSchema<EnumOperand<S$1, C$1>, EnumFilterBase<S$1, Values, C$1>>;
|
|
8220
8263
|
/**
|
|
8221
8264
|
* The list arms are the shared family, built PER FIELD: an enum's member and
|
|
8222
8265
|
* list schemas are a function of that field's declared values, so unlike every
|
|
8223
8266
|
* other kind there is no module-level pair to close over — and, for the same
|
|
8224
8267
|
* reason, no interning (a key would have to carry the whole value list).
|
|
8225
8268
|
*/
|
|
8226
|
-
type EnumListFilterSchema<S$1 extends V$1.Schema, Values extends string[]> = ListFilterSchema<S$1, V$1.Enum<Values>, V$1.Enum<Values, {
|
|
8269
|
+
type EnumListFilterSchema<S$1 extends V$1.Schema, Values extends readonly string[]> = ListFilterSchema<S$1, V$1.Enum<Values>, V$1.Enum<Values, {
|
|
8227
8270
|
array: true;
|
|
8228
8271
|
}>>;
|
|
8229
|
-
type EnumListUpdateSchema<S$1 extends V$1.Schema, Values extends string[]> = ListUpdateSchema<S$1, V$1.Enum<Values>, V$1.Enum<Values, {
|
|
8272
|
+
type EnumListUpdateSchema<S$1 extends V$1.Schema, Values extends readonly string[]> = ListUpdateSchema<S$1, V$1.Enum<Values>, V$1.Enum<Values, {
|
|
8230
8273
|
array: true;
|
|
8231
8274
|
}>>;
|
|
8232
|
-
interface EnumSchemas<Values extends string[], F$1 extends ScalarState<"enum">, C$1 extends V$1.Operand<any> = V$1.Operand<any>> {
|
|
8275
|
+
interface EnumSchemas<Values extends readonly string[], F$1 extends ScalarState<"enum">, C$1 extends V$1.Operand<any> = V$1.Operand<any>> {
|
|
8233
8276
|
base: F$1["base"];
|
|
8234
8277
|
create: V$1.Enum<Values, F$1>;
|
|
8235
8278
|
update: F$1["array"] extends true ? EnumListUpdateSchema<F$1["base"], Values> : SetUpdateSchema<F$1["base"]>;
|
|
@@ -10830,7 +10873,14 @@ type SeenWhereValue<Given, M$1, Seen> = true extends (Seen extends unknown ? Sam
|
|
|
10830
10873
|
type WhereLogicalKey = "AND" | "OR" | "NOT";
|
|
10831
10874
|
type WhereLogicalKeys<M$1 extends Model$1<any>> = Exclude<WhereLogicalKey, keyof M$1["~"]["state"]["shape"]>;
|
|
10832
10875
|
type WhereModelKeys<M$1 extends Model$1<any>> = keyof M$1["~"]["state"]["shape"] | WhereLogicalKey;
|
|
10833
|
-
|
|
10876
|
+
/** The unknown keys inside the quantifiers `Q` a relation filter spelled. */
|
|
10877
|
+
type QuantifiedWhereUnknownKeys<Given, R$1 extends AnyRelation, Seen, Q$1 extends PropertyKey> = { [K in Extract<SpelledClauseKeys<Given>, Q$1>]: WhereUnknownKeys<ValueAt<Given, K>, GetTargetModel<R$1>, Seen> }[Extract<SpelledClauseKeys<Given>, Q$1>];
|
|
10878
|
+
/**
|
|
10879
|
+
* A spelled `recurse` selects the recursive filter on either cardinality (the
|
|
10880
|
+
* runtime dispatcher's rule), so its quantifiers are walked and its option bag
|
|
10881
|
+
* is sealed exactly as on the select side.
|
|
10882
|
+
*/
|
|
10883
|
+
type RelationWhereUnknownKeys<Given, R$1 extends AnyRelation, Seen> = TargetKind<R$1> extends "model" ? "recurse" extends SpelledClauseKeys<Given> ? QuantifiedWhereUnknownKeys<Given, R$1, Seen, "some" | "every" | "none"> | MisspelledRecurrenceKeys<ValueAt<Given, "recurse">> : Cardinality<R$1> extends "one" ? [Extract<SpelledClauseKeys<Given>, "is" | "isNot">] extends [never] ? WhereUnknownKeys<Given, GetTargetModel<R$1>, Seen> : QuantifiedWhereUnknownKeys<Given, R$1, Seen, "is" | "isNot"> : QuantifiedWhereUnknownKeys<Given, R$1, Seen, "some" | "every" | "none"> : never;
|
|
10834
10884
|
type WhereUnknownKeys<Given, M$1 extends Model$1<any>, Seen = never, Allowed extends PropertyKey = WhereModelKeys<M$1>> = Given extends readonly unknown[] ? WhereUnknownKeys<Given[number], M$1, Seen, Allowed> : Given extends object ? string extends keyof Given ? never : Exclude<keyof Given, Allowed> | (SeenWhereValue<Given, M$1, Seen> extends true ? never : { [K in Extract<keyof Given, WhereLogicalKeys<M$1> | keyof M$1["~"]["state"]["relations"]>]: K extends WhereLogicalKeys<M$1> ? WhereUnknownKeys<NonNullable<Given[K]>, M$1, Seen | readonly [Given, M$1]> : K extends keyof M$1["~"]["state"]["relations"] ? RelationWhereUnknownKeys<NonNullable<Given[K]>, M$1["~"]["state"]["relations"][K], Seen | readonly [Given, M$1]> : never }[Extract<keyof Given, WhereLogicalKeys<M$1> | keyof M$1["~"]["state"]["relations"]>]) : never;
|
|
10835
10885
|
type NestedWhereClauseGuard<Arg, Payload, M$1 extends Model$1<any>> = "where" extends keyof Arg ? "where" extends keyof Payload ? [Extract<SpelledClauseKeys<NonNullable<Arg["where"]>>, WhereLogicalKeys<M$1> | keyof M$1["~"]["state"]["relations"]>] extends [never] ? unknown : SameWhereValue<NonNullable<Arg["where"]>, NonNullable<Payload["where"]>> extends true ? unknown : WhereUnknownKeys<NonNullable<Arg["where"]>, M$1, never, ClauseKeys<NonNullable<Payload["where"]>>> extends infer Extra ? [Extra] extends [never] ? unknown : {
|
|
10836
10886
|
where?: UnknownClauseKey<Extra>;
|
package/dist/index.d.mts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { $r as ConnectionError, $t as EmptyClientExtensionState, Ai as VibORMErrorCode, At as validateOperationPayload, B as ModelShape, Bi as DecimalDescriptor, Bn as IndexOptions, Ci as isValueTooLongError, Ct as ReferencesStage, Di as CacheOperationNotCacheableError, Dt as getOperationPayloadSchema, Ei as CacheInvalidTTLError, Er as BlobSchema, Et as getSchemas, F as FlatSchema, Fi as DiagnosticDisclosure, Fn as ModelFieldRefs, Fr as JsonNull, Gn as ModelState, Gr as RelationCardinality, Gt as NoControls, H as VariantToOneRelation, Hn as InitialModelState, Hr as Getter, I as Linked, Ii as GeoArea, In as createModelFieldRefs, Ir as JsonNullKind, It as VibORMClient, Jn as AutoGenerate, Jr as ValidationErrorSource, Jt as defineExtension, Kn as UpdateState, Kr as RelationSlot, Kt as PlacedControl, L as LinkedClientConfig, Li as GeoBounds, Ln as isFieldRef, Lr as JsonNullSentinel, Lt as VibORMConfig, Mi as isVibORMError, Mn as StringSchema, Mr as AnyJsonNullSentinel, Mt as ExtendedClient, Ni as toPrismaErrorCode, Nn as AnyFieldRef, Nr as AnyNull, Nt as ExtendedOperationResult, Oi as PrismaErrorCode, Or as BigIntSchema, Ot as renderOperationResultType, P as ClientSchema, Pi as wrapError, Pn as FieldRef, Pr as DbNull, Pt as ExtensionState, Qn as ScalarState, Qr as ClientInitializationError, Qt as ClientExtensionState, R as Links, Ri as GeoPoint, Rn as AnyModel, Rr as isJsonNullSentinel, Rt as createClient, Si as isUniqueConstraintError, Sr as EnumSchema, St as ModelToOneRelation, Ti as CacheInvalidKeyError, Tt as s, U as Scalar, Un as Model, V as VariantToManyRelation, Vi as Decimal, Vr as AnyRelation, W as BigIntScalar, Wn as ModelInternal, Wr as ReferentialAction, Xn as GeneratorDefaultBrand, Xr as InvalidTransactionInputError, Xt as StatementHandler, Yr as isValidationError, Yt as StatementContext, Z as VibSchema, Zn as InitialScalarState, Zr as TransactionError, Zt as AccumulatedExtensionState, _i as UniqueConstraintError, _n as isPendingOperation, _t as TimeScalar, ai as QueryEngineError, an as validateSchema, ar as PointSchema, bi as isForeignKeyError, br as IsoTimestampSchema, bt as BooleanScalar, ci as isClientInitializationError, cn as isSchemaValidationError, ct as NumericScalar, di as isUnsupportedOperationError, dn as ValidationResult, dt as PointScalar, ei as FeatureNotSupportedError, en as ExtensionCacheState, er as UpdateState$1, fi as MigrationError, fr as InputJsonValue, ft as NumberScalar, g as ObserveHandler, gi as NotNullConstraintError, gn as UnwrapPendingOperations, gt as DecimalScalar, h as ObservationUnit, hi as ForeignKeyError, hn as UnwrapPendingOperation, ht as EnumScalar, ii as PendingOperationError, in as RawOperation, ji as isRetryableError, ki as VibORMError, kt as renderSchemaType, li as isNotFoundError, ln as SchemaValidationIssue, lr as IntegerSchema, lt as VectorScalar, m as ObservationCompletion, mi as CheckConstraintError, mn as PendingOperation, mr as JsonValue, mt as IntScalar, ni as NestedWriteError, nn as ExtensionResultConsumerState, oi as QueryError, on as validateSchemaOrThrow, or as ObjectSchema, pi as isMigrationError, pr as JsonSchema, pt as JsonScalar, qn as DecimalSchema, qr as ValidationError, qt as ClientExtension, ri as NotFoundError, rn as MergeExtensionState, rr as VectorSchema, si as UnsupportedOperationError, sn as SchemaValidationError, ti as NestedWriteAssertionError, tn as ExtensionContributionState, ui as isPendingOperationError, un as Severity, ur as NumberSchema, ut as StringScalar, vi as ValueTooLongError, vr as IsoDateSchema, vt as DateTimeScalar, wi as CacheConfigurationError, wr as BooleanSchema, wt as ModelToManyRelation, xi as isNotNullConstraintError, xt as BlobScalar, yi as isCheckConstraintError, yr as IsoTimeSchema, yt as DateScalar, z as RelationLinks, zi as GeoPolygon, zn as IndexDefinition } from "./index-
|
|
1
|
+
import { $r as ConnectionError, $t as EmptyClientExtensionState, Ai as VibORMErrorCode, At as validateOperationPayload, B as ModelShape, Bi as DecimalDescriptor, Bn as IndexOptions, Ci as isValueTooLongError, Ct as ReferencesStage, Di as CacheOperationNotCacheableError, Dt as getOperationPayloadSchema, Ei as CacheInvalidTTLError, Er as BlobSchema, Et as getSchemas, F as FlatSchema, Fi as DiagnosticDisclosure, Fn as ModelFieldRefs, Fr as JsonNull, Gn as ModelState, Gr as RelationCardinality, Gt as NoControls, H as VariantToOneRelation, Hn as InitialModelState, Hr as Getter, I as Linked, Ii as GeoArea, In as createModelFieldRefs, Ir as JsonNullKind, It as VibORMClient, Jn as AutoGenerate, Jr as ValidationErrorSource, Jt as defineExtension, Kn as UpdateState, Kr as RelationSlot, Kt as PlacedControl, L as LinkedClientConfig, Li as GeoBounds, Ln as isFieldRef, Lr as JsonNullSentinel, Lt as VibORMConfig, Mi as isVibORMError, Mn as StringSchema, Mr as AnyJsonNullSentinel, Mt as ExtendedClient, Ni as toPrismaErrorCode, Nn as AnyFieldRef, Nr as AnyNull, Nt as ExtendedOperationResult, Oi as PrismaErrorCode, Or as BigIntSchema, Ot as renderOperationResultType, P as ClientSchema, Pi as wrapError, Pn as FieldRef, Pr as DbNull, Pt as ExtensionState, Qn as ScalarState, Qr as ClientInitializationError, Qt as ClientExtensionState, R as Links, Ri as GeoPoint, Rn as AnyModel, Rr as isJsonNullSentinel, Rt as createClient, Si as isUniqueConstraintError, Sr as EnumSchema, St as ModelToOneRelation, Ti as CacheInvalidKeyError, Tt as s, U as Scalar, Un as Model, V as VariantToManyRelation, Vi as Decimal, Vr as AnyRelation, W as BigIntScalar, Wn as ModelInternal, Wr as ReferentialAction, Xn as GeneratorDefaultBrand, Xr as InvalidTransactionInputError, Xt as StatementHandler, Yr as isValidationError, Yt as StatementContext, Z as VibSchema, Zn as InitialScalarState, Zr as TransactionError, Zt as AccumulatedExtensionState, _i as UniqueConstraintError, _n as isPendingOperation, _t as TimeScalar, ai as QueryEngineError, an as validateSchema, ar as PointSchema, bi as isForeignKeyError, br as IsoTimestampSchema, bt as BooleanScalar, ci as isClientInitializationError, cn as isSchemaValidationError, ct as NumericScalar, di as isUnsupportedOperationError, dn as ValidationResult, dt as PointScalar, ei as FeatureNotSupportedError, en as ExtensionCacheState, er as UpdateState$1, fi as MigrationError, fr as InputJsonValue, ft as NumberScalar, g as ObserveHandler, gi as NotNullConstraintError, gn as UnwrapPendingOperations, gt as DecimalScalar, h as ObservationUnit, hi as ForeignKeyError, hn as UnwrapPendingOperation, ht as EnumScalar, ii as PendingOperationError, in as RawOperation, ji as isRetryableError, ki as VibORMError, kt as renderSchemaType, li as isNotFoundError, ln as SchemaValidationIssue, lr as IntegerSchema, lt as VectorScalar, m as ObservationCompletion, mi as CheckConstraintError, mn as PendingOperation, mr as JsonValue, mt as IntScalar, ni as NestedWriteError, nn as ExtensionResultConsumerState, oi as QueryError, on as validateSchemaOrThrow, or as ObjectSchema, pi as isMigrationError, pr as JsonSchema, pt as JsonScalar, qn as DecimalSchema, qr as ValidationError, qt as ClientExtension, ri as NotFoundError, rn as MergeExtensionState, rr as VectorSchema, si as UnsupportedOperationError, sn as SchemaValidationError, ti as NestedWriteAssertionError, tn as ExtensionContributionState, ui as isPendingOperationError, un as Severity, ur as NumberSchema, ut as StringScalar, vi as ValueTooLongError, vr as IsoDateSchema, vt as DateTimeScalar, wi as CacheConfigurationError, wr as BooleanSchema, wt as ModelToManyRelation, xi as isNotNullConstraintError, xt as BlobScalar, yi as isCheckConstraintError, yr as IsoTimeSchema, yt as DateScalar, z as RelationLinks, zi as GeoPolygon, zn as IndexDefinition } from "./index-BbcE-gyl.mjs";
|
|
2
2
|
import { a as isSql, c as sqlTag, i as empty, n as Sql, o as join, r as Value, s as raw, t as RawValue } from "./sql--yhoVvRM.mjs";
|
|
3
3
|
export { type AccumulatedExtensionState, type AnyFieldRef, type AnyJsonNullSentinel, type AnyModel, AnyNull, type AnyRelation, type AutoGenerate, type BigIntScalar, type BigIntSchema, type BlobScalar, type BlobSchema, type BooleanScalar, type BooleanSchema, CacheConfigurationError, CacheInvalidKeyError, CacheInvalidTTLError, CacheOperationNotCacheableError, CheckConstraintError, type ClientExtension, type ClientExtensionState, ClientInitializationError, type ClientSchema, ConnectionError, type DateScalar, type DateTimeScalar, DbNull, Decimal, type DecimalDescriptor, type DecimalScalar, type DecimalSchema, type DiagnosticDisclosure, type EmptyClientExtensionState, type EnumScalar, type EnumSchema, type ExtendedClient, type ExtendedOperationResult, type ExtensionCacheState, type ExtensionContributionState, type ExtensionResultConsumerState, type ExtensionState, FeatureNotSupportedError, type FieldRef, type FlatSchema, ForeignKeyError, type GeneratorDefaultBrand, type GeoArea, type GeoBounds, type GeoPoint, type GeoPolygon, type Getter, type IndexDefinition, type IndexOptions, type InitialModelState, type InitialScalarState, type InputJsonValue, type IntScalar, type IntegerSchema, InvalidTransactionInputError, type IsoDateSchema, type IsoTimeSchema, type IsoTimestampSchema, JsonNull, type JsonNullKind, JsonNullSentinel, type JsonScalar, type JsonValue, type JsonSchema as JsonValueSchema, type Linked, type LinkedClientConfig, type Links, type MergeExtensionState, MigrationError, type Model, type ModelFieldRefs, type ModelInternal, type ModelShape, type ModelState, type ModelToManyRelation, type ModelToOneRelation, type UpdateState as ModelUpdateState, NestedWriteAssertionError, NestedWriteError, type NoControls, NotFoundError, NotNullConstraintError, type NumberScalar, type NumberSchema, type NumericScalar, type ObjectSchema, type ObservationCompletion, type ObservationUnit, type ObserveHandler, PendingOperation, PendingOperationError, type PlacedControl, type PointScalar, type PointSchema, type PrismaErrorCode, QueryEngineError, QueryError, type RawOperation, type RawValue, type ReferencesStage, type ReferentialAction, type RelationCardinality, type RelationLinks, type RelationSlot, type Scalar, type ScalarState, type UpdateState$1 as ScalarUpdateState, SchemaValidationError, type SchemaValidationIssue, type Severity, Sql, type StatementContext, type StatementHandler, type StringScalar, type StringSchema, type TimeScalar, TransactionError, UniqueConstraintError, UnsupportedOperationError, type UnwrapPendingOperation, type UnwrapPendingOperations, ValidationError, type ValidationErrorSource, type ValidationResult, type Value, ValueTooLongError, type VariantToManyRelation, type VariantToOneRelation, type VectorScalar, type VectorSchema, type VibORMClient, type VibORMConfig, VibORMError, VibORMErrorCode, type VibSchema, createClient, createModelFieldRefs, defineExtension, empty, getOperationPayloadSchema, getSchemas, isCheckConstraintError, isClientInitializationError, isFieldRef, isForeignKeyError, isJsonNullSentinel, isMigrationError, isNotFoundError, isNotNullConstraintError, isPendingOperation, isPendingOperationError, isRetryableError, isSchemaValidationError, isSql, isUniqueConstraintError, isUnsupportedOperationError, isValidationError, isValueTooLongError, isVibORMError, join, raw, renderOperationResultType, renderSchemaType, s, sqlTag as sql, toPrismaErrorCode, validateOperationPayload, validateSchema, validateSchemaOrThrow, wrapError };
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{_ as t,a as n,c as r,d as i,f as a,g as o,h as s,i as c,l,m as u,n as d,p as f,r as p,s as m,t as h,u as g}from"./validation-Du6j0Q38.mjs";import{s as _}from"./chain-uIFlkkXS.mjs";import{a as v,i as y,n as b,o as x,r as S,t as C}from"./base-vfur-DaU.mjs";import{g as w,h as T,m as E,p as D}from"./observation-CLp8ylmL.mjs";import{_ as O,
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{_ as t,a as n,c as r,d as i,f as a,g as o,h as s,i as c,l,m as u,n as d,p as f,r as p,s as m,t as h,u as g}from"./validation-Du6j0Q38.mjs";import{s as _}from"./chain-uIFlkkXS.mjs";import{a as v,i as y,n as b,o as x,r as S,t as C}from"./base-vfur-DaU.mjs";import{g as w,h as T,m as E,p as D}from"./observation-CLp8ylmL.mjs";import{_ as O,d as k,f as A,g as j,h as M,m as N,p as P,u as F,v as I,y as L}from"./error-mapping-LKqxnw-b.mjs";import{n as R,t as z}from"./migrations-BWZSBMZh.mjs";import{n as B,t as V}from"./transaction-oskVwmsf.mjs";import{f as H,g as U,h as W,m as G,p as K,v as q,x as J}from"./terminal-BbRi0CNZ.mjs";import{a as Y,i as X,n as Z,o as Q,r as $,t as ee}from"./sql--69HUgel.mjs";import{d as te,m as ne}from"./result-shape-CKLOBSKl.mjs";import{t as re}from"./client-C8gXvWIA.mjs";import{n as ie}from"./builder-DkWfNHEV.mjs";import{a as ae,i as oe}from"./validator-DMlEScV3.mjs";import{f as se,p as ce}from"./registration-preflight-BrA3EWvq.mjs";import{L as le}from"./geo-point-codec-DUTTtlav.mjs";import{i as ue,n as de,r as fe,t as pe}from"./schema-introspection-C7P7lwIs.mjs";import{t as me}from"./schema-BFNcMdO6.mjs";const getSchemas=e=>ie(e).proxy;export{H as AnyNull,D as CacheConfigurationError,E as CacheInvalidKeyError,T as CacheInvalidTTLError,w as CacheOperationNotCacheableError,F as CheckConstraintError,p as ClientInitializationError,c as ConnectionError,K as DbNull,le as Decimal,n as FeatureNotSupportedError,k as ForeignKeyError,V as InvalidTransactionInputError,G as JsonNull,W as JsonNullSentinel,z as MigrationError,m as NestedWriteAssertionError,r as NestedWriteError,l as NotFoundError,A as NotNullConstraintError,te as PendingOperation,g as PendingOperationError,i as QueryEngineError,a as QueryError,se as SchemaValidationError,ee as Sql,B as TransactionError,P as UniqueConstraintError,f as UnsupportedOperationError,h as ValidationError,N as ValueTooLongError,C as VibORMError,b as VibORMErrorCode,re as createClient,q as createModelFieldRefs,_ as defineExtension,Z as empty,pe as getOperationPayloadSchema,getSchemas,M as isCheckConstraintError,u as isClientInitializationError,J as isFieldRef,j as isForeignKeyError,U as isJsonNullSentinel,R as isMigrationError,s as isNotFoundError,O as isNotNullConstraintError,ne as isPendingOperation,o as isPendingOperationError,S as isRetryableError,ce as isSchemaValidationError,$ as isSql,I as isUniqueConstraintError,t as isUnsupportedOperationError,d as isValidationError,L as isValueTooLongError,y as isVibORMError,X as join,Y as raw,de as renderOperationResultType,fe as renderSchemaType,me as s,Q as sql,v as toPrismaErrorCode,ue as validateOperationPayload,oe as validateSchema,ae as validateSchemaOrThrow,x as wrapError};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Fi as DiagnosticDisclosure, _ as OFFICIAL_INSTRUMENTATION_NAME, c as Operation, g as ObserveHandler, ki as VibORMError } from "./index-
|
|
1
|
+
import { Fi as DiagnosticDisclosure, _ as OFFICIAL_INSTRUMENTATION_NAME, c as Operation, g as ObserveHandler, ki as VibORMError } from "./index-BbcE-gyl.mjs";
|
|
2
2
|
|
|
3
3
|
//#region src/instrumentation/types.d.ts
|
|
4
4
|
|
package/dist/instrumentation.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{C as t,E as n}from"./validation-Du6j0Q38.mjs";import{d as r,t as i}from"./chain-uIFlkkXS.mjs";import{C as a,T as o,b as s,f as c,h as l,p as u,v as ee,w as d,x as f,y as p}from"./base-vfur-DaU.mjs";import{c as m,s as h,u as te}from"./observation-CLp8ylmL.mjs";import{t as g}from"./version-Cr80LFvx.mjs";const _=new Set([`deprecation`,`event`,`notice`,`status`]);function sanitizeLogMetadata(e,t){return c(e,_,t,!0)}function prettyLog(e){let t=e.timestamp.toISOString(),r=e.duration===void 0?``:`${e.duration}ms`,i=e.model?[e.model,e.operation].filter(Boolean).join(`.`):e.operation??``;switch(e.level){case`query`:console.log([`[QUERY]`,t,i||`query`,r].filter(Boolean).join(` `)),e.sql&&console.log(` ${e.sql}`),e.params?.length&&console.log(` params: ${JSON.stringify(e.params)}`);break;case`cache`:console.log(`[CACHE]`,t,n(e.meta?.event)?e.meta.event:`unknown`,n(e.meta?.status)?`(${e.meta.status})`:``);break;case`warning`:console.warn(`[WARN]`,t,i,formatDiagnostic(e.meta));break;case`error`:console.error(`[ERROR]`,t,i,r),e.error&&console.error(` ${e.error.message}`),e.sql&&console.error(` ${e.sql}`);break}}function formatDiagnostic(e){return e===void 0?``:String(JSON.stringify(e))}function getHandler(e,t){let n=e[t];return n===void 0?e.all:n}function createLogger(e){let t=Object.freeze({includeParams:e.includeParams===!0,includeSql:e.includeSql===!0}),n=Object.freeze({cache:getHandler(e,`cache`),error:getHandler(e,`error`),query:getHandler(e,`query`),warning:getHandler(e,`warning`)});function sanitizeEvent(e,n){let r=t.includeParams&&e.params?u(e.params,t):void 0;return{level:n,timestamp:e.timestamp,duration:e.duration,model:e.model,operation:e.operation,correlationId:e.correlationId,sql:t.includeSql?e.sql:void 0,params:r,error:e.error?l(e.error,t):void 0,meta:e.meta?sanitizeLogMetadata(e.meta,t):void 0}}function emit(e,t){try{let r=n[t];if(!r)return;let i=sanitizeEvent(e,t),defaultLog=()=>{try{prettyLog(i)}catch{}};r===!0?defaultLog():Promise.resolve(r(i,defaultLog)).catch(()=>void 0)}catch{}}return Object.freeze({log(e){emit(e,e.level)},query(e){emit(e,`query`)},cache(e){emit(e,`cache`)},warn(e){emit(e,`warning`)},error(e){emit(e,`error`)},isLevelEnabled(e){return n[e]!==void 0}})}const v=`viborm.operation`,y=`viborm.execute`,b=`viborm.transaction`,x=`viborm.connect`,S=`viborm.disconnect`,C=`db.system.name`,w=`db.namespace`,T=`db.collection.name`,E=`db.operation.name`,D=`db.query.text`,O=`db.query.summary`,k=`db.operation.batch.size`,A=`server.address`,j=`server.port`,M=`db.response.returned_rows`,N=`error.type`,P=`db.system.driver`,F=`viborm.correlation.id`,I=`db.query.parameter`,L=`viborm.cache.get`,R=`viborm.cache.set`,z=`viborm.cache.delete`,B=`viborm.cache.clear`,V=`viborm.cache.invalidate`,H=`cache.driver`,U=`cache.result`,W=`cache.ttl`,G={SpanStatusCode:{OK:1,ERROR:2}},K=g,q=Symbol(`viborm.shouldTraceSpan`),J=new WeakMap,Y=new WeakSet,X={async startActiveSpan(e,t){return t()},isEnabled(){return!1}};Object.defineProperty(X,q,{value:()=>!1}),Object.freeze(X);function createTracerWrapper(e){let t=Object.freeze((e?.ignoreSpanTypes??[]).map(e=>n(e)?e:new RegExp(e.source,e.flags))),r=e?.includeSql===!0,i=e?.includeParams===!0;function shouldIgnoreSpan(e){return t.some(t=>n(t)?t===e:new RegExp(t.source,t.flags).test(e))}function buildAttributes(e){let t={...e.attributes};if(e.sql&&(r&&e.sql.query!==void 0&&(t[D]=e.sql.query),i&&e.sql.params)){let n=u(e.sql.params,{includeParams:!0,includeSql:r});for(let e=0;e<n.length;e++){let r=n[e];t[`${I}.${e}`]=formatSanitizedSpanParameter(r)}}return t}function presentThrough(e){return{async startActiveSpan(t,n){if(shouldIgnoreSpan(t.name))return n();let r=createExecution(n,G);try{let n=buildAttributes(t);Promise.resolve(e.startActiveSpan(t.name,e=>(setSpanAttributes(e,n),r(e)))).catch(()=>void 0)}catch{}return r()},isEnabled(){return!0}}}function autoDetect(){let e=null,t=null,n=!1;async function tryLoadOtel(){try{return e=await import(`@opentelemetry/api`),e}catch{return null}}function getTracer(e){return t||=e.trace.getTracer(`viborm`,K),t}let r=tryLoadOtel().then(e=>(n=!0,e)),i={async startActiveSpan(t,i){if(n||await r,!e||shouldIgnoreSpan(t.name))return i();let a,o;try{let n=buildAttributes(t),r=t.kind??e.SpanKind.INTERNAL,i=t.root?e.ROOT_CONTEXT:e.context.active();a=getTracer(e).startSpan(t.name,{kind:r,attributes:n},i),o=e.trace.setSpan(i,a)}catch{return i()}let s=createExecution(i,e);try{Promise.resolve(e.context.with(o,()=>s(a))).catch(()=>void 0)}catch{}return s(a)},isEnabled(){return e!==null}},a=r.then(()=>void 0);return J.set(i,a),a.then(()=>J.delete(i)),i}let a=e?.tracer,o=a===void 0?autoDetect():presentThrough(a);return Object.defineProperty(o,q,{value:e=>!shouldIgnoreSpan(e)}),Object.freeze(o)}function createExecution(e,t){let n=new Set,r,i,settle=(e,a)=>{r=e,i=a;for(let r of n)endSpan(r,e,t,a)},a,o=!1;return s=>{if(s!==void 0&&(n.add(s),r!==void 0&&endSpan(s,r,t,i)),a)return a;if(o)return Promise.reject(createTraceError());o=!0;try{return a=new Promise((t,n)=>{try{Promise.resolve(e(s)).then(e=>{settle(!1),t(e)},e=>{settle(!0,e),n(e)})}catch(e){settle(!0,e),n(e)}}),a}finally{o=!1}}}function endSpan(e,t,n,r){if(!Y.has(e)){if(Y.add(e),t){let t=s(r)?ee(r):void 0,i=typeof t?.name==`string`?t.name:`Error`;safely(()=>e.setAttribute(`error.type`,i));let a=t?.code;typeof a==`string`&&safely(()=>e.setAttribute(`viborm.error.code`,a));let o=t?.meta;if(typeof o==`object`&&o&&`providerSqlState`in o&&typeof o.providerSqlState==`string`){let t=o.providerSqlState;safely(()=>e.setAttribute(`db.response.sqlstate`,t))}safely(()=>e.setStatus?.({code:n.SpanStatusCode.ERROR,message:`Operation failed`}));let c=createTraceError();c.name=i,safely(()=>e.recordException?.(c))}else safely(()=>e.setStatus?.({code:n.SpanStatusCode.OK}));safely(()=>e.end())}}function setSpanAttributes(e,t){for(let[n,r]of Object.entries(t))safely(()=>e?.setAttribute(n,r))}function prewarmTracer(e){return J.get(e)}function shouldTraceSpan(e,t){try{let n=Reflect.get(e,q);return typeof n!=`function`||n(t)!==!1}catch{return!0}}function safely(e){try{let t=e(),n=typeof t==`object`&&t||typeof t==`function`?Reflect.get(t,`then`):void 0;typeof n==`function`&&Reflect.apply(n,t,[void 0,ignoreRejection])}catch{}}function ignoreRejection(){}function createTraceError(){let e=Error(`Operation failed`);return e.stack=void 0,e}function formatSanitizedSpanParameter(e){return n(e)?e:String(JSON.stringify(e))}function getNoopTracer(){return X}function createInstrumentationContext(e){let t=snapshotInstrumentationConfig(e),n;if(t.tracing){let e=t.tracing===!0?{}:t.tracing;n=createTracerWrapper({includeSql:e.includeSql,includeParams:e.includeParams,ignoreSpanTypes:e.ignoreSpanTypes,tracer:e.tracer})}else n=getNoopTracer();let r={config:t,tracer:n};return t.logging&&(r.logger=createLogger(t.logging===!0?{all:!0}:t.logging)),Object.freeze(r)}function snapshotInstrumentationConfig(e){let t=snapshotDisclosure(o(e,`diagnostics`)),n=o(e,`tracing`),r=o(e,`logging`),i=n===!0?!0:f(n)?snapshotTracingConfig(n):void 0,a=r===!0?!0:f(r)?snapshotLoggingConfig(r):void 0;return Object.freeze({diagnostics:t,tracing:i,logging:a})}function snapshotDisclosure(e){return Object.freeze({includeParams:f(e)&&o(e,`includeParams`)===!0,includeSql:f(e)&&o(e,`includeSql`)===!0,includeProviderDetails:f(e)&&o(e,`includeProviderDetails`)===!0,includeCallsite:f(e)&&o(e,`includeCallsite`)===!0})}function snapshotTracingConfig(e){let t=snapshotIgnorePatterns(o(e,`ignoreSpanTypes`)),n=o(e,`tracer`);return Object.freeze({includeParams:o(e,`includeParams`)===!0,includeSql:o(e,`includeSql`)===!0,...t.length>0?{ignoreSpanTypes:t}:{},...isPlatformTracer(n)?{tracer:n}:{}})}function isPlatformTracer(e){return f(e)&&t(o(e,`startActiveSpan`))}function snapshotIgnorePatterns(e){if(!p(e))return Object.freeze([]);let t=[],r=Math.min(a(e),128);for(let i=0;i<r;i+=1){let r=d(e,String(i));if(!(r&&`value`in r))continue;let a=r.value;if(n(a)){t.push(a);continue}try{a instanceof RegExp&&t.push(Object.freeze(new RegExp(a.source,a.flags)))}catch{}}return Object.freeze(t)}function snapshotLoggingConfig(e){let t=readLogHandler(e,`all`),n=readLogHandler(e,`cache`),r=readLogHandler(e,`error`),i=readLogHandler(e,`query`),a=readLogHandler(e,`warning`);if(![t,n,r,i,a].every(e=>!e))return Object.freeze({includeParams:o(e,`includeParams`)===!0,includeSql:o(e,`includeSql`)===!0,all:t,cache:n,error:r,query:i,warning:a})}function readLogHandler(e,n){let r=o(e,n);return r===!0||t(r)?r:void 0}const Z=Object.freeze({includeParams:!1,includeSql:!1}),ne={connect:x,disconnect:S,savepoint:b,transaction:b},Q={clear:B,delete:z,get:L,invalidate:V,revalidate:v,set:R};function createDriverAttributes(e){if(e===void 0)return{};let{dialect:t,driverName:n,namespace:r}=e;return{[C]:t,[P]:n,...r===void 0?{}:{[w]:r}}}function createCorrelationAttributes(e){let t=e?.correlationId;return t===void 0?{}:{[F]:t}}function createCacheSpanOptions(e,t){if(t.kind===`cache-backend`)return{name:Q[t.boundary],attributes:{[H]:t.driverName}};let{driverName:n,read:r,ttl:i}=t;return{name:Q[e],attributes:{...n===void 0?{}:{[H]:n},...i===void 0?{}:{[W]:String(i)},...r===void 0?{}:{...createDriverAttributes(r.identity),[T]:r.model,[E]:r.operation},...createCorrelationAttributes(t.context)},...r===void 0?{}:{root:!0}}}function presentCacheOutcome(e,t){let{error:n}=t;return Object.freeze({timestamp:new Date(t.at),model:e?.model,operation:e?.operation,correlationId:e?.correlationId,error:n instanceof Error?l(n):void 0,meta:Object.freeze({event:t.event,status:t.status})})}function createOperationSpanOptions(e){let{collection:t}=e;return{name:v,attributes:{...createDriverAttributes(e.identity),...t===void 0?{}:{[T]:t},[E]:e.requestedOperation,...createCorrelationAttributes(e.context)}}}function createOperationErrorLogEvent(e,t,n,r,i){return Object.freeze({timestamp:new Date(r),error:l(n),model:e.model,operation:e.operation,correlationId:t,duration:i})}function readChannelDisclosure(e){return e&&e!==!0?e:Z}function createContextAttributes(e,t){let{model:n,operation:i,correlationId:a}=t;return{...createDriverAttributes(r(e)),...n?{[T]:n}:{},...i?{[E]:i}:{},...a?{[F]:a}:{}}}function createStatementSpanOptions(e,t){let{includeParams:n,includeSql:r}=readChannelDisclosure(e);return{name:y,attributes:createContextAttributes(t.driver,t.context),...r||n?{sql:{...r?{query:t.sql}:{},...n?{params:t.params}:{}}}:{}}}function createLifecycleSpanOptions(e){return{name:ne[e.boundary],attributes:createContextAttributes(e.driver,e.context)}}function createStatementLogEvent(e,t,n){let{context:r,endedAt:i,failure:a}=e,o=readChannelDisclosure(n);return Object.freeze({timestamp:new Date(i),duration:i-t,model:r.model,operation:r.operation,correlationId:r.correlationId,sql:o.includeSql?e.sql:void 0,params:o.includeParams?e.params:void 0,error:a===void 0?void 0:l(a,o)})}const $=new WeakMap;function instrumentation(e){let t=createInstrumentationContext(e),n=Object.freeze({observesLifecycle:t.config.tracing!==void 0||t.config.logging!==void 0,...t.config.tracing===void 0?{}:{prewarm:()=>prewarmTracer(t.tracer)},diagnostics:t.config.diagnostics,wants:e=>wants(t,e),warn:e=>warn(t,e)}),r=function officialInstrumentationObserver(){};return $.set(n,t),te(r,n,(e,n)=>observeOfficialInstrumentation(t,e,n)),Object.freeze({name:i,observe:r})}function wants(e,t){switch(t){case`operation`:return traces(e,v);case`statement`:return traces(e,y);case`transaction`:case`savepoint`:return traces(e,b);case`connect`:return traces(e,x);case`disconnect`:return traces(e,S);case`cache`:return e.config.tracing!==void 0;case`cache-outcomes`:return logs(e,`cache`);case`query-log`:return logs(e,`query`);case`error-log`:return logs(e,`error`);default:return disclosesParameters(e)}}function traces(e,t){return e.config.tracing!==void 0&&shouldTraceSpan(e.tracer,t)}function logs(e,t){return e.logger?.isLevelEnabled(t)===!0}function disclosesParameters(e){let{logging:t,tracing:n}=e.config;return t!==void 0&&t!==!0&&t.includeParams===!0&&(logs(e,`query`)||logs(e,`error`))?!0:n!==void 0&&n!==!0&&n.includeParams===!0&&shouldTraceSpan(e.tracer,y)}function warn(e,t){let n=e.logger;return n?.isLevelEnabled(`warning`)===!0?(n.warn({timestamp:new Date,model:t.model,operation:t.operation,correlationId:t.correlationId,meta:{notice:t.message}}),!0):!1}function observeOfficialInstrumentation(e,t,n){let r=m(t);if(t.kind===`cache`&&(r?.kind===`cache`||r?.kind===`cache-backend`))return observeCacheInstrumentation(e,t.operation,t,r,n);if(r?.kind===`statement`){let i=n();return r.dispatch.then(n=>n===void 0?observeLifecycleCompletion(i):presentDispatch(e,n.start,wants(e,`statement`)?createStatementSpanOptions(e.config.tracing,n):void 0,()=>observeStatementCompletion(t,i,n.startedAt)))}if(r?.kind===`driver-lifecycle`){let i=n();return r.dispatch.then(n=>n===void 0?observeLifecycleCompletion(i):presentDispatch(e,n.start,createLifecycleSpanOptions(n),()=>observeLifecycleCompletion(i,t)))}if(r?.kind!==`operation`)return n();let i=r.context.correlationId,observeCompletion=()=>n().then(n=>{let a=h(t);if(a?.kind===`operation`){let{failure:t,readCacheOutcomes:o}=a;if(o!==void 0)for(let t of o())e.logger?.cache(presentCacheOutcome(r.context,t));t!==void 0&&a.skipLog!==!0&&e.logger?.error(createOperationErrorLogEvent(r,i,t,a.endedAt,n.durationMs))}if(n.status===`failure`)throw createObservedFailure(a?.kind===`operation`?a.failure:void 0)});return e.config.tracing===void 0?observeCompletion():e.tracer.startActiveSpan(createOperationSpanOptions(r),observeCompletion)}function observeCacheInstrumentation(e,t,n,r,i){let{logger:a,tracer:o}=e,s=wants(e,`cache`),c=r.kind===`cache`?r.context:void 0,l=r.kind===`cache`&&wants(e,`cache-outcomes`),u=Date.now(),observeCompletion=async e=>{l&&t===`revalidate`&&a?.cache(presentCacheOutcome(c,{event:`revalidate`,status:`start`,at:u}));let r=await i(),o=h(n);if(o?.kind===`cache`&&(s&&o.result!==void 0&&setSpanAttributes(e,{[U]:o.result}),l&&o.outcomes!==void 0))for(let e of o.outcomes)a?.cache(presentCacheOutcome(c,e));if(r.status===`failure`)throw createObservedFailure()};return s?o.startActiveSpan(createCacheSpanOptions(t,r),observeCompletion):observeCompletion()}async function presentDispatch(e,t,n,r){if(n===void 0)return t(),r();try{return await e.tracer.startActiveSpan(n,()=>(t(),r()))}finally{t()}}async function observeStatementCompletion(e,t,n){let r=await t,i=h(e);if(i?.kind===`statement`&&i.skipLog!==!0){let e=$.get(i.capability),t=createStatementLogEvent(i,n,e?.config.logging);i.failure===void 0?e?.logger?.query(t):e?.logger?.error(t)}if(r.status===`failure`)throw createObservedFailure(i?.kind===`statement`?i.failure:void 0)}async function observeLifecycleCompletion(e,t){let n=await e,r=t&&h(t);if(n.status===`failure`)throw createObservedFailure(r?.kind===`driver-lifecycle`?r.failure:void 0)}function createObservedFailure(e){if(e)return l(e);let t=Error(`Operation failed`);return t.stack=void 0,t}export{H as ATTR_CACHE_DRIVER,U as ATTR_CACHE_RESULT,W as ATTR_CACHE_TTL,k as ATTR_DB_BATCH_SIZE,T as ATTR_DB_COLLECTION,P as ATTR_DB_DRIVER,w as ATTR_DB_NAMESPACE,E as ATTR_DB_OPERATION_NAME,I as ATTR_DB_QUERY_PARAMETER_PREFIX,O as ATTR_DB_QUERY_SUMMARY,D as ATTR_DB_QUERY_TEXT,M as ATTR_DB_ROWS_RETURNED,C as ATTR_DB_SYSTEM,N as ATTR_ERROR_TYPE,A as ATTR_SERVER_ADDRESS,j as ATTR_SERVER_PORT,F as ATTR_VIBORM_CORRELATION_ID,B as SPAN_CACHE_CLEAR,z as SPAN_CACHE_DELETE,L as SPAN_CACHE_GET,V as SPAN_CACHE_INVALIDATE,R as SPAN_CACHE_SET,x as SPAN_CONNECT,S as SPAN_DISCONNECT,y as SPAN_EXECUTE,v as SPAN_OPERATION,b as SPAN_TRANSACTION,instrumentation};
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{C as t,E as n}from"./validation-Du6j0Q38.mjs";import{d as r,t as i}from"./chain-uIFlkkXS.mjs";import{C as a,T as o,b as s,f as c,h as l,p as u,v as ee,w as d,x as f,y as p}from"./base-vfur-DaU.mjs";import{c as m,s as h,u as te}from"./observation-CLp8ylmL.mjs";import{t as g}from"./version-De1l_ZMF.mjs";const _=new Set([`deprecation`,`event`,`notice`,`status`]);function sanitizeLogMetadata(e,t){return c(e,_,t,!0)}function prettyLog(e){let t=e.timestamp.toISOString(),r=e.duration===void 0?``:`${e.duration}ms`,i=e.model?[e.model,e.operation].filter(Boolean).join(`.`):e.operation??``;switch(e.level){case`query`:console.log([`[QUERY]`,t,i||`query`,r].filter(Boolean).join(` `)),e.sql&&console.log(` ${e.sql}`),e.params?.length&&console.log(` params: ${JSON.stringify(e.params)}`);break;case`cache`:console.log(`[CACHE]`,t,n(e.meta?.event)?e.meta.event:`unknown`,n(e.meta?.status)?`(${e.meta.status})`:``);break;case`warning`:console.warn(`[WARN]`,t,i,formatDiagnostic(e.meta));break;case`error`:console.error(`[ERROR]`,t,i,r),e.error&&console.error(` ${e.error.message}`),e.sql&&console.error(` ${e.sql}`);break}}function formatDiagnostic(e){return e===void 0?``:String(JSON.stringify(e))}function getHandler(e,t){let n=e[t];return n===void 0?e.all:n}function createLogger(e){let t=Object.freeze({includeParams:e.includeParams===!0,includeSql:e.includeSql===!0}),n=Object.freeze({cache:getHandler(e,`cache`),error:getHandler(e,`error`),query:getHandler(e,`query`),warning:getHandler(e,`warning`)});function sanitizeEvent(e,n){let r=t.includeParams&&e.params?u(e.params,t):void 0;return{level:n,timestamp:e.timestamp,duration:e.duration,model:e.model,operation:e.operation,correlationId:e.correlationId,sql:t.includeSql?e.sql:void 0,params:r,error:e.error?l(e.error,t):void 0,meta:e.meta?sanitizeLogMetadata(e.meta,t):void 0}}function emit(e,t){try{let r=n[t];if(!r)return;let i=sanitizeEvent(e,t),defaultLog=()=>{try{prettyLog(i)}catch{}};r===!0?defaultLog():Promise.resolve(r(i,defaultLog)).catch(()=>void 0)}catch{}}return Object.freeze({log(e){emit(e,e.level)},query(e){emit(e,`query`)},cache(e){emit(e,`cache`)},warn(e){emit(e,`warning`)},error(e){emit(e,`error`)},isLevelEnabled(e){return n[e]!==void 0}})}const v=`viborm.operation`,y=`viborm.execute`,b=`viborm.transaction`,x=`viborm.connect`,S=`viborm.disconnect`,C=`db.system.name`,w=`db.namespace`,T=`db.collection.name`,E=`db.operation.name`,D=`db.query.text`,O=`db.query.summary`,k=`db.operation.batch.size`,A=`server.address`,j=`server.port`,M=`db.response.returned_rows`,N=`error.type`,P=`db.system.driver`,F=`viborm.correlation.id`,I=`db.query.parameter`,L=`viborm.cache.get`,R=`viborm.cache.set`,z=`viborm.cache.delete`,B=`viborm.cache.clear`,V=`viborm.cache.invalidate`,H=`cache.driver`,U=`cache.result`,W=`cache.ttl`,G={SpanStatusCode:{OK:1,ERROR:2}},K=g,q=Symbol(`viborm.shouldTraceSpan`),J=new WeakMap,Y=new WeakSet,X={async startActiveSpan(e,t){return t()},isEnabled(){return!1}};Object.defineProperty(X,q,{value:()=>!1}),Object.freeze(X);function createTracerWrapper(e){let t=Object.freeze((e?.ignoreSpanTypes??[]).map(e=>n(e)?e:new RegExp(e.source,e.flags))),r=e?.includeSql===!0,i=e?.includeParams===!0;function shouldIgnoreSpan(e){return t.some(t=>n(t)?t===e:new RegExp(t.source,t.flags).test(e))}function buildAttributes(e){let t={...e.attributes};if(e.sql&&(r&&e.sql.query!==void 0&&(t[D]=e.sql.query),i&&e.sql.params)){let n=u(e.sql.params,{includeParams:!0,includeSql:r});for(let e=0;e<n.length;e++){let r=n[e];t[`${I}.${e}`]=formatSanitizedSpanParameter(r)}}return t}function presentThrough(e){return{async startActiveSpan(t,n){if(shouldIgnoreSpan(t.name))return n();let r=createExecution(n,G);try{let n=buildAttributes(t);Promise.resolve(e.startActiveSpan(t.name,e=>(setSpanAttributes(e,n),r(e)))).catch(()=>void 0)}catch{}return r()},isEnabled(){return!0}}}function autoDetect(){let e=null,t=null,n=!1;async function tryLoadOtel(){try{return e=await import(`@opentelemetry/api`),e}catch{return null}}function getTracer(e){return t||=e.trace.getTracer(`viborm`,K),t}let r=tryLoadOtel().then(e=>(n=!0,e)),i={async startActiveSpan(t,i){if(n||await r,!e||shouldIgnoreSpan(t.name))return i();let a,o;try{let n=buildAttributes(t),r=t.kind??e.SpanKind.INTERNAL,i=t.root?e.ROOT_CONTEXT:e.context.active();a=getTracer(e).startSpan(t.name,{kind:r,attributes:n},i),o=e.trace.setSpan(i,a)}catch{return i()}let s=createExecution(i,e);try{Promise.resolve(e.context.with(o,()=>s(a))).catch(()=>void 0)}catch{}return s(a)},isEnabled(){return e!==null}},a=r.then(()=>void 0);return J.set(i,a),a.then(()=>J.delete(i)),i}let a=e?.tracer,o=a===void 0?autoDetect():presentThrough(a);return Object.defineProperty(o,q,{value:e=>!shouldIgnoreSpan(e)}),Object.freeze(o)}function createExecution(e,t){let n=new Set,r,i,settle=(e,a)=>{r=e,i=a;for(let r of n)endSpan(r,e,t,a)},a,o=!1;return s=>{if(s!==void 0&&(n.add(s),r!==void 0&&endSpan(s,r,t,i)),a)return a;if(o)return Promise.reject(createTraceError());o=!0;try{return a=new Promise((t,n)=>{try{Promise.resolve(e(s)).then(e=>{settle(!1),t(e)},e=>{settle(!0,e),n(e)})}catch(e){settle(!0,e),n(e)}}),a}finally{o=!1}}}function endSpan(e,t,n,r){if(!Y.has(e)){if(Y.add(e),t){let t=s(r)?ee(r):void 0,i=typeof t?.name==`string`?t.name:`Error`;safely(()=>e.setAttribute(`error.type`,i));let a=t?.code;typeof a==`string`&&safely(()=>e.setAttribute(`viborm.error.code`,a));let o=t?.meta;if(typeof o==`object`&&o&&`providerSqlState`in o&&typeof o.providerSqlState==`string`){let t=o.providerSqlState;safely(()=>e.setAttribute(`db.response.sqlstate`,t))}safely(()=>e.setStatus?.({code:n.SpanStatusCode.ERROR,message:`Operation failed`}));let c=createTraceError();c.name=i,safely(()=>e.recordException?.(c))}else safely(()=>e.setStatus?.({code:n.SpanStatusCode.OK}));safely(()=>e.end())}}function setSpanAttributes(e,t){for(let[n,r]of Object.entries(t))safely(()=>e?.setAttribute(n,r))}function prewarmTracer(e){return J.get(e)}function shouldTraceSpan(e,t){try{let n=Reflect.get(e,q);return typeof n!=`function`||n(t)!==!1}catch{return!0}}function safely(e){try{let t=e(),n=typeof t==`object`&&t||typeof t==`function`?Reflect.get(t,`then`):void 0;typeof n==`function`&&Reflect.apply(n,t,[void 0,ignoreRejection])}catch{}}function ignoreRejection(){}function createTraceError(){let e=Error(`Operation failed`);return e.stack=void 0,e}function formatSanitizedSpanParameter(e){return n(e)?e:String(JSON.stringify(e))}function getNoopTracer(){return X}function createInstrumentationContext(e){let t=snapshotInstrumentationConfig(e),n;if(t.tracing){let e=t.tracing===!0?{}:t.tracing;n=createTracerWrapper({includeSql:e.includeSql,includeParams:e.includeParams,ignoreSpanTypes:e.ignoreSpanTypes,tracer:e.tracer})}else n=getNoopTracer();let r={config:t,tracer:n};return t.logging&&(r.logger=createLogger(t.logging===!0?{all:!0}:t.logging)),Object.freeze(r)}function snapshotInstrumentationConfig(e){let t=snapshotDisclosure(o(e,`diagnostics`)),n=o(e,`tracing`),r=o(e,`logging`),i=n===!0?!0:f(n)?snapshotTracingConfig(n):void 0,a=r===!0?!0:f(r)?snapshotLoggingConfig(r):void 0;return Object.freeze({diagnostics:t,tracing:i,logging:a})}function snapshotDisclosure(e){return Object.freeze({includeParams:f(e)&&o(e,`includeParams`)===!0,includeSql:f(e)&&o(e,`includeSql`)===!0,includeProviderDetails:f(e)&&o(e,`includeProviderDetails`)===!0,includeCallsite:f(e)&&o(e,`includeCallsite`)===!0})}function snapshotTracingConfig(e){let t=snapshotIgnorePatterns(o(e,`ignoreSpanTypes`)),n=o(e,`tracer`);return Object.freeze({includeParams:o(e,`includeParams`)===!0,includeSql:o(e,`includeSql`)===!0,...t.length>0?{ignoreSpanTypes:t}:{},...isPlatformTracer(n)?{tracer:n}:{}})}function isPlatformTracer(e){return f(e)&&t(o(e,`startActiveSpan`))}function snapshotIgnorePatterns(e){if(!p(e))return Object.freeze([]);let t=[],r=Math.min(a(e),128);for(let i=0;i<r;i+=1){let r=d(e,String(i));if(!(r&&`value`in r))continue;let a=r.value;if(n(a)){t.push(a);continue}try{a instanceof RegExp&&t.push(Object.freeze(new RegExp(a.source,a.flags)))}catch{}}return Object.freeze(t)}function snapshotLoggingConfig(e){let t=readLogHandler(e,`all`),n=readLogHandler(e,`cache`),r=readLogHandler(e,`error`),i=readLogHandler(e,`query`),a=readLogHandler(e,`warning`);if(![t,n,r,i,a].every(e=>!e))return Object.freeze({includeParams:o(e,`includeParams`)===!0,includeSql:o(e,`includeSql`)===!0,all:t,cache:n,error:r,query:i,warning:a})}function readLogHandler(e,n){let r=o(e,n);return r===!0||t(r)?r:void 0}const Z=Object.freeze({includeParams:!1,includeSql:!1}),ne={connect:x,disconnect:S,savepoint:b,transaction:b},Q={clear:B,delete:z,get:L,invalidate:V,revalidate:v,set:R};function createDriverAttributes(e){if(e===void 0)return{};let{dialect:t,driverName:n,namespace:r}=e;return{[C]:t,[P]:n,...r===void 0?{}:{[w]:r}}}function createCorrelationAttributes(e){let t=e?.correlationId;return t===void 0?{}:{[F]:t}}function createCacheSpanOptions(e,t){if(t.kind===`cache-backend`)return{name:Q[t.boundary],attributes:{[H]:t.driverName}};let{driverName:n,read:r,ttl:i}=t;return{name:Q[e],attributes:{...n===void 0?{}:{[H]:n},...i===void 0?{}:{[W]:String(i)},...r===void 0?{}:{...createDriverAttributes(r.identity),[T]:r.model,[E]:r.operation},...createCorrelationAttributes(t.context)},...r===void 0?{}:{root:!0}}}function presentCacheOutcome(e,t){let{error:n}=t;return Object.freeze({timestamp:new Date(t.at),model:e?.model,operation:e?.operation,correlationId:e?.correlationId,error:n instanceof Error?l(n):void 0,meta:Object.freeze({event:t.event,status:t.status})})}function createOperationSpanOptions(e){let{collection:t}=e;return{name:v,attributes:{...createDriverAttributes(e.identity),...t===void 0?{}:{[T]:t},[E]:e.requestedOperation,...createCorrelationAttributes(e.context)}}}function createOperationErrorLogEvent(e,t,n,r,i){return Object.freeze({timestamp:new Date(r),error:l(n),model:e.model,operation:e.operation,correlationId:t,duration:i})}function readChannelDisclosure(e){return e&&e!==!0?e:Z}function createContextAttributes(e,t){let{model:n,operation:i,correlationId:a}=t;return{...createDriverAttributes(r(e)),...n?{[T]:n}:{},...i?{[E]:i}:{},...a?{[F]:a}:{}}}function createStatementSpanOptions(e,t){let{includeParams:n,includeSql:r}=readChannelDisclosure(e);return{name:y,attributes:createContextAttributes(t.driver,t.context),...r||n?{sql:{...r?{query:t.sql}:{},...n?{params:t.params}:{}}}:{}}}function createLifecycleSpanOptions(e){return{name:ne[e.boundary],attributes:createContextAttributes(e.driver,e.context)}}function createStatementLogEvent(e,t,n){let{context:r,endedAt:i,failure:a}=e,o=readChannelDisclosure(n);return Object.freeze({timestamp:new Date(i),duration:i-t,model:r.model,operation:r.operation,correlationId:r.correlationId,sql:o.includeSql?e.sql:void 0,params:o.includeParams?e.params:void 0,error:a===void 0?void 0:l(a,o)})}const $=new WeakMap;function instrumentation(e){let t=createInstrumentationContext(e),n=Object.freeze({observesLifecycle:t.config.tracing!==void 0||t.config.logging!==void 0,...t.config.tracing===void 0?{}:{prewarm:()=>prewarmTracer(t.tracer)},diagnostics:t.config.diagnostics,wants:e=>wants(t,e),warn:e=>warn(t,e)}),r=function officialInstrumentationObserver(){};return $.set(n,t),te(r,n,(e,n)=>observeOfficialInstrumentation(t,e,n)),Object.freeze({name:i,observe:r})}function wants(e,t){switch(t){case`operation`:return traces(e,v);case`statement`:return traces(e,y);case`transaction`:case`savepoint`:return traces(e,b);case`connect`:return traces(e,x);case`disconnect`:return traces(e,S);case`cache`:return e.config.tracing!==void 0;case`cache-outcomes`:return logs(e,`cache`);case`query-log`:return logs(e,`query`);case`error-log`:return logs(e,`error`);default:return disclosesParameters(e)}}function traces(e,t){return e.config.tracing!==void 0&&shouldTraceSpan(e.tracer,t)}function logs(e,t){return e.logger?.isLevelEnabled(t)===!0}function disclosesParameters(e){let{logging:t,tracing:n}=e.config;return t!==void 0&&t!==!0&&t.includeParams===!0&&(logs(e,`query`)||logs(e,`error`))?!0:n!==void 0&&n!==!0&&n.includeParams===!0&&shouldTraceSpan(e.tracer,y)}function warn(e,t){let n=e.logger;return n?.isLevelEnabled(`warning`)===!0?(n.warn({timestamp:new Date,model:t.model,operation:t.operation,correlationId:t.correlationId,meta:{notice:t.message}}),!0):!1}function observeOfficialInstrumentation(e,t,n){let r=m(t);if(t.kind===`cache`&&(r?.kind===`cache`||r?.kind===`cache-backend`))return observeCacheInstrumentation(e,t.operation,t,r,n);if(r?.kind===`statement`){let i=n();return r.dispatch.then(n=>n===void 0?observeLifecycleCompletion(i):presentDispatch(e,n.start,wants(e,`statement`)?createStatementSpanOptions(e.config.tracing,n):void 0,()=>observeStatementCompletion(t,i,n.startedAt)))}if(r?.kind===`driver-lifecycle`){let i=n();return r.dispatch.then(n=>n===void 0?observeLifecycleCompletion(i):presentDispatch(e,n.start,createLifecycleSpanOptions(n),()=>observeLifecycleCompletion(i,t)))}if(r?.kind!==`operation`)return n();let i=r.context.correlationId,observeCompletion=()=>n().then(n=>{let a=h(t);if(a?.kind===`operation`){let{failure:t,readCacheOutcomes:o}=a;if(o!==void 0)for(let t of o())e.logger?.cache(presentCacheOutcome(r.context,t));t!==void 0&&a.skipLog!==!0&&e.logger?.error(createOperationErrorLogEvent(r,i,t,a.endedAt,n.durationMs))}if(n.status===`failure`)throw createObservedFailure(a?.kind===`operation`?a.failure:void 0)});return e.config.tracing===void 0?observeCompletion():e.tracer.startActiveSpan(createOperationSpanOptions(r),observeCompletion)}function observeCacheInstrumentation(e,t,n,r,i){let{logger:a,tracer:o}=e,s=wants(e,`cache`),c=r.kind===`cache`?r.context:void 0,l=r.kind===`cache`&&wants(e,`cache-outcomes`),u=Date.now(),observeCompletion=async e=>{l&&t===`revalidate`&&a?.cache(presentCacheOutcome(c,{event:`revalidate`,status:`start`,at:u}));let r=await i(),o=h(n);if(o?.kind===`cache`&&(s&&o.result!==void 0&&setSpanAttributes(e,{[U]:o.result}),l&&o.outcomes!==void 0))for(let e of o.outcomes)a?.cache(presentCacheOutcome(c,e));if(r.status===`failure`)throw createObservedFailure()};return s?o.startActiveSpan(createCacheSpanOptions(t,r),observeCompletion):observeCompletion()}async function presentDispatch(e,t,n,r){if(n===void 0)return t(),r();try{return await e.tracer.startActiveSpan(n,()=>(t(),r()))}finally{t()}}async function observeStatementCompletion(e,t,n){let r=await t,i=h(e);if(i?.kind===`statement`&&i.skipLog!==!0){let e=$.get(i.capability),t=createStatementLogEvent(i,n,e?.config.logging);i.failure===void 0?e?.logger?.query(t):e?.logger?.error(t)}if(r.status===`failure`)throw createObservedFailure(i?.kind===`statement`?i.failure:void 0)}async function observeLifecycleCompletion(e,t){let n=await e,r=t&&h(t);if(n.status===`failure`)throw createObservedFailure(r?.kind===`driver-lifecycle`?r.failure:void 0)}function createObservedFailure(e){if(e)return l(e);let t=Error(`Operation failed`);return t.stack=void 0,t}export{H as ATTR_CACHE_DRIVER,U as ATTR_CACHE_RESULT,W as ATTR_CACHE_TTL,k as ATTR_DB_BATCH_SIZE,T as ATTR_DB_COLLECTION,P as ATTR_DB_DRIVER,w as ATTR_DB_NAMESPACE,E as ATTR_DB_OPERATION_NAME,I as ATTR_DB_QUERY_PARAMETER_PREFIX,O as ATTR_DB_QUERY_SUMMARY,D as ATTR_DB_QUERY_TEXT,M as ATTR_DB_ROWS_RETURNED,C as ATTR_DB_SYSTEM,N as ATTR_ERROR_TYPE,A as ATTR_SERVER_ADDRESS,j as ATTR_SERVER_PORT,F as ATTR_VIBORM_CORRELATION_ID,B as SPAN_CACHE_CLEAR,z as SPAN_CACHE_DELETE,L as SPAN_CACHE_GET,V as SPAN_CACHE_INVALIDATE,R as SPAN_CACHE_SET,x as SPAN_CONNECT,S as SPAN_DISCONNECT,y as SPAN_EXECUTE,v as SPAN_OPERATION,b as SPAN_TRANSACTION,instrumentation};
|
|
2
2
|
//# sourceMappingURL=instrumentation.mjs.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{n as e}from"./chunk-BuuaeEvq.mjs";const t=`%!.17g`;function sqliteBinary64JsonNumber(e){return`json(printf('${t}', ${e}))`}export{sqliteBinary64JsonNumber as n,t};
|
|
2
|
-
//# sourceMappingURL=json-number-
|
|
2
|
+
//# sourceMappingURL=json-number-TpD-pfqt.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json-number-
|
|
1
|
+
{"version":3,"file":"json-number-TpD-pfqt.mjs","names":[],"sources":["../src/adapters/databases/sqlite/storage/json-number.ts"],"sourcesContent":["/** SQLite printf spelling that round-trips every finite binary64 coordinate. */\nexport const SQLITE_BINARY64_FORMAT = \"%!.17g\";\nexport function sqliteBinary64JsonNumber(expression: string): string {\n return `json(printf('${SQLITE_BINARY64_FORMAT}', ${expression}))`;\n}\n"],"mappings":"yCACA,MAAa,EAAyB,SACtC,SAAgB,yBAAyB,EAA4B,CACnE,MAAO,gBAAgB,EAAuB,KAAK,EAAW"}
|
package/dist/libsql.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, Vt as DriverTransactionOptions, 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, Vt as DriverTransactionOptions, f as DriverResultParser, jt as DriverConfig, s as DatabaseAdapter, u as Driver } from "./index-BbcE-gyl.mjs";
|
|
2
2
|
import { Client, Config, Transaction } from "@libsql/client";
|
|
3
3
|
|
|
4
4
|
//#region src/drivers/libsql/index.d.ts
|
|
@@ -19,7 +19,6 @@ declare class LibSQLDriver extends Driver<Client, Client | Transaction> {
|
|
|
19
19
|
protected readonly serializeTransactions: boolean;
|
|
20
20
|
private readonly driverOptions;
|
|
21
21
|
private readonly suppliedClient;
|
|
22
|
-
private integerAdmission;
|
|
23
22
|
constructor(options?: LibSQLDriverOptions);
|
|
24
23
|
protected initClient(): Promise<Client>;
|
|
25
24
|
protected closeClient(client: Client | Transaction): Promise<void>;
|
|
@@ -36,9 +35,15 @@ declare class LibSQLDriver extends Driver<Client, Client | Transaction> {
|
|
|
36
35
|
protected transaction<T>(client: Client | Transaction, fn: (tx: Client | Transaction) => Promise<T>, context?: QueryExecutionContext, options?: DriverTransactionOptions): Promise<T>;
|
|
37
36
|
protected transactionCleanupFailed(_error: Error): void;
|
|
38
37
|
private executeStatement;
|
|
38
|
+
/**
|
|
39
|
+
* A local BUSY can leave the failed statement unfinished on libSQL's pooled
|
|
40
|
+
* connection; SQLite then never commits that connection's later autocommit
|
|
41
|
+
* writes. Statements and transaction acquisition (its BEGIN) both borrow
|
|
42
|
+
* that connection, so both quarantine this exact client.
|
|
43
|
+
*/
|
|
44
|
+
private quarantineOnBusy;
|
|
39
45
|
protected getClient(context?: QueryExecutionContext): Promise<Client | Transaction>;
|
|
40
46
|
private assertLocalClientUsable;
|
|
41
|
-
private ensureSuppliedIntegerPrecision;
|
|
42
47
|
private getDatabaseUrl;
|
|
43
48
|
}
|
|
44
49
|
declare function createClient<S extends Schema, C extends DriverConfig<S>>(config: LibSQLClientConfig<C> & DriverConfig<S> & NoExtraDriverConfigKeys<C, LibSQLDriverOptions, S>): VibORMClient<{ [P in keyof LinkedClientConfig<C & {
|
package/dist/libsql.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t}from"./validation-Du6j0Q38.mjs";import{c as n}from"./bind-parameter-capacity-DzMcIB95.mjs";import{n as r}from"./base-vfur-DaU.mjs";import{r as i,s as a}from"./transactions-gjmrWN5W.mjs";import{s as o}from"./execution-context-Bm_qTp1i.mjs";import{n as s}from"./client-C8gXvWIA.mjs";import{n as c,r as l,t as u}from"./driver-CHclfK3q.mjs";import{o as d,r as f,s as p,t as m}from"./sqlite-utils-D26BFuJJ.mjs";import{t as h}from"./sqlite-adapter-1krz0OXw.mjs";const g=new WeakSet;function convertValuesForLibSQL(e){return e.map(e=>{let t=m(e);if(typeof t==`string`&&t.includes(`\0`))throw TypeError(`libSQL cannot preserve strings containing NUL bytes`);if(f(t))return t instanceof ArrayBuffer?t:d(t);if(t===null||typeof t==`string`||typeof t==`number`||typeof t==`bigint`||typeof t==`boolean`||t instanceof Date)return t;throw TypeError(`Driver "libsql" received an unsupported SQLite parameter value.`)})}const libsqlRowCount=(e,t)=>{let r=n(e.rowsAffected,{provider:`libsql`,operation:t});return e.rows.length>0?e.rows.length:r};var LibSQLDriver=class extends u{adapter=new h;maxBindParametersPerStatement=32766;result=p;serializeTransactions;driverOptions;suppliedClient;constructor(e={}){super(`sqlite`,`libsql`),this.driverOptions=e,this.suppliedClient=e.client,this.serializeTransactions=this.suppliedClient?this.suppliedClient.protocol===`file`:this.getDatabaseUrl().startsWith(`file:`),this.suppliedClient&&(this.client=this.suppliedClient,this.serializeTransactions&&Object.defineProperty(this,`connectionQueue`,{value:c(this.suppliedClient)}))}async initClient(){if(this.suppliedClient)return this.suppliedClient;let{createClient:e}=await import(`@libsql/client`),t=this.getDatabaseUrl(),n=this.driverOptions.authToken;return e({url:t,authToken:n,timeout:5e3,...this.driverOptions.options??{},intMode:`bigint`})}async closeClient(e){e!==this.suppliedClient&&`close`in e&&(e.close(),`commit`in e||g.delete(e))}async execute(e,t,n,r){let i=r?.operation??`execute`,a=convertValuesForLibSQL(n),o=await this.executeStatement(e,{sql:t,args:a});return{rows:o.rows,rowCount:libsqlRowCount(o,i)}}async executeRaw(e,t,n,r){let i=r?.operation??`executeRaw`,a=n?convertValuesForLibSQL(n):[],o=await this.executeStatement(e,{sql:t,args:a});return{rows:o.rows,rowCount:libsqlRowCount(o,i)}}transactionOptionSupport(){return{isolationLevel:`serializable-only`,isolationLevelReason:`libSQL serializes writers the way SQLite does and has no statement to weaken isolation, so only Serializable can be honored truthfully`,timeout:!0,maxWait:this.serializeTransactions?`queue`:`acquisition`}}async transaction(e,t,n,r){if(`commit`in e)throw i(this.driverName);let s=await l(()=>this.quarantineOnBusy(e,()=>e.transaction(`write`)),e=>e.close(),r?.maxWaitMs,{driverName:this.driverName,form:`callback`});return a({begin:()=>void 0,callback:()=>t(s),commit:()=>s.commit(),rollback:()=>s.rollback(),phases:o(n),close:()=>s.close()})}transactionCleanupFailed(e){}executeStatement(e,t){return this.quarantineOnBusy(e,()=>e.execute(t))}async quarantineOnBusy(e,t){try{return await t()}catch(t){throw this.serializeTransactions&&!(`commit`in e)&&typeof t==`object`&&t&&`code`in t&&typeof t.code==`string`&&(t.code===`SQLITE_BUSY`||t.code.startsWith(`SQLITE_BUSY_`))&&(g.add(e),this.closeRetryClient=e,this.client=null,this.initPromise=null),t}}async getClient(e){let t=await super.getClient(e);return this.assertLocalClientUsable(t),t}assertLocalClientUsable(e){if(!(`commit`in e)&&g.has(e))throw new t(`Local libSQL execution encountered SQLITE_BUSY; disconnect an owned driver, or close and replace the supplied native client, before reuse.`,{code:r.CONNECTION_CLOSED,meta:{driver:`libsql`}})}getDatabaseUrl(){return this.driverOptions.databaseUrl?this.driverOptions.databaseUrl:this.driverOptions.dataDir?`file:${this.driverOptions.dataDir}`:`file::memory:`}};function createClient(e){let{client:t,databaseUrl:n,dataDir:r,authToken:i,options:a}=e;return s(e,new LibSQLDriver({client:t,databaseUrl:n,dataDir:r,authToken:i,options:a}))}export{LibSQLDriver,createClient};
|
|
2
2
|
//# sourceMappingURL=libsql.mjs.map
|