vite-plugin-postgres-import 0.6.0 → 0.8.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.
Files changed (5) hide show
  1. package/README.md +146 -31
  2. package/package.json +10 -5
  3. package/parse.js +118 -21
  4. package/plugin.js +113 -7
  5. package/index.d.ts +0 -47
package/README.md CHANGED
@@ -37,22 +37,30 @@ delete from t
37
37
  where foo = :foo;
38
38
  ```
39
39
 
40
- `usage.js`:
40
+ `db-runtime.js` (the default runtime, should be mapped to `#db-runtime` via [subpath imports](https://nodejs.org/api/packages.html#subpath-imports)):
41
41
 
42
42
  ```js
43
43
  import { Pool } from "pg";
44
- import { Query, UpdateQuery, QueryMany, MultiStatement } from "./module.sql";
45
44
 
46
- const pool = new Pool("...");
45
+ export const db = new Pool("...");
46
+ ```
47
47
 
48
- const { id } = await Query(pool, { id: 1 });
48
+ `usage.js`:
49
49
 
50
- const rowsUpdated = await UpdateQuery(pool, { id: 1, newFoo: "bar" });
50
+ ```js
51
+ import { Query, UpdateQuery, QueryMany, MultiStatement } from "./module.sql";
52
+
53
+ const { id } = await Query({ id: 1 });
54
+
55
+ const rowsUpdated = await UpdateQuery({ id: 1, newFoo: "bar" });
51
56
 
52
- const array = await QueryMany(pool);
57
+ const array = await QueryMany();
53
58
 
54
59
  // array, object, number respectively
55
- const [all, something, deleted] = await MultiStatement(pool, { foo: "bar" });
60
+ const [all, something, deleted] = await MultiStatement({ foo: "bar" });
61
+
62
+ // override the runtime per call, e.g. to run inside a transaction
63
+ const rowsUpdated = await UpdateQuery({ id: 1, newFoo: "baz" }, { db: tx });
56
64
  ```
57
65
 
58
66
  > [!Warning]
@@ -67,19 +75,19 @@ The only 4 sqlc annotations that are available are the following:
67
75
 
68
76
  - `:execresult` - default if neither of the 3 below are provided, returns `QueryResult`.
69
77
 
70
- ex.: `Query<R extends QueryResultRow = { ... }>(c): Promise<QueryResult<R>>`
78
+ ex.: `Query<R extends QueryResultRow = { ... }>(params?, config?): Promise<QueryResult<R>>`
71
79
 
72
80
  - `:one` - returns template argument, or the default-parsed ones from the select/returning clause.
73
81
 
74
- ex.: `Query<R extends QueryResultRow = { ... }>(c): Promise<R>`
82
+ ex.: `Query<R extends QueryResultRow = { ... }>(params?, config?): Promise<R>`
75
83
 
76
84
  - `:many` - returns template argument as an array, or the default-parsed ones from the select/returning clause.
77
85
 
78
- ex.: `Query<R extends QueryResultRow = { ... }>(c): Promise<R[]>`
86
+ ex.: `Query<R extends QueryResultRow = { ... }>(params?, config?): Promise<R[]>`
79
87
 
80
88
  - `:execrows` - returns number of affected rows.
81
89
 
82
- ex.: `Query(c): Promise<number>`
90
+ ex.: `Query(params?, config?): Promise<number>`
83
91
 
84
92
  4 additional annotations not found in sqlc are available:
85
93
 
@@ -117,25 +125,25 @@ The only 4 sqlc annotations that are available are the following:
117
125
  > import { One as AnotherOne } from "./another-one.sql";
118
126
  >
119
127
  > // definitely don't do this
