vite-plugin-postgres-import 0.7.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -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
+
48
+ `usage.js`:
47
49
 
48
- const { id } = await Query(pool, { id: 1 });
50
+ ```js
51
+ import { Query, UpdateQuery, QueryMany, MultiStatement } from "./module.sql";
49
52
 
50
- const rowsUpdated = await UpdateQuery(pool, { id: 1, newFoo: "bar" });
53
+ const { id } = await Query({ id: 1 });
51
54
 
52
- const array = await QueryMany(pool);
55
+ const rowsUpdated = await UpdateQuery({ id: 1, newFoo: "bar" });
56
+
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,7 +164,7 @@ 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
 
@@ -166,20 +174,129 @@ Root folder relative to which path calculation will be happening. May be useful
166
174
 
167
175
  _default:_ `process.cwd()`
168
176
 
169
- ## What this plugin does NOT do
177
+ ### `runtime`
170
178
 
171
- This plugin does not connect to the database or scan a schema folder, instead naively
172
- 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.
173
202
 
174
- In a real TypeScript project you should probably still roll your own types?
203
+ ## Transactions
175
204
 
176
- 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.
177
211
 
178
- ## SvelteKit use case
212
+ `vite.config.js`:
179
213
 
180
- 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";
181
223
 
182
- Also, when using SvelteKit aliases you can absolutely shove all your sql modules in a `src/sql` directory with a `$sql` alias and have module declarations generated for all of the files! Works automagically out of the box.
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.
183
300
 
184
301
  ## License
185
302
 
package/package.json CHANGED
@@ -1,15 +1,20 @@
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.7.0",
4
+ "version": "0.8.1",
5
5
  "main": "plugin.js",
6
+ "types": "plugin.d.ts",
6
7
  "type": "module",
8
+ "scripts": {
9
+ "prepack": "tsc -p ."
10
+ },
7
11
  "author": "SirKostya009",
8
12
  "license": "MIT",
9
13
  "repository": "github:sirkostya009/vite-plugin-postgres-import",
10
14
  "files": [
11
- "index.d.ts",
12
- "parse.js"
15
+ "parse.js",
16
+ "plugin.d.ts",
17
+ "plugin.d.ts.map"
13
18
  ],
14
19
  "keywords": [
15
20
  "vite",
@@ -19,20 +24,16 @@
19
24
  "sqlc"
20
25
  ],
21
26
  "devDependencies": {
22
- "@sveltejs/kit": "^2",
23
27
  "@types/pg": "*",
24
- "vite": "^6"
28
+ "typescript": "^7",
29
+ "vite": "^8"
25
30
  },
26
31
  "peerDependencies": {
27
- "@sveltejs/kit": "^2",
32
+ "@types/pg": "*",
28
33
  "pg": "*",
29
- "pg-cursor": "*",
30
- "@types/pg": "*"
34
+ "pg-cursor": "*"
31
35
  },
32
36
  "peerDependenciesMeta": {
33
- "@sveltejs/kit": {
34
- "optional": true
35
- },
36
37
  "pg-cursor": {
37
38
  "optional": true
38
39
  },
package/parse.js CHANGED
@@ -1,7 +1,5 @@
1
1
  const annotationRegex = /--\s*name:\s*(?<name>[a-zA-Z][\w_]*)\s*(?<tags>(:\w+\s*)*)?\r?\n/g;
2
2
 
3
- const partial = Symbol();
4
-
5
3
  export function* parseModule(/** @type {string} */ sql) {
6
4
  annotationRegex.lastIndex = 0;
7
5
 
@@ -15,13 +13,88 @@ export function* parseModule(/** @type {string} */ sql) {
15
13
  .split(/;\s*$/m)
16
14
  .map((s) => s.trim())
17
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);
18
19
  if (rest.length > 0) {
19
- const firstMeta = metadata(first);
20
+ const firstMeta = Object.assign(metadata(first), { srcLine: pos.line, srcCol: pos.column });
20
21
  yield [firstMeta, ...rest.map((r) => metadata(r, firstMeta))];
21
22
  } else {
22
- yield metadata(first);
23
+ yield Object.assign(metadata(first), { srcLine: pos.line, srcCol: pos.column });
24
+ }
25
+ }
26
+ }
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;
23
35
  }
24
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;
25
98
  }
26
99
 
27
100
  function metadata(/** @type {string} */ s, /** @type {ReturnType<typeof metadata>} */ firstMeta = undefined) {
@@ -90,13 +163,22 @@ function metadata(/** @type {string} */ s, /** @type {ReturnType<typeof metadata
90
163
  export function codegen(
91
164
  /** @type {Iterable<ReturnType<typeof metadata> | ReturnType<typeof metadata>[]>} */ modules,
92
165
  /** @type {string} */ filename,
93
- /** @type {ReturnType<typeof parseLocalSvelteConfigAliases>} */ aliases
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
+ }
94
172
  ) {
95
173
  let dts = [
96
174
  // `declare module '${modulePrefix}${filename}.sql' {`
97
175
  `import type { QueryResultRow, QueryResult, QueryArrayResult } from 'pg';\nimport { Queryable } from 'vite-plugin-postgres-import';`,
98
176
  ];
99
- let js = [`import { escapeLiteral } from 'pg';`];
177
+ let js = [
178
+ `import { escapeLiteral } from 'pg';\nimport { ${runtime.export} as __runtime } from '${runtime.module}';`,
179
+ ];
180
+ const rt = runtime.type === "function" ? "__runtime()" : "__runtime";
181
+ const mappings = [];
100
182
 
101
183
  for (let module of modules) {
102
184
  module = Array.isArray(module)
@@ -119,9 +201,11 @@ export function codegen(
119
201
  module.returnSymbols = module.returnSymbols.map((rs) => [...new Set(rs)]);
120
202
  }
121
203
 
122
- if (module.mode) {
204
+ mappings.push({ name: module.name, srcLine: module.srcLine ?? 0, srcCol: module.srcCol ?? 0 });
205
+
206
+ if (module.mode && !js[0].includes("pg-cursor")) {
123
207
  dts[0] += `\nimport Cursor from 'pg-cursor';`;
124
- js.push(`import Cursor from 'pg-cursor';`);
208
+ js[0] += `\nimport Cursor from 'pg-cursor';`;
125
209
  }
126
210
 
127
211
  const keys = module.params
@@ -148,9 +232,8 @@ export function ${module.name}<${module.returnSymbols
148
232
  }${r.length > 3 ? "\n" : " "}}`
149
233
  )
