nitro-drizzle 0.3.0-beta.5 → 0.3.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 CHANGED
@@ -9,8 +9,8 @@
9
9
 
10
10
  ## ✨ Features
11
11
 
12
- - **Datasource Management**: Easily configure and manage multiple Drizzle ORM datasources within your Nitro project.
13
- - **Multiple Database Drivers**: Support for various database drivers including SQLite (with `better-sqlite3`), PostgreSQL (with `pglite`), MySQL (with `mysql2`), and Cloudflare D1.
12
+ - **Datasource Management**: Easily configure and manage multiple Drizzle ORM datasources within your Nitro project with granular driver activation/deactivation.
13
+ - **Multiple Database Drivers**: Support for various database drivers including SQLite (with `better-sqlite3`), PostgreSQL (with `pglite`), MySQL (with `mysql2`), and Cloudflare D1. Drivers can be enabled or disabled via array entries (using underscore prefixes like `_d1`) or object maps (`{ sqlite: true, d1: false }`).
14
14
  - **Automatic Migrations**: Configure automatic database migrations on application initialization.
15
15
  - **Type-Safe Schemas**: Leverage Drizzle ORM's type-safe schemas for a better development experience.
16
16
  - **Nitro Task Integration**: Run Drizzle migrations as Nitro tasks.
@@ -47,7 +47,7 @@ export default defineNitroConfig({
47
47
  modules: ["nitro-drizzle"],
48
48
  drizzle: {
49
49
  datasources: {
50
- content: { drivers: ["sqlite", "d1"] },
50
+ content: { drivers: ["sqlite", "d1", "_pglite"] }, // Use underscore prefix (e.g., _pglite) to exclude specific drivers, but preserve type safety
51
51
  },
52
52
  },
53
53
  });
@@ -1 +1 @@
1
- {"version":3,"file":"templates.mjs","names":["#files"],"sources":["../../../src/context/internal/templates.ts"],"sourcesContent":["import { genTypeImport, genString, genObjectFromValues, genInlineTypeImport } from \"knitwork\";\nimport type { DatasourceInfo, DriverOptions } from \"..\";\nimport { genVariants, type Selector, type VirtualModules } from \"nitro-drizzle/shared\";\nimport { script } from \"./format\";\nimport { genReference, genTypeName } from \"./codegen\";\n\ntype ConnectorInfo = {\n name: string;\n driver: DriverOptions;\n};\n\nfunction getConnectorDimensions({ name, driver }: ConnectorInfo) {\n return {\n name,\n dialect: driver.dialect,\n driver: driver.name,\n };\n}\n\nclass ImportedModules {\n readonly #files: string[] = [];\n\n values(): readonly string[] {\n return [...this.#files];\n }\n\n getOrAdd(value: string): number {\n let index = this.#files.indexOf(value);\n if (!~index) {\n index = this.#files.push(value);\n }\n return index;\n }\n}\n\nexport function sharedTypeDeclarations(\n datasources: readonly DatasourceInfo[],\n): VirtualModules<`${string}.d.ts`> {\n const moduleId = \"nitro-drizzle/shared\";\n const connectors = datasources.flatMap(({ name, drivers }) => {\n return drivers.map((driver) => {\n return {\n name,\n driver,\n };\n });\n });\n\n const SCHEMA_PARTS_TYPE = \"SchemaParts\";\n const SCHEMA_TYPE = \"SchemaVariants\";\n const CONNECTOR_TYPE = \"Connectors\";\n const UNWRAP_VARIANT_TYPE = \"UnwrapVariant\";\n const MERGE_SCHEMA_TYPE = \"MergeSchema\";\n\n const schemaFiles = new ImportedModules();\n connectors\n .flatMap((connector) => {\n return connector.driver.imports.schema;\n })\n .forEach((schemaFile) => {\n schemaFiles.getOrAdd(schemaFile);\n });\n\n const driverImports = new ImportedModules();\n connectors.forEach((connector) => {\n driverImports.getOrAdd(connector.driver.imports.connector);\n });\n\n const content = [\n genTypeImport(\"nitro-drizzle/shared\", [\"Variant\", UNWRAP_VARIANT_TYPE]),\n genTypeImport(\"nitro-drizzle/drivers\", [\"Schema\", MERGE_SCHEMA_TYPE]),\n\n script /* ts */ `type ${SCHEMA_PARTS_TYPE} = [\n ${schemaFiles\n .values()\n .map((file) => {\n return `typeof import(${genString(file)})`;\n })\n .join(\",\\n\")}\n ]`,\n\n script /* ts */ `type ${CONNECTOR_TYPE}<TSchema extends Schema> = [\n ${driverImports\n .values()\n .map((file) => {\n return genInlineTypeImport(file) + `<TSchema>`;\n })\n .join(\",\\n\")}\n ]`,\n\n script /**ts */ `type ${SCHEMA_TYPE} = \n ${genVariants({\n variants: connectors.map((connector): [schemaType: string, dimensions: Selector] => {\n return [\n genTypeName(MERGE_SCHEMA_TYPE, {\n generic: [\n SCHEMA_PARTS_TYPE,\n connector.driver.imports.schema\n .map((schemaFile) => {\n return schemaFiles.getOrAdd(schemaFile).toString();\n })\n .join(\" | \") || \"never\",\n ],\n }),\n getConnectorDimensions(connector),\n ];\n }),\n })}\n `,\n\n script /**ts */ `\n declare module ${genString(moduleId)} {\n type ConnectorVariants = ${genVariants({\n variants: connectors.map((connector): [connectorType: string, selector: Selector] => {\n const dimensions = getConnectorDimensions(connector);\n return [\n genTypeName(CONNECTOR_TYPE, {\n generic: [\n genTypeName(UNWRAP_VARIANT_TYPE, {\n generic: [SCHEMA_TYPE, genObjectFromValues(dimensions)],\n }),\n ],\n }) + `[${driverImports.getOrAdd(connector.driver.imports.connector)}]`,\n dimensions,\n ];\n }),\n })};\n }\n `,\n ].join(\"\\n\\n\");\n\n return {\n [`${moduleId}.d.ts`]: content,\n };\n}\n\n/** @deprecated */\nexport function runtimeDeclarations(_datasources: readonly DatasourceInfo[]) {\n return \"\";\n}\n\nexport function moduleTypeDeclarations(\n _datasources: readonly DatasourceInfo[],\n): VirtualModules<`${string}.d.ts`> {\n const moduleId = \"nitro-drizzle/module\";\n\n const content = [genReference({ types: moduleId })].join(\"\\n\");\n\n return {\n \"nitro-drizzle/module.d.ts\": content,\n };\n}\n\n/** @deprecated */\nexport function dialectDeclarations(_datasources: readonly DatasourceInfo[]) {\n return ``;\n}\n"],"mappings":";;;;;AAWA,SAAS,uBAAuB,EAAE,MAAM,UAAyB;CAC/D,OAAO;EACL;EACA,SAAS,OAAO;EAChB,QAAQ,OAAO;CACjB;AACF;AAEA,IAAM,kBAAN,MAAsB;CACpB,SAA4B,CAAC;CAE7B,SAA4B;EAC1B,OAAO,CAAC,GAAG,KAAKA,MAAM;CACxB;CAEA,SAAS,OAAuB;EAC9B,IAAI,QAAQ,KAAKA,OAAO,QAAQ,KAAK;EACrC,IAAI,CAAC,CAAC,OACJ,QAAQ,KAAKA,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KAAK,KAAK,OACpB,EACF,CAAC,GACD,uBAAuB,SAAS,CAClC;EACF,CAAC,EACH,CAAC,EAAE;;EAGL,MAAgB;uBACG,UAAU,QAAQ,EAAE;mCACR,YAAY,EACrC,UAAU,WAAW,KAAK,cAA2D;GACnF,MAAM,aAAa,uBAAuB,SAAS;GACnD,OAAO,CACL,YAAY,gBAAgB,EAC1B,SAAS,CACP,YAAY,qBAAqB,EAC/B,SAAS,CAAC,aAAa,oBAAoB,UAAU,CAAC,EACxD,CAAC,CACH,EACF,CAAC,IAAI,IAAI,cAAc,SAAS,UAAU,OAAO,QAAQ,SAAS,EAAE,IACpE,UACF;EACF,CAAC,EACH,CAAC,EAAE;;;CAGT,CAAC,CAAC,KAAK,MAAM;CAEb,OAAO,GACJ,GAAG,SAAS,SAAS,QACxB;AACF;;AAGA,SAAgB,oBAAoB,cAAyC;CAC3E,OAAO;AACT;AAEA,SAAgB,uBACd,cACkC;CAKlC,OAAO,EACL,6BAHc,CAAC,aAAa,EAAE,OAAO,uBAAS,CAAC,CAAC,CAAC,CAAC,KAAK,IAGpB,EACrC;AACF;;AAGA,SAAgB,oBAAoB,cAAyC;CAC3E,OAAO;AACT"}
1
+ {"version":3,"file":"templates.mjs","names":[],"sources":["../../../src/context/internal/templates.ts"],"sourcesContent":["import { genTypeImport, genString, genObjectFromValues, genInlineTypeImport } from \"knitwork\";\nimport type { DatasourceInfo, DriverOptions } from \"..\";\nimport { genVariants, type Selector, type VirtualModules } from \"nitro-drizzle/shared\";\nimport { script } from \"./format\";\nimport { genReference, genTypeName } from \"./codegen\";\n\ntype ConnectorInfo = {\n name: string;\n driver: DriverOptions;\n};\n\nfunction getConnectorDimensions({ name, driver }: ConnectorInfo) {\n return {\n name,\n dialect: driver.dialect,\n driver: driver.name,\n };\n}\n\nclass ImportedModules {\n readonly #files: string[] = [];\n\n values(): readonly string[] {\n return [...this.#files];\n }\n\n getOrAdd(value: string): number {\n let index = this.#files.indexOf(value);\n if (!~index) {\n index = this.#files.push(value);\n }\n return index;\n }\n}\n\nexport function sharedTypeDeclarations(\n datasources: readonly DatasourceInfo[],\n): VirtualModules<`${string}.d.ts`> {\n const moduleId = \"nitro-drizzle/shared\";\n const connectors = datasources.flatMap(({ name, drivers }) => {\n return drivers.map((driver) => {\n return {\n name,\n driver,\n };\n });\n });\n\n const SCHEMA_PARTS_TYPE = \"SchemaParts\";\n const SCHEMA_TYPE = \"SchemaVariants\";\n const CONNECTOR_TYPE = \"Connectors\";\n const UNWRAP_VARIANT_TYPE = \"UnwrapVariant\";\n const MERGE_SCHEMA_TYPE = \"MergeSchema\";\n\n const schemaFiles = new ImportedModules();\n connectors\n .flatMap((connector) => {\n return connector.driver.imports.schema;\n })\n .forEach((schemaFile) => {\n schemaFiles.getOrAdd(schemaFile);\n });\n\n const driverImports = new ImportedModules();\n connectors.forEach((connector) => {\n driverImports.getOrAdd(connector.driver.imports.connector);\n });\n\n const content = [\n genTypeImport(\"nitro-drizzle/shared\", [\"Variant\", UNWRAP_VARIANT_TYPE]),\n genTypeImport(\"nitro-drizzle/drivers\", [\"Schema\", MERGE_SCHEMA_TYPE]),\n\n script /* ts */ `type ${SCHEMA_PARTS_TYPE} = [\n ${schemaFiles\n .values()\n .map((file) => {\n return `typeof import(${genString(file)})`;\n })\n .join(\",\\n\")}\n ]`,\n\n script /* ts */ `type ${CONNECTOR_TYPE}<TSchema extends Schema> = [\n ${driverImports\n .values()\n .map((file) => {\n return genInlineTypeImport(file) + `<TSchema>`;\n })\n .join(\",\\n\")}\n ]`,\n\n script /**ts */ `type ${SCHEMA_TYPE} = \n ${genVariants({\n variants: connectors.map((connector): [schemaType: string, dimensions: Selector] => {\n return [\n genTypeName(MERGE_SCHEMA_TYPE, {\n generic: [\n SCHEMA_PARTS_TYPE,\n connector.driver.imports.schema\n .map((schemaFile) => {\n return schemaFiles.getOrAdd(schemaFile).toString();\n })\n .join(\" | \") || \"never\",\n ],\n }),\n getConnectorDimensions(connector),\n ];\n }),\n })}\n `,\n\n script /**ts */ `\n declare module ${genString(moduleId)} {\n type ConnectorVariants = ${genVariants({\n variants: connectors.map((connector): [connectorType: string, selector: Selector] => {\n const dimensions = getConnectorDimensions(connector);\n return [\n genTypeName(CONNECTOR_TYPE, {\n generic: [\n genTypeName(UNWRAP_VARIANT_TYPE, {\n generic: [SCHEMA_TYPE, genObjectFromValues(dimensions)],\n }),\n ],\n }) + `[${driverImports.getOrAdd(connector.driver.imports.connector)}]`,\n dimensions,\n ];\n }),\n })};\n }\n `,\n ].join(\"\\n\\n\");\n\n return {\n [`${moduleId}.d.ts`]: content,\n };\n}\n\n/** @deprecated */\nexport function runtimeDeclarations(_datasources: readonly DatasourceInfo[]) {\n return \"\";\n}\n\nexport function moduleTypeDeclarations(\n _datasources: readonly DatasourceInfo[],\n): VirtualModules<`${string}.d.ts`> {\n const moduleId = \"nitro-drizzle/module\";\n\n const content = [genReference({ types: moduleId })].join(\"\\n\");\n\n return {\n \"nitro-drizzle/module.d.ts\": content,\n };\n}\n\n/** @deprecated */\nexport function dialectDeclarations(_datasources: readonly DatasourceInfo[]) {\n return ``;\n}\n"],"mappings":";;;;;AAWA,SAAS,uBAAuB,EAAE,MAAM,UAAyB;CAC/D,OAAO;EACL;EACA,SAAS,OAAO;EAChB,QAAQ,OAAO;CACjB;AACF;AAEA,IAAM,kBAAN,MAAsB;CACpB,SAA4B,CAAC;CAE7B,SAA4B;EAC1B,OAAO,CAAC,GAAG,KAAK,MAAM;CACxB;CAEA,SAAS,OAAuB;EAC9B,IAAI,QAAQ,KAAK,OAAO,QAAQ,KAAK;EACrC,IAAI,CAAC,CAAC,OACJ,QAAQ,KAAK,OAAO,KAAK,KAAK;EAEhC,OAAO;CACT;AACF;AAEA,SAAgB,uBACd,aACkC;CAClC,MAAM,WAAW;CACjB,MAAM,aAAa,YAAY,SAAS,EAAE,MAAM,cAAc;EAC5D,OAAO,QAAQ,KAAK,WAAW;GAC7B,OAAO;IACL;IACA;GACF;EACF,CAAC;CACH,CAAC;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YAAY,gBAAgB,EAC1B,SAAS,CACP,YAAY,qBAAqB,EAC/B,SAAS,CAAC,aAAa,oBAAoB,UAAU,CAAC,EACxD,CAAC,CACH,EACF,CAAC,IAAI,IAAI,cAAc,SAAS,UAAU,OAAO,QAAQ,SAAS,EAAE,IACpE,UACF;EACF,CAAC,EACH,CAAC,EAAE;;;CAGT,CAAC,CAAC,KAAK,MAAM;CAEb,OAAO,GACJ,GAAG,SAAS,SAAS,QACxB;AACF;;AAGA,SAAgB,oBAAoB,cAAyC;CAC3E,OAAO;AACT;AAEA,SAAgB,uBACd,cACkC;CAKlC,OAAO,EACL,6BAHc,CAAC,aAAa,EAAE,OAAO,uBAAS,CAAC,CAAC,CAAC,CAAC,KAAK,IAGpB,EACrC;AACF;;AAGA,SAAgB,oBAAoB,cAAyC;CAC3E,OAAO;AACT"}
@@ -29,6 +29,8 @@ function runtimeVirtualModule(datasources, { legacyNitro, runtimeConfigProp, ini
29
29
  driver
30
30
  };
31
31
  });