120
- > await One(c);
121
- > await AnotherOne(c, { id: ... });
128
+ > await One();
129
+ > await AnotherOne({ id: ... });
122
130
  > ```
123
131
  >
124
132
  > At best, you'd get an error in the provided example, due to mismatch in provided values, and at worst, assuming different examples, you'd be getting obscure bugs related to incorrect data.
125
133
 
126
134
  - `:array` - sets `rowMode` to `'array'`. Modifies to type declarations accordingly:
127
135
 
128
- ex. `:execresult`: `Query<R extends any[] = [ ... ]>(c): Promise<QueryArrayResult<R>>`
136
+ ex. `:execresult`: `Query<R extends any[] = [ ... ]>(params?, config?): Promise<QueryArrayResult<R>>`
129
137
 
130
- ex. `:one`: `Query<R extends any[] = [ ... ]>(c): Promise<R>`
138
+ ex. `:one`: `Query<R extends any[] = [ ... ]>(params?, config?): Promise<R>`
131
139
 
132
- ex. `:many`: `Query<R extends any[] = [ ... ]>(c): Promise<R[]>`
140
+ ex. `:many`: `Query<R extends any[] = [ ... ]>(params?, config?): Promise<R[]>`
133
141
 
134
142
  - `:iterable` - returns an `AsyncGenerator`. Once [Async Iterator Helpers](https://github.com/tc39/proposal-async-iterator-helpers)
135
143
  are in the standard, you can use crazy piping as following:
136
144
 
137
145
  ```js
138
- const result = await IterableQuery<{ ... }>(c, { foo: 'bar' })
146
+ const result = await IterableQuery<{ ... }>({ foo: 'bar' })
139
147
  .flatMap(superComplicatedCodeThatIsMoreUsefulToRunFromJS)
140
148
  .filter(Boolean)
141
149
  .toArray();
@@ -146,9 +154,9 @@ some of that computation to JS, you can finally do that! Or at least when that p
146
154
 
147
155
  - `:cursor` - returns an `Cursor`
148
156
 
149
- ex.: `Query<R extends QueryResultRow = { ... }>(c): Promise<Cursor<R>>`
157
+ ex.: `Query<R extends QueryResultRow = { ... }>(params?, config?): Promise<Cursor<R>>`
150
158
 
151
- ex. `:array`: `Query<R extends any[] = [ ... ]>(c): Promise<Cursor<R>>`
159
+ ex. `:array`: `Query<R extends any[] = [ ... ]>(params?, config?): Promise<Cursor<R>>`
152
160
 
153
161
  ## Configuring
154
162
 
@@ -156,32 +164,139 @@ ex.: `Query<R extends QueryResultRow = { ... }>(c): Promise<Cursor<R>>`
156
164
 
157
165
  Path to a folder where all declaration are kept relative to `rootFolder`, i.e.
158
166
  a file at path `src/sql/module.sql` will have its `.d.ts` file generated into `${typesFolder}/src/sql/module.sql.d.ts`.
159
- Make sure you include this one in your `tsconfig.json` as `"${typesFolder}/**/*.sql.d.ts"`.
167
+ Make sure you include this one in your tsconfig's `rootDirs` array as `"${typesFolder}/**/*.sql.d.ts"`.
160
168
 
161
169
  _default:_ `'node_modules/@types/vite-plugin-postgres-import/'`
162
170
 
163
- ### `modulePrefix`
164
-
165
- **CURRENTLY DISABLED**. This one changes the type declaration generation strategy to generate everything as `declare module` statements.
166
-
167
171
  ### `rootFolder`
168
172
 
169
173
  Root folder relative to which path calculation will be happening. May be useful for some I guess.
170
174
 
171
175
  _default:_ `process.cwd()`
172
176
 
173
- ## What this plugin does NOT do
177
+ ### `runtime`
174
178
 
