nitro-drizzle 0.2.8 → 0.2.9
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/dist/context/internal/templates.mjs.map +1 -1
- package/dist/context/internal/virtual.mjs +19 -2
- package/dist/context/internal/virtual.mjs.map +1 -1
- package/dist/context.d.mts +24 -9
- package/dist/context.mjs +65 -11
- package/dist/context.mjs.map +1 -1
- package/dist/module/internal/assets.mjs +8 -16
- package/dist/module/internal/assets.mjs.map +1 -1
- package/dist/module/internal/externals.mjs +2 -11
- package/dist/module/internal/externals.mjs.map +1 -1
- package/dist/module.d.mts +3 -3
- package/dist/module.mjs +44 -42
- package/dist/module.mjs.map +1 -1
- package/package.json +5 -1
- package/dist/module/internal/assets.d.mts +0 -12
- package/dist/module/internal/plugins.mjs +0 -13
- package/dist/module/internal/plugins.mjs.map +0 -1
- package/dist/module/internal/virtual.mjs +0 -23
- package/dist/module/internal/virtual.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"templates.mjs","names":[],"sources":["../../../src/context/internal/templates.ts"],"sourcesContent":["import {\n genTypeImport,\n genAugmentation,\n genInlineTypeImport,\n genString,\n genExport,\n} from \"knitwork\";\nimport type { DatasourceInfo } from \"..\";\nimport type { VirtualModules } from \"nitro-drizzle/shared\";\n\nexport function runtimeDeclarations(datasources: DatasourceInfo[]) {\n if (!datasources.length) {\n return \"\";\n }\n\n return [\n genTypeImport(\"nitro-drizzle/runtime\", [\"ToDatasourceProvider\"]),\n genAugmentation(\"nitro-drizzle/runtime\", {\n DatasourceRegistry: Object.fromEntries(\n datasources\n .filter((datasource) => {\n return datasource.enabled;\n })\n .map(({ name, imports }): [string, string] => {\n const schemaType = genSchemaType(imports.schema);\n const driverType = genInlineTypeImport(imports.connector);\n return [name, `${\"ToDatasourceProvider\"}<${schemaType}, ${driverType}<${schemaType}>>`];\n }),\n ),\n }),\n ].join(\"\\n\");\n}\n\nfunction genSchemaType(imports: string[]) {\n return imports.map((id) => `typeof import('${id}')`).join(\" & \");\n}\n\nexport type TypeReference = { types: string };\n\nexport type PathReference = { path: string };\n\nexport function genReference(reference: TypeReference | PathReference) {\n return /* ts */ `/// <reference ${Object.entries(reference)\n .map(([prop, value]) => `${prop}=\"${value}\"`)\n .join(\"\")} />`;\n}\n\nexport function moduleTypeDeclarations(\n datasources: DatasourceInfo[],\n): VirtualModules<`${string}.d.ts`> {\n if (!datasources.length) {\n return {};\n }\n\n const names = datasources.map((d) => d.name);\n\n const moduleId = \"nitro-drizzle/module\";\n\n const content = [\n genReference({ types: moduleId }),\n genAugmentation(moduleId, {\n DatasourceOptions: [\n {},\n {\n extends: `Record<${names.map((n) => genString(n)).join(\" | \")}, { connector: string; }>`,\n },\n ],\n }),\n /* ts */ `export {};`,\n ].join(\"\\n\");\n\n return {\n \"nitro-drizzle/module.d.ts\": content,\n };\n}\n\nexport function dialectDeclarations(datasources: DatasourceInfo[]) {\n return datasources\n .filter((d) => d.enabled)\n .map(({ name, dialect }) => {\n return /*ts*/ `\n declare module \"#nitro-drizzle/dialects/${name}\" {\n ${genExport(`nitro-drizzle/dialects/${dialect}`, \"*\")}\n }\n `;\n })\n .join(\"\\n\");\n}\n"],"mappings":";;AAUA,SAAgB,oBAAoB,
|
|
1
|
+
{"version":3,"file":"templates.mjs","names":[],"sources":["../../../src/context/internal/templates.ts"],"sourcesContent":["import {\n genTypeImport,\n genAugmentation,\n genInlineTypeImport,\n genString,\n genExport,\n} from \"knitwork\";\nimport type { DatasourceInfo } from \"..\";\nimport type { VirtualModules } from \"nitro-drizzle/shared\";\n\nexport function runtimeDeclarations(datasources: readonly DatasourceInfo[]) {\n if (!datasources.length) {\n return \"\";\n }\n\n return [\n genTypeImport(\"nitro-drizzle/runtime\", [\"ToDatasourceProvider\"]),\n genAugmentation(\"nitro-drizzle/runtime\", {\n DatasourceRegistry: Object.fromEntries(\n datasources\n .filter((datasource) => {\n return datasource.enabled;\n })\n .map(({ name, imports }): [string, string] => {\n const schemaType = genSchemaType(imports.schema);\n const driverType = genInlineTypeImport(imports.connector);\n return [name, `${\"ToDatasourceProvider\"}<${schemaType}, ${driverType}<${schemaType}>>`];\n }),\n ),\n }),\n ].join(\"\\n\");\n}\n\nfunction genSchemaType(imports: string[]) {\n return imports.map((id) => `typeof import('${id}')`).join(\" & \");\n}\n\nexport type TypeReference = { types: string };\n\nexport type PathReference = { path: string };\n\nexport function genReference(reference: TypeReference | PathReference) {\n return /* ts */ `/// <reference ${Object.entries(reference)\n .map(([prop, value]) => `${prop}=\"${value}\"`)\n .join(\"\")} />`;\n}\n\nexport function moduleTypeDeclarations(\n datasources: readonly DatasourceInfo[],\n): VirtualModules<`${string}.d.ts`> {\n if (!datasources.length) {\n return {};\n }\n\n const names = datasources.map((d) => d.name);\n\n const moduleId = \"nitro-drizzle/module\";\n\n const content = [\n genReference({ types: moduleId }),\n genAugmentation(moduleId, {\n DatasourceOptions: [\n {},\n {\n extends: `Record<${names.map((n) => genString(n)).join(\" | \")}, { connector: string; }>`,\n },\n ],\n }),\n /* ts */ `export {};`,\n ].join(\"\\n\");\n\n return {\n \"nitro-drizzle/module.d.ts\": content,\n };\n}\n\nexport function dialectDeclarations(datasources: readonly DatasourceInfo[]) {\n return datasources\n .filter((d) => d.enabled)\n .map(({ name, dialect }) => {\n return /*ts*/ `\n declare module \"#nitro-drizzle/dialects/${name}\" {\n ${genExport(`nitro-drizzle/dialects/${dialect}`, \"*\")}\n }\n `;\n })\n .join(\"\\n\");\n}\n"],"mappings":";;AAUA,SAAgB,oBAAoB,aAAwC;CAC1E,IAAI,CAAC,YAAY,QACf,OAAO;CAGT,OAAO,CACL,cAAc,yBAAyB,CAAC,sBAAsB,CAAC,GAC/D,gBAAgB,yBAAyB,EACvC,oBAAoB,OAAO,YACzB,YACG,QAAQ,eAAe;EACtB,OAAO,WAAW;CACpB,CAAC,CAAC,CACD,KAAK,EAAE,MAAM,cAAgC;EAC5C,MAAM,aAAa,cAAc,QAAQ,MAAM;EAE/C,OAAO,CAAC,MAAM,wBAA6B,WAAW,IADnC,oBAAoB,QAAQ,SACoB,EAAE,GAAG,WAAW,GAAG;CACxF,CAAC,CACL,EACF,CAAC,CACH,CAAC,CAAC,KAAK,IAAI;AACb;AAEA,SAAS,cAAc,SAAmB;CACxC,OAAO,QAAQ,KAAK,OAAO,kBAAkB,GAAG,GAAG,CAAC,CAAC,KAAK,KAAK;AACjE;AAMA,SAAgB,aAAa,WAA0C;CACrE,OAAgB,kBAAkB,OAAO,QAAQ,SAAS,CAAC,CACxD,KAAK,CAAC,MAAM,WAAW,GAAG,KAAK,IAAI,MAAM,EAAE,CAAC,CAC5C,KAAK,EAAE,EAAE;AACd;AAEA,SAAgB,uBACd,aACkC;CAClC,IAAI,CAAC,YAAY,QACf,OAAO,CAAC;CAGV,MAAM,QAAQ,YAAY,KAAK,MAAM,EAAE,IAAI;CAE3C,MAAM,WAAW;CAejB,OAAO,EACL,6BAdc;EACd,aAAa,EAAE,OAAO,SAAS,CAAC;EAChC,gBAAgB,UAAU,EACxB,mBAAmB,CACjB,CAAC,GACD,EACE,SAAS,UAAU,MAAM,KAAK,MAAM,UAAU,CAAC,CAAC,CAAC,CAAC,KAAK,KAAK,EAAE,2BAChE,CACF,EACF,CAAC;EACQ;CACX,CAAC,CAAC,KAAK,IAG8B,EACrC;AACF;AAEA,SAAgB,oBAAoB,aAAwC;CAC1E,OAAO,YACJ,QAAQ,MAAM,EAAE,OAAO,CAAC,CACxB,KAAK,EAAE,MAAM,cAAc;EAC1B,OAAc;kDAC8B,KAAK;YAC3C,UAAU,0BAA0B,WAAW,GAAG,EAAE;;;CAG5D,CAAC,CAAC,CACD,KAAK,IAAI;AACd"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { genExport, genImport, genObjectFromRaw, genObjectFromRawEntries, genSafeVariableName } from "knitwork";
|
|
1
|
+
import { genArrayFromRaw, genExport, genImport, genObjectFromRaw, genObjectFromRawEntries, genSafeVariableName, genString } from "knitwork";
|
|
2
2
|
//#region src/context/internal/virtual.ts
|
|
3
3
|
function genDatasourceModuleVariableName(dbModuleIndex) {
|
|
4
4
|
return genSafeVariableName(`dbModule${dbModuleIndex}`);
|
|
@@ -61,7 +61,24 @@ function dialectVirtualModules(datasources) {
|
|
|
61
61
|
return [`#nitro-drizzle/dialects/${name}`, genExport(`nitro-drizzle/dialects/${dialect}`, "*")];
|
|
62
62
|
}));
|
|
63
63
|
}
|
|
64
|
+
function migrationsVirtualModule(datasources, options) {
|
|
65
|
+
if (!options) return {};
|
|
66
|
+
const parts = [];
|
|
67
|
+
const enabledDatasources = datasources.filter((d) => d.enabled);
|
|
68
|
+
parts.push(`
|
|
69
|
+
export const migrationConfig = ${genObjectFromRawEntries(enabledDatasources.map(({ name, migrations }) => {
|
|
70
|
+
return [name, JSON.stringify(migrations.config)];
|
|
71
|
+
}))};
|
|
72
|
+
`);
|
|
73
|
+
let migrateOnInit = enabledDatasources.map((d) => d.name);
|
|
74
|
+
if (options && Array.isArray(options.migrateOnInit)) migrateOnInit = migrateOnInit.filter((name) => options.migrateOnInit.includes(name));
|
|
75
|
+
parts.push(`
|
|
76
|
+
export const MIGRATIONS_STORAGE_BASE = ${genString(options.storageBase)};
|
|
77
|
+
export const MIGRATE_ON_INIT = ${genArrayFromRaw(migrateOnInit.map((name) => genString(name)))};
|
|
78
|
+
`);
|
|
79
|
+
return { "#nitro-drizzle/migrations": parts.join("\n") };
|
|
80
|
+
}
|
|
64
81
|
//#endregion
|
|
65
|
-
export { dialectVirtualModules, runtimeVirtualModule };
|
|
82
|
+
export { dialectVirtualModules, migrationsVirtualModule, runtimeVirtualModule };
|
|
66
83
|
|
|
67
84
|
//# sourceMappingURL=virtual.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"virtual.mjs","names":[],"sources":["../../../src/context/internal/virtual.ts"],"sourcesContent":["import {\n genExport,\n genImport,\n genObjectFromRaw,\n genObjectFromRawEntries,\n genSafeVariableName,\n} from \"knitwork\";\nimport type { DatasourceInfo } from \"..\";\nimport type { VirtualModules } from \"nitro-drizzle/shared\";\n\nfunction genDatasourceModuleVariableName(dbModuleIndex: number) {\n return genSafeVariableName(`dbModule${dbModuleIndex}`);\n}\n\nfunction genMergedSchemaVariableName(dbModuleIndex: number) {\n return genSafeVariableName(`mergedSchema${dbModuleIndex}`);\n}\n\nconst genSchemaModuleVariableName = (dbModuleIndex: number, schemaIndex: number) =>\n genSafeVariableName(`schemaModule${dbModuleIndex}_${schemaIndex}`);\n\nfunction mergeSchemaModules(schemaIds: 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 function runtimeVirtualModule(datasources: DatasourceInfo[]) {\n const parts = datasources\n .filter((datasource) => datasource.enabled)\n .map(({ name, imports: { schema, connector } }, datasourceIndex) => {\n const datasourceModuleVariableName = genDatasourceModuleVariableName(datasourceIndex);\n\n const imports = [\n genImport(connector, datasourceModuleVariableName),\n ...schema.map((schemaModuleId, schemaIndex) => {\n return genImport(schemaModuleId, {\n name: \"*\",\n as: genSchemaModuleVariableName(datasourceIndex, schemaIndex),\n });\n }),\n ];\n\n const mergedSchemaVariableName = genMergedSchemaVariableName(datasourceIndex);\n const mergedSchemaObject = mergeSchemaModules(schema, datasourceIndex);\n\n const schemaDefinitions = [\n /* js */ `const ${mergedSchemaVariableName} = ${mergedSchemaObject};`,\n ];\n\n const entries: [string, string][] = [\n [\n name,\n genObjectFromRaw({\n create: /* js */ `(config) => ${datasourceModuleVariableName}(config, ${mergedSchemaVariableName})`,\n schema: mergedSchemaVariableName,\n }),\n ],\n ];\n\n return {\n imports,\n schemaDefinitions,\n entries,\n };\n })\n .reduce(\n (acc, { imports, schemaDefinitions, entries }) => {\n return {\n imports: [...acc.imports, ...imports],\n schemaDefinitions: [...acc.schemaDefinitions, ...schemaDefinitions],\n entries: [...acc.entries, ...entries],\n };\n },\n {\n imports: [] as string[],\n schemaDefinitions: [] as string[],\n entries: [] as [string, string][],\n },\n );\n\n const datasourceRegistryVarName = genSafeVariableName(\"datasourceRegistry\");\n\n return /* js */ `\n ${parts.imports.join(\"\\n\")}\n \n ${parts.schemaDefinitions.join(\"\\n\")}\n \n const ${datasourceRegistryVarName} = ${genObjectFromRawEntries(parts.entries)};\n\n export function useDatasourceRegistry() {\n return ${datasourceRegistryVarName};\n }\n `;\n}\n\n// Replaced with aliases\nexport function dialectVirtualModules(\n datasources: DatasourceInfo[],\n): VirtualModules<`#nitro-drizzle/${string}`> {\n return Object.fromEntries(\n datasources\n .filter((d) => d.enabled)\n .map(({ name, dialect }) => {\n return [\n `#nitro-drizzle/dialects/${name}`,\n genExport(`nitro-drizzle/dialects/${dialect}`, \"*\"),\n ] as const;\n }),\n );\n}\n"],"mappings":";;
|
|
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\";\n\nfunction genDatasourceModuleVariableName(dbModuleIndex: number) {\n return genSafeVariableName(`dbModule${dbModuleIndex}`);\n}\n\nfunction genMergedSchemaVariableName(dbModuleIndex: number) {\n return genSafeVariableName(`mergedSchema${dbModuleIndex}`);\n}\n\nconst genSchemaModuleVariableName = (dbModuleIndex: number, schemaIndex: number) =>\n genSafeVariableName(`schemaModule${dbModuleIndex}_${schemaIndex}`);\n\nfunction mergeSchemaModules(schemaIds: 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 function runtimeVirtualModule(datasources: readonly DatasourceInfo[]) {\n const parts = datasources\n .filter((datasource) => datasource.enabled)\n .map(({ name, imports: { schema, connector } }, datasourceIndex) => {\n const datasourceModuleVariableName = genDatasourceModuleVariableName(datasourceIndex);\n\n const imports = [\n genImport(connector, datasourceModuleVariableName),\n ...schema.map((schemaModuleId, schemaIndex) => {\n return genImport(schemaModuleId, {\n name: \"*\",\n as: genSchemaModuleVariableName(datasourceIndex, schemaIndex),\n });\n }),\n ];\n\n const mergedSchemaVariableName = genMergedSchemaVariableName(datasourceIndex);\n const mergedSchemaObject = mergeSchemaModules(schema, datasourceIndex);\n\n const schemaDefinitions = [\n /* js */ `const ${mergedSchemaVariableName} = ${mergedSchemaObject};`,\n ];\n\n const entries: [string, string][] = [\n [\n name,\n genObjectFromRaw({\n create: /* js */ `(config) => ${datasourceModuleVariableName}(config, ${mergedSchemaVariableName})`,\n schema: mergedSchemaVariableName,\n }),\n ],\n ];\n\n return {\n imports,\n schemaDefinitions,\n entries,\n };\n })\n .reduce(\n (acc, { imports, schemaDefinitions, entries }) => {\n return {\n imports: [...acc.imports, ...imports],\n schemaDefinitions: [...acc.schemaDefinitions, ...schemaDefinitions],\n entries: [...acc.entries, ...entries],\n };\n },\n {\n imports: [] as string[],\n schemaDefinitions: [] as string[],\n entries: [] as [string, string][],\n },\n );\n\n const datasourceRegistryVarName = genSafeVariableName(\"datasourceRegistry\");\n\n return /* js */ `\n ${parts.imports.join(\"\\n\")}\n \n ${parts.schemaDefinitions.join(\"\\n\")}\n \n const ${datasourceRegistryVarName} = ${genObjectFromRawEntries(parts.entries)};\n\n export function useDatasourceRegistry() {\n return ${datasourceRegistryVarName};\n }\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, dialect }) => {\n return [\n `#nitro-drizzle/dialects/${name}`,\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, migrations }) => {\n return [name, JSON.stringify(migrations.config)];\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(/*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":";;AAYA,SAAS,gCAAgC,eAAuB;CAC9D,OAAO,oBAAoB,WAAW,eAAe;AACvD;AAEA,SAAS,4BAA4B,eAAuB;CAC1D,OAAO,oBAAoB,eAAe,eAAe;AAC3D;AAEA,MAAM,+BAA+B,eAAuB,gBAC1D,oBAAoB,eAAe,cAAc,GAAG,aAAa;AAEnE,SAAS,mBAAmB,WAAqB,eAAuB;CACtE,OAAgB;;QAEV,CACS,MACT,GAAG,UAAU,KAAK,GAAG,wBACnB,4BAA4B,eAAe,mBAAmB,CAChE,CACF,CAAC,CAAC,KAAK,GAAG,EAAE;;;AAGlB;AAEA,SAAgB,qBAAqB,aAAwC;CAC3E,MAAM,QAAQ,YACX,QAAQ,eAAe,WAAW,OAAO,CAAC,CAC1C,KAAK,EAAE,MAAM,SAAS,EAAE,QAA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AC5C,IAAI,CAAC,SACH,OAAO,CAAC;CAGV,MAAM,QAAkB,CAAC;CAEzB,MAAM,qBAAqB,YAAY,QAAQ,MAAM,EAAE,OAAO;CAE9D,MAAM,KAAY;qCACiB,wBAC/B,mBAAmB,KAAK,EAAE,MAAM,iBAAiB;EAC/C,OAAO,CAAC,MAAM,KAAK,UAAU,WAAW,MAAM,CAAC;CACjD,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,KAAY;6CACyB,UAAU,QAAQ,WAAW,EAAE;qCACvC,gBAAgB,cAAc,KAAK,SAAS,UAAU,IAAI,CAAC,CAAC,EAAE;GAChG;CAED,OAAO,EACL,6BAA6B,MAAM,KAAK,IAAI,EAC9C;AACF"}
|
package/dist/context.d.mts
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
import { Config } from "drizzle-kit";
|
|
2
2
|
import { ConsolaInstance } from "consola";
|
|
3
3
|
import { MaybePromise, VirtualModules } from "nitro-drizzle/shared";
|
|
4
|
+
import { ServerAssetDir } from "nitropack/types";
|
|
4
5
|
|
|
5
6
|
//#region src/context/index.d.ts
|
|
6
7
|
/**
|
|
7
8
|
* Context interface for managing Drizzle datasource configurations.
|
|
8
9
|
*/
|
|
9
10
|
interface Context {
|
|
11
|
+
init(): MaybePromise<void>;
|
|
10
12
|
/**
|
|
11
13
|
* Reloads the context, clearing any cached datasource information.
|
|
12
14
|
*/
|
|
@@ -15,13 +17,6 @@ interface Context {
|
|
|
15
17
|
* Returns a list of all resolved datasource information.
|
|
16
18
|
*/
|
|
17
19
|
datasources(): MaybePromise<DatasourceInfo[]>;
|
|
18
|
-
/**
|
|
19
|
-
* Returns virtual module code for runtime datasource access.
|
|
20
|
-
*/
|
|
21
|
-
virtualModules(): MaybePromise<VirtualModules>;
|
|
22
|
-
virtualTypeDeclarations(): MaybePromise<Record<string, VirtualModules>>;
|
|
23
|
-
moduleTypeDeclarations(): MaybePromise<VirtualModules<`${string}.d.ts`>>;
|
|
24
|
-
runtimeTypeDeclarations(): MaybePromise<VirtualModules<`${string}.d.ts`>>;
|
|
25
20
|
}
|
|
26
21
|
/**
|
|
27
22
|
* Glob pattern or array of patterns to match Drizzle configuration files.
|
|
@@ -40,6 +35,13 @@ interface Resolver {
|
|
|
40
35
|
*/
|
|
41
36
|
tryResolve(id: string): string | undefined;
|
|
42
37
|
}
|
|
38
|
+
type ContextHook<TArgs extends readonly any[] = []> = (this: void, ...args: TArgs) => MaybePromise<void>;
|
|
39
|
+
interface MigrationOptions {
|
|
40
|
+
/** Base storage key path for migrations. */
|
|
41
|
+
storageBase: string;
|
|
42
|
+
/** Whether and which datasources to migrate on initialization. */
|
|
43
|
+
migrateOnInit: boolean | readonly string[];
|
|
44
|
+
}
|
|
43
45
|
interface ContextOptions {
|
|
44
46
|
logger?: ConsolaInstance;
|
|
45
47
|
/**
|
|
@@ -64,7 +66,20 @@ interface ContextOptions {
|
|
|
64
66
|
datasource: Record<string, {
|
|
65
67
|
connector: string;
|
|
66
68
|
}>;
|
|
67
|
-
|
|
69
|
+
migrations: MigrationOptions | undefined;
|
|
70
|
+
tasks?: ContextHook<[tasks: Record<string, {
|
|
71
|
+
handler: string;
|
|
72
|
+
description: string;
|
|
73
|
+
}>]>;
|
|
74
|
+
plugins: ContextHook<[plugins: readonly string[]]>;
|
|
75
|
+
declarations: ContextHook<[declarations: {
|
|
76
|
+
module: VirtualModules<`${string}.d.ts`>;
|
|
77
|
+
runtime: VirtualModules<`${string}.d.ts`>;
|
|
78
|
+
virtual: Record<string, VirtualModules<`${string}.d.ts`>>;
|
|
79
|
+
}]>;
|
|
80
|
+
virtualModules: ContextHook<[modules: VirtualModules]>;
|
|
81
|
+
assets: ContextHook<[assets: readonly ServerAssetDir[]]>;
|
|
82
|
+
inlineExternals?: ContextHook<[modules: readonly string[]]>;
|
|
68
83
|
}
|
|
69
84
|
/**
|
|
70
85
|
* Creates a Context instance for managing Drizzle datasource configurations.
|
|
@@ -100,5 +115,5 @@ interface DatasourceInfo {
|
|
|
100
115
|
};
|
|
101
116
|
}
|
|
102
117
|
//#endregion
|
|
103
|
-
export { ConfigPattern, Context, ContextOptions, DatasourceInfo, Resolver, createContext };
|
|
118
|
+
export { ConfigPattern, Context, ContextHook, ContextOptions, DatasourceInfo, MigrationOptions, Resolver, createContext };
|
|
104
119
|
//# sourceMappingURL=context.d.mts.map
|
package/dist/context.mjs
CHANGED
|
@@ -3,7 +3,9 @@ import { accent } from "./context/internal/logger.mjs";
|
|
|
3
3
|
import { resolveFiles } from "./context/internal/fs.mjs";
|
|
4
4
|
import { dialectDeclarations, genReference, moduleTypeDeclarations, runtimeDeclarations } from "./context/internal/templates.mjs";
|
|
5
5
|
import { transformDrizzleConfig } from "./context/internal/config.mjs";
|
|
6
|
-
import { dialectVirtualModules, runtimeVirtualModule } from "./context/internal/virtual.mjs";
|
|
6
|
+
import { dialectVirtualModules, migrationsVirtualModule, runtimeVirtualModule } from "./context/internal/virtual.mjs";
|
|
7
|
+
import { join } from "pathe";
|
|
8
|
+
import { pkgDir, pkgName } from "nitro-drizzle/meta";
|
|
7
9
|
import { colorize } from "consola/utils";
|
|
8
10
|
import { loadConfig } from "c12";
|
|
9
11
|
//#region src/context/index.ts
|
|
@@ -13,6 +15,40 @@ var DefaultContext = class {
|
|
|
13
15
|
constructor(options) {
|
|
14
16
|
this.#options = options;
|
|
15
17
|
}
|
|
18
|
+
async init() {
|
|
19
|
+
const datasources = await this.datasources();
|
|
20
|
+
await this.#options.plugins(this.enabledPlugins());
|
|
21
|
+
const [virtualModules, virtualTypes, moduleTypes, runtimeTypes] = await Promise.all([
|
|
22
|
+
this.virtualModules(datasources),
|
|
23
|
+
this.virtualTypeDeclarations(datasources),
|
|
24
|
+
this.moduleTypeDeclarations(datasources),
|
|
25
|
+
this.runtimeTypeDeclarations(datasources)
|
|
26
|
+
]);
|
|
27
|
+
await this.#options.virtualModules(virtualModules);
|
|
28
|
+
await this.#options.declarations({
|
|
29
|
+
virtual: virtualTypes,
|
|
30
|
+
module: moduleTypes,
|
|
31
|
+
runtime: runtimeTypes
|
|
32
|
+
});
|
|
33
|
+
if (this.#options.migrations) {
|
|
34
|
+
const assets = await this.migrationAssets(datasources);
|
|
35
|
+
if (assets) await this.#options.assets(assets);
|
|
36
|
+
await this.#options.tasks?.({ "drizzle:migrate": {
|
|
37
|
+
description: "Run drizzle migrations for a datasource.",
|
|
38
|
+
handler: "nitro-drizzle/migrations/task"
|
|
39
|
+
} });
|
|
40
|
+
}
|
|
41
|
+
if (this.#options.inlineExternals) {
|
|
42
|
+
const inlineModuleIds = [
|
|
43
|
+
"runtime",
|
|
44
|
+
"plugins",
|
|
45
|
+
"migrations"
|
|
46
|
+
].flatMap((id) => {
|
|
47
|
+
return [join(pkgName, id), join(pkgDir, "dist", id)];
|
|
48
|
+
});
|
|
49
|
+
await this.#options.inlineExternals(inlineModuleIds);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
16
52
|
async datasources() {
|
|
17
53
|
const { logger, baseDir, configPattern, resolver, datasource: datasourceOptions } = this.#options;
|
|
18
54
|
if (!this.#datasources) {
|
|
@@ -52,27 +88,45 @@ var DefaultContext = class {
|
|
|
52
88
|
}
|
|
53
89
|
return this.#datasources;
|
|
54
90
|
}
|
|
55
|
-
async
|
|
56
|
-
|
|
91
|
+
async migrationAssets(datasources) {
|
|
92
|
+
const migrationOptions = this.#options.migrations;
|
|
93
|
+
if (!migrationOptions) return [];
|
|
94
|
+
return datasources.reduce((acc, { name, migrations }) => {
|
|
95
|
+
const dir = migrations.assets;
|
|
96
|
+
if (dir) acc.push({
|
|
97
|
+
baseName: `${migrationOptions.storageBase}:${name}`,
|
|
98
|
+
dir
|
|
99
|
+
});
|
|
100
|
+
return acc;
|
|
101
|
+
}, []);
|
|
57
102
|
}
|
|
58
|
-
async
|
|
59
|
-
return
|
|
103
|
+
async virtualTypeDeclarations(datasources) {
|
|
104
|
+
return { "#nitro-drizzle/*": { "nitro-drizzle/virtual.d.ts": [dialectDeclarations(datasources)].join("\n") } };
|
|
60
105
|
}
|
|
61
|
-
|
|
62
|
-
const
|
|
106
|
+
enabledPlugins() {
|
|
107
|
+
const plugins = [];
|
|
108
|
+
const migrationOptions = this.#options.migrations;
|
|
109
|
+
if (migrationOptions ? Array.isArray(migrationOptions) ? 0 < migrationOptions.length : true == migrationOptions.migrateOnInit : false) plugins.push("migrate");
|
|
110
|
+
plugins.push("init");
|
|
111
|
+
return plugins.map((pluginName) => `nitro-drizzle/plugins/${pluginName}`);
|
|
112
|
+
}
|
|
113
|
+
async moduleTypeDeclarations(datasources) {
|
|
114
|
+
return moduleTypeDeclarations(datasources);
|
|
115
|
+
}
|
|
116
|
+
async runtimeTypeDeclarations(datasources) {
|
|
63
117
|
return { "nitro-drizzle/runtime.d.ts": [
|
|
64
|
-
...[...(/* @__PURE__ */ new Set([{ types: "nitro-drizzle/runtime" }, ...this
|
|
118
|
+
...[...(/* @__PURE__ */ new Set([{ types: "nitro-drizzle/runtime" }, ...this.enabledPlugins().map((pluginId) => {
|
|
65
119
|
return { types: pluginId };
|
|
66
120
|
})])).values()].map((reference) => genReference(reference)),
|
|
67
121
|
runtimeDeclarations(datasources),
|
|
68
122
|
`export {};`
|
|
69
123
|
].join("\n") };
|
|
70
124
|
}
|
|
71
|
-
async virtualModules() {
|
|
72
|
-
const datasources = await this.datasources();
|
|
125
|
+
async virtualModules(datasources) {
|
|
73
126
|
return {
|
|
74
127
|
"#nitro-drizzle/runtime": runtimeVirtualModule(datasources),
|
|
75
|
-
...dialectVirtualModules(datasources)
|
|
128
|
+
...dialectVirtualModules(datasources),
|
|
129
|
+
...migrationsVirtualModule(datasources, this.#options.migrations)
|
|
76
130
|
};
|
|
77
131
|
}
|
|
78
132
|
reload() {
|
package/dist/context.mjs.map
CHANGED
|
@@ -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\";\n\nimport { mapAsync } from \"./internal/async\";\nimport { accent } from \"./internal/logger\";\nimport { resolveFiles } from \"./internal/fs\";\nimport {\n dialectDeclarations,\n genReference,\n moduleTypeDeclarations,\n runtimeDeclarations,\n} from \"./internal/templates\";\nimport { transformDrizzleConfig } from \"./internal/config\";\nimport { dialectVirtualModules, runtimeVirtualModule } from \"./internal/virtual\";\n\nimport type { MaybePromise, VirtualModules } from \"nitro-drizzle/shared\";\n\n/**\n * Context interface for managing Drizzle datasource configurations.\n */\nexport interface Context {\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 * Returns virtual module code for runtime datasource access.\n */\n virtualModules(): MaybePromise<VirtualModules>;\n virtualTypeDeclarations(): MaybePromise<Record<string, VirtualModules>>;\n moduleTypeDeclarations(): MaybePromise<VirtualModules<`${string}.d.ts`>>;\n runtimeTypeDeclarations(): MaybePromise<VirtualModules<`${string}.d.ts`>>;\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 datasources() {\n const {\n logger,\n baseDir,\n configPattern,\n resolver,\n datasource: 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 let datasources: DatasourceInfo[] = await mapAsync(\n drizzleConfigsResolvedPaths,\n async (path) => {\n const { config } = await loadConfig<DrizzleConfig>({\n configFile: path,\n });\n const [_, dirName] = path.match(/(.+\\/(.+))\\/.+$/)!.slice(1, 3) as [string, string];\n\n return await transformDrizzleConfig(config, {\n cwd: this.#options.cwd,\n path,\n dirName,\n resolver,\n });\n },\n );\n\n datasources = Object.entries(datasourceOptions).reduce((_datasources, [name, options]) => {\n const datasource = datasources.find(\n (d) => d.name == name && options.connector == (d.driver ? d.driver : d.dialect),\n );\n if (!datasource) {\n return _datasources;\n }\n return [..._datasources, datasource];\n }, [] as DatasourceInfo[]);\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(\"yellow\", \"(\" + (datasource.driver || datasource.dialect) + \")\"),\n ].join(\" \");\n })\n .join(\", \"),\n );\n\n this.#datasources = datasources;\n }\n\n return this.#datasources;\n }\n\n async virtualTypeDeclarations(): Promise<Record<string, VirtualModules<`${string}.d.ts`>>> {\n const datasources = [...(await this.datasources())].filter((d) => d.enabled);\n return {\n \"#nitro-drizzle/*\": {\n \"nitro-drizzle/virtual.d.ts\": [dialectDeclarations(datasources)].join(\"\\n\"),\n },\n };\n }\n\n async moduleTypeDeclarations(): Promise<VirtualModules> {\n return moduleTypeDeclarations(await this.datasources());\n }\n\n async runtimeTypeDeclarations(): Promise<VirtualModules<`${string}.d.ts`>> {\n const datasources = await this.datasources();\n const references = new Set([\n { types: \"nitro-drizzle/runtime\" },\n ...this.#options.plugins.map((pluginId) => {\n return { types: pluginId };\n }),\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 async virtualModules(): Promise<VirtualModules<`#nitro-drizzle/${string}`>> {\n const datasources = await this.datasources();\n return {\n \"#nitro-drizzle/runtime\": runtimeVirtualModule(datasources),\n ...dialectVirtualModules(datasources),\n };\n }\n\n reload() {\n this.#datasources = null;\n }\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 * Attempts to resolve a module ID, returns undefined if not found.\n */\n tryResolve(id: string): string | undefined;\n}\n\nexport interface ContextOptions {\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 datasource: Record<string, { connector: string }>;\n\n plugins: 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 /** Directory name of the datasource (derived from config file location). */\n dirName: string;\n /** Unique name identifier for the datasource. */\n name: string;\n /** Whether the datasource is enabled (filtered by connector configuration). */\n enabled: boolean;\n /** Database dialect (e.g., 'sqlite', 'postgresql', 'mysql'). */\n dialect: string;\n /** Driver type if specified in config, otherwise undefined. */\n driver: string | undefined;\n /** Import paths for schema, connector, and helpers. */\n imports: {\n config: string;\n schema: string[];\n connector: string;\n helpers: string;\n };\n /** Migration configuration for this datasource. */\n migrations: {\n assets?: string;\n config?: Config[\"migrations\"];\n };\n}\n"],"mappings":";;;;;;;;;AAwCA,IAAM,iBAAN,MAAwC;CACtC,eAAwC;CACxC;CAEA,YAAY,SAAyB;EACnC,KAAKA,WAAW;CAClB;CAEA,MAAM,cAAc;EAClB,MAAM,EACJ,QACA,SACA,eACA,UACA,YAAY,sBACV,KAAKA;EAET,IAAI,CAAC,KAAKC,cAAc;GACtB,QAAQ,KAAK,oCAAoC,SAAS,QAAQ,OAAO,CAAC;GAO1E,IAAI,cAAgC,MAAM,SACxC,MANwC,aACxC,SACA,CAAC,aAAa,CAAC,CAAC,KAAK,CAAC,CAAC,KAAK,YAAY,OAAO,OAAO,CACxD,GAIE,OAAO,SAAS;IACd,MAAM,EAAE,WAAW,MAAM,WAA0B,EACjD,YAAY,KACd,CAAC;IACD,MAAM,CAAC,GAAG,WAAW,KAAK,MAAM,iBAAiB,CAAC,CAAE,MAAM,GAAG,CAAC;IAE9D,OAAO,MAAM,uBAAuB,QAAQ;KAC1C,KAAK,KAAKD,SAAS;KACnB;KACA;KACA;IACF,CAAC;GACH,CACF;GAEA,cAAc,OAAO,QAAQ,iBAAiB,CAAC,CAAC,QAAQ,cAAc,CAAC,MAAM,aAAa;IACxF,MAAM,aAAa,YAAY,MAC5B,MAAM,EAAE,QAAQ,QAAQ,QAAQ,cAAc,EAAE,SAAS,EAAE,SAAS,EAAE,QACzE;IACA,IAAI,CAAC,YACH,OAAO;IAET,OAAO,CAAC,GAAG,cAAc,UAAU;GACrC,GAAG,CAAC,CAAqB;GAEzB,QAAQ,KACN,8BACA,YACG,UAAU,eAAe;IACxB,OAAO,WAAW,UAAU,KAAK;GACnC,CAAC,CAAC,CACD,KAAK,eAAe;IACnB,IAAI,MAAM,CAAC,WAAW,IAAI;IAC1B,IAAI;IACJ,IAAI,WAAW,SACb,QAA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EAC3C,OAAO;GACL,0BAA0B,qBAAqB,WAAW;GAC1D,GAAG,sBAAsB,WAAW;EACtC;CACF;CAEA,SAAS;EACP,KAAKC,eAAe;CACtB;AACF;;;;;;AAoDA,SAAgB,cAAc,SAAkC;CAC9D,OAAO,IAAI,eAAe,OAAO;AACnC"}
|
|
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 genReference,\n moduleTypeDeclarations,\n runtimeDeclarations,\n} from \"./internal/templates\";\nimport { transformDrizzleConfig } from \"./internal/config\";\nimport {\n dialectVirtualModules,\n migrationsVirtualModule,\n runtimeVirtualModule,\n} from \"./internal/virtual\";\n\nimport type { MaybePromise, VirtualModules } from \"nitro-drizzle/shared\";\nimport type { ServerAssetDir } from \"nitropack/types\";\nimport { join } from \"pathe\";\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 [virtualModules, virtualTypes, moduleTypes, runtimeTypes] = await Promise.all([\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 virtual: virtualTypes,\n module: moduleTypes,\n runtime: runtimeTypes,\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.inlineExternals) {\n const inlineModuleIds = [\"runtime\", \"plugins\", \"migrations\"].flatMap((id) => {\n return [join(pkgName, id), join(pkgDir, \"dist\", id)];\n });\n\n await this.#options.inlineExternals(inlineModuleIds);\n }\n }\n\n async datasources() {\n const {\n logger,\n baseDir,\n configPattern,\n resolver,\n datasource: 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 let datasources: DatasourceInfo[] = await mapAsync(\n drizzleConfigsResolvedPaths,\n async (path) => {\n const { config } = await loadConfig<DrizzleConfig>({\n configFile: path,\n });\n const [_, dirName] = path.match(/(.+\\/(.+))\\/.+$/)!.slice(1, 3) as [string, string];\n\n return await transformDrizzleConfig(config, {\n cwd: this.#options.cwd,\n path,\n dirName,\n resolver,\n });\n },\n );\n\n datasources = Object.entries(datasourceOptions).reduce((_datasources, [name, options]) => {\n const datasource = datasources.find(\n (d) => d.name == name && options.connector == (d.driver ? d.driver : d.dialect),\n );\n if (!datasource) {\n return _datasources;\n }\n return [..._datasources, datasource];\n }, [] as DatasourceInfo[]);\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(\"yellow\", \"(\" + (datasource.driver || datasource.dialect) + \")\"),\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[]> {\n const migrationOptions = this.#options.migrations;\n\n if (!migrationOptions) {\n return [];\n }\n\n return datasources.reduce((acc, { name, migrations }) => {\n const dir = migrations.assets;\n if (dir) {\n acc.push({\n baseName: `${migrationOptions.storageBase}:${name}`,\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 }, [] as ServerAssetDir[]);\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 const pluginIds = plugins.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 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 ...dialectVirtualModules(datasources),\n ...migrationsVirtualModule(datasources, this.#options.migrations),\n };\n }\n\n reload() {\n this.#datasources = null;\n }\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 * Attempts to resolve a module ID, returns undefined if not found.\n */\n tryResolve(id: string): string | undefined;\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 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 datasource: Record<string, { connector: string }>;\n\n migrations: MigrationOptions | undefined;\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 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[]]>;\n\n inlineExternals?: 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 /** Directory name of the datasource (derived from config file location). */\n dirName: string;\n /** Unique name identifier for the datasource. */\n name: string;\n /** Whether the datasource is enabled (filtered by connector configuration). */\n enabled: boolean;\n /** Database dialect (e.g., 'sqlite', 'postgresql', 'mysql'). */\n dialect: string;\n /** Driver type if specified in config, otherwise undefined. */\n driver: string | undefined;\n /** Import paths for schema, connector, and helpers. */\n imports: {\n config: string;\n schema: string[];\n connector: string;\n helpers: string;\n };\n /** Migration configuration for this datasource. */\n migrations: {\n assets?: string;\n config?: Config[\"migrations\"];\n };\n}\n"],"mappings":";;;;;;;;;;;AAyCA,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,gBAAgB,cAAc,aAAa,gBAAgB,MAAM,QAAQ,IAAI;GAClF,KAAK,eAAe,WAAW;GAC/B,KAAK,wBAAwB,WAAW;GACx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
|
10
|
-
baseName: `${migrationOptions.storageBase}:${name}`,
|
|
11
|
-
dir
|
|
12
|
-
};
|
|
13
|
-
}).filter((value) => !!value);
|
|
14
|
-
config.serverAssets = [config.serverAssets ?? []].flat().filter((serverAsset) => {
|
|
15
|
-
return serverAsset?.baseName?.startsWith(migrationOptions.storageBase);
|
|
16
|
-
}).concat(migrationAssets);
|
|
2
|
+
function updateServerAssets(config, assets) {
|
|
3
|
+
config.serverAssets ||= [];
|
|
4
|
+
config.serverAssets = config.serverAssets.filter((_assets) => {
|
|
5
|
+
const baseName = _assets?.baseName;
|
|
6
|
+
if (!baseName) return true;
|
|
7
|
+
return assets.some((assets) => baseName == assets.baseName);
|
|
8
|
+
}).concat(assets);
|
|
17
9
|
}
|
|
18
10
|
//#endregion
|
|
19
|
-
export {
|
|
11
|
+
export { updateServerAssets };
|
|
20
12
|
|
|
21
13
|
//# sourceMappingURL=assets.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"assets.mjs","names":[],"sources":["../../../src/module/internal/assets.ts"],"sourcesContent":["import type {
|
|
1
|
+
{"version":3,"file":"assets.mjs","names":[],"sources":["../../../src/module/internal/assets.ts"],"sourcesContent":["import type { NitroConfig, ServerAssetDir } from \"nitropack/types\";\n\nexport function updateServerAssets(config: NitroConfig, assets: readonly ServerAssetDir[]) {\n config.serverAssets ||= [];\n config.serverAssets = config.serverAssets\n .filter((_assets) => {\n const baseName = _assets?.baseName;\n if (!baseName) {\n return true;\n }\n return assets.some((assets) => baseName == assets.baseName);\n })\n .concat(assets);\n}\n"],"mappings":";AAEA,SAAgB,mBAAmB,QAAqB,QAAmC;CACzF,OAAO,iBAAiB,CAAC;CACzB,OAAO,eAAe,OAAO,aAC1B,QAAQ,YAAY;EACnB,MAAM,WAAW,SAAS;EAC1B,IAAI,CAAC,UACH,OAAO;EAET,OAAO,OAAO,MAAM,WAAW,YAAY,OAAO,QAAQ;CAC5D,CAAC,CAAC,CACD,OAAO,MAAM;AAClB"}
|
|
@@ -1,17 +1,8 @@
|
|
|
1
|
-
import { pkgDir, pkgName } from "nitro-drizzle/meta";
|
|
2
|
-
import { join } from "node:path";
|
|
3
1
|
//#region src/module/internal/externals.ts
|
|
4
|
-
|
|
5
|
-
"runtime",
|
|
6
|
-
"plugins",
|
|
7
|
-
"migrations"
|
|
8
|
-
].flatMap((id) => {
|
|
9
|
-
return [join(pkgName, id), join(pkgDir, "dist", id)];
|
|
10
|
-
});
|
|
11
|
-
function addInlineExternals(nitroOptions) {
|
|
2
|
+
function addInlineExternals(nitroOptions, moduleIds) {
|
|
12
3
|
nitroOptions.externals ||= {};
|
|
13
4
|
nitroOptions.externals.inline ||= [];
|
|
14
|
-
nitroOptions.externals.inline.push(...
|
|
5
|
+
nitroOptions.externals.inline.push(...moduleIds);
|
|
15
6
|
}
|
|
16
7
|
//#endregion
|
|
17
8
|
export { addInlineExternals };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"externals.mjs","names":[],"sources":["../../../src/module/internal/externals.ts"],"sourcesContent":["import type { NitroOptions } from \"nitropack/types\";\
|
|
1
|
+
{"version":3,"file":"externals.mjs","names":[],"sources":["../../../src/module/internal/externals.ts"],"sourcesContent":["import type { NitroOptions } from \"nitropack/types\";\n\nexport function addInlineExternals(nitroOptions: NitroOptions, moduleIds: readonly string[]) {\n // @ts-expect-error\n nitroOptions.externals ||= {};\n nitroOptions.externals.inline ||= [];\n nitroOptions.externals.inline.push(...moduleIds);\n}\n"],"mappings":";AAEA,SAAgB,mBAAmB,cAA4B,WAA8B;CAE3F,aAAa,cAAc,CAAC;CAC5B,aAAa,UAAU,WAAW,CAAC;CACnC,aAAa,UAAU,OAAO,KAAK,GAAG,SAAS;AACjD"}
|
package/dist/module.d.mts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import { MigrationOptions } from "
|
|
2
|
-
import { ConfigPattern } from "nitro-drizzle/context";
|
|
1
|
+
import { ConfigPattern, MigrationOptions } from "nitro-drizzle/context";
|
|
3
2
|
import { NitroModule } from "nitropack/types";
|
|
4
3
|
|
|
5
4
|
//#region src/module/index.d.ts
|
|
@@ -28,7 +27,8 @@ interface ModuleOptions {
|
|
|
28
27
|
*/
|
|
29
28
|
migrations: false | MigrationOptions;
|
|
30
29
|
}
|
|
30
|
+
declare function createDefaultOptions(): ModuleOptions;
|
|
31
31
|
declare const module: NitroModule;
|
|
32
32
|
//#endregion
|
|
33
|
-
export { DatasourceOptions, ModuleOptions, module as default };
|
|
33
|
+
export { DatasourceOptions, ModuleOptions, createDefaultOptions, module as default };
|
|
34
34
|
//# sourceMappingURL=module.d.mts.map
|
package/dist/module.mjs
CHANGED
|
@@ -1,71 +1,73 @@
|
|
|
1
1
|
import { addAugmentations, addDeclarations } from "./module/internal/types.mjs";
|
|
2
2
|
import { createResolver } from "./module/internal/resolver.mjs";
|
|
3
|
-
import {
|
|
3
|
+
import { updateServerAssets } from "./module/internal/assets.mjs";
|
|
4
4
|
import { addInlineExternals } from "./module/internal/externals.mjs";
|
|
5
5
|
import { reloadPlugin } from "./module/internal/reload.mjs";
|
|
6
6
|
import { addPlugin } from "./module/internal/rollup.mjs";
|
|
7
|
-
import { migrationsVirtualModule } from "./module/internal/virtual.mjs";
|
|
8
|
-
import { enablePlugins } from "./module/internal/plugins.mjs";
|
|
9
7
|
import { defu } from "defu";
|
|
10
8
|
import { resolve } from "pathe";
|
|
11
9
|
import { resolveAlias } from "pathe/utils";
|
|
12
10
|
import { createContext } from "nitro-drizzle/context";
|
|
13
11
|
import { pkgName } from "nitro-drizzle/meta";
|
|
14
12
|
//#region src/module/index.ts
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
}
|
|
13
|
+
function createDefaultOptions() {
|
|
14
|
+
return {
|
|
15
|
+
baseDir: "~/drizzle",
|
|
16
|
+
configPattern: ["drizzle.config.{js,ts}", "drizzle-*.config.{js,ts}"],
|
|
17
|
+
migrations: {
|
|
18
|
+
storageBase: "drizzle:migrations",
|
|
19
|
+
migrateOnInit: false
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
23
|
const module = {
|
|
24
24
|
name: pkgName,
|
|
25
25
|
async setup(nitro) {
|
|
26
|
-
const moduleOptions = defu(nitro.options.drizzle,
|
|
27
|
-
const plugins = enablePlugins(nitro.options, moduleOptions);
|
|
26
|
+
const moduleOptions = defu(nitro.options.drizzle, createDefaultOptions());
|
|
28
27
|
const resolver = createResolver(nitro.options.rootDir, { alias: nitro.options.alias });
|
|
29
|
-
const
|
|
30
|
-
const
|
|
28
|
+
const baseDir = resolve(nitro.options.srcDir, resolveAlias(moduleOptions.baseDir, nitro.options.alias));
|
|
29
|
+
const context = createContext({
|
|
31
30
|
cwd: process.cwd(),
|
|
32
31
|
resolver,
|
|
33
|
-
baseDir
|
|
32
|
+
baseDir,
|
|
34
33
|
logger: nitro.logger,
|
|
35
34
|
configPattern: moduleOptions.configPattern,
|
|
36
35
|
datasource: { ...moduleOptions.datasources },
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
const context = createContext(contextOptions);
|
|
40
|
-
addInlineExternals(nitro.options);
|
|
41
|
-
Object.assign(nitro.options.virtual, await context.virtualModules(), migrationsVirtualModule(await context.datasources(), moduleOptions.migrations));
|
|
42
|
-
if (nitro.options.imports) nitro.options.imports.imports ||= [];
|
|
43
|
-
if (moduleOptions.migrations) {
|
|
44
|
-
await updateMigrationAssets(context, nitro.options, moduleOptions.migrations);
|
|
45
|
-
if (nitro.options.experimental.tasks) {
|
|
36
|
+
migrations: moduleOptions.migrations || void 0,
|
|
37
|
+
tasks: nitro.options.experimental.tasks ? (tasks) => {
|
|
46
38
|
nitro.options.tasks ||= {};
|
|
47
|
-
nitro.options.tasks
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
39
|
+
Object.assign(nitro.options.tasks, tasks);
|
|
40
|
+
} : void 0,
|
|
41
|
+
plugins(plugins) {
|
|
42
|
+
nitro.options.plugins.push(...plugins);
|
|
43
|
+
},
|
|
44
|
+
virtualModules(modules) {
|
|
45
|
+
Object.assign(nitro.options.virtual, modules);
|
|
46
|
+
},
|
|
47
|
+
declarations(declarations) {
|
|
48
|
+
nitro.hooks.hook("types:extend", async (types) => {
|
|
49
|
+
await addAugmentations(nitro.options, types, {
|
|
50
|
+
...declarations.runtime,
|
|
51
|
+
...declarations.module
|
|
52
|
+
});
|
|
53
|
+
await addDeclarations(nitro.options, types, declarations.virtual);
|
|
54
|
+
});
|
|
55
|
+
},
|
|
56
|
+
assets(assets) {
|
|
57
|
+
updateServerAssets(nitro.options, assets);
|
|
58
|
+
},
|
|
59
|
+
inlineExternals(modules) {
|
|
60
|
+
addInlineExternals(nitro.options, modules);
|
|
51
61
|
}
|
|
52
|
-
}
|
|
53
|
-
nitro.hooks.hook("rollup:before", async (nitro, config) => {
|
|
54
|
-
await addPlugin(config, reloadPlugin(nitro, contextOptions));
|
|
55
62
|
});
|
|
56
|
-
nitro.
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
await addAugmentations(nitro.options, types, {
|
|
60
|
-
...runtimeTypeDeclarations,
|
|
61
|
-
...moduleTypeDeclarations
|
|
62
|
-
});
|
|
63
|
-
const virtualTypeDeclarations = await context.virtualTypeDeclarations();
|
|
64
|
-
await addDeclarations(nitro.options, types, virtualTypeDeclarations);
|
|
63
|
+
if (nitro.options.imports) nitro.options.imports.imports ||= [];
|
|
64
|
+
nitro.hooks.hook("rollup:before", async (nitro, config) => {
|
|
65
|
+
await addPlugin(config, reloadPlugin(nitro, { baseDir }));
|
|
65
66
|
});
|
|
67
|
+
await context.init();
|
|
66
68
|
}
|
|
67
69
|
};
|
|
68
70
|
//#endregion
|
|
69
|
-
export { module as default };
|
|
71
|
+
export { createDefaultOptions, module as default };
|
|
70
72
|
|
|
71
73
|
//# sourceMappingURL=module.mjs.map
|
package/dist/module.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"module.mjs","names":[],"sources":["../src/module/index.ts"],"sourcesContent":["import type { NitroModule } from \"nitropack/types\";\nimport { defu } from \"defu\";\nimport { resolve } from \"pathe\";\nimport { resolveAlias } from \"pathe/utils\";\n\nimport {
|
|
1
|
+
{"version":3,"file":"module.mjs","names":[],"sources":["../src/module/index.ts"],"sourcesContent":["import type { NitroModule } from \"nitropack/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 } from \"nitro-drizzle/shared\";\nimport { pkgName } from \"nitro-drizzle/meta\";\n\nimport { addAugmentations, addDeclarations } from \"./internal/types\";\nimport { createResolver } from \"./internal/resolver\";\nimport { updateServerAssets } from \"./internal/assets\";\nimport { addInlineExternals } from \"./internal/externals\";\nimport { reloadPlugin } from \"./internal/reload\";\nimport { addPlugin } from \"./internal/rollup\";\n\n/**\n * Datasource-specific configuration options.\n * This interface is augmented by the module with connector-specific options.\n */\nexport interface DatasourceOptions {\n // augmented by module\n}\n\ndeclare module \"nitropack/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 | MigrationOptions;\n}\n\nexport function createDefaultOptions(): ModuleOptions {\n return {\n baseDir: \"~/drizzle\",\n configPattern: [\"drizzle.config.{js,ts}\", \"drizzle-*.config.{js,ts}\"],\n migrations: {\n storageBase: \"drizzle:migrations\",\n migrateOnInit: false,\n },\n };\n}\n\nconst module: NitroModule = {\n name: pkgName,\n async setup(nitro) {\n const moduleOptions = defu(nitro.options.drizzle, createDefaultOptions());\n\n const resolver = createResolver(nitro.options.rootDir, {\n alias: nitro.options.alias,\n });\n\n const baseDir = resolve(\n nitro.options.srcDir,\n resolveAlias(moduleOptions.baseDir, nitro.options.alias),\n );\n\n const contextOptions: ContextOptions = {\n cwd: process.cwd(),\n resolver: resolver,\n baseDir,\n logger: nitro.logger,\n configPattern: moduleOptions.configPattern,\n datasource: { ...moduleOptions.datasources },\n migrations: moduleOptions.migrations || void 0,\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(...plugins);\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.options, types, {\n ...declarations.runtime,\n ...declarations.module,\n });\n\n await addDeclarations(nitro.options, types, declarations.virtual);\n });\n },\n\n assets(assets) {\n updateServerAssets(nitro.options, assets);\n },\n\n inlineExternals(modules: readonly string[]) {\n addInlineExternals(nitro.options, modules);\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"],"mappings":";;;;;;;;;;;;AAqDA,SAAgB,uBAAsC;CACpD,OAAO;EACL,SAAS;EACT,eAAe,CAAC,0BAA0B,0BAA0B;EACpE,YAAY;GACV,aAAa;GACb,eAAe;EACjB;CACF;AACF;AAEA,MAAM,SAAsB;CAC1B,MAAM;CACN,MAAM,MAAM,OAAO;EACjB,MAAM,gBAAgB,KAAK,MAAM,QAA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@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nitro-drizzle",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.9",
|
|
4
4
|
"description": "Nitro module to integrate Drizzle ORM with ease.",
|
|
5
5
|
"homepage": "https://github.com/Myshkouski/nitro-drizzle#readme",
|
|
6
6
|
"bugs": {
|
|
@@ -52,6 +52,7 @@
|
|
|
52
52
|
"unstorage": "^1.17.5"
|
|
53
53
|
},
|
|
54
54
|
"devDependencies": {
|
|
55
|
+
"@arethetypeswrong/core": "^0.18.4",
|
|
55
56
|
"@cloudflare/workers-types": "^4.20260702.1",
|
|
56
57
|
"@testcontainers/mysql": "^12.0.4",
|
|
57
58
|
"@testcontainers/postgresql": "^12.0.4",
|
|
@@ -64,9 +65,11 @@
|
|
|
64
65
|
"oxfmt": "^0.57.0",
|
|
65
66
|
"oxlint": "^1.72.0",
|
|
66
67
|
"oxlint-tsgolint": "^0.24.0",
|
|
68
|
+
"publint": "^0.3.21",
|
|
67
69
|
"testcontainers": "^12.0.4",
|
|
68
70
|
"tsdown": "^0.22.3",
|
|
69
71
|
"typescript": "^6.0.3",
|
|
72
|
+
"unplugin-unused": "^0.5.7",
|
|
70
73
|
"vitest": "^4.1.10"
|
|
71
74
|
},
|
|
72
75
|
"peerDependencies": {
|
|
@@ -105,6 +108,7 @@
|
|
|
105
108
|
"test": "vitest run",
|
|
106
109
|
"test:coverage": "vitest run --coverage",
|
|
107
110
|
"typecheck": "tsc --noEmit",
|
|
111
|
+
"typecheck:fixtures": "nitro prepare fixtures/blog-api && tsc --noEmit -p fixtures/blog-api/tsconfig.json",
|
|
108
112
|
"release": "changelogen --release"
|
|
109
113
|
}
|
|
110
114
|
}
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
import { DatasourceOptions } from "../../module.mjs";
|
|
2
|
-
//#region src/module/internal/assets.d.ts
|
|
3
|
-
/** Options for configuring migration storage. */
|
|
4
|
-
interface MigrationOptions {
|
|
5
|
-
/** Base storage key path for migrations. */
|
|
6
|
-
storageBase: string;
|
|
7
|
-
/** Whether and which datasources to migrate on initialization. */
|
|
8
|
-
migrateOnInit: boolean | readonly (keyof DatasourceOptions extends never ? string : keyof DatasourceOptions)[];
|
|
9
|
-
}
|
|
10
|
-
//#endregion
|
|
11
|
-
export { MigrationOptions };
|
|
12
|
-
//# sourceMappingURL=assets.d.mts.map
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
//#region src/module/internal/plugins.ts
|
|
2
|
-
function enablePlugins(nitroOptions, moduleOptions) {
|
|
3
|
-
const plugins = [];
|
|
4
|
-
if (moduleOptions.migrations && moduleOptions.migrations.migrateOnInit) plugins.push("migrate");
|
|
5
|
-
plugins.push("init");
|
|
6
|
-
const pluginIds = plugins.map((pluginName) => `nitro-drizzle/plugins/${pluginName}`);
|
|
7
|
-
nitroOptions.plugins.push(...pluginIds);
|
|
8
|
-
return pluginIds;
|
|
9
|
-
}
|
|
10
|
-
//#endregion
|
|
11
|
-
export { enablePlugins };
|
|
12
|
-
|
|
13
|
-
//# sourceMappingURL=plugins.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"plugins.mjs","names":[],"sources":["../../../src/module/internal/plugins.ts"],"sourcesContent":["import type { NitroOptions } from \"nitropack\";\nimport type { ModuleOptions } from \"..\";\n\nexport function enablePlugins(\n nitroOptions: NitroOptions,\n moduleOptions: ModuleOptions,\n): readonly string[] {\n const plugins: (\"init\" | \"migrate\")[] = [];\n\n if (moduleOptions.migrations && moduleOptions.migrations.migrateOnInit) {\n plugins.push(\"migrate\");\n }\n\n plugins.push(\"init\");\n\n const pluginIds = plugins.map((pluginName) => `nitro-drizzle/plugins/${pluginName}`);\n\n nitroOptions.plugins.push(...pluginIds);\n\n return pluginIds;\n}\n"],"mappings":";AAGA,SAAgB,cACd,cACA,eACmB;CACnB,MAAM,UAAkC,CAAC;CAEzC,IAAI,cAAc,cAAc,cAAc,WAAW,eACvD,QAAQ,KAAK,SAAS;CAGxB,QAAQ,KAAK,MAAM;CAEnB,MAAM,YAAY,QAAQ,KAAK,eAAe,yBAAyB,YAAY;CAEnF,aAAa,QAAQ,KAAK,GAAG,SAAS;CAEtC,OAAO;AACT"}
|
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
import { genArrayFromRaw, genObjectFromRawEntries, genString } from "knitwork";
|
|
2
|
-
//#region src/module/internal/virtual.ts
|
|
3
|
-
function migrationsVirtualModule(datasources, options) {
|
|
4
|
-
if (!options) return {};
|
|
5
|
-
const parts = [];
|
|
6
|
-
const enabledDatasources = datasources.filter((d) => d.enabled);
|
|
7
|
-
parts.push(`
|
|
8
|
-
export const migrationConfig = ${genObjectFromRawEntries(enabledDatasources.map(({ name, migrations }) => {
|
|
9
|
-
return [name, JSON.stringify(migrations.config)];
|
|
10
|
-
}))};
|
|
11
|
-
`);
|
|
12
|
-
let migrateOnInit = enabledDatasources.map((d) => d.name);
|
|
13
|
-
if (options && Array.isArray(options.migrateOnInit)) migrateOnInit = migrateOnInit.filter((name) => options.migrateOnInit.includes(name));
|
|
14
|
-
parts.push(`
|
|
15
|
-
export const MIGRATIONS_STORAGE_BASE = ${genString(options.storageBase)};
|
|
16
|
-
export const MIGRATE_ON_INIT = ${genArrayFromRaw(migrateOnInit.map((name) => genString(name)))};
|
|
17
|
-
`);
|
|
18
|
-
return { "#nitro-drizzle/migrations": parts.join("\n") };
|
|
19
|
-
}
|
|
20
|
-
//#endregion
|
|
21
|
-
export { migrationsVirtualModule };
|
|
22
|
-
|
|
23
|
-
//# sourceMappingURL=virtual.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"virtual.mjs","names":[],"sources":["../../../src/module/internal/virtual.ts"],"sourcesContent":["import { genString, genArrayFromRaw, genObjectFromRawEntries } from \"knitwork\";\nimport type { VirtualModules } from \"nitro-drizzle/shared\";\nimport type { MigrationOptions } from \"./assets\";\nimport type { DatasourceInfo } from \"nitro-drizzle/context\";\n\nexport function migrationsVirtualModule(\n datasources: DatasourceInfo[],\n options: false | MigrationOptions,\n): VirtualModules {\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, migrations }) => {\n return [name, JSON.stringify(migrations.config)];\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(/*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":";;AAKA,SAAgB,wBACd,aACA,SACgB;CAChB,IAAI,CAAC,SACH,OAAO,CAAC;CAGV,MAAM,QAAkB,CAAC;CAEzB,MAAM,qBAAqB,YAAY,QAAQ,MAAM,EAAE,OAAO;CAE9D,MAAM,KAAY;qCACiB,wBAC/B,mBAAmB,KAAK,EAAE,MAAM,iBAAiB;EAC/C,OAAO,CAAC,MAAM,KAAK,UAAU,WAAW,MAAM,CAAC;CACjD,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,KAAY;6CACyB,UAAU,QAAQ,WAAW,EAAE;qCACvC,gBAAgB,cAAc,KAAK,SAAS,UAAU,IAAI,CAAC,CAAC,EAAE;GAChG;CAED,OAAO,EACL,6BAA6B,MAAM,KAAK,IAAI,EAC9C;AACF"}
|