150
234
  .join(", ")}>(
151
- tx: Queryable,${keys && `\n\tparams: Record<${keys}, unknown>,`}${
152
- module.mode === ":iterable" ? `\n\tread?: number,` : ""
153
- }
235
+ ${keys ? `params: Record<${keys}, unknown>` : `params?: Record<string, never>`},
236
+ config?: { db?: Queryable${module.mode === ":iterable" ? "; read?: number" : ""} },
154
237
  ): ${
155
238
  module.mode === ":cursor"
156
239
  ? `Cursor<R1>`
@@ -194,14 +277,12 @@ export function ${module.name}<${module.returnSymbols
194
277
 
195
278
  js.push(
196
279
  module.mode === ":cursor"
197
- ? `export const ${module.name} = async (tx${
198
- paramsString && `, { ${paramsString} } = {}`
199
- }) => (await tx).query(new Cursor(\`${module.query}\`${paramsString && `, [ ${paramsString} ]`}${
200
- module.rowArray ? `, { rowMode: "array" }` : ""
201
- }));`
280
+ ? `export const ${module.name} = async ({ ${paramsString} } = {}, { db: __db = ${rt} } = {}) => (await __db).query(new Cursor(\`${
281
+ module.query
282
+ }\`${paramsString && `, [ ${paramsString} ]`}${module.rowArray ? `, { rowMode: "array" }` : ""}));`
202
283
  : module.mode === ":iterable"
203
- ? `export async function* ${module.name}(tx, ${paramsString && `{ ${paramsString} } = {}, `}read = 10) {
204
- const cursor = (await tx).query(new Cursor(\`${module.query}\`${paramsString && `, [ ${paramsString} ]`}${
284
+ ? `export async function* ${module.name}({ ${paramsString} } = {}, { db: __db = ${rt}, read = 10 } = {}) {
285
+ const cursor = (await __db).query(new Cursor(\`${module.query}\`${paramsString && `, [ ${paramsString} ]`}${
205
286
  module.rowArray ? `, { rowMode: "array" }` : ""
206
287
  }));
207
288
  try {
@@ -214,10 +295,10 @@ export function ${module.name}<${module.returnSymbols
214
295
  await cursor.close();
215
296
  }
216
297
  }`
217
- : `export const ${module.name} = async (tx, { ${paramsString} } = {}) => (await tx).query({
298
+ : `export const ${module.name} = async ({ ${paramsString} } = {}, { db: __db = ${rt} } = {}) => (await __db).query({
218
299
  ${module.prepared ? `name: "${module.name}",` : ""}
219
- text: \`${module.multiStatement ? module.query : module.query}\`,
220
- values: [ ${module.multiStatement || paramsString} ],
300
+ text: \`${module.query}\`,
301
+ ${module.multiStatement ? "" : `values: [ ${paramsString} ],`}
221
302
  ${module.rowArray ? `rowMode: "array",` : ""}
222
303
  }).then((${module.multiStatement && "["}${module.returnSymbols.map((_, i) => `r${i + 1}`).join()}${
223
304
  module.multiStatement && "]"
@@ -237,38 +318,10 @@ export function ${module.name}<${module.returnSymbols
237
318
  );
238
319
  }
239
320
 
240
- const match = aliases[filename] ?? aliases[partial].find(({ path }) => filename.startsWith(path));
241
321
  let moduleDeclaration = [];
242
- if (match) {
243
- const mod = "path" in match ? match.alias + filename.replace(match.path, "") : match.alias;
244
- moduleDeclaration.push(`declare module "${mod}" {`, dts[0], ...dts.slice(1), `}`);
322
+ if (moduleName) {
323
+ moduleDeclaration.push(`declare module "${moduleName}" {`, dts[0], ...dts.slice(1), `}`);
245
324
  }
246
325
 
247
- return { js: js.join("\n"), dts: dts.join("\n\n") + "\n", moduleDeclaration };
248
- }
249
-
250
- /** @returns {{ [partial]: { path: string; alias: string; }[]; [k: string]: { alias: string } }} */
251
- export async function parseLocalSvelteConfigAliases() {
252
- /** @type {{ default: import('@sveltejs/kit').Config }} */
253
- const { default: svelteConfig } = await import(process.cwd() + "/svelte.config.js").catch(() => ({
254
- default: {},
255
- }));
256
-
257
- const aliases = svelteConfig.kit?.alias ?? {};
258
-
259
- return Object.entries(aliases).reduce(
260
- (acc, [alias, path]) => {
261
- if (path.endsWith(".sql")) {
262
- acc[path] = { alias };
263
- } else {
264
- if (path.endsWith("/*")) {
265
- path = path.substring(0, path.length - 1);
266
- alias = alias.substring(0, alias.length - 1);
267
- }
268
- acc[partial].push({ path, alias });
269
- }
270
- return acc;
271
- },
272
- { [partial]: [] }
273
- );
326
+ return { js: js.join("\n"), dts: dts.join("\n\n") + "\n", moduleDeclaration, mappings };
274
327
  }
package/plugin.d.ts ADDED
@@ -0,0 +1,68 @@
1
+ import type { QueryArrayConfig, QueryArrayResult, QueryConfig, QueryConfigValues, QueryResult, QueryResultRow, Submittable } from "pg";
2
+ import type { Plugin } from "vite";
3
+ export type QueryableObject = {
4
+ query<T extends Submittable>(queryStream: T): T;
5
+ query<R extends any[] = any[], I = any[]>(queryConfig: QueryArrayConfig<I>, values?: QueryConfigValues<I>): Promise<QueryArrayResult<R>>;
6
+ query<R extends QueryResultRow = any, I = any>(queryConfig: QueryConfig<I>): Promise<QueryResult<R>>;
7
+ query<R extends QueryResultRow = any, I = any[]>(queryTextOrConfig: string | QueryConfig<I>, values?: QueryConfigValues<I>): Promise<QueryResult<R>>;
8
+ };
9
+ export type Queryable = QueryableObject | Promise<QueryableObject>;
10
+ export type PostgresOptions = {
11
+ /**
12
+ * 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`. Defaults to `"node_modules/@types/vite-plugin-postgres-import/"`.
13
+ */
14
+ typesFolder?: string;
15
+ /**
16
+ * Root folder relative to which path calculation will be happening. Defaults to `process.cwd()`.
17
+ */
18
+ rootFolder?: string;
19
+ /**
20
+ * Where the default runtime comes from.
21
+ */
22
+ runtime?: RuntimeOptions;
23
+ };
24
+ export type RuntimeOptions = {
25
+ /**
26
+ * Module specifier the default runtime is imported from in every generated module. Defaults to `"#db-runtime"`.
27
+ */
28
+ module?: string;
29
+ /**
30
+ * Named export of `module` providing the default runtime. Defaults to `"db"`.
31
+ */
32
+ export?: string;
33
+ /**
34
+ * Whether the export is a `Queryable` itself or a function returning one (possibly async). Defaults to `"object"`.
35
+ */
36
+ type?: "object" | "function";
37
+ };
38
+ /**
39
+ * @import { QueryArrayConfig, QueryArrayResult, QueryConfig, QueryConfigValues, QueryResult, QueryResultRow, Submittable } from "pg"
40
+ * @import { Plugin, TransformResult } from "vite"
41
+ */
42
+ /**
43
+ * @typedef {{
44
+ * query<T extends Submittable>(queryStream: T): T;
45
+ * query<R extends any[] = any[], I = any[]>(queryConfig: QueryArrayConfig<I>, values?: QueryConfigValues<I>): Promise<QueryArrayResult<R>>;
46
+ * query<R extends QueryResultRow = any, I = any>(queryConfig: QueryConfig<I>): Promise<QueryResult<R>>;
47
+ * query<R extends QueryResultRow = any, I = any[]>(queryTextOrConfig: string | QueryConfig<I>, values?: QueryConfigValues<I>): Promise<QueryResult<R>>;
48
+ * }} QueryableObject
49
+ */
50
+ /** @typedef {QueryableObject | Promise<QueryableObject>} Queryable */
51
+ /**
52
+ * @typedef {object} PostgresOptions
53
+ * @property {string} [typesFolder] 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`. Defaults to `"node_modules/@types/vite-plugin-postgres-import/"`.
54
+ * @property {string} [rootFolder] Root folder relative to which path calculation will be happening. Defaults to `process.cwd()`.
55
+ * @property {RuntimeOptions} [runtime] Where the default runtime comes from.
56
+ */
57
+ /**
58
+ * @typedef {object} RuntimeOptions
59
+ * @property {string} [module] Module specifier the default runtime is imported from in every generated module. Defaults to `"#db-runtime"`.
60
+ * @property {string} [export] Named export of `module` providing the default runtime. Defaults to `"db"`.
61
+ * @property {"object" | "function"} [type] Whether the export is a `Queryable` itself or a function returning one (possibly async). Defaults to `"object"`.
62
+ */
63
+ /**
64
+ * @param {PostgresOptions} [opts]
65
+ * @returns {Promise<Plugin>}
66
+ */
67
+ export default function postgres(opts?: PostgresOptions): Promise<Plugin>;
68
+ //# sourceMappingURL=plugin.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["plugin.js"],"names":[],"mappings":"AAKG,OAAQ,KAAA,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,WAAW,EAAE,iBAAiB,EAAE,WAAW,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,IAAI,CAClI;AAAA,OAAQ,KAAA,EAAE,MAAM,EAAmB,MAAM,MAAM,CAAA;AAI/C,YAKG,eAAe,GALR;IACR,KAAK,CAAC,CAAC,SAAS,WAAW,EAAE,WAAW,EAAE,CAAC,GAAG,CAAC,CAAC;IAChD,KAAK,CAAC,CAAC,SAAS,GAAG,EAAE,GAAG,GAAG,EAAE,EAAE,CAAC,GAAG,GAAG,EAAE,EAAE,WAAW,EAAE,gBAAgB,CAAC,CAAC,CAAC,EAAE,MAAM,CAAC,EAAE,iBAAiB,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAAC,CAAC,CAAC,CAAC;IACzI,KAAK,CAAC,CAAC,SAAS,cAAc,GAAG,GAAG,EAAE,CAAC,GAAG,GAAG,EAAE,WAAW,EAAE,WAAW,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC;IACrG,KAAK,CAAC,CAAC,SAAS,cAAc,GAAG,GAAG,EAAE,CAAC,GAAG,GAAG,EAAE,EAAE,iBAAiB,EAAE,MAAM,GAAG,WAAW,CAAC,CAAC,CAAC,EAAE,MAAM,CAAC,EAAE,iBAAiB,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC;CACtJ,CAAiB;AAGjB,YAAsD,SAAS,GAArD,eAAe,GAAG,OAAO,CAAC,eAAe,CAAC,CAAW;AAGhE,YAAkB,eAAe,GACjC;;;;IAAoB,WAAW,AAA/B,CACA,EADW,MAAM,CACjB;;;;IAAoB,UAAU,AAA9B,CACA,EADW,MAAM,CACjB;;;;IAA4B,OAAO,AAAnC,CACF,EADa,cAAc,CAC3B;CAAA,CAAA;AAGE,YAAkB,cAAc,GAChC;;;;IAAoB,MAAM,AAA1B,CACA,EADW,MAAM,CACjB;;;;IAAoB,MAAM,AAA1B,CACA,EADW,MAAM,CACjB;;;;IAAmC,IAAI,AAAvC,CACF,EADa,QAAQ,GAAG,UAAU,CAClC;CAAA,CAAA;AA5BD;;;GAGG;AAEH;;;;;;;GAOG;AAEH,sEAAsE;AAEtE;;;;;GAKG;AAEH;;;;;GAKG;AAEH;;;GAGG;AACH,wBAA8B,QAAQ,CAAC,IAAI,AAHxC,CACA,EADQ,eAGqC,GAFnC,OAAO,CAAC,MAAM,CAAC,CAiJ3B"}
package/plugin.js CHANGED
@@ -1,16 +1,80 @@
1
1
  import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
- import { codegen, parseLocalSvelteConfigAliases, parseModule } from "./parse.js";
3
+ import { codegen, encodeMappings, exportMappings, parseModule } from "./parse.js";
4
4
 
5
- /** @returns {import('vite').Plugin} */
6
- export default async function postgres({
7
- typesFolder = "node_modules/@types/vite-plugin-postgres-import/",
8
- rootFolder = process.cwd(),
9
- } = {}) {
10
- const aliases = await parseLocalSvelteConfigAliases();
5
+ /**
6
+ * @import { QueryArrayConfig, QueryArrayResult, QueryConfig, QueryConfigValues, QueryResult, QueryResultRow, Submittable } from "pg"
7
+ * @import { Plugin, TransformResult } from "vite"
8
+ */
9
+
10
+ /**
11
+ * @typedef {{
12
+ * query<T extends Submittable>(queryStream: T): T;
13
+ * query<R extends any[] = any[], I = any[]>(queryConfig: QueryArrayConfig<I>, values?: QueryConfigValues<I>): Promise<QueryArrayResult<R>>;
14
+ * query<R extends QueryResultRow = any, I = any>(queryConfig: QueryConfig<I>): Promise<QueryResult<R>>;
15
+ * query<R extends QueryResultRow = any, I = any[]>(queryTextOrConfig: string | QueryConfig<I>, values?: QueryConfigValues<I>): Promise<QueryResult<R>>;
16
+ * }} QueryableObject
17
+ */
18
+
19
+ /** @typedef {QueryableObject | Promise<QueryableObject>} Queryable */
20
+
21
+ /**
22
+ * @typedef {object} PostgresOptions
23
+ * @property {string} [typesFolder] 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`. Defaults to `"node_modules/@types/vite-plugin-postgres-import/"`.
24
+ * @property {string} [rootFolder] Root folder relative to which path calculation will be happening. Defaults to `process.cwd()`.
25
+ * @property {RuntimeOptions} [runtime] Where the default runtime comes from.
26
+ */
27
+
28
+ /**
29
+ * @typedef {object} RuntimeOptions
30
+ * @property {string} [module] Module specifier the default runtime is imported from in every generated module. Defaults to `"#db-runtime"`.
31
+ * @property {string} [export] Named export of `module` providing the default runtime. Defaults to `"db"`.
32
+ * @property {"object" | "function"} [type] Whether the export is a `Queryable` itself or a function returning one (possibly async). Defaults to `"object"`.
33
+ */
34
+
35
+ /**
36
+ * @param {PostgresOptions} [opts]
37
+ * @returns {Promise<Plugin>}
38
+ */
39
+ export default async function postgres(opts = {}) {
40
+ const {
41
+ typesFolder = "node_modules/@types/vite-plugin-postgres-import/",
42
+ rootFolder = process.cwd(),
43
+ runtime: { module: runtimeModule = "#db-runtime", export: runtimeExport = "db", type: runtimeType = "object" } = {},
44
+ } = opts;
45
+ const runtime = { module: runtimeModule, export: runtimeExport, type: runtimeType };
46
+ const imports = await fs
47
+ .readFile(path.join(rootFolder, "package.json"), "utf8")
48
+ .then((s) => JSON.parse(s).imports)
49
+ .catch(() => null);
11
50
 
12
51
  const moduleDeclarations = new Map();
13
52
 
53
+ function* targets(/** @type {unknown} */ value) {
54
+ if (typeof value === "string") yield value;
55
+ else if (Array.isArray(value)) for (const v of value) yield* targets(v);
56
+ else if (value) for (const v of Object.values(value)) yield* targets(v);
57
+ }
58
+
59
+ function moduleName(/** @type {string} */ filename) {
60
+ const rel = filename.replaceAll(path.sep, "/");
61
+ for (const [key, value] of Object.entries(imports ?? {})) {
62
+ for (let target of targets(value)) {
63
+ target = target.replace(/^\.\//, "");
64
+ const star = target.indexOf("*");
65
+ if (star < 0) {
66
+ if (target === rel) return key;
67
+ continue;
68
+ }
69
+ const prefix = target.substring(0, star);
70
+ const suffix = target.substring(star + 1);
71
+ if (rel.length >= prefix.length + suffix.length && rel.startsWith(prefix) && rel.endsWith(suffix)) {
72
+ return key.replace("*", rel.substring(prefix.length, rel.length - suffix.length));
73
+ }
74
+ }
75
+ }
76
+ }
77
+
14
78
  return {
15
79
  name: "vite-plugin-sql-postgres",
16
80
  transform: {
@@ -40,25 +104,78 @@ export default async function postgres({
40
104
  },
41
105
  };
42
106
 
43
- /** @returns {Promise<import("vite").TransformResult>} */
107
+ /** @returns {Promise<TransformResult | undefined>} */
44
108
  async function transform(/** @type {string} */ sql, /** @type {string} */ id) {
45
109
  if (!/\.sql$/.test(id)) {
46
110
  return;
47
111
  }
48
112
  const filename = path.relative(rootFolder, id);
49
113
 
50
- const { js, dts, moduleDeclaration } = codegen(parseModule(sql), filename, aliases);
114
+ const { js, dts, moduleDeclaration, mappings } = codegen(
115
+ parseModule(sql),
116
+ filename,
117
+ moduleName(filename),
118
+ runtime,
119
+ );
51
120
 
52
121
  const dtsFolder = path.join(typesFolder, path.relative(rootFolder, path.dirname(id)));
122
+ const dtsName = path.basename(filename, ".sql") + ".sql.d.ts";
53
123
  await fs.mkdir(dtsFolder, { recursive: true });
54
- await fs.writeFile(path.join(dtsFolder, path.basename(filename, ".sql") + ".sql.d.ts"), dts);
124
+ await fs.writeFile(path.join(dtsFolder, dtsName), dts + `//# sourceMappingURL=${dtsName}.map\n`);
125
+ await fs.writeFile(
126
+ path.join(dtsFolder, dtsName + ".map"),
127
+ JSON.stringify({
128
+ version: 3,
129
+ file: dtsName,
130
+ sources: [path.relative(dtsFolder, id).replaceAll(path.sep, "/")],
131
+ names: [],
132
+ mappings: encodeMappings([
133
+ { genLine: 0, genCol: 0, srcLine: 0, srcCol: 0 },
134
+ ...exportMappings(dts, mappings),
135
+ ]),
136
+ }),
137
+ );
55
138
  if (moduleDeclaration.length) {
56
- moduleDeclarations.set(filename, moduleDeclaration.join("\n"));
57
- await fs.writeFile(path.join(typesFolder, "modules.sql.d.ts"), [...moduleDeclarations.values()].join("\n"));
139
+ moduleDeclarations.set(filename, { text: moduleDeclaration.join("\n"), mappings, id });
140
+ let line = 0;
141
+ const sources = [];
142
+ const combined = [];
143
+ const texts = [];
144
+ for (const { text, mappings, id } of moduleDeclarations.values()) {
145
+ const srcIdx = sources.push(path.relative(typesFolder, id).replaceAll(path.sep, "/")) - 1;
146
+ combined.push({ genLine: line, genCol: 0, srcIdx, srcLine: 0, srcCol: 0 });
147
+ combined.push(...exportMappings(text, mappings, srcIdx, line));
148
+ texts.push(text);
149
+ line += text.split("\n").length;
150
+ }
151
+ await fs.writeFile(
152
+ path.join(typesFolder, "modules.sql.d.ts"),
153
+ texts.join("\n") + "\n//# sourceMappingURL=modules.sql.d.ts.map\n",
154
+ );
155
+ await fs.writeFile(
156
+ path.join(typesFolder, "modules.sql.d.ts.map"),
157
+ JSON.stringify({
158
+ version: 3,
159
+ file: "modules.sql.d.ts",
160
+ sources,
161
+ names: [],
162
+ mappings: encodeMappings(combined),
163
+ }),
164
+ );
58
165
  }
59
166
 
60
167
  return {
61
168
  code: js,
169
+ map: {
170
+ version: 3,
171
+ sources: [id],
172
+ sourcesContent: [sql],
173
+ names: [],
174
+ mappings: encodeMappings([
175
+ { genLine: 0, genCol: 0, srcLine: 0, srcCol: 0 },
176
+ ...exportMappings(js, mappings),
177
+ ]),
178
+ },
62
179
  moduleType: "js",
63
180
  };
64
181
  }
package/index.d.ts DELETED
@@ -1,43 +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
- * Root folder relative to which path calculation will be happening. May be useful for some I guess.
21
- *
22
- * @default process.cwd()
23
- */
24
- rootFolder?: string;
25
- }): Plugin;
26
-
27
- export interface QueryableObject {
28
- query<T extends Submittable>(queryStream: T): T;
29
-
30
- query<R extends any[] = any[], I = any[]>(
31
- queryConfig: QueryArrayConfig<I>,
32
- values?: QueryConfigValues<I>
33
- ): Promise<QueryArrayResult<R>>;
34
-
35
- query<R extends QueryResultRow = any, I = any>(queryConfig: QueryConfig<I>): Promise<QueryResult<R>>;
36
-
37
- query<R extends QueryResultRow = any, I = any[]>(
38
- queryTextOrConfig: string | QueryConfig<I>,
39
- values?: QueryConfigValues<I>
40
- ): Promise<QueryResult<R>>;
41
- }
42
-
43
- export type Queryable = QueryableObject | Promise<QueryableObject>;