175
- This plugin does not connect to the database or scan a schema folder, instead naively
176
- parsing select or returning clauses to figure out potential response types.
179
+ Where the default runtime comes from:
180
+
181
+ - `module` - specifier every generated module imports the runtime from. Point it at a module of yours
182
+ (typically via a subpath import) that provides the database connection. _default:_ `'#db-runtime'`
183
+ - `export` - named export of `module` holding the runtime. _default:_ `'db'`
184
+ - `type` - either `'object'` — the export is a `Queryable` (or a promise of one) — or `'function'` — the export
185
+ is called on each query invocation and returns a `Queryable` (or a promise of one). _default:_ `'object'`
186
+
187
+ ## Import aliases
188
+
189
+ If your `package.json` declares [subpath imports](https://nodejs.org/api/packages.html#subpath-imports),
190
+ matching `.sql` files get ambient module declarations generated for their aliased paths:
191
+
192
+ ```json
193
+ {
194
+ "imports": {
195
+ "#sql/*": "./src/sql/*"
196
+ }
197
+ }
198
+ ```
199
+
200
+ With that, `import { Query } from "#sql/module.sql"` is fully typed — declarations land in `${typesFolder}/modules.sql.d.ts`.
201
+ Exact and conditional (`{ "node": ..., "default": ... }`) targets are supported too.
177
202
 
178
- In a real TypeScript project you should probably still roll your own types?
203
+ ## Transactions
179
204
 
180
- And JavaScript projects still get the benefits of completions.
205
+ With the `'function'` runtime type, the runtime is re-evaluated on every query call — which means it can
206
+ consult [`AsyncLocalStorage`](https://nodejs.org/api/async_context.html#class-asynclocalstorage) and pick up
207
+ an _ambient_ transaction: queries anywhere down the call stack automatically run on the transaction's client,
208
+ no threading of `{ db }` through your functions. Combined with
209
+ [explicit resource management](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/await_using)
210
+ you get commit-explicitly, rollback-on-dispose semantics without any callback wrapping.
181
211
 
182
- ## SvelteKit use case
212
+ `vite.config.js`:
183
213
 
184
- I primarily use this in a SvelteKit project. The only thing I modify is setting `typesFolder` to `'.svelte-kit/types'` directory, and adding a `".svelte-kit/types/**/*.sql.d.ts"` record to my `include` array in `tsconfig.json`.
214
+ ```js
215
+ postgres({ runtime: { type: "function" } });
216
+ ```
217
+
218
+ `db-runtime.js`:
219
+
220
+ ```js
221
+ import { AsyncLocalStorage } from "node:async_hooks";
222
+ import { Pool } from "pg";
223
+
224
+ const pool = new Pool("...");
225
+ export const als = new AsyncLocalStorage();
226
+
227
+ export const db = () => als.getStore()?.current ?? pool;
228
+
229
+ let spSeq = 0;
230
+
231
+ // pushes a new transaction on the frame,
232
+ // nested calls result in savepoints.
233
+ export async function transaction(begin = "begin") {
234
+ const frame = als.getStore();
235
+
236
+ if (frame.current) {
237
+ // already inside a transaction - nest via a savepoint on the same client
238
+ const client = frame.current;
239
+ const name = `sp_${++spSeq}`;
240
+ await client.query(`savepoint ${name}`);
241
+ let done = false;
242
+ const finish = async (q) => {
243
+ done = true;
244
+ await client.query(q);
245
+ };
246
+ return {
247
+ db: client,
248
+ commit: () => finish(`release savepoint ${name}`),
249
+ rollback: () => finish(`rollback to savepoint ${name}`),
250
+ async [Symbol.asyncDispose]() {
251
+ if (!done) await finish(`rollback to savepoint ${name}`);
252
+ },
253
+ };
254
+ }
255
+
256
+ const client = await pool.connect();
257
+ await client.query(begin);
258
+ frame.current = client;
259
+ let done = false;
260
+ const finish = async (q) => {
261
+ done = true;
262
+ frame.current = undefined;
263
+ try {
264
+ await client.query(q);
265
+ } finally {
266
+ client.release();
267
+ }
268
+ };
269
+ return {
270
+ db: client,
271
+ commit: () => finish("commit"),
272
+ rollback: () => finish("rollback"),
273
+ async [Symbol.asyncDispose]() {
274
+ if (!done) await finish("rollback");
275
+ },
276
+ };
277
+ }
278
+ ```
279
+
280
+ ```js
281
+ import { transaction } from "#db-runtime";
282
+
283
+ await using tx = await transaction();
284
+ await UpdateQuery({ id: 1, newFoo: "bar" });
285
+ await InsertAudit({ id: 1 }); // same transaction, however deep the call stack
286
+ await tx.commit(); // anything thrown before this point rolls back on scope exit
287
+ ```
288
+
289
+ ## Jump to source
290
+
291
+ Generated `.d.ts` files ship with declaration maps pointing back at the original `.sql` file,
292
+ so "Go to Definition" / "Go to Source Definition" on an imported function (or the import path itself) lands you
293
+ on the query source itself. The vite transform also emits a sourcemap, so runtime stack traces
294
+ and debugger stepping map back to the `.sql` source.
295
+
296
+ ## What this plugin does NOT do
297
+
298
+ This plugin does not connect to the database or scan a schema folder, instead naively
299
+ parsing select or returning clauses to figure out potential response types.
185
300
 
186
301
  ## License
187
302
 
package/package.json CHANGED
@@ -1,14 +1,13 @@
1
1
  {
2
2
  "name": "vite-plugin-postgres-import",
3
3
  "description": "Vite plugin for importing SQL files as JS modules with sqlc-style annotations",
4
- "version": "0.6.0",
4
+ "version": "0.8.0",
5
5
  "main": "plugin.js",
6
6
  "type": "module",
7
7
  "author": "SirKostya009",
8
8
  "license": "MIT",
9
9
  "repository": "github:sirkostya009/vite-plugin-postgres-import",
10
10
  "files": [
11
- "index.d.ts",
12
11
  "parse.js"
13
12
  ],
14
13
  "keywords": [
@@ -19,14 +18,20 @@
19
18
  "sqlc"
20
19
  ],
21
20
  "devDependencies": {
22
- "vite": "^6"
21
+ "@sveltejs/kit": "^2",
22
+ "@types/pg": "*",
23
+ "vite": "^8"
23
24
  },
24
25
  "peerDependencies": {
26
+ "@sveltejs/kit": "^2",
27
+ "@types/pg": "*",
25
28
  "pg": "*",
26
- "pg-cursor": "*",
27
- "@types/pg": "*"
29
+ "pg-cursor": "*"
28
30
  },
29
31
  "peerDependenciesMeta": {
32
+ "@sveltejs/kit": {
33
+ "optional": true
34
+ },
30
35
  "pg-cursor": {
31
36
  "optional": true
32
37
  },
package/parse.js CHANGED
@@ -13,15 +13,90 @@ export function* parseModule(/** @type {string} */ sql) {
13
13
  .split(/;\s*$/m)
14
14
  .map((s) => s.trim())
15
15
  .filter(Boolean);
16
+ let queryStart = rema.index + rema[0].length;
17
+ while (queryStart < sql.length && /\s/.test(sql[queryStart])) queryStart++;
18
+ const pos = lineCol(sql, queryStart);
16
19
  if (rest.length > 0) {
17
- const firstMeta = metadata(first);
20
+ const firstMeta = Object.assign(metadata(first), { srcLine: pos.line, srcCol: pos.column });
18
21
  yield [firstMeta, ...rest.map((r) => metadata(r, firstMeta))];
19
22
  } else {
20
- yield metadata(first);
23
+ yield Object.assign(metadata(first), { srcLine: pos.line, srcCol: pos.column });
21
24
  }
22
25
  }
23
26
  }
24
27
 
28
+ function lineCol(/** @type {string} */ text, /** @type {number} */ index) {
29
+ let line = 0;
30
+ let lineStart = 0;
31
+ for (let i = 0; i < index; ++i) {
32
+ if (text.charCodeAt(i) === 10) {
33
+ line++;
34
+ lineStart = i + 1;
35
+ }
36
+ }
37
+ return { line, column: index - lineStart };
38
+ }
39
+
40
+ const b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
41
+
42
+ function vlq(/** @type {number} */ n) {
43
+ let v = n < 0 ? (-n << 1) | 1 : n << 1;
44
+ let out = "";
45
+ do {
46
+ let digit = v & 31;
47
+ v >>>= 5;
48
+ if (v) digit |= 32;
49
+ out += b64[digit];
50
+ } while (v);
51
+ return out;
52
+ }
53
+
54
+ /** @param {{genLine: number, genCol: number, srcIdx?: number, srcLine: number, srcCol: number}[]} mappings */
55
+ export function encodeMappings(mappings) {
56
+ mappings = mappings.toSorted((a, b) => a.genLine - b.genLine || a.genCol - b.genCol);
57
+ let out = "";
58
+ let prevGenLine = 0, prevGenCol = 0, prevSrcIdx = 0, prevSrcLine = 0, prevSrcCol = 0;
59
+ for (const m of mappings) {
60
+ if (m.genLine > prevGenLine) {
61
+ out += ";".repeat(m.genLine - prevGenLine);
62
+ prevGenLine = m.genLine;
63
+ prevGenCol = 0;
64
+ } else if (out) {
65
+ out += ",";
66
+ }
67
+ const srcIdx = m.srcIdx ?? 0;
68
+ out += vlq(m.genCol - prevGenCol) + vlq(srcIdx - prevSrcIdx) + vlq(m.srcLine - prevSrcLine) + vlq(m.srcCol - prevSrcCol);
69
+ prevGenCol = m.genCol;
70
+ prevSrcIdx = srcIdx;
71
+ prevSrcLine = m.srcLine;
72
+ prevSrcCol = m.srcCol;
73
+ }
74
+ return out;
75
+ }
76
+
77
+ /**
78
+ * Locates each module's export declaration in generated text and maps it back to its source position.
79
+ * @param {string} text
80
+ * @param {{name: string, srcLine: number, srcCol: number}[]} moduleMappings
81
+ */
82
+ export function exportMappings(text, moduleMappings, srcIdx = 0, lineOffset = 0) {
83
+ const out = [];
84
+ for (const m of moduleMappings) {
85
+ for (const decl of [`export function ${m.name}`, `export const ${m.name}`, `export async function* ${m.name}`]) {
86
+ let i = text.indexOf(decl);
87
+ while (i >= 0 && /[\w$]/.test(text[i + decl.length] ?? "")) {
88
+ i = text.indexOf(decl, i + 1);
89
+ }
90
+ if (i >= 0) {
91
+ const pos = lineCol(text, i + decl.length - m.name.length);
92
+ out.push({ genLine: pos.line + lineOffset, genCol: pos.column, srcIdx, srcLine: m.srcLine, srcCol: m.srcCol });
93
+ break;
94
+ }
95
+ }
96
+ }
97
+ return out;
98
+ }
99
+
25
100
  function metadata(/** @type {string} */ s, /** @type {ReturnType<typeof metadata>} */ firstMeta = undefined) {
26
101
  annotationRegex.lastIndex = 0;
27
102
  const match = firstMeta ? /--\s*(?<tags>(:\w+\s*)*)\r?\n/.exec(s) : annotationRegex.exec(s);
@@ -88,13 +163,31 @@ function metadata(/** @type {string} */ s, /** @type {ReturnType<typeof metadata
88
163
  export function codegen(
89
164
  /** @type {Iterable<ReturnType<typeof metadata> | ReturnType<typeof metadata>[]>} */ modules,
90
165
  /** @type {string} */ filename,
91
- /** @type {string} */ modulePrefix
166
+ /** @type {string=} */ moduleName,
167
+ /** @type {{module: string, export: string, type: "object" | "function"}} */ runtime = {
168
+ module: "#db-runtime",
169
+ export: "db",
170
+ type: "object",
171
+ }
92
172
  ) {
93
173
  let dts = [
94
174
  // `declare module '${modulePrefix}${filename}.sql' {`
95
- `import type { QueryResultRow, QueryResult, QueryArrayResult } from 'pg';\nimport { Queryable } from 'vite-plugin-postgres-import';`,
175
+ `import type { QueryResultRow, QueryResult, QueryArrayResult, QueryConfig, QueryArrayConfig, QueryConfigValues, Submittable } from 'pg';
176
+
177
+ interface QueryableObject {
178
+ query<T extends Submittable>(queryStream: T): T;
179
+ query<R extends any[] = any[], I = any[]>(queryConfig: QueryArrayConfig<I>, values?: QueryConfigValues<I>): Promise<QueryArrayResult<R>>;
180
+ query<R extends QueryResultRow = any, I = any>(queryConfig: QueryConfig<I>): Promise<QueryResult<R>>;
181
+ query<R extends QueryResultRow = any, I = any[]>(queryTextOrConfig: string | QueryConfig<I>, values?: QueryConfigValues<I>): Promise<QueryResult<R>>;
182
+ }
183
+
184
+ type Queryable = QueryableObject | Promise<QueryableObject>;`,
185
+ ];
186
+ let js = [
187
+ `import { escapeLiteral } from 'pg';\nimport { ${runtime.export} as __runtime } from '${runtime.module}';`,
96
188
  ];
97
- let js = [`import { escapeLiteral } from 'pg';`];
189
+ const rt = runtime.type === "function" ? "__runtime()" : "__runtime";
190
+ const mappings = [];
98
191
 
99
192
  for (let module of modules) {
100
193
  module = Array.isArray(module)
@@ -117,9 +210,11 @@ export function codegen(
117
210
  module.returnSymbols = module.returnSymbols.map((rs) => [...new Set(rs)]);
118
211
  }
119
212
 
120
- if (module.mode) {
213
+ mappings.push({ name: module.name, srcLine: module.srcLine ?? 0, srcCol: module.srcCol ?? 0 });
214
+
215
+ if (module.mode && !js[0].includes("pg-cursor")) {
121
216
  dts[0] += `\nimport Cursor from 'pg-cursor';`;
122
- js.push(`import Cursor from 'pg-cursor';`);
217
+ js[0] += `\nimport Cursor from 'pg-cursor';`;
123
218
  }
124
219
 
125
220
  const keys = module.params
@@ -146,9 +241,8 @@ export function ${module.name}<${module.returnSymbols
146
241
  }${r.length > 3 ? "\n" : " "}}`
147
242
  )
148
243
  .join(", ")}>(
149
- tx: Queryable,${keys && `\n\tparams: Record<${keys}, unknown>,`}${
150
- module.mode === ":iterable" ? `\n\tread?: number,` : ""
151
- }
244
+ ${keys ? `params: Record<${keys}, unknown>` : `params?: Record<string, never>`},
245
+ config?: { db?: Queryable${module.mode === ":iterable" ? "; read?: number" : ""} },
152
246
  ): ${
153
247
  module.mode === ":cursor"
154
248
  ? `Cursor<R1>`
@@ -192,14 +286,12 @@ export function ${module.name}<${module.returnSymbols
192
286
 
193
287
  js.push(
194
288
  module.mode === ":cursor"
195
- ? `export const ${module.name} = async (tx${
196
- paramsString && `, { ${paramsString} } = {}`
197
- }) => (await tx).query(new Cursor(\`${module.query}\`${paramsString && `, [ ${paramsString} ]`}${
198
- module.rowArray ? `, { rowMode: "array" }` : ""
199
- }));`
289
+ ? `export const ${module.name} = async ({ ${paramsString} } = {}, { db: __db = ${rt} } = {}) => (await __db).query(new Cursor(\`${
290
+ module.query
291
+ }\`${paramsString && `, [ ${paramsString} ]`}${module.rowArray ? `, { rowMode: "array" }` : ""}));`
200
292
  : module.mode === ":iterable"
201
- ? `export async function* ${module.name}(tx, ${paramsString && `{ ${paramsString} } = {}, `}read = 10) {
202
- const cursor = (await tx).query(new Cursor(\`${module.query}\`${paramsString && `, [ ${paramsString} ]`}${
293
+ ? `export async function* ${module.name}({ ${paramsString} } = {}, { db: __db = ${rt}, read = 10 } = {}) {
294
+ const cursor = (await __db).query(new Cursor(\`${module.query}\`${paramsString && `, [ ${paramsString} ]`}${
203
295
  module.rowArray ? `, { rowMode: "array" }` : ""
204
296
  }));
205
297
  try {
@@ -212,10 +304,10 @@ export function ${module.name}<${module.returnSymbols
212
304
  await cursor.close();
213
305
  }
214
306
  }`
215
- : `export const ${module.name} = async (tx, { ${paramsString} } = {}) => (await tx).query({
307
+ : `export const ${module.name} = async ({ ${paramsString} } = {}, { db: __db = ${rt} } = {}) => (await __db).query({
216
308
  ${module.prepared ? `name: "${module.name}",` : ""}
217
- text: \`${module.multiStatement ? module.query : module.query}\`,
218
- values: [ ${module.multiStatement || paramsString} ],
309
+ text: \`${module.query}\`,
310
+ ${module.multiStatement ? "" : `values: [ ${paramsString} ],`}
219
311
  ${module.rowArray ? `rowMode: "array",` : ""}
220
312
  }).then((${module.multiStatement && "["}${module.returnSymbols.map((_, i) => `r${i + 1}`).join()}${
221
313
  module.multiStatement && "]"
@@ -235,5 +327,10 @@ export function ${module.name}<${module.returnSymbols
235
327
  );
236
328
  }
237
329
 
238
- return { js: js.join("\n"), dts: dts.join("\n\n") + "\n" };
330
+ let moduleDeclaration = [];
331
+ if (moduleName) {
332
+ moduleDeclaration.push(`declare module "${moduleName}" {`, dts[0], ...dts.slice(1), `}`);
333
+ }
334
+
335
+ return { js: js.join("\n"), dts: dts.join("\n\n") + "\n", moduleDeclaration, mappings };
239
336
  }
package/plugin.js CHANGED
@@ -1,13 +1,62 @@
1
1
  import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
- import { codegen, parseModule } from "./parse.js";
3
+ import { codegen, encodeMappings, exportMappings, parseModule } from "./parse.js";
4
4
 
5
- /** @returns {import('vite').Plugin} */
6
- export default function postgres({
5
+ /**
6
+ * @param {object} [opts]
7
+ * @param {string} [opts.typesFolder="node_modules/@types/vite-plugin-postgres-import/"]
8
+ * Path to a folder where all declarations are kept relative to `rootFolder`, i.e. a file at path
9
+ * `src/sql/module.sql` will have its `.d.ts` file generated into `${typesFolder}/src/sql/module.sql.d.ts`.
10
+ * Make sure you include this one in your `tsconfig.json`.
11
+ * @param {string} [opts.rootFolder=process.cwd()]
12
+ * Root folder relative to which path calculation will be happening.
13
+ * @param {object} [opts.runtime] Where the default runtime comes from.
14
+ * @param {string} [opts.runtime.module="#db-runtime"]
15
+ * Module specifier the default runtime is imported from in every generated module.
16
+ * @param {string} [opts.runtime.export="db"]
17
+ * Named export of `runtime.module` providing the default runtime.
18
+ * @param {"object" | "function"} [opts.runtime.type="object"]
19
+ * Whether the runtime export is a `Queryable` itself or a function returning one (possibly async).
20
+ * @returns {Promise<import('vite').Plugin>}
21
+ */
22
+ export default async function postgres({
7
23
  typesFolder = "node_modules/@types/vite-plugin-postgres-import/",
8
- modulePrefix = "",
9
24
  rootFolder = process.cwd(),
25
+ runtime: { module: runtimeModule = "#db-runtime", export: runtimeExport = "db", type: runtimeType = "object" } = {},
10
26
  } = {}) {
27
+ const runtime = { module: runtimeModule, export: runtimeExport, type: runtimeType };
28
+ const imports = await fs
29
+ .readFile(path.join(rootFolder, "package.json"), "utf8")
30
+ .then((s) => JSON.parse(s).imports)
31
+ .catch(() => null);
32
+
33
+ const moduleDeclarations = new Map();
34
+
35
+ function* targets(/** @type {unknown} */ value) {
36
+ if (typeof value === "string") yield value;
37
+ else if (Array.isArray(value)) for (const v of value) yield* targets(v);
38
+ else if (value) for (const v of Object.values(value)) yield* targets(v);
39
+ }
40
+
41
+ function moduleName(/** @type {string} */ filename) {
42
+ const rel = filename.replaceAll(path.sep, "/");
43
+ for (const [key, value] of Object.entries(imports ?? {})) {
44
+ for (let target of targets(value)) {
45
+ target = target.replace(/^\.\//, "");
46
+ const star = target.indexOf("*");
47
+ if (star < 0) {
48
+ if (target === rel) return key;
49
+ continue;
50
+ }
51
+ const prefix = target.substring(0, star);
52
+ const suffix = target.substring(star + 1);
53
+ if (rel.length >= prefix.length + suffix.length && rel.startsWith(prefix) && rel.endsWith(suffix)) {
54
+ return key.replace("*", rel.substring(prefix.length, rel.length - suffix.length));
55
+ }
56
+ }
57
+ }
58
+ }
59
+
11
60
  return {
12
61
  name: "vite-plugin-sql-postgres",
13
62
  transform: {
@@ -42,16 +91,73 @@ export default function postgres({
42
91
  if (!/\.sql$/.test(id)) {
43
92
  return;
44
93
  }
45
- const filename = path.basename(id, ".sql");
94
+ const filename = path.relative(rootFolder, id);
46
95
 
47
- const { js, dts } = codegen(parseModule(sql), filename, modulePrefix);
96
+ const { js, dts, moduleDeclaration, mappings } = codegen(
97
+ parseModule(sql),
98
+ filename,
99
+ moduleName(filename),
100
+ runtime,
101
+ );
48
102
 
49
103
  const dtsFolder = path.join(typesFolder, path.relative(rootFolder, path.dirname(id)));
104
+ const dtsName = path.basename(filename, ".sql") + ".sql.d.ts";
50
105
  await fs.mkdir(dtsFolder, { recursive: true });
51
- await fs.writeFile(path.join(dtsFolder, filename + ".sql.d.ts"), dts);
106
+ await fs.writeFile(path.join(dtsFolder, dtsName), dts + `//# sourceMappingURL=${dtsName}.map\n`);
107
+ await fs.writeFile(
108
+ path.join(dtsFolder, dtsName + ".map"),
109
+ JSON.stringify({
110
+ version: 3,
111
+ file: dtsName,
112
+ sources: [path.relative(dtsFolder, id).replaceAll(path.sep, "/")],
113
+ names: [],
114
+ mappings: encodeMappings([
115
+ { genLine: 0, genCol: 0, srcLine: 0, srcCol: 0 },
116
+ ...exportMappings(dts, mappings),
117
+ ]),
118
+ }),
119
+ );
120
+ if (moduleDeclaration.length) {
121
+ moduleDeclarations.set(filename, { text: moduleDeclaration.join("\n"), mappings, id });
122
+ let line = 0;
123
+ const sources = [];
124
+ const combined = [];
125
+ const texts = [];
126
+ for (const { text, mappings, id } of moduleDeclarations.values()) {
127
+ const srcIdx = sources.push(path.relative(typesFolder, id).replaceAll(path.sep, "/")) - 1;
128
+ combined.push({ genLine: line, genCol: 0, srcIdx, srcLine: 0, srcCol: 0 });
129
+ combined.push(...exportMappings(text, mappings, srcIdx, line));
130
+ texts.push(text);
131
+ line += text.split("\n").length;
132
+ }
133
+ await fs.writeFile(
134
+ path.join(typesFolder, "modules.sql.d.ts"),
135
+ texts.join("\n") + "\n//# sourceMappingURL=modules.sql.d.ts.map\n",
136
+ );
137
+ await fs.writeFile(
138
+ path.join(typesFolder, "modules.sql.d.ts.map"),
139
+ JSON.stringify({
140
+ version: 3,
141
+ file: "modules.sql.d.ts",
142
+ sources,
143
+ names: [],
144
+ mappings: encodeMappings(combined),
145
+ }),
146
+ );
147
+ }
52
148
 
53
149
  return {
54
150
  code: js,
151
+ map: {
152
+ version: 3,
153
+ sources: [id],
154
+ sourcesContent: [sql],
155
+ names: [],
156
+ mappings: encodeMappings([
157
+ { genLine: 0, genCol: 0, srcLine: 0, srcCol: 0 },
158
+ ...exportMappings(js, mappings),
159
+ ]),
160
+ },
55
161
  moduleType: "js",
56
162
  };
57
163
  }
package/index.d.ts DELETED
@@ -1,47 +0,0 @@
1
- import type {
2
- QueryArrayConfig,
3
- QueryArrayResult,
4
- QueryConfig,
5
- QueryConfigValues,
6
- QueryResult,
7
- QueryResultRow,
8
- Submittable,
9
- } from "pg";
10
- import type { Plugin } from "vite";
11
-
12
- export default function postgres(opts?: {
13
- /**
14
- * Path to a folder where all declaration are kept relative to `rootFolder`, i.e. a file at path `src/sql/module.sql` will have its `.d.ts` file generated into `${typesFolder}/src/sql/module.sql.d.ts`. Make sure you include this one in your `tsconfig.json`.
15
- *
16
- * @default "node_modules/@types/vite-plugin-postgres-import/"
17
- */
18
- typesFolder?: string;
19
- /**
20
- * **CURRENTLY DISABLED**. This one changes the type declaration generation strategy to generate everything as `declare module` statements.
21
- */
22
- modulePrefix?: string;
23
- /**
24
- * Root folder relative to which path calculation will be happening. May be useful for some I guess.
25
- *
26
- * @default process.cwd()
27
- */
28
- rootFolder?: string;
29
- }): Plugin;
30
-
31
- export interface QueryableObject {
32
- query<T extends Submittable>(queryStream: T): T;
33
-
34
- query<R extends any[] = any[], I = any[]>(
35
- queryConfig: QueryArrayConfig<I>,
36
- values?: QueryConfigValues<I>
37
- ): Promise<QueryArrayResult<R>>;
38
-
39
- query<R extends QueryResultRow = any, I = any>(queryConfig: QueryConfig<I>): Promise<QueryResult<R>>;
40
-
41
- query<R extends QueryResultRow = any, I = any[]>(
42
- queryTextOrConfig: string | QueryConfig<I>,
43
- values?: QueryConfigValues<I>
44
- ): Promise<QueryResult<R>>;
45
- }
46
-
47
- export type Queryable = QueryableObject | Promise<QueryableObject>;