32
+ }).filter(({ driver }) => {
33
+ return driver.enabled;
32
34
  }).map(({ name, driver }, datasourceIndex) => {
33
35
  const connectorVarName = genConnectorModuleVariableName(datasourceIndex);
34
36
  const imports = [genImport(driver.imports.connector, connectorVarName), ...driver.imports.schema.map((schemaModuleId, schemaIndex) => {
@@ -1 +1 @@
1
- {"version":3,"file":"virtual.mjs","names":[],"sources":["../../../src/context/internal/virtual.ts"],"sourcesContent":["import {\n genArrayFromRaw,\n genExport,\n genImport,\n genObjectFromRaw,\n genObjectFromRawEntries,\n genSafeVariableName,\n genString,\n} from \"knitwork\";\nimport type { DatasourceInfo, MigrationOptions } from \"..\";\nimport type { VirtualModules } from \"nitro-drizzle/shared\";\nimport { script } from \"./format\";\n\nfunction genConnectorModuleVariableName(dbModuleIndex: number) {\n return genSafeVariableName(`dbModule${dbModuleIndex}`);\n}\n\nfunction genMergeSchemaVariableName(dbModuleIndex: number) {\n return genSafeVariableName(`mergedSchema${dbModuleIndex}`);\n}\n\nconst genSchemaModuleVariableName = (dbModuleIndex: number, schemaIndex: number) =>\n genSafeVariableName(`schemaModule${dbModuleIndex}_${schemaIndex}`);\n\nfunction mergeSchemaModules(schemaIds: readonly string[], dbModuleIndex: number) {\n return /* js */ `\n Object.assign(\n ${[\n /* js */ `{}`,\n ...schemaIds.map((_, schemaModuleIdIndex) =>\n genSchemaModuleVariableName(dbModuleIndex, schemaModuleIdIndex),\n ),\n ].join(\",\")}\n )\n `;\n}\n\nexport type RuntimeVirtualModuleOptions = {\n /** Whether to use the legacy Nitro API (nitropack/runtime) instead of the modern one (nitro/runtime-config). */\n legacyNitro: boolean;\n /** The property name in the runtime config where drizzle configuration is stored. */\n runtimeConfigProp: string;\n /** Hooks that are allowed to trigger the \"drizzle:init\" hook. */\n initHooks?: readonly string[];\n};\n\n/**\n * Generates the runtime virtual module code for datasource management.\n * @param datasources - The resolved datasource information\n * @param options - Runtime virtual module options\n * @returns The virtual module code string\n */\nexport function runtimeVirtualModule(\n datasources: readonly DatasourceInfo[],\n { legacyNitro, runtimeConfigProp, initHooks }: RuntimeVirtualModuleOptions,\n) {\n const datasourceRegistryParts = datasources\n .filter((datasource) => datasource.enabled)\n .flatMap(({ name, drivers }) => {\n return drivers.map((driver) => {\n return {\n name,\n driver,\n };\n });\n })\n .map(({ name, driver }, datasourceIndex) => {\n const connectorVarName = genConnectorModuleVariableName(datasourceIndex);\n\n const imports = [\n genImport(driver.imports.connector, connectorVarName),\n ...driver.imports.schema.map((schemaModuleId, schemaIndex) => {\n return genImport(schemaModuleId, {\n name: \"*\",\n as: genSchemaModuleVariableName(datasourceIndex, schemaIndex),\n });\n }),\n ];\n\n const mergedSchemaVariableName = genMergeSchemaVariableName(datasourceIndex);\n const mergedSchemaObject = mergeSchemaModules(driver.imports.schema, datasourceIndex);\n\n const schemaDefinitions = [\n /* js */ `const ${mergedSchemaVariableName} = ${mergedSchemaObject};`,\n ];\n\n const factoryObject = {\n name,\n driver: driver.name,\n factory: {\n create: /* js */ `(config) => ${connectorVarName}(config, ${mergedSchemaVariableName})`,\n schema: mergedSchemaVariableName,\n dialect: genString(driver.dialect),\n },\n };\n\n return {\n imports,\n schemaDefinitions,\n factoryObject,\n };\n })\n .reduce(\n (acc, { imports, schemaDefinitions, factoryObject }) => {\n const accFactoryObject = acc.factoryObject;\n accFactoryObject[factoryObject.name] ||= {};\n accFactoryObject[factoryObject.name][factoryObject.driver] = factoryObject.factory;\n\n return {\n imports: [...acc.imports, ...imports],\n schemaDefinitions: [...acc.schemaDefinitions, ...schemaDefinitions],\n factoryObject: accFactoryObject,\n };\n },\n {\n imports: [] as string[],\n schemaDefinitions: [] as string[],\n factoryObject: {} as { [name: string]: { [driver: string]: object } },\n },\n );\n\n const datasourceRegistryVarName = genSafeVariableName(\"datasourceRegistry\");\n\n const nitroRuntimeParts = {\n imports: [\n legacyNitro\n ? genImport(\"nitropack/runtime\", [\"useNitroApp\"])\n : genImport(\"nitro/app\", [\"useNitroHooks\"]),\n genImport(legacyNitro ? \"nitropack/runtime\" : \"nitro/runtime-config\", [\n {\n name: \"useRuntimeConfig\",\n as: \"useNitroRuntimeConfig\",\n },\n ]),\n ],\n declarations: [\n script /* js */ `\n export function useRuntimeConfig() {\n const runtimeConfig = useNitroRuntimeConfig();\n return runtimeConfig[${genString(runtimeConfigProp)}]\n }\n\n ${\n legacyNitro\n ? script /* js */ `\n function useNitroHooks() {\n return useNitroApp().hooks;\n }\n `\n : \"\"\n }\n\n export function onServerClose(cb) {\n return useNitroHooks().hook(\"close\", cb);\n }\n\n export function callConfigHook(...args) {\n return useNitroHooks().callHook(\"drizzle:config\", ...args);\n }\n `,\n ],\n exports: [genExport(legacyNitro ? \"nitropack/runtime\" : \"nitro/storage\", [\"useStorage\"])],\n };\n\n return script /* js */ `\n ${datasourceRegistryParts.imports.join(\"\\n\")}\n ${nitroRuntimeParts.imports.join(\"\\n\")}\n \n ${datasourceRegistryParts.schemaDefinitions.join(\"\\n\")}\n \n const ${datasourceRegistryVarName} = ${genObjectFromRaw(datasourceRegistryParts.factoryObject)};\n\n export function useDatasourceRegistry() {\n return ${datasourceRegistryVarName};\n }\n\n ${nitroRuntimeParts.declarations.join(\"\\n\")}\n\n ${nitroRuntimeParts.exports.join(\"\\n\")}\n\n export const initHooks = ${JSON.stringify(initHooks || [])};\n `;\n}\n\n// Replaced with aliases\nexport function dialectVirtualModules(\n datasources: readonly DatasourceInfo[],\n): VirtualModules<`#nitro-drizzle/${string}`> {\n return Object.fromEntries(\n datasources\n .filter((d) => d.enabled)\n .map(({ name }) => {\n return [\n `#nitro-drizzle/dialects/${name}`,\n `export {};`,\n // genExport(`nitro-drizzle/dialects/${dialect}`, \"*\"),\n ] as const;\n }),\n );\n}\n\nexport function migrationsVirtualModule(\n datasources: readonly DatasourceInfo[],\n options: MigrationOptions | undefined,\n): VirtualModules<`#nitro-drizzle/${string}`> {\n if (!options) {\n return {};\n }\n\n const parts: string[] = [];\n\n const enabledDatasources = datasources.filter((d) => d.enabled);\n\n parts.push(/*js*/ `\n export const migrationConfig = ${genObjectFromRawEntries(\n enabledDatasources.map(({ name, drivers }) => {\n return [\n name,\n genObjectFromRawEntries(\n drivers.map((driver) => {\n return [driver.name, JSON.stringify(driver.migrations.config)];\n }),\n ),\n ];\n }),\n )};\n `);\n\n let migrateOnInit = enabledDatasources.map((d) => d.name);\n if (options && Array.isArray(options.migrateOnInit)) {\n migrateOnInit = migrateOnInit.filter((name) =>\n (options.migrateOnInit as readonly string[]).includes(name),\n );\n }\n\n parts.push(script /*js*/ `\n export const MIGRATIONS_STORAGE_BASE = ${genString(options.storageBase)};\n export const MIGRATE_ON_INIT = ${genArrayFromRaw(migrateOnInit.map((name) => genString(name)))};\n `);\n\n return {\n \"#nitro-drizzle/migrations\": parts.join(\"\\n\"),\n };\n}\n"],"mappings":";;;AAaA,SAAS,+BAA+B,eAAuB;CAC7D,OAAO,oBAAoB,WAAW,eAAe;AACvD;AAEA,SAAS,2BAA2B,eAAuB;CACzD,OAAO,oBAAoB,eAAe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AAM,QAAkB,CAAC;CAEzB,MAAM,qBAAqB,YAAY,QAAQ,MAAM,EAAE,OAAO;CAE9D,MAAM,KAAY;qCACiB,wBAC/B,mBAAmB,KAAK,EAAE,MAAM,cAAc;EAC5C,OAAO,CACL,MACA,wBACE,QAAQ,KAAK,WAAW;GACtB,OAAO,CAAC,OAAO,MAAM,KAAK,UAAU,OAAO,WAAW,MAAM,CAAC;EAC/D,CAAC,CACH,CACF;CACF,CAAC,CACH,EAAE;GACH;CAED,IAAI,gBAAgB,mBAAmB,KAAK,MAAM,EAAE,IAAI;CACxD,IAAI,WAAW,MAAM,QAAQ,QAAQ,aAAa,GAChD,gBAAgB,cAAc,QAAQ,SACnC,QAAQ,cAAoC,SAAS,IAAI,CAC5D;CAGF,MAAM,KAAK,MAAc;6CACkB,UAAU,QAAQ,WAAW,EAAE;qCACvC,gBAAgB,cAAc,KAAK,SAAS,UAAU,IAAI,CAAC,CAAC,EAAE;GAChG;CAED,OAAO,EACL,6BAA6B,MAAM,KAAK,IAAI,EAC9C;AACF"}
1
+ {"version":3,"file":"virtual.mjs","names":[],"sources":["../../../src/context/internal/virtual.ts"],"sourcesContent":["import {\n genArrayFromRaw,\n genExport,\n genImport,\n genObjectFromRaw,\n genObjectFromRawEntries,\n genSafeVariableName,\n genString,\n} from \"knitwork\";\nimport type { DatasourceInfo, MigrationOptions } from \"..\";\nimport type { VirtualModules } from \"nitro-drizzle/shared\";\nimport { script } from \"./format\";\n\nfunction genConnectorModuleVariableName(dbModuleIndex: number) {\n return genSafeVariableName(`dbModule${dbModuleIndex}`);\n}\n\nfunction genMergeSchemaVariableName(dbModuleIndex: number) {\n return genSafeVariableName(`mergedSchema${dbModuleIndex}`);\n}\n\nconst genSchemaModuleVariableName = (dbModuleIndex: number, schemaIndex: number) =>\n genSafeVariableName(`schemaModule${dbModuleIndex}_${schemaIndex}`);\n\nfunction mergeSchemaModules(schemaIds: readonly string[], dbModuleIndex: number) {\n return /* js */ `\n Object.assign(\n ${[\n /* js */ `{}`,\n ...schemaIds.map((_, schemaModuleIdIndex) =>\n genSchemaModuleVariableName(dbModuleIndex, schemaModuleIdIndex),\n ),\n ].join(\",\")}\n )\n `;\n}\n\nexport type RuntimeVirtualModuleOptions = {\n /** Whether to use the legacy Nitro API (nitropack/runtime) instead of the modern one (nitro/runtime-config). */\n legacyNitro: boolean;\n /** The property name in the runtime config where drizzle configuration is stored. */\n runtimeConfigProp: string;\n /** Hooks that are allowed to trigger the \"drizzle:init\" hook. */\n initHooks?: readonly string[];\n};\n\n/**\n * Generates the runtime virtual module code for datasource management.\n * @param datasources - The resolved datasource information\n * @param options - Runtime virtual module options\n * @returns The virtual module code string\n */\nexport function runtimeVirtualModule(\n datasources: readonly DatasourceInfo[],\n { legacyNitro, runtimeConfigProp, initHooks }: RuntimeVirtualModuleOptions,\n) {\n const datasourceRegistryParts = datasources\n .filter((datasource) => datasource.enabled)\n .flatMap(({ name, drivers }) => {\n return drivers.map((driver) => {\n return {\n name,\n driver,\n };\n });\n })\n .filter(({ driver }) => {\n return driver.enabled;\n })\n .map(({ name, driver }, datasourceIndex) => {\n const connectorVarName = genConnectorModuleVariableName(datasourceIndex);\n\n const imports = [\n genImport(driver.imports.connector, connectorVarName),\n ...driver.imports.schema.map((schemaModuleId, schemaIndex) => {\n return genImport(schemaModuleId, {\n name: \"*\",\n as: genSchemaModuleVariableName(datasourceIndex, schemaIndex),\n });\n }),\n ];\n\n const mergedSchemaVariableName = genMergeSchemaVariableName(datasourceIndex);\n const mergedSchemaObject = mergeSchemaModules(driver.imports.schema, datasourceIndex);\n\n const schemaDefinitions = [\n /* js */ `const ${mergedSchemaVariableName} = ${mergedSchemaObject};`,\n ];\n\n const factoryObject = {\n name,\n driver: driver.name,\n factory: {\n create: /* js */ `(config) => ${connectorVarName}(config, ${mergedSchemaVariableName})`,\n schema: mergedSchemaVariableName,\n dialect: genString(driver.dialect),\n },\n };\n\n return {\n imports,\n schemaDefinitions,\n factoryObject,\n };\n })\n .reduce(\n (acc, { imports, schemaDefinitions, factoryObject }) => {\n const accFactoryObject = acc.factoryObject;\n accFactoryObject[factoryObject.name] ||= {};\n accFactoryObject[factoryObject.name][factoryObject.driver] = factoryObject.factory;\n\n return {\n imports: [...acc.imports, ...imports],\n schemaDefinitions: [...acc.schemaDefinitions, ...schemaDefinitions],\n factoryObject: accFactoryObject,\n };\n },\n {\n imports: [] as string[],\n schemaDefinitions: [] as string[],\n factoryObject: {} as { [name: string]: { [driver: string]: object } },\n },\n );\n\n const datasourceRegistryVarName = genSafeVariableName(\"datasourceRegistry\");\n\n const nitroRuntimeParts = {\n imports: [\n legacyNitro\n ? genImport(\"nitropack/runtime\", [\"useNitroApp\"])\n : genImport(\"nitro/app\", [\"useNitroHooks\"]),\n genImport(legacyNitro ? \"nitropack/runtime\" : \"nitro/runtime-config\", [\n {\n name: \"useRuntimeConfig\",\n as: \"useNitroRuntimeConfig\",\n },\n ]),\n ],\n declarations: [\n script /* js */ `\n export function useRuntimeConfig() {\n const runtimeConfig = useNitroRuntimeConfig();\n return runtimeConfig[${genString(runtimeConfigProp)}]\n }\n\n ${\n legacyNitro\n ? script /* js */ `\n function useNitroHooks() {\n return useNitroApp().hooks;\n }\n `\n : \"\"\n }\n\n export function onServerClose(cb) {\n return useNitroHooks().hook(\"close\", cb);\n }\n\n export function callConfigHook(...args) {\n return useNitroHooks().callHook(\"drizzle:config\", ...args);\n }\n `,\n ],\n exports: [genExport(legacyNitro ? \"nitropack/runtime\" : \"nitro/storage\", [\"useStorage\"])],\n };\n\n return script /* js */ `\n ${datasourceRegistryParts.imports.join(\"\\n\")}\n ${nitroRuntimeParts.imports.join(\"\\n\")}\n \n ${datasourceRegistryParts.schemaDefinitions.join(\"\\n\")}\n \n const ${datasourceRegistryVarName} = ${genObjectFromRaw(datasourceRegistryParts.factoryObject)};\n\n export function useDatasourceRegistry() {\n return ${datasourceRegistryVarName};\n }\n\n ${nitroRuntimeParts.declarations.join(\"\\n\")}\n\n ${nitroRuntimeParts.exports.join(\"\\n\")}\n\n export const initHooks = ${JSON.stringify(initHooks || [])};\n `;\n}\n\n// Replaced with aliases\nexport function dialectVirtualModules(\n datasources: readonly DatasourceInfo[],\n): VirtualModules<`#nitro-drizzle/${string}`> {\n return Object.fromEntries(\n datasources\n .filter((d) => d.enabled)\n .map(({ name }) => {\n return [\n `#nitro-drizzle/dialects/${name}`,\n `export {};`,\n // genExport(`nitro-drizzle/dialects/${dialect}`, \"*\"),\n ] as const;\n }),\n );\n}\n\nexport function migrationsVirtualModule(\n datasources: readonly DatasourceInfo[],\n options: MigrationOptions | undefined,\n): VirtualModules<`#nitro-drizzle/${string}`> {\n if (!options) {\n return {};\n }\n\n const parts: string[] = [];\n\n const enabledDatasources = datasources.filter((d) => d.enabled);\n\n parts.push(/*js*/ `\n export const migrationConfig = ${genObjectFromRawEntries(\n enabledDatasources.map(({ name, drivers }) => {\n return [\n name,\n genObjectFromRawEntries(\n drivers.map((driver) => {\n return [driver.name, JSON.stringify(driver.migrations.config)];\n }),\n ),\n ];\n }),\n )};\n `);\n\n let migrateOnInit = enabledDatasources.map((d) => d.name);\n if (options && Array.isArray(options.migrateOnInit)) {\n migrateOnInit = migrateOnInit.filter((name) =>\n (options.migrateOnInit as readonly string[]).includes(name),\n );\n }\n\n parts.push(script /*js*/ `\n export const MIGRATIONS_STORAGE_BASE = ${genString(options.storageBase)};\n export const MIGRATE_ON_INIT = ${genArrayFromRaw(migrateOnInit.map((name) => genString(name)))};\n `);\n\n return {\n \"#nitro-drizzle/migrations\": parts.join(\"\\n\"),\n };\n}\n"],"mappings":";;;AAaA,SAAS,+BAA+B,eAAuB;CAC7D,OAAO,oBAAoB,WAAW,eAAe;AACvD;AAEA,SAAS,2BAA2B,eAAuB;CACzD,OAAO,oBAAoB,eAAe,eAAe;AAC3D;AAEA,MAAM,+BAA+B,eAAuB,gBAC1D,oBAAoB,eAAe,cAAc,GAAG,aAAa;AAEnE,SAAS,mBAAmB,WAA8B,eAAuB;CAC/E,OAAg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CAE9D,MAAM,KAAY;qCACiB,wBAC/B,mBAAmB,KAAK,EAAE,MAAM,cAAc;EAC5C,OAAO,CACL,MACA,wBACE,QAAQ,KAAK,WAAW;GACtB,OAAO,CAAC,OAAO,MAAM,KAAK,UAAU,OAAO,WAAW,MAAM,CAAC;EAC/D,CAAC,CACH,CACF;CACF,CAAC,CACH,EAAE;GACH;CAED,IAAI,gBAAgB,mBAAmB,KAAK,MAAM,EAAE,IAAI;CACxD,IAAI,WAAW,MAAM,QAAQ,QAAQ,aAAa,GAChD,gBAAgB,cAAc,QAAQ,SACnC,QAAQ,cAAoC,SAAS,IAAI,CAC5D;CAGF,MAAM,KAAK,MAAc;6CACkB,UAAU,QAAQ,WAAW,EAAE;qCACvC,gBAAgB,cAAc,KAAK,SAAS,UAAU,IAAI,CAAC,CAAC,EAAE;GAChG;CAED,OAAO,EACL,6BAA6B,MAAM,KAAK,IAAI,EAC9C;AACF"}
@@ -104,6 +104,7 @@ interface DatasourceInfo {
104
104
  }
105
105
  /** Options for a specific driver within a datasource. */
106
106
  type DriverOptions = {
107
+ enabled: boolean;
107
108
  name: string;
108
109
  dialect: string;
109
110
  imports: {
package/dist/context.mjs CHANGED
@@ -71,15 +71,30 @@ var DefaultContext = class {
71
71
  return 1;
72
72
  });
73
73
  const datasources = Object.entries(datasourceOptions).map(([name, options]) => {
74
+ const connectorOptions = Array.isArray(options.drivers) ? options.drivers.reduce((acc, driver) => {
75
+ const match = driver.match(/^([_-]*)([^_]+)/);
76
+ if (!match) throw new Error("Invalid driver name format");
77
+ const [_, disabled, driverName] = match;
78
+ return {
79
+ ...acc,
80
+ [driverName]: { enabled: !disabled }
81
+ };
82
+ }, {}) : Object.entries(options.drivers).reduce((acc, [name, enabled]) => {
83
+ return {
84
+ ...acc,
85
+ [name]: { enabled }
86
+ };
87
+ }, {});
74
88
  return {
75
89
  name,
76
90
  enabled: true,
77
- drivers: (Array.isArray(options.drivers) ? options.drivers : Object.entries(options.drivers).filter(([_name, enabled]) => enabled).map(([name]) => name)).map((driverName) => {
91
+ drivers: Object.entries(connectorOptions).map(([driverName, options]) => {
78
92
  const dialect = driverToDialect(driverName);
79
93
  const drizzleConfig = drizzleConfigs.find((config) => {
80
94
  return config.name == name && config.dialect == dialect;
81
95
  });
82
96
  return {
97
+ enabled: options.enabled,
83
98
  name: driverName,
84
99
  dialect,
85
100
  imports: {
@@ -89,7 +104,7 @@ var DefaultContext = class {
89
104
  },
90
105
  migrations: { ...drizzleConfig?.migrations }
91
106
  };
92
- })
107
+ }).sort((a, b) => (b.enabled ? 1 : 0) - (a.enabled ? 1 : 0))
93
108
  };
94
109
  });
95
110
  logger?.info("Found drizzle datasources:", datasources.toSorted((datasource) => {
@@ -97,7 +112,7 @@ var DefaultContext = class {
97
112
  }).map((datasource) => {
98
113
  let msg = [datasource.name];
99
114
  let color;
100
- if (datasource.enabled) color = "greenBright";
115
+ if (datasource.enabled) color = "yellow";
101
116
  else {
102
117
  color = "gray";
103
118
  msg.push("(disabled)");
@@ -106,8 +121,15 @@ var DefaultContext = class {
106
121
  }).join(", "));
107
122
  const enabledDatasources = datasources.filter((d) => d.enabled);
108
123
  logger?.info(accent`Using ${enabledDatasources.length} of ${datasources.length} resolved datasources` + (enabledDatasources.length > 0 ? ":" : ""), enabledDatasources.map((datasource) => {
109
- return [colorize("greenBright", datasource.name), colorize("yellow", "(" + datasource.drivers.map((driver) => driver.name).join(", ") + ")")].join(" ");
110
- }).join(", "));
124
+ return [
125
+ "\n ",
126
+ colorize("yellow", datasource.name),
127
+ "(" + datasource.drivers.map((driver) => {
128
+ const [color, postfix] = driver.enabled ? ["greenBright", ""] : ["strikethrough", " (types only)"];
129
+ return colorize("gray", [colorize(color, driver.name), postfix].join(""));
130
+ }).join(", ") + ")"
131
+ ].join(" ");
132
+ }).join(""));
111
133
  this.#datasources = datasources;
112
134
  }
113
135
  return this.#datasources;
@@ -1 +1 @@
1
- {"version":3,"file":"context.mjs","names":["#options","#datasources"],"sources":["../src/context/index.ts"],"sourcesContent":["import type { ConsolaInstance } from \"consola\";\nimport { colorize, type ColorName } from \"consola/utils\";\nimport type { Config, Config as DrizzleConfig } from \"drizzle-kit\";\nimport { loadConfig } from \"c12\";\nimport { pkgDir, pkgName } from \"nitro-drizzle/meta\";\n\nimport { mapAsync } from \"./internal/async\";\nimport { accent } from \"./internal/logger\";\nimport { resolveFiles } from \"./internal/fs\";\nimport {\n dialectDeclarations,\n moduleTypeDeclarations,\n runtimeDeclarations,\n sharedTypeDeclarations,\n} from \"./internal/templates\";\nimport { transformDrizzleConfig } from \"./internal/config\";\nimport {\n dialectVirtualModules,\n migrationsVirtualModule,\n runtimeVirtualModule,\n} from \"./internal/virtual\";\n\nimport type { MaybePromise, NitroHookName, VirtualModules } from \"nitro-drizzle/shared\";\nimport type { ServerAssetDir as LegacyServerAssetDir } from \"nitropack/types\";\nimport type { ServerAssetDir } from \"nitro/types\";\nimport { join } from \"pathe\";\nimport { genReference } from \"./internal/codegen\";\n\n/**\n * Context interface for managing Drizzle datasource configurations.\n */\nexport interface Context {\n init(): MaybePromise<void>;\n /**\n * Reloads the context, clearing any cached datasource information.\n */\n reload(): MaybePromise<void>;\n /**\n * Returns a list of all resolved datasource information.\n */\n datasources(): MaybePromise<DatasourceInfo[]>;\n}\n\nclass DefaultContext implements Context {\n #datasources: DatasourceInfo[] | null = null;\n readonly #options: ContextOptions;\n\n constructor(options: ContextOptions) {\n this.#options = options;\n }\n\n async init(): Promise<void> {\n const datasources = await this.datasources();\n\n await this.#options.plugins(this.enabledPlugins());\n\n const [sharedTypes, virtualModules, virtualTypes, moduleTypes, runtimeTypes] =\n await Promise.all([\n sharedTypeDeclarations(datasources),\n this.virtualModules(datasources),\n this.virtualTypeDeclarations(datasources),\n this.moduleTypeDeclarations(datasources),\n this.runtimeTypeDeclarations(datasources),\n ]);\n\n await this.#options.virtualModules(virtualModules);\n\n await this.#options.declarations({\n shared: sharedTypes,\n module: moduleTypes,\n runtime: runtimeTypes,\n virtual: virtualTypes,\n });\n\n if (this.#options.migrations) {\n const assets = await this.migrationAssets(datasources);\n if (assets) {\n await this.#options.assets(assets);\n }\n\n await this.#options.tasks?.({\n \"drizzle:migrate\": {\n description: \"Run drizzle migrations for a datasource.\",\n handler: \"nitro-drizzle/migrations/task\",\n },\n });\n }\n\n if (this.#options.externals) {\n const inlineModuleIds = [\"runtime\", \"plugins\", \"migrations\"].flatMap((id) => {\n return [join(pkgName, id), join(pkgDir, \"dist\", id)];\n });\n\n await this.#options.externals(inlineModuleIds);\n }\n }\n\n async datasources() {\n const {\n logger,\n baseDir,\n configPattern,\n resolver,\n datasources: datasourceOptions,\n } = this.#options;\n\n if (!this.#datasources) {\n logger?.info(\"Searching drizzle datasources in\", colorize(\"blue\", baseDir));\n\n const drizzleConfigsResolvedPaths = await resolveFiles(\n baseDir,\n [configPattern].flat().map((pattern) => \"*/\" + pattern),\n );\n\n const drizzleConfigs = [\n ...(await mapAsync(drizzleConfigsResolvedPaths, async (path) => {\n const [_, dirName] = path.match(/(.+\\/(.+))\\/.+$/)!.slice(1, 3) as [string, string];\n const { config } = await loadConfig<DrizzleConfig>({\n configFile: path,\n });\n\n return await transformDrizzleConfig(config, {\n cwd: this.#options.cwd,\n path,\n dirName,\n resolver,\n });\n })),\n ].sort((a, b) => {\n if (a.driver && b.driver) {\n return 0;\n }\n return 1;\n });\n\n const datasources: DatasourceInfo[] = Object.entries(datasourceOptions).map(\n ([name, options]) => {\n const drivers: readonly string[] = Array.isArray(options.drivers)\n ? options.drivers\n : Object.entries(options.drivers as { [name: string]: boolean })\n .filter(([_name, enabled]) => enabled)\n .map(([name]) => name);\n return {\n name,\n enabled: true,\n drivers: drivers.map((driverName) => {\n const dialect = driverToDialect(driverName);\n const drizzleConfig = drizzleConfigs.find((config) => {\n return config.name == name && config.dialect == dialect;\n });\n return {\n name: driverName,\n dialect,\n imports: {\n connector: `nitro-drizzle/drivers/${driverName}`,\n helpers: `nitro-drizzle/dialects/${dialect}`,\n schema: drizzleConfig?.imports.schema || [],\n },\n migrations: {\n ...drizzleConfig?.migrations,\n },\n };\n }),\n } satisfies DatasourceInfo;\n },\n );\n\n logger?.info(\n \"Found drizzle datasources:\",\n datasources\n .toSorted((datasource) => {\n return datasource.enabled ? -1 : 1;\n })\n .map((datasource) => {\n let msg = [datasource.name];\n let color: ColorName;\n if (datasource.enabled) {\n color = \"greenBright\";\n } else {\n color = \"gray\";\n msg.push(\"(disabled)\");\n }\n return colorize(color, msg.join(\" \"));\n })\n .join(\", \"),\n );\n\n const enabledDatasources = datasources.filter((d) => d.enabled);\n\n logger?.info(\n accent`Using ${enabledDatasources.length} of ${datasources.length} resolved datasources` +\n (enabledDatasources.length > 0 ? \":\" : \"\"),\n enabledDatasources\n .map((datasource) => {\n return [\n colorize(\"greenBright\", datasource.name),\n colorize(\n \"yellow\",\n \"(\" + datasource.drivers.map((driver) => driver.name).join(\", \") + \")\",\n ),\n ].join(\" \");\n })\n .join(\", \"),\n );\n\n this.#datasources = datasources;\n }\n\n return this.#datasources;\n }\n\n private async migrationAssets(\n datasources: readonly DatasourceInfo[],\n ): Promise<readonly (ServerAssetDir | LegacyServerAssetDir)[]> {\n const migrationOptions = this.#options.migrations;\n\n if (!migrationOptions) {\n return [];\n }\n\n return datasources\n .flatMap((datasource) => {\n return datasource.drivers.map((driver) => {\n return {\n name: datasource.name,\n driver: driver.name,\n dialect: driver.dialect,\n migrations: driver.migrations,\n };\n });\n })\n .reduce(\n (acc, { name, driver, migrations }) => {\n const dir = migrations.assets;\n if (dir) {\n acc.push({\n baseName: [migrationOptions.storageBase, name, driver].join(\":\"),\n dir,\n /**\n * @todo Doesn't work in dev mode - 'fs' driver does not support 'pattern'\n * Disabled - include all files to use with meta/_journal.json\n */\n // pattern: '*.sql',\n });\n }\n return acc;\n },\n [] as (ServerAssetDir | LegacyServerAssetDir)[],\n );\n }\n\n private async virtualTypeDeclarations(\n datasources: readonly DatasourceInfo[],\n ): Promise<Record<string, VirtualModules<`${string}.d.ts`>>> {\n return {\n \"#nitro-drizzle/*\": {\n \"nitro-drizzle/virtual.d.ts\": [dialectDeclarations(datasources)].join(\"\\n\"),\n },\n };\n }\n\n private enabledPlugins(): readonly string[] {\n const plugins: (\"init\" | \"migrate\")[] = [];\n\n const migrationOptions = this.#options.migrations;\n const enableMigrationPlugin = migrationOptions\n ? Array.isArray(migrationOptions)\n ? 0 < migrationOptions.length\n : true == migrationOptions.migrateOnInit\n : false;\n\n if (enableMigrationPlugin) {\n plugins.push(\"migrate\");\n }\n\n plugins.push(\"init\");\n\n let pluginIds: readonly string[] = plugins;\n if (this.#options.legacy) {\n pluginIds = pluginIds.map((pluginName) => `legacy/${pluginName}`);\n }\n pluginIds = pluginIds.map((pluginName) => `nitro-drizzle/plugins/${pluginName}`);\n\n return pluginIds;\n }\n\n private async moduleTypeDeclarations(\n datasources: readonly DatasourceInfo[],\n ): Promise<VirtualModules> {\n return moduleTypeDeclarations(datasources);\n }\n\n private async runtimeTypeDeclarations(\n datasources: readonly DatasourceInfo[],\n ): Promise<VirtualModules<`${string}.d.ts`>> {\n const references = new Set([\n { types: \"nitro-drizzle/runtime\" },\n ...this.enabledPlugins().map((pluginId) => {\n return { types: pluginId };\n }),\n ]);\n if (!this.#options.legacy) {\n references.add({ types: \"nitro-drizzle/middleware/context\" });\n }\n const content = [\n ...[...references.values()].map((reference) => genReference(reference)),\n runtimeDeclarations(datasources),\n /* ts */ `export {};`,\n ].join(\"\\n\");\n return {\n \"nitro-drizzle/runtime.d.ts\": content,\n };\n }\n\n private async virtualModules(\n datasources: readonly DatasourceInfo[],\n ): Promise<VirtualModules<`#nitro-drizzle/${string}`>> {\n return {\n \"#nitro-drizzle/runtime\": runtimeVirtualModule(datasources, {\n legacyNitro: this.#options.legacy,\n runtimeConfigProp: \"drizzle\",\n initHooks: this.#options.initHooks,\n }),\n ...dialectVirtualModules(datasources),\n ...migrationsVirtualModule(datasources, this.#options.migrations),\n };\n }\n\n reload() {\n this.#datasources = null;\n }\n}\n\nfunction driverToDialect(driver: string) {\n let dialect = driver;\n if (driver.startsWith(\"d1\")) {\n dialect = \"sqlite\";\n }\n if (driver == \"pglite\") {\n dialect = \"postgresql\";\n }\n return dialect;\n}\n\n/**\n * Glob pattern or array of patterns to match Drizzle configuration files.\n */\nexport type ConfigPattern = string | readonly string[];\n\n/**\n * Resolver interface for importing modules and resolving paths.\n */\nexport interface Resolver {\n /**\n * Resolves a module ID to its full path.\n */\n resolve(id: string): string;\n}\n\nexport type ContextHook<TArgs extends readonly any[] = []> = (\n this: void,\n ...args: TArgs\n) => MaybePromise<void>;\n\nexport interface MigrationOptions {\n /** Base storage key path for migrations. */\n storageBase: string;\n /** Whether and which datasources to migrate on initialization. */\n migrateOnInit: boolean | readonly string[];\n}\n\nexport interface ContextOptions {\n legacy: boolean;\n\n logger?: ConsolaInstance;\n /**\n * Current working directory\n */\n cwd: string;\n /**\n * Base project directory to search drizzle config files\n */\n baseDir: string;\n /**\n * Pattern for drizzle config files\n */\n configPattern: ConfigPattern;\n /**\n * Nuxt Kit resolver\n */\n resolver: Resolver;\n /**\n * Connector options\n */\n datasources: Record<string, { drivers: readonly string[] | { [name: string]: boolean } }>;\n\n migrations: MigrationOptions | undefined;\n\n /**\n * Hooks that allowed to call \"drizzle:init\" hook.\n */\n initHooks?: readonly NitroHookName[];\n\n tasks?: ContextHook<\n [\n tasks: Record<\n string,\n {\n handler: string;\n description: string;\n }\n >,\n ]\n >;\n\n plugins: ContextHook<[plugins: readonly string[]]>;\n\n declarations: ContextHook<\n [\n declarations: {\n shared: VirtualModules<`${string}.d.ts`>;\n module: VirtualModules<`${string}.d.ts`>;\n runtime: VirtualModules<`${string}.d.ts`>;\n virtual: Record<string, VirtualModules<`${string}.d.ts`>>;\n },\n ]\n >;\n\n virtualModules: ContextHook<[modules: VirtualModules]>;\n\n assets: ContextHook<[assets: readonly (ServerAssetDir | LegacyServerAssetDir)[]]>;\n\n externals?: ContextHook<[modules: readonly string[]]>;\n}\n\n/**\n * Creates a Context instance for managing Drizzle datasource configurations.\n * @param options - Configuration options for the context\n * @returns A Context instance\n */\nexport function createContext(options: ContextOptions): Context {\n return new DefaultContext(options);\n}\n\n/**\n * Information about a resolved Drizzle datasource.\n */\nexport interface DatasourceInfo {\n /** Unique name identifier for the datasource. */\n name: string;\n /** Whether the datasource is enabled (filtered by connector configuration). */\n enabled: boolean;\n /** Driver configurations for this datasource. */\n drivers: readonly DriverOptions[];\n}\n\n/** Options for a specific driver within a datasource. */\nexport type DriverOptions = {\n name: string;\n dialect: string;\n imports: {\n // config: string;\n schema: readonly string[];\n connector: string;\n helpers: string;\n };\n /** Migration configuration for this datasource driver. */\n migrations: {\n assets?: string;\n config?: Config[\"migrations\"];\n };\n};\n"],"mappings":";;;;;;;;;;;;AA2CA,IAAM,iBAAN,MAAwC;CACtC,eAAwC;CACxC;CAEA,YAAY,SAAyB;EACnC,KAAKA,WAAW;CAClB;CAEA,MAAM,OAAsB;EAC1B,MAAM,cAAc,MAAM,KAAK,YAAY;EAE3C,MAAM,KAAKA,SAAS,QAAQ,KAAK,eAAe,CAAC;EAEjD,MAAM,CAAC,aAAa,gBAAgB,cAAc,aAAa,gBAC7D,MAAM,QAAQ,IAAI;GAChB,uBAAuB,WAAW;GAClC,KAAK,eAAe,WAAW;GAC/B,KAAK,wBAAwB,WAAW;GACxC,KAAK,uBAAuB,WAAW;GACvC,KAAK,wBAAwB,WAAW;EAC1C,CAAC;EAEH,MAAM,KAAKA,SAAS,eAAe,cAAc;EAEjD,MAAM,KAAKA,SAAS,aAAa;GAC/B,QAAQ;GACR,QAAQ;GACR,SAAS;GACT,SAAS;EACX,CAAC;EAED,IAAI,KAAKA,SAAS,YAAY;GAC5B,MAAM,SAAS,MAAM,KAAK,gBAAgB,WAAW;GACrD,IAAI,QACF,MAAM,KAAKA,SAAS,OAAO,MAAM;GAGnC,MAAM,KAAKA,SAAS,QAAQ,EAC1B,mBAAmB;IACjB,aAAa;IACb,SAAS;GACX,EACF,CAAC;EACH;EAEA,I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GACtE,oBAAoB,WAAW;GACtB;EACX,CAAC,CAAC,KAAK,IAE+B,EACtC;CACF;CAEA,MAAc,eACZ,aACqD;EACrD,OAAO;GACL,0BAA0B,qBAAqB,aAAa;IAC1D,aAAa,KAAKA,SAAS;IAC3B,mBAAmB;IACnB,WAAW,KAAKA,SAAS;GAC3B,CAAC;GACD,GAAG,sBAAsB,WAAW;GACpC,GAAG,wBAAwB,aAAa,KAAKA,SAAS,UAAU;EAClE;CACF;CAEA,SAAS;EACP,KAAKC,eAAe;CACtB;AACF;AAEA,SAAS,gBAAgB,QAAgB;CACvC,IAAI,UAAU;CACd,IAAI,OAAO,WAAW,IAAI,GACxB,UAAU;CAEZ,IAAI,UAAU,UACZ,UAAU;CAEZ,OAAO;AACT;;;;;;AAkGA,SAAgB,cAAc,SAAkC;CAC9D,OAAO,IAAI,eAAe,OAAO;AACnC"}
1
+ {"version":3,"file":"context.mjs","names":[],"sources":["../src/context/index.ts"],"sourcesContent":["import type { ConsolaInstance } from \"consola\";\nimport { colorize, type ColorName } from \"consola/utils\";\nimport type { Config, Config as DrizzleConfig } from \"drizzle-kit\";\nimport { loadConfig } from \"c12\";\nimport { pkgDir, pkgName } from \"nitro-drizzle/meta\";\n\nimport { mapAsync } from \"./internal/async\";\nimport { accent } from \"./internal/logger\";\nimport { resolveFiles } from \"./internal/fs\";\nimport {\n dialectDeclarations,\n moduleTypeDeclarations,\n runtimeDeclarations,\n sharedTypeDeclarations,\n} from \"./internal/templates\";\nimport { transformDrizzleConfig } from \"./internal/config\";\nimport {\n dialectVirtualModules,\n migrationsVirtualModule,\n runtimeVirtualModule,\n} from \"./internal/virtual\";\n\nimport type { MaybePromise, NitroHookName, VirtualModules } from \"nitro-drizzle/shared\";\nimport type { ServerAssetDir as LegacyServerAssetDir } from \"nitropack/types\";\nimport type { ServerAssetDir } from \"nitro/types\";\nimport { join } from \"pathe\";\nimport { genReference } from \"./internal/codegen\";\n\n/**\n * Context interface for managing Drizzle datasource configurations.\n */\nexport interface Context {\n init(): MaybePromise<void>;\n /**\n * Reloads the context, clearing any cached datasource information.\n */\n reload(): MaybePromise<void>;\n /**\n * Returns a list of all resolved datasource information.\n */\n datasources(): MaybePromise<DatasourceInfo[]>;\n}\n\nclass DefaultContext implements Context {\n #datasources: DatasourceInfo[] | null = null;\n readonly #options: ContextOptions;\n\n constructor(options: ContextOptions) {\n this.#options = options;\n }\n\n async init(): Promise<void> {\n const datasources = await this.datasources();\n\n await this.#options.plugins(this.enabledPlugins());\n\n const [sharedTypes, virtualModules, virtualTypes, moduleTypes, runtimeTypes] =\n await Promise.all([\n sharedTypeDeclarations(datasources),\n this.virtualModules(datasources),\n this.virtualTypeDeclarations(datasources),\n this.moduleTypeDeclarations(datasources),\n this.runtimeTypeDeclarations(datasources),\n ]);\n\n await this.#options.virtualModules(virtualModules);\n\n await this.#options.declarations({\n shared: sharedTypes,\n module: moduleTypes,\n runtime: runtimeTypes,\n virtual: virtualTypes,\n });\n\n if (this.#options.migrations) {\n const assets = await this.migrationAssets(datasources);\n if (assets) {\n await this.#options.assets(assets);\n }\n\n await this.#options.tasks?.({\n \"drizzle:migrate\": {\n description: \"Run drizzle migrations for a datasource.\",\n handler: \"nitro-drizzle/migrations/task\",\n },\n });\n }\n\n if (this.#options.externals) {\n const inlineModuleIds = [\"runtime\", \"plugins\", \"migrations\"].flatMap((id) => {\n return [join(pkgName, id), join(pkgDir, \"dist\", id)];\n });\n\n await this.#options.externals(inlineModuleIds);\n }\n }\n\n async datasources() {\n const {\n logger,\n baseDir,\n configPattern,\n resolver,\n datasources: datasourceOptions,\n } = this.#options;\n\n if (!this.#datasources) {\n logger?.info(\"Searching drizzle datasources in\", colorize(\"blue\", baseDir));\n\n const drizzleConfigsResolvedPaths = await resolveFiles(\n baseDir,\n [configPattern].flat().map((pattern) => \"*/\" + pattern),\n );\n\n const drizzleConfigs = [\n ...(await mapAsync(drizzleConfigsResolvedPaths, async (path) => {\n const [_, dirName] = path.match(/(.+\\/(.+))\\/.+$/)!.slice(1, 3) as [string, string];\n const { config } = await loadConfig<DrizzleConfig>({\n configFile: path,\n });\n\n return await transformDrizzleConfig(config, {\n cwd: this.#options.cwd,\n path,\n dirName,\n resolver,\n });\n })),\n ].sort((a, b) => {\n if (a.driver && b.driver) {\n return 0;\n }\n return 1;\n });\n\n const datasources: DatasourceInfo[] = Object.entries(datasourceOptions).map(\n ([name, options]) => {\n const connectorOptions = Array.isArray(options.drivers)\n ? (options.drivers as string[]).reduce(\n (acc, driver) => {\n const match = driver.match(/^([_-]*)([^_]+)/);\n if (!match) throw new Error(\"Invalid driver name format\");\n const [_, disabled, driverName] = match;\n return {\n ...acc,\n [driverName]: { enabled: !disabled },\n };\n },\n {} as { [driver: string]: { enabled: boolean } },\n )\n : Object.entries(options.drivers as { [name: string]: boolean }).reduce(\n (acc, [name, enabled]) => {\n return {\n ...acc,\n [name]: { enabled },\n };\n },\n {} as { [driver: string]: { enabled: boolean } },\n );\n\n return {\n name,\n enabled: true,\n drivers: Object.entries(connectorOptions)\n .map(([driverName, options]) => {\n const dialect = driverToDialect(driverName);\n const drizzleConfig = drizzleConfigs.find((config) => {\n return config.name == name && config.dialect == dialect;\n });\n return {\n enabled: options.enabled,\n name: driverName,\n dialect,\n imports: {\n connector: `nitro-drizzle/drivers/${driverName}`,\n helpers: `nitro-drizzle/dialects/${dialect}`,\n schema: drizzleConfig?.imports.schema || [],\n },\n migrations: {\n ...drizzleConfig?.migrations,\n },\n };\n })\n .sort((a, b) => (b.enabled ? 1 : 0) - (a.enabled ? 1 : 0)),\n } satisfies DatasourceInfo;\n },\n );\n\n logger?.info(\n \"Found drizzle datasources:\",\n datasources\n .toSorted((datasource) => {\n return datasource.enabled ? -1 : 1;\n })\n .map((datasource) => {\n let msg = [datasource.name];\n let color: ColorName;\n if (datasource.enabled) {\n color = \"yellow\";\n } else {\n color = \"gray\";\n msg.push(\"(disabled)\");\n }\n return colorize(color, msg.join(\" \"));\n })\n .join(\", \"),\n );\n\n const enabledDatasources = datasources.filter((d) => d.enabled);\n\n logger?.info(\n accent`Using ${enabledDatasources.length} of ${datasources.length} resolved datasources` +\n (enabledDatasources.length > 0 ? \":\" : \"\"),\n enabledDatasources\n .map((datasource) => {\n return [\n \"\\n\\t\",\n colorize(\"yellow\", datasource.name),\n \"(\" +\n datasource.drivers\n .map((driver) => {\n const [color, postfix] = driver.enabled\n ? ([\"greenBright\", \"\"] as const)\n : ([\"strikethrough\", \" (types only)\"] as const);\n\n return colorize(\"gray\", [colorize(color, driver.name), postfix].join(\"\"));\n })\n .join(\", \") +\n \")\",\n ].join(\" \");\n })\n .join(\"\"),\n );\n\n this.#datasources = datasources;\n }\n\n return this.#datasources;\n }\n\n private async migrationAssets(\n datasources: readonly DatasourceInfo[],\n ): Promise<readonly (ServerAssetDir | LegacyServerAssetDir)[]> {\n const migrationOptions = this.#options.migrations;\n\n if (!migrationOptions) {\n return [];\n }\n\n return datasources\n .flatMap((datasource) => {\n return datasource.drivers.map((driver) => {\n return {\n name: datasource.name,\n driver: driver.name,\n dialect: driver.dialect,\n migrations: driver.migrations,\n };\n });\n })\n .reduce(\n (acc, { name, driver, migrations }) => {\n const dir = migrations.assets;\n if (dir) {\n acc.push({\n baseName: [migrationOptions.storageBase, name, driver].join(\":\"),\n dir,\n /**\n * @todo Doesn't work in dev mode - 'fs' driver does not support 'pattern'\n * Disabled - include all files to use with meta/_journal.json\n */\n // pattern: '*.sql',\n });\n }\n return acc;\n },\n [] as (ServerAssetDir | LegacyServerAssetDir)[],\n );\n }\n\n private async virtualTypeDeclarations(\n datasources: readonly DatasourceInfo[],\n ): Promise<Record<string, VirtualModules<`${string}.d.ts`>>> {\n return {\n \"#nitro-drizzle/*\": {\n \"nitro-drizzle/virtual.d.ts\": [dialectDeclarations(datasources)].join(\"\\n\"),\n },\n };\n }\n\n private enabledPlugins(): readonly string[] {\n const plugins: (\"init\" | \"migrate\")[] = [];\n\n const migrationOptions = this.#options.migrations;\n const enableMigrationPlugin = migrationOptions\n ? Array.isArray(migrationOptions)\n ? 0 < migrationOptions.length\n : true == migrationOptions.migrateOnInit\n : false;\n\n if (enableMigrationPlugin) {\n plugins.push(\"migrate\");\n }\n\n plugins.push(\"init\");\n\n let pluginIds: readonly string[] = plugins;\n if (this.#options.legacy) {\n pluginIds = pluginIds.map((pluginName) => `legacy/${pluginName}`);\n }\n pluginIds = pluginIds.map((pluginName) => `nitro-drizzle/plugins/${pluginName}`);\n\n return pluginIds;\n }\n\n private async moduleTypeDeclarations(\n datasources: readonly DatasourceInfo[],\n ): Promise<VirtualModules> {\n return moduleTypeDeclarations(datasources);\n }\n\n private async runtimeTypeDeclarations(\n datasources: readonly DatasourceInfo[],\n ): Promise<VirtualModules<`${string}.d.ts`>> {\n const references = new Set([\n { types: \"nitro-drizzle/runtime\" },\n ...this.enabledPlugins().map((pluginId) => {\n return { types: pluginId };\n }),\n ]);\n if (!this.#options.legacy) {\n references.add({ types: \"nitro-drizzle/middleware/context\" });\n }\n const content = [\n ...[...references.values()].map((reference) => genReference(reference)),\n runtimeDeclarations(datasources),\n /* ts */ `export {};`,\n ].join(\"\\n\");\n return {\n \"nitro-drizzle/runtime.d.ts\": content,\n };\n }\n\n private async virtualModules(\n datasources: readonly DatasourceInfo[],\n ): Promise<VirtualModules<`#nitro-drizzle/${string}`>> {\n return {\n \"#nitro-drizzle/runtime\": runtimeVirtualModule(datasources, {\n legacyNitro: this.#options.legacy,\n runtimeConfigProp: \"drizzle\",\n initHooks: this.#options.initHooks,\n }),\n ...dialectVirtualModules(datasources),\n ...migrationsVirtualModule(datasources, this.#options.migrations),\n };\n }\n\n reload() {\n this.#datasources = null;\n }\n}\n\nfunction driverToDialect(driver: string) {\n let dialect = driver;\n if (driver.startsWith(\"d1\")) {\n dialect = \"sqlite\";\n }\n if (driver == \"pglite\") {\n dialect = \"postgresql\";\n }\n return dialect;\n}\n\n/**\n * Glob pattern or array of patterns to match Drizzle configuration files.\n */\nexport type ConfigPattern = string | readonly string[];\n\n/**\n * Resolver interface for importing modules and resolving paths.\n */\nexport interface Resolver {\n /**\n * Resolves a module ID to its full path.\n */\n resolve(id: string): string;\n}\n\nexport type ContextHook<TArgs extends readonly any[] = []> = (\n this: void,\n ...args: TArgs\n) => MaybePromise<void>;\n\nexport interface MigrationOptions {\n /** Base storage key path for migrations. */\n storageBase: string;\n /** Whether and which datasources to migrate on initialization. */\n migrateOnInit: boolean | readonly string[];\n}\n\nexport interface ContextOptions {\n legacy: boolean;\n\n logger?: ConsolaInstance;\n /**\n * Current working directory\n */\n cwd: string;\n /**\n * Base project directory to search drizzle config files\n */\n baseDir: string;\n /**\n * Pattern for drizzle config files\n */\n configPattern: ConfigPattern;\n /**\n * Nuxt Kit resolver\n */\n resolver: Resolver;\n /**\n * Connector options\n */\n datasources: Record<string, { drivers: readonly string[] | { [name: string]: boolean } }>;\n\n migrations: MigrationOptions | undefined;\n\n /**\n * Hooks that allowed to call \"drizzle:init\" hook.\n */\n initHooks?: readonly NitroHookName[];\n\n tasks?: ContextHook<\n [\n tasks: Record<\n string,\n {\n handler: string;\n description: string;\n }\n >,\n ]\n >;\n\n plugins: ContextHook<[plugins: readonly string[]]>;\n\n declarations: ContextHook<\n [\n declarations: {\n shared: VirtualModules<`${string}.d.ts`>;\n module: VirtualModules<`${string}.d.ts`>;\n runtime: VirtualModules<`${string}.d.ts`>;\n virtual: Record<string, VirtualModules<`${string}.d.ts`>>;\n },\n ]\n >;\n\n virtualModules: ContextHook<[modules: VirtualModules]>;\n\n assets: ContextHook<[assets: readonly (ServerAssetDir | LegacyServerAssetDir)[]]>;\n\n externals?: ContextHook<[modules: readonly string[]]>;\n}\n\n/**\n * Creates a Context instance for managing Drizzle datasource configurations.\n * @param options - Configuration options for the context\n * @returns A Context instance\n */\nexport function createContext(options: ContextOptions): Context {\n return new DefaultContext(options);\n}\n\n/**\n * Information about a resolved Drizzle datasource.\n */\nexport interface DatasourceInfo {\n /** Unique name identifier for the datasource. */\n name: string;\n /** Whether the datasource is enabled (filtered by connector configuration). */\n enabled: boolean;\n /** Driver configurations for this datasource. */\n drivers: readonly DriverOptions[];\n}\n\n/** Options for a specific driver within a datasource. */\nexport type DriverOptions = {\n enabled: boolean;\n name: string;\n dialect: string;\n imports: {\n // config: string;\n schema: readonly string[];\n connector: string;\n helpers: string;\n };\n /** Migration configuration for this datasource driver. */\n migrations: {\n assets?: string;\n config?: Config[\"migrations\"];\n };\n};\n"],"mappings":";;;;;;;;;;;;AA2CA,IAAM,iBAAN,MAAwC;CACtC,eAAwC;CACxC;CAEA,YAAY,SAAyB;EACnC,KAAK,WAAW;CAClB;CAEA,MAAM,OAAsB;EAC1B,MAAM,cAAc,MAAM,KAAK,YAAY;EAE3C,MAAM,KAAK,SAAS,QAAQ,KAAK,eAAe,CAAC;EAEjD,MAAM,CAAC,aAAa,gBAAgB,cAAc,aAAa,gBAC7D,MAAM,QAAQ,IAAI;GAChB,uBAAuB,WAAW;GAClC,KAAK,eAAe,WAAW;GAC/B,KAAK,wBAAwB,WAAW;GACxC,KAAK,uBAAuB,WAAW;GACvC,KAAK,wBAAwB,WAAW;EAC1C,CAAC;EAEH,MAAM,KAAK,SAAS,eAAe,cAAc;EAEjD,MAAM,KAAK,SAAS,aAAa;GAC/B,QAAQ;GACR,QAAQ;GACR,SAAS;GACT,SAAS;EACX,CAAC;EAED,IAAI,KAAK,SAAS,YAAY;GAC5B,MAAM,SAAS,MAAM,KAAK,gBAAgB,WAAW;GACrD,IAAI,QACF,MAAM,KAAK,SAAS,OAAO,MAAM;GAGnC,MAAM,KAAK,SAAS,QAAQ,EAC1B,mBAAmB;IACjB,aAAa;IACb,SAAS;GACX,EACF,CAAC;EACH;EAEA,IAAI,KAAK,SAAS,WAAW;GAC3B,MAAM,kBAAkB;IAAC;IAAW;IAAW;GAAY,CAAC,CAAC,SAAS,OAAO;IAC3E,OAAO,CAAC,KAAK,SAAS,EAAE,GAAG,KAAK,QAAQ,QAAQ,EAAE,CAAC;GACrD,CAAC;GAED,MAAM,KAAK,SAAS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B,WAAW;CAC3C;CAEA,MAAc,wBACZ,aAC2C;EAC3C,MAAM,6BAAa,IAAI,IAAI,CACzB,EAAE,OAAO,wBAAwB,GACjC,GAAG,KAAK,eAAe,CAAC,CAAC,KAAK,aAAa;GACzC,OAAO,EAAE,OAAO,SAAS;EAC3B,CAAC,CACH,CAAC;EACD,IAAI,CAAC,KAAK,SAAS,QACjB,WAAW,IAAI,EAAE,OAAO,mCAAmC,CAAC;EAO9D,OAAO,EACL,8BANc;GACd,GAAG,CAAC,GAAG,WAAW,OAAO,CAAC,CAAC,CAAC,KAAK,cAAc,aAAa,SAAS,CAAC;GACtE,oBAAoB,WAAW;GACtB;EACX,CAAC,CAAC,KAAK,IAE+B,EACtC;CACF;CAEA,MAAc,eACZ,aACqD;EACrD,OAAO;GACL,0BAA0B,qBAAqB,aAAa;IAC1D,aAAa,KAAK,SAAS;IAC3B,mBAAmB;IACnB,WAAW,KAAK,SAAS;GAC3B,CAAC;GACD,GAAG,sBAAsB,WAAW;GACpC,GAAG,wBAAwB,aAAa,KAAK,SAAS,UAAU;EAClE;CACF;CAEA,SAAS;EACP,KAAK,eAAe;CACtB;AACF;AAEA,SAAS,gBAAgB,QAAgB;CACvC,IAAI,UAAU;CACd,IAAI,OAAO,WAAW,IAAI,GACxB,UAAU;CAEZ,IAAI,UAAU,UACZ,UAAU;CAEZ,OAAO;AACT;;;;;;AAkGA,SAAgB,cAAc,SAAkC;CAC9D,OAAO,IAAI,eAAe,OAAO;AACnC"}
@@ -1 +1 @@
1
- {"version":3,"file":"resolver.mjs","names":["#jiti"],"sources":["../../../src/module/internal/resolver.ts"],"sourcesContent":["import { createJiti, type Jiti, type JitiOptions } from \"jiti\";\nimport type { Resolver } from \"nitro-drizzle/context\";\nimport { fileURLToPath } from \"url\";\n\n/**\n * Creates a module resolver using jiti.\n * @param id - The base module ID for resolution\n * @param options - Optional resolver configuration\n * @returns A Resolver instance\n */\nexport function createResolver(id: string, options?: { alias?: Record<string, string> }): Resolver {\n return new JitiResolver(id, {\n alias: options?.alias,\n });\n}\n\nclass JitiResolver implements Resolver {\n readonly #jiti: Jiti;\n\n constructor(id: string, options?: JitiOptions) {\n this.#jiti = createJiti(id, options);\n }\n\n resolve(id: string): string {\n return fileURLToPath(this.#jiti.esmResolve(id));\n }\n}\n"],"mappings":";;;;;;;;;AAUA,SAAgB,eAAe,IAAY,SAAwD;CACjG,OAAO,IAAI,aAAa,IAAI,EAC1B,OAAO,SAAS,MAClB,CAAC;AACH;AAEA,IAAM,eAAN,MAAuC;CACrC;CAEA,YAAY,IAAY,SAAuB;EAC7C,KAAKA,QAAQ,WAAW,IAAI,OAAO;CACrC;CAEA,QAAQ,IAAoB;EAC1B,OAAO,cAAc,KAAKA,MAAM,WAAW,EAAE,CAAC;CAChD;AACF"}
1
+ {"version":3,"file":"resolver.mjs","names":[],"sources":["../../../src/module/internal/resolver.ts"],"sourcesContent":["import { createJiti, type Jiti, type JitiOptions } from \"jiti\";\nimport type { Resolver } from \"nitro-drizzle/context\";\nimport { fileURLToPath } from \"url\";\n\n/**\n * Creates a module resolver using jiti.\n * @param id - The base module ID for resolution\n * @param options - Optional resolver configuration\n * @returns A Resolver instance\n */\nexport function createResolver(id: string, options?: { alias?: Record<string, string> }): Resolver {\n return new JitiResolver(id, {\n alias: options?.alias,\n });\n}\n\nclass JitiResolver implements Resolver {\n readonly #jiti: Jiti;\n\n constructor(id: string, options?: JitiOptions) {\n this.#jiti = createJiti(id, options);\n }\n\n resolve(id: string): string {\n return fileURLToPath(this.#jiti.esmResolve(id));\n }\n}\n"],"mappings":";;;;;;;;;AAUA,SAAgB,eAAe,IAAY,SAAwD;CACjG,OAAO,IAAI,aAAa,IAAI,EAC1B,OAAO,SAAS,MAClB,CAAC;AACH;AAEA,IAAM,eAAN,MAAuC;CACrC;CAEA,YAAY,IAAY,SAAuB;EAC7C,KAAK,QAAQ,WAAW,IAAI,OAAO;CACrC;CAEA,QAAQ,IAAoB;EAC1B,OAAO,cAAc,KAAK,MAAM,WAAW,EAAE,CAAC;CAChD;AACF"}
package/dist/module.d.mts CHANGED
@@ -2,24 +2,17 @@ import { updateServerAssets } from "./module/utils/assets.mjs";
2
2
  import { addInlineExternals } from "./module/utils/externals.mjs";
3
3
  import { isLegacy } from "./module/utils/nitro.mjs";
4
4
  import { ConfigPattern, MigrationOptions } from "nitro-drizzle/context";
5
- import { ConnectorSpecifier, ConnectorVariants, ExpandVariants, Variant } from "nitro-drizzle/shared";
6
5
  import { NitroModule } from "nitropack/types";
7
6
  import { NitroModule as NitroModule$1 } from "nitro/types";
8
- import { Connector } from "nitro-drizzle/drivers";
9
7
  //#region src/module/index.d.ts
10
8
  /**
11
- * Datasource-specific configuration options.
9
+ * Datasource-specific configuration options mapped by datasource name.
12
10
  */
13
- type DatasourceOptionsMapper<T extends Variant<Connector<any, any, any, any>, ConnectorSpecifier>> = T extends any ? Variant<{
11
+ type DatasourceOptions = Record<string, {
14
12
  drivers: readonly string[] | {
15
13
  [name: string]: boolean;
16
14
  };
17
- }, Pick<T["selector"], "name">> : never;
18
- type DatasourceOptionsVariants = DatasourceOptionsMapper<ConnectorVariants>;
19
- /**
20
- * Datasource-specific configuration options mapped by datasource name.
21
- */
22
- type DatasourceOptions = ExpandVariants<DatasourceOptionsVariants, ["name"]>;
15
+ }>;
23
16
  declare module "nitropack/types" {
24
17
  interface NitroOptions {
25
18
  drizzle?: ModuleOptions;
@@ -1 +1 @@
1
- {"version":3,"file":"module.mjs","names":[],"sources":["../src/module/index.ts"],"sourcesContent":["import type { NitroModule as LegacyNitroModule } from \"nitropack/types\";\nimport type { NitroModule } from \"nitro/types\";\nimport { defu } from \"defu\";\nimport { resolve } from \"pathe\";\nimport { resolveAlias } from \"pathe/utils\";\n\nimport {\n createContext,\n type ConfigPattern,\n type ContextOptions,\n type MigrationOptions,\n} from \"nitro-drizzle/context\";\nimport type {\n VirtualModules,\n MaybePromise,\n NitroHookName,\n Variant,\n ConnectorSpecifier,\n ConnectorVariants,\n ExpandVariants,\n} from \"nitro-drizzle/shared\";\nimport { pkgName } from \"nitro-drizzle/meta\";\nimport type { Connector } from \"nitro-drizzle/drivers\";\n\nimport { updateServerAssets } from \"./utils/assets\";\nimport { addInlineExternals, addNoExternals } from \"./utils/externals\";\n\nimport { addAugmentations, addDeclarations } from \"./internal/types\";\nimport { createResolver } from \"./internal/resolver\";\nimport { reloadPlugin } from \"./internal/reload\";\nimport { addPlugin } from \"./internal/rollup\";\nimport { isLegacy } from \"./utils/nitro\";\n\n/**\n * Datasource-specific configuration options.\n */\ntype DatasourceOptionsMapper<T extends Variant<Connector<any, any, any, any>, ConnectorSpecifier>> =\n T extends any\n ? Variant<\n { drivers: readonly string[] | { [name: string]: boolean } },\n Pick<T[\"selector\"], \"name\">\n >\n : never;\n\ntype DatasourceOptionsVariants = DatasourceOptionsMapper<ConnectorVariants>;\n\n/**\n * Datasource-specific configuration options mapped by datasource name.\n */\nexport type DatasourceOptions = ExpandVariants<DatasourceOptionsVariants, [\"name\"]>;\n\ndeclare module \"nitropack/types\" {\n interface NitroOptions {\n drizzle?: ModuleOptions;\n }\n}\n\ndeclare module \"nitro/types\" {\n interface NitroOptions {\n drizzle?: ModuleOptions;\n }\n}\n\nexport interface ModuleOptions {\n /**\n * Directory to search datasources\n */\n baseDir?: string;\n /**\n * Patterns to search Drizzle configs\n */\n configPattern?: ConfigPattern;\n\n datasources?: DatasourceOptions;\n\n /**\n * Enable migrations storage\n */\n migrations?: false | Partial<MigrationOptions>;\n}\n\n/**\n * Resolved module configuration with required fields.\n */\nexport type ModuleConfig = Required<ModuleOptions> & {\n migrations: false | Required<MigrationOptions>;\n};\n\n/**\n * Creates the default module configuration options.\n * @returns The default module configuration\n */\nexport function createDefaultOptions() {\n return {\n baseDir: \"./drizzle\",\n configPattern: [\"drizzle.config.{js,ts}\", \"drizzle-*.config.{js,ts}\"],\n datasources: {},\n migrations: {\n storageBase: \"drizzle:migrations\",\n migrateOnInit: false,\n },\n } as const satisfies ModuleConfig;\n}\n\n/**\n * Merges user-provided module options with defaults.\n * @param options - Optional module configuration overrides\n * @returns The resolved module configuration\n */\nexport function defineModuleConfig(options?: ModuleOptions): ModuleConfig {\n return defu(options, createDefaultOptions());\n}\n\nconst module: LegacyNitroModule & NitroModule = {\n name: pkgName,\n async setup(nitro) {\n const logger = nitro.logger.withTag(pkgName);\n const moduleConfig = defineModuleConfig(nitro.options.drizzle);\n\n const resolver = createResolver(nitro.options.rootDir, {\n alias: nitro.options.alias,\n });\n\n const serverDir = isLegacy(nitro) ? nitro.options.srcDir : nitro.options.serverDir;\n if (!serverDir) {\n logger.info(\"No server directory configured.\");\n return;\n }\n\n const baseDir = resolve(serverDir, resolveAlias(moduleConfig.baseDir, nitro.options.alias));\n\n if (!isLegacy(nitro)) {\n nitro.options.handlers ||= [];\n nitro.options.handlers.push({\n route: \"/**\",\n handler: resolver.resolve(\"nitro-drizzle/middleware/context\"),\n middleware: true,\n });\n }\n\n const contextOptions: ContextOptions = {\n legacy: isLegacy(nitro),\n cwd: process.cwd(),\n resolver: resolver,\n baseDir,\n logger,\n configPattern: moduleConfig.configPattern,\n datasources: { ...moduleConfig.datasources },\n migrations: moduleConfig.migrations || void 0,\n get initHooks() {\n const hooks: NitroHookName[] = [];\n if (nitro.options.preset.startsWith(\"cloudflare\")) {\n if (nitro.options.preset.endsWith(\"durable\")) {\n hooks.push(\"cloudflare:durable:init\", \"cloudflare:durable:alarm\");\n }\n hooks.push(\n \"request\",\n \"cloudflare:email\",\n \"cloudflare:queue\",\n \"cloudflare:scheduled\",\n \"cloudflare:tail\",\n \"cloudflare:trace\",\n );\n }\n return hooks;\n },\n\n tasks: nitro.options.experimental.tasks\n ? (tasks) => {\n nitro.options.tasks ||= {};\n Object.assign(nitro.options.tasks, tasks);\n }\n : void 0,\n\n plugins(plugins) {\n nitro.options.plugins.push(\n ...plugins.map((plugin) => resolver.resolve(plugin).replace(/\\.mjs$/, \"\")),\n );\n },\n\n virtualModules(modules: VirtualModules): MaybePromise<void> {\n Object.assign(nitro.options.virtual, modules);\n },\n\n declarations(declarations): MaybePromise<void> {\n nitro.hooks.hook(\"types:extend\", async (types) => {\n await addAugmentations(nitro, types, {\n ...declarations.shared,\n ...declarations.runtime,\n ...declarations.module,\n });\n\n await addDeclarations(nitro, types, declarations.virtual);\n });\n },\n\n assets(assets) {\n updateServerAssets(nitro.options, assets);\n },\n\n externals(modules) {\n if (isLegacy(nitro)) {\n addInlineExternals(nitro.options, modules);\n } else {\n addNoExternals(nitro.options, modules);\n }\n },\n };\n\n const context = createContext(contextOptions);\n\n // auto-imports\n if (nitro.options.imports) {\n nitro.options.imports.imports ||= [];\n\n // TODO\n // nitro.options.imports.imports.push({\n // name: 'useMigrations',\n // as: 'useDrizzleMigrations',\n // from: 'nitro-drizzle/runtime',\n // })\n }\n\n nitro.hooks.hook(\"rollup:before\", async (nitro, config) => {\n await addPlugin(config, reloadPlugin(nitro, { baseDir }));\n });\n\n await context.init();\n },\n};\n\nexport default module;\n\nexport { addInlineExternals, updateServerAssets, isLegacy as isLegacyNitro };\n"],"mappings":";;;;;;;;;;;;;;;;;AA4FA,SAAgB,uBAAuB;CACrC,OAAO;EACL,SAAS;EACT,eAAe,CAAC,0BAA0B,0BAA0B;EACpE,aAAa,CAAC;EACd,YAAY;GACV,aAAa;GACb,eAAe;EACjB;CACF;AACF;;;;;;AAOA,SAAgB,mBAAmB,SAAuC;CACxE,OAAO,KAAK,SAAS,qBAAqB,CAAC;AAC7C;AAEA,MAAM,SAA0C;CAC9C,MAAM;CACN,MAAM,MAAM,OAAO;EACjB,MAAM,SAAS,MAAM,OAAO,QAAQ,OAAO;EAC3C,MAAM,eAAe,mBAAmB,MAAM,QAAQ,OAAO;EAE7D,MAAM,WAAW,eAAe,MAAM,QAAQ,SAAS,EACrD,OAAO,MAAM,QAAQ,MACvB,CAAC;EAED,MAAM,YAAY,SAAS,KAAK,IAAI,MAAM,QAAQ,SAAS,MAAM,QAAQ;EACzE,IAAI,CAAC,WAAW;GACd,OAA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,OAAO,aAAa,OAAO;IAC1D,CAAC;GACH;GAEA,OAAO,QAAQ;IACb,mBAAmB,MAAM,SAAS,MAAM;GAC1C;GAEA,UAAU,SAAS;IACjB,IAAI,SAAS,KAAK,GAChB,mBAAmB,MAAM,SAAS,OAAO;SAEzC,eAAe,MAAM,SAAS,OAAO;GAEzC;EACF;EAEA,MAAM,UAAU,cAAc,cAAc;EAG5C,IAAI,MAAM,QAAQ,SAChB,MAAM,QAAQ,QAAQ,YAAY,CAAC;EAUrC,MAAM,MAAM,KAAK,iBAAiB,OAAO,OAAO,WAAW;GACzD,MAAM,UAAU,QAAQ,aAAa,OAAO,EAAE,QAAQ,CAAC,CAAC;EAC1D,CAAC;EAED,MAAM,QAAQ,KAAK;CACrB;AACF"}
1
+ {"version":3,"file":"module.mjs","names":[],"sources":["../src/module/index.ts"],"sourcesContent":["import type { NitroModule as LegacyNitroModule } from \"nitropack/types\";\nimport type { NitroModule } from \"nitro/types\";\nimport { defu } from \"defu\";\nimport { resolve } from \"pathe\";\nimport { resolveAlias } from \"pathe/utils\";\n\nimport {\n createContext,\n type ConfigPattern,\n type ContextOptions,\n type MigrationOptions,\n} from \"nitro-drizzle/context\";\nimport type { VirtualModules, MaybePromise, NitroHookName } from \"nitro-drizzle/shared\";\nimport { pkgName } from \"nitro-drizzle/meta\";\n\nimport { updateServerAssets } from \"./utils/assets\";\nimport { addInlineExternals, addNoExternals } from \"./utils/externals\";\n\nimport { addAugmentations, addDeclarations } from \"./internal/types\";\nimport { createResolver } from \"./internal/resolver\";\nimport { reloadPlugin } from \"./internal/reload\";\nimport { addPlugin } from \"./internal/rollup\";\nimport { isLegacy } from \"./utils/nitro\";\n\n/**\n * Datasource-specific configuration options mapped by datasource name.\n */\nexport type DatasourceOptions = Record<\n string,\n {\n drivers: readonly string[] | { [name: string]: boolean };\n }\n>;\n\ndeclare module \"nitropack/types\" {\n interface NitroOptions {\n drizzle?: ModuleOptions;\n }\n}\n\ndeclare module \"nitro/types\" {\n interface NitroOptions {\n drizzle?: ModuleOptions;\n }\n}\n\nexport interface ModuleOptions {\n /**\n * Directory to search datasources\n */\n baseDir?: string;\n /**\n * Patterns to search Drizzle configs\n */\n configPattern?: ConfigPattern;\n\n datasources?: DatasourceOptions;\n\n /**\n * Enable migrations storage\n */\n migrations?: false | Partial<MigrationOptions>;\n}\n\n/**\n * Resolved module configuration with required fields.\n */\nexport type ModuleConfig = Required<ModuleOptions> & {\n migrations: false | Required<MigrationOptions>;\n};\n\n/**\n * Creates the default module configuration options.\n * @returns The default module configuration\n */\nexport function createDefaultOptions() {\n return {\n baseDir: \"./drizzle\",\n configPattern: [\"drizzle.config.{js,ts}\", \"drizzle-*.config.{js,ts}\"],\n datasources: {},\n migrations: {\n storageBase: \"drizzle:migrations\",\n migrateOnInit: false,\n },\n } as const satisfies ModuleConfig;\n}\n\n/**\n * Merges user-provided module options with defaults.\n * @param options - Optional module configuration overrides\n * @returns The resolved module configuration\n */\nexport function defineModuleConfig(options?: ModuleOptions): ModuleConfig {\n return defu(options, createDefaultOptions());\n}\n\nconst module: LegacyNitroModule & NitroModule = {\n name: pkgName,\n async setup(nitro) {\n const logger = nitro.logger.withTag(pkgName);\n const moduleConfig = defineModuleConfig(nitro.options.drizzle);\n\n const resolver = createResolver(nitro.options.rootDir, {\n alias: nitro.options.alias,\n });\n\n const serverDir = isLegacy(nitro) ? nitro.options.srcDir : nitro.options.serverDir;\n if (!serverDir) {\n logger.info(\"No server directory configured.\");\n return;\n }\n\n const baseDir = resolve(serverDir, resolveAlias(moduleConfig.baseDir, nitro.options.alias));\n\n if (!isLegacy(nitro)) {\n nitro.options.handlers ||= [];\n nitro.options.handlers.push({\n route: \"/**\",\n handler: resolver.resolve(\"nitro-drizzle/middleware/context\"),\n middleware: true,\n });\n }\n\n const contextOptions: ContextOptions = {\n legacy: isLegacy(nitro),\n cwd: process.cwd(),\n resolver: resolver,\n baseDir,\n logger,\n configPattern: moduleConfig.configPattern,\n datasources: { ...moduleConfig.datasources },\n migrations: moduleConfig.migrations || void 0,\n get initHooks() {\n const hooks: NitroHookName[] = [];\n if (nitro.options.preset.startsWith(\"cloudflare\")) {\n if (nitro.options.preset.endsWith(\"durable\")) {\n hooks.push(\"cloudflare:durable:init\", \"cloudflare:durable:alarm\");\n }\n hooks.push(\n \"request\",\n \"cloudflare:email\",\n \"cloudflare:queue\",\n \"cloudflare:scheduled\",\n \"cloudflare:tail\",\n \"cloudflare:trace\",\n );\n }\n return hooks;\n },\n\n tasks: nitro.options.experimental.tasks\n ? (tasks) => {\n nitro.options.tasks ||= {};\n Object.assign(nitro.options.tasks, tasks);\n }\n : void 0,\n\n plugins(plugins) {\n nitro.options.plugins.push(\n ...plugins.map((plugin) => resolver.resolve(plugin).replace(/\\.mjs$/, \"\")),\n );\n },\n\n virtualModules(modules: VirtualModules): MaybePromise<void> {\n Object.assign(nitro.options.virtual, modules);\n },\n\n declarations(declarations): MaybePromise<void> {\n nitro.hooks.hook(\"types:extend\", async (types) => {\n await addAugmentations(nitro, types, {\n ...declarations.shared,\n ...declarations.runtime,\n ...declarations.module,\n });\n\n await addDeclarations(nitro, types, declarations.virtual);\n });\n },\n\n assets(assets) {\n updateServerAssets(nitro.options, assets);\n },\n\n externals(modules) {\n if (isLegacy(nitro)) {\n addInlineExternals(nitro.options, modules);\n } else {\n addNoExternals(nitro.options, modules);\n }\n },\n };\n\n const context = createContext(contextOptions);\n\n // auto-imports\n if (nitro.options.imports) {\n nitro.options.imports.imports ||= [];\n\n // TODO\n // nitro.options.imports.imports.push({\n // name: 'useMigrations',\n // as: 'useDrizzleMigrations',\n // from: 'nitro-drizzle/runtime',\n // })\n }\n\n nitro.hooks.hook(\"rollup:before\", async (nitro, config) => {\n await addPlugin(config, reloadPlugin(nitro, { baseDir }));\n });\n\n await context.init();\n },\n};\n\nexport default module;\n\nexport { addInlineExternals, updateServerAssets, isLegacy as isLegacyNitro };\n"],"mappings":";;;;;;;;;;;;;;;;;AA2EA,SAAgB,uBAAuB;CACrC,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AAM,QAAQ,aAAa,SAC7B,UAAU;IACT,MAAM,QAAQ,UAAU,CAAC;IACzB,OAAO,OAAO,MAAM,QAAQ,OAAO,KAAK;GAC1C,IACA,KAAK;GAET,QAAQ,SAAS;IACf,MAAM,QAAQ,QAAQ,KACpB,GAAG,QAAQ,KAAK,WAAW,SAAS,QAAQ,MAAM,CAAC,CAAC,QAAQ,UAAU,EAAE,CAAC,CAC3E;GACF;GAEA,eAAe,SAA6C;IAC1D,OAAO,OAAO,MAAM,QAAQ,SAAS,OAAO;GAC9C;GAEA,aAAa,cAAkC;IAC7C,MAAM,MAAM,KAAK,gBAAgB,OAAO,UAAU;KAChD,MAAM,iBAAiB,OAAO,OAAO;MACnC,GAAG,aAAa;MAChB,GAAG,aAAa;MAChB,GAAG,aAAa;KAClB,CAAC;KAED,MAAM,gBAAgB,OAAO,OAAO,aAAa,OAAO;IAC1D,CAAC;GACH;GAEA,OAAO,QAAQ;IACb,mBAAmB,MAAM,SAAS,MAAM;GAC1C;GAEA,UAAU,SAAS;IACjB,IAAI,SAAS,KAAK,GAChB,mBAAmB,MAAM,SAAS,OAAO;SAEzC,eAAe,MAAM,SAAS,OAAO;GAEzC;EACF;EAEA,MAAM,UAAU,cAAc,cAAc;EAG5C,IAAI,MAAM,QAAQ,SAChB,MAAM,QAAQ,QAAQ,YAAY,CAAC;EAUrC,MAAM,MAAM,KAAK,iBAAiB,OAAO,OAAO,WAAW;GACzD,MAAM,UAAU,QAAQ,aAAa,OAAO,EAAE,QAAQ,CAAC,CAAC;EAC1D,CAAC;EAED,MAAM,QAAQ,KAAK;CACrB;AACF"}
@@ -1,26 +1,34 @@
1
- import { ConnectorSpecifier, ExpandVariants, Variant } from "nitro-drizzle/shared";
1
+ import { ConnectorSpecifier, UnwrapVariant, Variant } from "nitro-drizzle/shared";
2
2
  import { DatasourceVariants, Datasources } from "nitro-drizzle/runtime";
3
3
  import { Datasource, Schema } from "nitro-drizzle/drivers";
4
4
  //#region src/runtime/useDialect.d.ts
5
5
  /**
6
- * Provides type-safe dialect-specific handlers for a datasource.
7
- * Automatically resolves the correct handler based on the configured driver.
6
+ * Executes a callback with type-safe context (datasource, driver, dialect) for the specified datasource.
7
+ * Automatically resolves the active datasource, driver, and dialect based on the runtime configuration.
8
8
  * @template TName - The datasource name
9
- * @template THandlers - The dialect handlers mapping
9
+ * @template TArgs - The dialect callback arguments type
10
+ * @template TReturn - The return type of the callback
10
11
  * @param name - The datasource name
11
- * @param handlers - An object mapping dialect names to handler functions
12
- * @returns The result of the handler for the current dialect
12
+ * @param callback - The callback function receiving `{ datasource, driver, dialect }`
13
+ * @returns A promise that resolves to the return value of the callback
13
14
  */
14
- declare function useDialect<TName extends keyof Datasources & string, THandlers extends DialectHandlers<TName, DialectHandlerArgs[TName]>>(name: TName, handlers: THandlers): Promise<{ [K in keyof THandlers]: ReturnType<THandlers[K]>; }[keyof THandlers]>;
15
+ declare function useDialect<TName extends keyof Datasources & string, TArgs extends DialectCallbackArgs<TName>, TReturn>(name: TName, callback: DialectCallback<TName, TArgs, TReturn>): Promise<TReturn>;
16
+ type DialectCallbackArgsMapper<T extends Variant<Datasource<string, any, Schema>, ConnectorSpecifier>> = T extends Variant<infer V, infer S> ? Variant<Pick<S, "dialect" | "driver"> & {
17
+ datasource: V;
18
+ }, Pick<S, "name">> : never;
19
+ type DialectCallbackArgsVariants = DialectCallbackArgsMapper<DatasourceVariants>;
20
+ type DialectCallbackArgs<TName extends keyof Datasources & string> = UnwrapVariant<DialectCallbackArgsVariants, {
21
+ name: TName;
22
+ }>;
15
23
  /**
16
- * Maps dialect names to their handler argument types for a datasource.
24
+ * Callback function signature for `useDialect`.
17
25
  * @template TName - The datasource name
18
- * @template T - The datasource type
26
+ * @template TArgs - The callback argument types
27
+ * @template TReturn - The return type of the callback
19
28
  */
20
- type DialectHandlers<TName extends keyof Datasources & string, T> = T extends DialectHandlerArgs[TName] ? { [K in keyof T]: K extends keyof DialectHandlerArgs[TName] ? (...args: DialectHandlerArgs[TName][K]) => any : never; } : never;
21
- type DialectHandlersArgsMapper<T extends Variant<Datasource<string, any, Schema>, ConnectorSpecifier>> = T extends Variant<infer V, infer S> ? Variant<[datasource: V], Pick<S, "name" | "dialect">> : never;
22
- type DialectHandlerVariants = DialectHandlersArgsMapper<DatasourceVariants>;
23
- type DialectHandlerArgs = ExpandVariants<DialectHandlerVariants, ["name", "dialect"]>;
29
+ type DialectCallback<TName extends keyof Datasources & string, TArgs extends DialectCallbackArgs<TName>, TReturn> = {
30
+ (args: TArgs): TReturn;
31
+ };
24
32
  //#endregion
25
- export { useDialect };
33
+ export { DialectCallback, useDialect };
26
34
  //# sourceMappingURL=useDialect.d.mts.map
@@ -1,20 +1,25 @@
1
1
  import { useDatasourceProvider } from "./internal/createDatasource.mjs";
2
- import { useDatasource } from "nitro-drizzle/runtime";
2
+ import { useConfig, useDatasource } from "nitro-drizzle/runtime";
3
3
  //#region src/runtime/useDialect.ts
4
4
  /**
5
- * Provides type-safe dialect-specific handlers for a datasource.
6
- * Automatically resolves the correct handler based on the configured driver.
5
+ * Executes a callback with type-safe context (datasource, driver, dialect) for the specified datasource.
6
+ * Automatically resolves the active datasource, driver, and dialect based on the runtime configuration.
7
7
  * @template TName - The datasource name
8
- * @template THandlers - The dialect handlers mapping
8
+ * @template TArgs - The dialect callback arguments type
9
+ * @template TReturn - The return type of the callback
9
10
  * @param name - The datasource name
10
- * @param handlers - An object mapping dialect names to handler functions
11
- * @returns The result of the handler for the current dialect
11
+ * @param callback - The callback function receiving `{ datasource, driver, dialect }`
12
+ * @returns A promise that resolves to the return value of the callback
12
13
  */
13
- async function useDialect(name, handlers) {
14
+ async function useDialect(name, callback) {
14
15
  const datasource = await useDatasource(name);
15
16
  const { dialect } = useDatasourceProvider(name);
16
- if (false === dialect in handlers) throw new Error(`No dialect-specific handler provided for dialect "${dialect}".`);
17
- return await handlers[dialect](datasource);
17
+ const { driver } = useConfig(name);
18
+ return await callback({
19
+ datasource,
20
+ driver,
21
+ dialect
22
+ });
18
23
  }
19
24
  //#endregion
20
25
  export { useDialect };
@@ -1 +1 @@
1
- {"version":3,"file":"useDialect.mjs","names":[],"sources":["../../src/runtime/useDialect.ts"],"sourcesContent":["import type { Datasource, Schema } from \"nitro-drizzle/drivers\";\nimport { useDatasource, type Datasources, type DatasourceVariants } from \"nitro-drizzle/runtime\";\nimport type { ConnectorSpecifier, ExpandVariants, Variant } from \"nitro-drizzle/shared\";\nimport { useDatasourceProvider } from \"./internal/createDatasource\";\n\n/**\n * Provides type-safe dialect-specific handlers for a datasource.\n * Automatically resolves the correct handler based on the configured driver.\n * @template TName - The datasource name\n * @template THandlers - The dialect handlers mapping\n * @param name - The datasource name\n * @param handlers - An object mapping dialect names to handler functions\n * @returns The result of the handler for the current dialect\n */\nexport async function useDialect<\n TName extends keyof Datasources & string,\n THandlers extends DialectHandlers<TName, DialectHandlerArgs[TName]>,\n>(\n name: TName,\n handlers: THandlers,\n): Promise<{ [K in keyof THandlers]: ReturnType<THandlers[K]> }[keyof THandlers]> {\n const datasource = await useDatasource(name);\n const { dialect } = useDatasourceProvider(name);\n if (false === dialect in handlers) {\n throw new Error(`No dialect-specific handler provided for dialect \"${dialect}\".`);\n }\n return await handlers[dialect](datasource);\n}\n\n/**\n * Maps dialect names to their handler argument types for a datasource.\n * @template TName - The datasource name\n * @template T - The datasource type\n */\ntype DialectHandlers<\n TName extends keyof Datasources & string,\n T,\n> = T extends DialectHandlerArgs[TName]\n ? {\n [K in keyof T]: K extends keyof DialectHandlerArgs[TName]\n ? (...args: DialectHandlerArgs[TName][K]) => any\n : never;\n }\n : never;\n\ntype DialectHandlersArgsMapper<\n T extends Variant<Datasource<string, any, Schema>, ConnectorSpecifier>,\n> =\n T extends Variant<infer V, infer S>\n ? Variant<[datasource: V], Pick<S, \"name\" | \"dialect\">>\n : never;\n\ntype DialectHandlerVariants = DialectHandlersArgsMapper<DatasourceVariants>;\n\ntype DialectHandlerArgs = ExpandVariants<DialectHandlerVariants, [\"name\", \"dialect\"]>;\n"],"mappings":";;;;;;;;;;;;AAcA,eAAsB,WAIpB,MACA,UACgF;CAChF,MAAM,aAAa,MAAM,cAAc,IAAI;CAC3C,MAAM,EAAE,YAAY,sBAAsB,IAAI;CAC9C,IAAI,UAAU,WAAW,UACvB,MAAM,IAAI,MAAM,qDAAqD,QAAQ,GAAG;CAElF,OAAO,MAAM,SAAS,QAAQ,CAAC,UAAU;AAC3C"}
1
+ {"version":3,"file":"useDialect.mjs","names":[],"sources":["../../src/runtime/useDialect.ts"],"sourcesContent":["import type { Datasource, Schema } from \"nitro-drizzle/drivers\";\nimport {\n useConfig,\n useDatasource,\n type Datasources,\n type DatasourceVariants,\n} from \"nitro-drizzle/runtime\";\nimport type { ConnectorSpecifier, UnwrapVariant, Variant } from \"nitro-drizzle/shared\";\nimport { useDatasourceProvider } from \"./internal/createDatasource\";\n\n/**\n * Executes a callback with type-safe context (datasource, driver, dialect) for the specified datasource.\n * Automatically resolves the active datasource, driver, and dialect based on the runtime configuration.\n * @template TName - The datasource name\n * @template TArgs - The dialect callback arguments type\n * @template TReturn - The return type of the callback\n * @param name - The datasource name\n * @param callback - The callback function receiving `{ datasource, driver, dialect }`\n * @returns A promise that resolves to the return value of the callback\n */\nexport async function useDialect<\n TName extends keyof Datasources & string,\n TArgs extends DialectCallbackArgs<TName>,\n TReturn,\n>(name: TName, callback: DialectCallback<TName, TArgs, TReturn>): Promise<TReturn> {\n const datasource = await useDatasource(name);\n const { dialect } = useDatasourceProvider(name);\n const { driver } = useConfig(name);\n\n // @ts-expect-error\n return await callback({\n datasource,\n driver,\n dialect,\n });\n}\n\ntype DialectCallbackArgsMapper<\n T extends Variant<Datasource<string, any, Schema>, ConnectorSpecifier>,\n> =\n T extends Variant<infer V, infer S>\n ? Variant<Pick<S, \"dialect\" | \"driver\"> & { datasource: V }, Pick<S, \"name\">>\n : never;\n\ntype DialectCallbackArgsVariants = DialectCallbackArgsMapper<DatasourceVariants>;\n\ntype DialectCallbackArgs<TName extends keyof Datasources & string> = UnwrapVariant<\n DialectCallbackArgsVariants,\n { name: TName }\n>;\n\n/**\n * Callback function signature for `useDialect`.\n * @template TName - The datasource name\n * @template TArgs - The callback argument types\n * @template TReturn - The return type of the callback\n */\nexport type DialectCallback<\n TName extends keyof Datasources & string,\n TArgs extends DialectCallbackArgs<TName>,\n TReturn,\n> = {\n (args: TArgs): TReturn;\n};\n"],"mappings":";;;;;;;;;;;;;AAoBA,eAAsB,WAIpB,MAAa,UAAoE;CACjF,MAAM,aAAa,MAAM,cAAc,IAAI;CAC3C,MAAM,EAAE,YAAY,sBAAsB,IAAI;CAC9C,MAAM,EAAE,WAAW,UAAU,IAAI;CAGjC,OAAO,MAAM,SAAS;EACpB;EACA;EACA;CACF,CAAC;AACH"}
@@ -1,5 +1,5 @@
1
1
  import { UseDatasourceOptions, useDatasource } from "./runtime/useDatasource.mjs";
2
- import { useDialect } from "./runtime/useDialect.mjs";
2
+ import { DialectCallback, useDialect } from "./runtime/useDialect.mjs";
3
3
  import { useConfig } from "./runtime/useConfig.mjs";
4
4
  import { ConnectorSpecifier, ConnectorVariants, ExpandVariants, MaybePromise, Selector, Variant } from "nitro-drizzle/shared";
5
5
  import { Connector, Datasource } from "nitro-drizzle/drivers";
@@ -32,7 +32,14 @@ type ConfigOf<T extends Connector<any, any, any, any>> = T extends Connector<any
32
32
  * Extracts the datasource type from a Connector factory.
33
33
  * @template T - The Connector type
34
34
  */
35
- type DatasourceOf<T extends Connector<any, any, any, any>> = T extends ((...args: any) => MaybePromise<infer R>) ? R extends Datasource<any, any, any> ? R : never : never;
35
+ type DatasourceOf<T extends Connector<any, any, any, any>> = T extends ((...args: any) => MaybePromise<infer R>) ? R extends Datasource<any, any, any> ? R : never : T extends ((...args: any) => any) ? Parameters<Parameters<T>[0]>[0] : never;
36
+ /**
37
+ * Infers the transaction type from a datasource, database instance, or transaction function.
38
+ * @template T - The datasource, database instance, or transaction function type
39
+ */
40
+ type TransactionOf<T> = T extends {
41
+ transaction: (transaction: (tx: infer TTx, ...args: any[]) => any, ...args: any[]) => any;
42
+ } ? TTx : never;
36
43
  type DatasourceMapper<T extends Variant<Connector<any, any, any, any>, ConnectorSpecifier>> = T extends any ? Variant<DatasourceOf<T["value"]>, T["selector"]> : never;
37
44
  /**
38
45
  * Mapped type of all datasources from the registry.
@@ -99,5 +106,5 @@ declare module "nitro/types" {
99
106
  interface NitroRuntimeHooks extends ConfigHooks {}
100
107
  }
101
108
  //#endregion
102
- export { ConfigHookArgs, ConfigHooks, ConfigOf, DatasourceConfig, DatasourceOf, DatasourceProvider, DatasourceProviderConfig, DatasourceProviderVariants, DatasourceRegistry, DatasourceVariants, Datasources, DriverRuntimeConfig, Primitive, PrimitiveProps, RuntimeConfig, UseDatasourceOptions, useConfig, useDatasource, useDialect };
109
+ export { ConfigHookArgs, ConfigHooks, ConfigOf, DatasourceConfig, DatasourceOf, DatasourceProvider, DatasourceProviderConfig, DatasourceProviderVariants, DatasourceRegistry, DatasourceVariants, Datasources, DialectCallback, DriverRuntimeConfig, Primitive, PrimitiveProps, RuntimeConfig, TransactionOf, UseDatasourceOptions, useConfig, useDatasource, useDialect };
103
110
  //# sourceMappingURL=runtime.d.mts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nitro-drizzle",
3
- "version": "0.3.0-beta.5",
3
+ "version": "0.3.0",
4
4
  "description": "Nitro module to integrate Drizzle ORM with ease.",
5
5
  "homepage": "https://github.com/myshkouski/nitro-drizzle#readme",
6
6
  "bugs": {
@@ -46,9 +46,9 @@
46
46
  "knitwork": "^1.3.0",
47
47
  "nitro": "3.0.260610-beta",
48
48
  "nitropack": "^2.13.4",
49
- "ohash": "^2.0.11",
49
+ "ohash": "^2.0.12",
50
50
  "pathe": "^2.0.3",
51
- "rollup": "^4.62.4",
51
+ "rollup": "^4.63.0",
52
52
  "strip-indent": "^4.1.1",
53
53
  "tinyglobby": "^0.2.17",
54
54
  "unstorage": "^1.17.5"
@@ -57,31 +57,31 @@
57
57
  "@arethetypeswrong/core": "^0.18.5",
58
58
  "@testcontainers/mysql": "^12.1.0",
59
59
  "@testcontainers/postgresql": "^12.1.0",
60
- "@types/node": "^26.1.2",
61
- "@vitest/coverage-v8": "^4.1.10",
62
- "@vitest/ui": "^4.1.10",
60
+ "@types/node": "^26.3.0",
61
+ "@vitest/coverage-v8": "^4.1.11",
62
+ "@vitest/ui": "^4.1.11",
63
63
  "changelogen": "^0.6.2",
64
64
  "lefthook": "^2.1.10",
65
65
  "listhen": "^1.10.1",
66
- "oxfmt": "^0.62.0",
67
- "oxlint": "^1.77.0",
66
+ "oxfmt": "^0.65.0",
67
+ "oxlint": "^1.80.0",
68
68
  "oxlint-tsgolint": "^7.0.2001",
69
- "publint": "^0.3.23",
69
+ "publint": "^0.3.24",
70
70
  "testcontainers": "^12.1.0",
71
71
  "tsdown": "^0.22.14",
72
72
  "typescript": "^7.0.2",
73
- "unplugin-unused": "^0.5.7",
74
- "vitest": "^4.1.10",
75
- "wrangler": "^4.118.0"
73
+ "unplugin-unused": "^0.6.0",
74
+ "vitest": "^4.1.11",
75
+ "wrangler": "^4.126.0"
76
76
  },
77
77
  "peerDependencies": {
78
- "@cloudflare/workers-types": "^5.20260804.1",
79
- "@electric-sql/pglite": "^0.5.4",
78
+ "@cloudflare/workers-types": "^5.20260826.1",
79
+ "@electric-sql/pglite": "^0.5.8",
80
80
  "better-sqlite3": "^12.11.1",
81
81
  "drizzle-kit": "^0.31.10",
82
82
  "drizzle-orm": "^0.45.2",
83
83
  "h3": "^1.15.11",
84
- "mysql2": "^3.23.2",
84
+ "mysql2": "^3.24.2",
85
85
  "postgres": "^3.4.9",
86
86
  "srvx": "^0.12.5"
87
87
  },