sqlstack 3.7.0 → 3.7.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.
@@ -8,6 +8,12 @@ export declare function coerceRootPath(input?: string): {
8
8
  from?: 'file' | 'folder';
9
9
  };
10
10
  export declare function guessDecoratorDir(): string | undefined;
11
+ /**
12
+ * The directory of the first consumer frame in `stack` (stack lines below
13
+ * the Error header): the module that applied the decorator.
14
+ * @internal Exported for testing
15
+ */
16
+ export declare function decoratorDirFromStack(stack: string[], packageRoot?: string | undefined, codeRoot?: string | undefined): string | undefined;
11
17
  /**
12
18
  * Finds the package root from a starting directory by walking up to find package.json.
13
19
  * @internal Exported for testing
@@ -1 +1 @@
1
- {"version":3,"file":"fileResolution.d.ts","sourceRoot":"","sources":["../../../src/core/fileResolution.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAe3C,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,GAAG;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,EAAE,CAAA;CAAE,CAgCxH;AAED,wBAAgB,cAAc,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG;IAAE,OAAO,CAAC,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE,MAAM,GAAG,QAAQ,CAAA;CAAE,CAO7F;AAED,wBAAgB,iBAAiB,IAAI,MAAM,GAAG,SAAS,CAsCtD;AAmCD;;;GAGG;AACH,wBAAgB,eAAe,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAqBpE;AAUD;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CASxD;AAED;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,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S,CAwB7E;AAED;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAChC,YAAY,EAAE,MAAM,GAAG,SAAS,EAChC,aAAa,EAAE,MAAM,GAAG,SAAS,EACjC,QAAQ,EAAE,MAAM,MAAM,GACrB,MAAM,GAAG,SAAS,CA0BpB;AAQD;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,QAAQ,EAAE,MAAM,MAAM,GAAG,MAAM,GAAG,SAAS,CAK1E"}
@@ -6,6 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.resolveSqlFromFs = resolveSqlFromFs;
7
7
  exports.coerceRootPath = coerceRootPath;
8
8
  exports.guessDecoratorDir = guessDecoratorDir;
9
+ exports.decoratorDirFromStack = decoratorDirFromStack;
9
10
  exports.findPackageRoot = findPackageRoot;
10
11
  exports.isSqlstackPath = isSqlstackPath;
11
12
  exports.findSqlstackFromStack = findSqlstackFromStack;
@@ -67,12 +68,14 @@ function coerceRootPath(input) {
67
68
  }
68
69
  function guessDecoratorDir() {
69
70
  const err = new Error();
70
- const stack = (err.stack || '').split('\n').slice(2);
71
- const packageRoot = PACKAGE_ROOT_NORMALIZED;
72
- const codeRoot = SQLSTACK_CODE_ROOT;
73
- // DEBUG: Uncomment to trace issues
74
- // console.log('[guessDecoratorDir] packageRoot:', packageRoot);
75
- // console.log('[guessDecoratorDir] stack:', stack.slice(0, 5));
71
+ return decoratorDirFromStack((err.stack || '').split('\n').slice(2));
72
+ }
73
+ /**
74
+ * The directory of the first consumer frame in `stack` (stack lines below
75
+ * the Error header): the module that applied the decorator.
76
+ * @internal Exported for testing
77
+ */
78
+ function decoratorDirFromStack(stack, packageRoot = PACKAGE_ROOT_NORMALIZED, codeRoot = SQLSTACK_CODE_ROOT) {
76
79
  for (const line of stack) {
77
80
  const m = line.match(/\((.*?):\d+:\d+\)/) || line.match(/at (.*?):\d+:\d+/);
78
81
  const file = m?.[1];
@@ -113,8 +116,11 @@ function toAbsolutePath(file) {
113
116
  if (file.startsWith('file://')) {
114
117
  return (0, url_1.fileURLToPath)(file);
115
118
  }
116
- // Skip Node.js internal modules and bundler internals
117
- if (file.startsWith('node:') || file.startsWith('webpack://')) {
119
+ // Skip Node.js internal modules and bundler internals. A NUL byte marks a
120
+ // Rollup/Vite virtual module (e.g. Vitest's oxc decorator helper, reported
121
+ // as `<cwd>/\0@oxc-project+runtime@x/helpers/esm/decorate.js`); it is never
122
+ // the decorating module and must not be mistaken for one.
123
+ if (file.includes('\0') || file.startsWith('node:') || file.startsWith('webpack://')) {
118
124
  return undefined;
119
125
  }
120
126
  if (!path_1.default.isAbsolute(file)) {
@@ -1 +1 @@
1
- {"version":3,"file":"fileResolution.js","sourceRoot":"","sources":["../../../src/core/fileResolution.ts"],"names":[],"mappings":";;;;;AAkBA,4CAgCC;AAED,wCAOC;AAED,8CAsCC;AAuCD,0CAqBC;AAeD,wCASC;AAOD,sDAwBC;AAQD,gDA8BC;AAcD,0CAKC;AA/QD,4CAAoB;AACpB,gDAAwB;AACxB,6BAAoC;AAGpC,MAAM,WAAW,GAA4B;IAC3C,QAAQ,EAAE,IAAI;IACd,KAAK,EAAE,OAAO;IACd,MAAM,EAAE,QAAQ;CACjB,CAAC;AAEF,MAAM,YAAY,GAAG,IAAI,GAAG,EAAkB,CAAC;AAC/C,MAAM,SAAS,GAAG,IAAI,GAAG,EAAkB,CAAC;AAE5C,SAAS,GAAG,CAAC,IAAY,EAAE,MAAc,EAAE,OAAgB;IACzD,OAAO,GAAG,IAAI,KAAK,MAAM,KAAK,OAAO,EAAE,CAAC;AAC1C,CAAC;AAED,SAAgB,gBAAgB,CAAC,OAAe,EAAE,UAAkB,EAAE,OAAgB;IACpF,MAAM,CAAC,GAAG,GAAG,CAAC,OAAO,EAAE,UAAU,EAAE,OAAO,CAAC,CAAC;IAC5C,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,MAAM,GAAG,GAAG,WAAW,CAAC,OAAO,CAAC,CAAC;IACjC,MAAM,WAAW,GAAG,c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AAa,CAAC,cAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC;IAClD,OAAO,IAAI,CAAC,CAAC,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;AACpD,CAAC;AAED,MAAM,kBAAkB,GAAG,eAAe,CAAC,GAAG,EAAE,CAAC,IAAI,KAAK,EAAE,CAAC,KAAK,IAAI,EAAE,CAAC,CAAC","sourcesContent":["import fs from 'fs';\nimport path from 'path';\nimport { fileURLToPath } from 'url';\nimport type { Dialect } from '../registry';\n\nconst DIALECT_EXT: Record<Dialect, string> = {\n postgres: 'pg',\n mysql: 'mysql',\n sqlite: 'sqlite',\n};\n\nconst contentCache = new Map<string, string>();\nconst pathCache = new Map<string, string>();\n\nfunction key(root: string, method: string, dialect: Dialect): string {\n return `${root}::${method}::${dialect}`;\n}\n\nexport function resolveSqlFromFs(rootDir: string, methodName: string, dialect: Dialect): { sql: string; tried: string[] } {\n const k = key(rootDir, methodName, dialect);\n const tried: string[] = [];\n const ext = DIALECT_EXT[dialect];\n const dialectPath = path.join(rootDir, `${methodName}.${ext}.sql`);\n const genericPath = path.join(rootDir, `${methodName}.sql`);\n\n // Cached path\n let chosen = pathCache.get(k);\n if (!chosen) {\n if (fs.existsSync(dialectPath)) {\n chosen = dialectPath;\n } else if (fs.existsSync(genericPath)) {\n chosen = genericPath;\n }\n if (chosen) pathCache.set(k, chosen);\n }\n\n if (!chosen) {\n tried.push(dialectPath, genericPath);\n throw new Error(\n `sqlstack: SQL file not found for ${methodName}\\ntried: ${tried.join(\"\\n\")}`\n );\n }\n\n // Cached content\n let sql = contentCache.get(chosen);\n if (!sql) {\n sql = fs.readFileSync(chosen, 'utf8');\n contentCache.set(chosen, sql);\n }\n return { sql, tried: [chosen] };\n}\n\nexport function coerceRootPath(input?: string): { rootDir?: string; from?: 'file' | 'folder' } {\n if (!input) return {};\n const stat = fs.existsSync(input) ? fs.statSync(input) : undefined;\n if (stat?.isDirectory()) return { rootDir: input, from: 'folder' };\n if (stat?.isFile()) return { rootDir: path.dirname(input), from: 'file' };\n // If not found, treat as folder hint anyway\n return { rootDir: input, from: 'folder' };\n}\n\nexport function guessDecoratorDir(): string | undefined {\n const err = new Error();\n const stack = (err.stack || '').split('\\n').slice(2);\n const packageRoot = PACKAGE_ROOT_NORMALIZED;\n const codeRoot = SQLSTACK_CODE_ROOT;\n\n // DEBUG: Uncomment to trace issues\n // console.log('[guessDecoratorDir] packageRoot:', packageRoot);\n // console.log('[guessDecoratorDir] stack:', stack.slice(0, 5));\n\n for (const line of stack) {\n const m = line.match(/\\((.*?):\\d+:\\d+\\)/) || line.match(/at (.*?):\\d+:\\d+/);\n const file = m?.[1];\n if (!file) continue;\n\n const resolved = toAbsolutePath(file);\n if (!resolved) continue;\n\n const normalized = safeNormalize(resolved);\n if (!normalized) continue;\n\n // Skip every node_modules frame (sqlstack as a dependency, decorator\n // helpers such as reflect-metadata, test runners) and sqlstack's own\n // src/ and dist/ under its package root (running from source or a linked\n // checkout). A consumer module under a node_modules-free path that merely\n // contains the word \"sqlstack\" — this package's own tests/fixtures — is\n // a consumer and is NOT skipped.\n if (normalized.includes(path.sep + 'node_modules' + path.sep)) continue;\n if (packageRoot && isSqlstackCodePath(normalized, packageRoot)) continue;\n // Filesystem-free: sqlstack's own code root (the directory holding\n // core/, decorators/, …) as the STACK names it — the only reliable\n // reference on hosts without fs (workerd) or with re-rooted trees.\n if (codeRoot && normalized.startsWith(codeRoot)) continue;\n\n // Return the first consumer frame - this is where @Query is applied\n return path.dirname(resolved);\n }\n return undefined;\n}\n\nfunction isSqlstackCodePath(normalized: string, packageRoot: string): boolean {\n const root = process.platform === 'win32' ? packageRoot.toLowerCase() : packageRoot;\n return normalized.startsWith(root + 'src' + path.sep) || normalized.startsWith(root + 'dist' + path.sep);\n}\n\nfunction toAbsolutePath(file: string): string | undefined {\n try {\n if (file.startsWith('file://')) {\n return fileURLToPath(file);\n }\n // Skip Node.js internal modules and bundler internals\n if (file.startsWith('node:') || file.startsWith('webpack://')) {\n return undefined;\n }\n if (!path.isAbsolute(file)) {\n return path.resolve(file);\n }\n return file;\n } catch {\n return undefined;\n }\n}\n\nfunction ensureTrailingSep(p: string): string {\n return p.endsWith(path.sep) ? p : p + path.sep;\n}\n\nfunction safeNormalize(p?: string): string | undefined {\n if (!p) return undefined;\n const normalized = path.normalize(p);\n return process.platform === 'win32' ? normalized.toLowerCase() : normalized;\n}\n\n/**\n * Finds the package root from a starting directory by walking up to find package.json.\n * @internal Exported for testing\n */\nexport function findPackageRoot(startDir: string): string | undefined {\n // The ESM build ships a nested dist/esm/package.json ({ type: module });\n // keep walking past any package.json that is not sqlstack's own so the\n // root is the real package directory (whose src/ and dist/ are skipped by\n // guessDecoratorDir). The first package.json found is the fallback.\n let current = startDir;\n let fallback: string | undefined;\n for (let i = 0; i < 8; i++) {\n const candidate = path.join(current, 'package.json');\n if (fs.existsSync(candidate)) {\n const root = path.dirname(candidate);\n const normalizedRoot = safeNormalize(root);\n const asRoot = normalizedRoot ? ensureTrailingSep(normalizedRoot) : ensureTrailingSep(root);\n if (packageNameOf(candidate) === 'sqlstack') return asRoot;\n fallback ??= asRoot;\n }\n const parent = path.dirname(current);\n if (parent === current) break;\n current = parent;\n }\n return fallback;\n}\n\nfunction packageNameOf(packageJsonPath: string): string | undefined {\n try {\n return JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'))?.name;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Detects if a path belongs to sqlstack package.\n * Handles both source paths (contains 'sqlstack') and node_modules paths.\n * @internal Exported for testing\n */\nexport function isSqlstackPath(filePath: string): boolean {\n const normalized = filePath.toLowerCase();\n // Check for source development path (e.g., /path/to/sqlstack/src/...)\n if (normalized.includes(path.sep + 'sqlstack' + path.sep)) return true;\n // Check for node_modules installation\n if (normalized.includes('node_modules' + path.sep + 'sqlstack' + path.sep)) return true;\n // Check for scoped package (@noego/sqlstack or similar)\n if (normalized.includes('node_modules' + path.sep + '@') && normalized.includes('sqlstack' + path.sep)) return true;\n return false;\n}\n\n/**\n * Extracts sqlstack's location from a stack trace.\n * Handles absolute paths, file:// URLs, and relative paths (Vitest uses relative paths).\n * @internal Exported for testing\n */\nexport function findSqlstackFromStack(stackString: string): string | undefined {\n const lines = stackString.split('\\n');\n for (const line of lines) {\n const m = line.match(/\\((.*?):\\d+:\\d+\\)/) || line.match(/at (.*?):\\d+:\\d+/);\n const file = m?.[1];\n if (!file) continue;\n try {\n let resolved: string | undefined;\n if (file.startsWith('file://')) {\n resolved = fileURLToPath(file);\n } else if (path.isAbsolute(file)) {\n resolved = file;\n } else if (!file.startsWith('node:') && !file.startsWith('webpack://')) {\n // Relative path - resolve it (Vitest uses relative paths in stack traces)\n resolved = path.resolve(file);\n }\n if (resolved && resolved.includes('fileResolution')) {\n return path.dirname(resolved);\n }\n } catch {\n // Skip invalid paths\n }\n }\n return undefined;\n}\n\n/**\n * Computes the sqlstack package root directory.\n * Handles both CJS (__dirname) and ESM (stack trace) detection.\n * Validates that __dirname actually points to sqlstack (guards against Vitest injection).\n * @internal Exported for testing\n */\nexport function computePackageRoot(\n dirnameValue: string | undefined,\n filenameValue: string | undefined,\n getStack: () => string\n): string | undefined {\n const candidates: string[] = [];\n\n // CJS: use __dirname/__filename, but validate they actually point to sqlstack\n // (Vitest can inject __dirname incorrectly when transforming CJS modules)\n if (typeof dirnameValue === 'string' && isSqlstackPath(dirnameValue)) {\n candidates.push(dirnameValue);\n }\n if (typeof filenameValue === 'string' && isSqlstackPath(filenameValue)) {\n candidates.push(path.dirname(filenameValue));\n }\n\n // ESM fallback or when __dirname was incorrectly injected: parse stack trace\n if (candidates.length === 0) {\n const stackDir = findSqlstackFromStack(getStack());\n if (stackDir) {\n candidates.push(stackDir);\n }\n }\n\n // Find the package root from the first valid candidate\n for (const base of candidates) {\n const root = findPackageRoot(base);\n if (root) return root;\n }\n return undefined;\n}\n\nconst PACKAGE_ROOT_NORMALIZED = computePackageRoot(\n typeof __dirname === 'string' ? __dirname : undefined,\n typeof __filename === 'string' ? __filename : undefined,\n () => new Error().stack || ''\n);\n\n/**\n * sqlstack's code root as the runtime names this module in stack traces:\n * the parent of this file's directory (`src/`, `dist/cjs/`, `dist/esm/`, or\n * a bundler's re-rooted copy). Needs no filesystem.\n * @internal Exported for testing\n */\nexport function computeCodeRoot(getStack: () => string): string | undefined {\n const coreDir = findSqlstackFromStack(getStack());\n if (!coreDir) return undefined;\n const root = safeNormalize(path.dirname(coreDir));\n return root ? ensureTrailingSep(root) : undefined;\n}\n\nconst SQLSTACK_CODE_ROOT = computeCodeRoot(() => new Error().stack || '');\n"]}
1
+ {"version":3,"file":"fileResolution.js","sourceRoot":"","sources":["../../../src/core/fileResolution.ts"],"names":[],"mappings":";;;;;AAkBA,4CAgCC;AAED,wCAOC;AAED,8CAGC;AAOD,sDAiCC;AA0CD,0CAqBC;AAeD,wCASC;AAOD,sDAwBC;AAQD,gDA8BC;AAcD,0CAKC;AAvRD,4CAAoB;AACpB,gDAAwB;AACxB,6BAAoC;AAGpC,MAAM,WAAW,GAA4B;IAC3C,QAAQ,EAAE,IAAI;IACd,KAAK,EAAE,OAAO;IACd,MAAM,EAAE,QAAQ;CACjB,CAAC;AAEF,MAAM,YAAY,GAAG,IAAI,GAAG,EAAkB,CAAC;AAC/C,MAAM,SAAS,GAAG,IAAI,GAAG,EAAkB,CAAC;AAE5C,SAAS,GAAG,CAAC,IAAY,EAAE,MAAc,EAAE,OAAgB;IACzD,OAAO,GAAG,IAAI,KAAK,MAAM,KAAK,OAAO,EAAE,CAAC;AAC1C,CAAC;AAED,SAAgB,gBAAgB,CAAC,OAAe,EAAE,UAAkB,EAAE,OAAgB;IACpF,MAAM,CAAC,GAAG,GAAG,CAAC,OAAO,EAAE,UAAU,EAAE,OAAO,CAAC,CAAC;IAC5C,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,MAAM,GAAG,GAAG,WAAW,CAAC,OAAO,CAAC,CAAC;IACjC,MAAM,WAAW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AC,CAAC;IAClD,IAAI,CAAC,OAAO;QAAE,OAAO,SAAS,CAAC;IAC/B,MAAM,IAAI,GAAG,aAAa,CAAC,cAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC;IAClD,OAAO,IAAI,CAAC,CAAC,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;AACpD,CAAC;AAED,MAAM,kBAAkB,GAAG,eAAe,CAAC,GAAG,EAAE,CAAC,IAAI,KAAK,EAAE,CAAC,KAAK,IAAI,EAAE,CAAC,CAAC","sourcesContent":["import fs from 'fs';\nimport path from 'path';\nimport { fileURLToPath } from 'url';\nimport type { Dialect } from '../registry';\n\nconst DIALECT_EXT: Record<Dialect, string> = {\n postgres: 'pg',\n mysql: 'mysql',\n sqlite: 'sqlite',\n};\n\nconst contentCache = new Map<string, string>();\nconst pathCache = new Map<string, string>();\n\nfunction key(root: string, method: string, dialect: Dialect): string {\n return `${root}::${method}::${dialect}`;\n}\n\nexport function resolveSqlFromFs(rootDir: string, methodName: string, dialect: Dialect): { sql: string; tried: string[] } {\n const k = key(rootDir, methodName, dialect);\n const tried: string[] = [];\n const ext = DIALECT_EXT[dialect];\n const dialectPath = path.join(rootDir, `${methodName}.${ext}.sql`);\n const genericPath = path.join(rootDir, `${methodName}.sql`);\n\n // Cached path\n let chosen = pathCache.get(k);\n if (!chosen) {\n if (fs.existsSync(dialectPath)) {\n chosen = dialectPath;\n } else if (fs.existsSync(genericPath)) {\n chosen = genericPath;\n }\n if (chosen) pathCache.set(k, chosen);\n }\n\n if (!chosen) {\n tried.push(dialectPath, genericPath);\n throw new Error(\n `sqlstack: SQL file not found for ${methodName}\\ntried: ${tried.join(\"\\n\")}`\n );\n }\n\n // Cached content\n let sql = contentCache.get(chosen);\n if (!sql) {\n sql = fs.readFileSync(chosen, 'utf8');\n contentCache.set(chosen, sql);\n }\n return { sql, tried: [chosen] };\n}\n\nexport function coerceRootPath(input?: string): { rootDir?: string; from?: 'file' | 'folder' } {\n if (!input) return {};\n const stat = fs.existsSync(input) ? fs.statSync(input) : undefined;\n if (stat?.isDirectory()) return { rootDir: input, from: 'folder' };\n if (stat?.isFile()) return { rootDir: path.dirname(input), from: 'file' };\n // If not found, treat as folder hint anyway\n return { rootDir: input, from: 'folder' };\n}\n\nexport function guessDecoratorDir(): string | undefined {\n const err = new Error();\n return decoratorDirFromStack((err.stack || '').split('\\n').slice(2));\n}\n\n/**\n * The directory of the first consumer frame in `stack` (stack lines below\n * the Error header): the module that applied the decorator.\n * @internal Exported for testing\n */\nexport function decoratorDirFromStack(\n stack: string[],\n packageRoot: string | undefined = PACKAGE_ROOT_NORMALIZED,\n codeRoot: string | undefined = SQLSTACK_CODE_ROOT\n): string | undefined {\n for (const line of stack) {\n const m = line.match(/\\((.*?):\\d+:\\d+\\)/) || line.match(/at (.*?):\\d+:\\d+/);\n const file = m?.[1];\n if (!file) continue;\n\n const resolved = toAbsolutePath(file);\n if (!resolved) continue;\n\n const normalized = safeNormalize(resolved);\n if (!normalized) continue;\n\n // Skip every node_modules frame (sqlstack as a dependency, decorator\n // helpers such as reflect-metadata, test runners) and sqlstack's own\n // src/ and dist/ under its package root (running from source or a linked\n // checkout). A consumer module under a node_modules-free path that merely\n // contains the word \"sqlstack\" — this package's own tests/fixtures — is\n // a consumer and is NOT skipped.\n if (normalized.includes(path.sep + 'node_modules' + path.sep)) continue;\n if (packageRoot && isSqlstackCodePath(normalized, packageRoot)) continue;\n // Filesystem-free: sqlstack's own code root (the directory holding\n // core/, decorators/, …) as the STACK names it — the only reliable\n // reference on hosts without fs (workerd) or with re-rooted trees.\n if (codeRoot && normalized.startsWith(codeRoot)) continue;\n\n // Return the first consumer frame - this is where @Query is applied\n return path.dirname(resolved);\n }\n return undefined;\n}\n\nfunction isSqlstackCodePath(normalized: string, packageRoot: string): boolean {\n const root = process.platform === 'win32' ? packageRoot.toLowerCase() : packageRoot;\n return normalized.startsWith(root + 'src' + path.sep) || normalized.startsWith(root + 'dist' + path.sep);\n}\n\nfunction toAbsolutePath(file: string): string | undefined {\n try {\n if (file.startsWith('file://')) {\n return fileURLToPath(file);\n }\n // Skip Node.js internal modules and bundler internals. A NUL byte marks a\n // Rollup/Vite virtual module (e.g. Vitest's oxc decorator helper, reported\n // as `<cwd>/\\0@oxc-project+runtime@x/helpers/esm/decorate.js`); it is never\n // the decorating module and must not be mistaken for one.\n if (file.includes('\\0') || file.startsWith('node:') || file.startsWith('webpack://')) {\n return undefined;\n }\n if (!path.isAbsolute(file)) {\n return path.resolve(file);\n }\n return file;\n } catch {\n return undefined;\n }\n}\n\nfunction ensureTrailingSep(p: string): string {\n return p.endsWith(path.sep) ? p : p + path.sep;\n}\n\nfunction safeNormalize(p?: string): string | undefined {\n if (!p) return undefined;\n const normalized = path.normalize(p);\n return process.platform === 'win32' ? normalized.toLowerCase() : normalized;\n}\n\n/**\n * Finds the package root from a starting directory by walking up to find package.json.\n * @internal Exported for testing\n */\nexport function findPackageRoot(startDir: string): string | undefined {\n // The ESM build ships a nested dist/esm/package.json ({ type: module });\n // keep walking past any package.json that is not sqlstack's own so the\n // root is the real package directory (whose src/ and dist/ are skipped by\n // guessDecoratorDir). The first package.json found is the fallback.\n let current = startDir;\n let fallback: string | undefined;\n for (let i = 0; i < 8; i++) {\n const candidate = path.join(current, 'package.json');\n if (fs.existsSync(candidate)) {\n const root = path.dirname(candidate);\n const normalizedRoot = safeNormalize(root);\n const asRoot = normalizedRoot ? ensureTrailingSep(normalizedRoot) : ensureTrailingSep(root);\n if (packageNameOf(candidate) === 'sqlstack') return asRoot;\n fallback ??= asRoot;\n }\n const parent = path.dirname(current);\n if (parent === current) break;\n current = parent;\n }\n return fallback;\n}\n\nfunction packageNameOf(packageJsonPath: string): string | undefined {\n try {\n return JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'))?.name;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Detects if a path belongs to sqlstack package.\n * Handles both source paths (contains 'sqlstack') and node_modules paths.\n * @internal Exported for testing\n */\nexport function isSqlstackPath(filePath: string): boolean {\n const normalized = filePath.toLowerCase();\n // Check for source development path (e.g., /path/to/sqlstack/src/...)\n if (normalized.includes(path.sep + 'sqlstack' + path.sep)) return true;\n // Check for node_modules installation\n if (normalized.includes('node_modules' + path.sep + 'sqlstack' + path.sep)) return true;\n // Check for scoped package (@noego/sqlstack or similar)\n if (normalized.includes('node_modules' + path.sep + '@') && normalized.includes('sqlstack' + path.sep)) return true;\n return false;\n}\n\n/**\n * Extracts sqlstack's location from a stack trace.\n * Handles absolute paths, file:// URLs, and relative paths (Vitest uses relative paths).\n * @internal Exported for testing\n */\nexport function findSqlstackFromStack(stackString: string): string | undefined {\n const lines = stackString.split('\\n');\n for (const line of lines) {\n const m = line.match(/\\((.*?):\\d+:\\d+\\)/) || line.match(/at (.*?):\\d+:\\d+/);\n const file = m?.[1];\n if (!file) continue;\n try {\n let resolved: string | undefined;\n if (file.startsWith('file://')) {\n resolved = fileURLToPath(file);\n } else if (path.isAbsolute(file)) {\n resolved = file;\n } else if (!file.startsWith('node:') && !file.startsWith('webpack://')) {\n // Relative path - resolve it (Vitest uses relative paths in stack traces)\n resolved = path.resolve(file);\n }\n if (resolved && resolved.includes('fileResolution')) {\n return path.dirname(resolved);\n }\n } catch {\n // Skip invalid paths\n }\n }\n return undefined;\n}\n\n/**\n * Computes the sqlstack package root directory.\n * Handles both CJS (__dirname) and ESM (stack trace) detection.\n * Validates that __dirname actually points to sqlstack (guards against Vitest injection).\n * @internal Exported for testing\n */\nexport function computePackageRoot(\n dirnameValue: string | undefined,\n filenameValue: string | undefined,\n getStack: () => string\n): string | undefined {\n const candidates: string[] = [];\n\n // CJS: use __dirname/__filename, but validate they actually point to sqlstack\n // (Vitest can inject __dirname incorrectly when transforming CJS modules)\n if (typeof dirnameValue === 'string' && isSqlstackPath(dirnameValue)) {\n candidates.push(dirnameValue);\n }\n if (typeof filenameValue === 'string' && isSqlstackPath(filenameValue)) {\n candidates.push(path.dirname(filenameValue));\n }\n\n // ESM fallback or when __dirname was incorrectly injected: parse stack trace\n if (candidates.length === 0) {\n const stackDir = findSqlstackFromStack(getStack());\n if (stackDir) {\n candidates.push(stackDir);\n }\n }\n\n // Find the package root from the first valid candidate\n for (const base of candidates) {\n const root = findPackageRoot(base);\n if (root) return root;\n }\n return undefined;\n}\n\nconst PACKAGE_ROOT_NORMALIZED = computePackageRoot(\n typeof __dirname === 'string' ? __dirname : undefined,\n typeof __filename === 'string' ? __filename : undefined,\n () => new Error().stack || ''\n);\n\n/**\n * sqlstack's code root as the runtime names this module in stack traces:\n * the parent of this file's directory (`src/`, `dist/cjs/`, `dist/esm/`, or\n * a bundler's re-rooted copy). Needs no filesystem.\n * @internal Exported for testing\n */\nexport function computeCodeRoot(getStack: () => string): string | undefined {\n const coreDir = findSqlstackFromStack(getStack());\n if (!coreDir) return undefined;\n const root = safeNormalize(path.dirname(coreDir));\n return root ? ensureTrailingSep(root) : undefined;\n}\n\nconst SQLSTACK_CODE_ROOT = computeCodeRoot(() => new Error().stack || '');\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"query.d.ts","sourceRoot":"","sources":["../../../src/decorators/query.ts"],"names":[],"mappings":"AAyBA,KAAK,YAAY,GAAG;IAClB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,OAAO,CAAC,EAAE,QAAQ,GAAG,OAAO,GAAG,UAAU,CAAC;CAC3C,CAAC;AAEF;;;;;;;;;;;;;GAaG;AACH,wBAAgB,KAAK,CAAC,GAAG,CAAC,EAAE,MAAM,GAAG,YAAY,IAC9B,SAAS,GAAG,EAAE,MAAM,MAAM,GAAG,MAAM,EAAE,MAAM,kBAAkB,wBA6Y/E"}
1
+ {"version":3,"file":"query.d.ts","sourceRoot":"","sources":["../../../src/decorators/query.ts"],"names":[],"mappings":"AA0BA,KAAK,YAAY,GAAG;IAClB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,OAAO,CAAC,EAAE,QAAQ,GAAG,OAAO,GAAG,UAAU,CAAC;CAC3C,CAAC;AAEF;;;;;;;;;;;;;GAaG;AACH,wBAAgB,KAAK,CAAC,GAAG,CAAC,EAAE,MAAM,GAAG,YAAY,IAC9B,SAAS,GAAG,EAAE,MAAM,MAAM,GAAG,MAAM,EAAE,MAAM,kBAAkB,wBA6Y/E"}
@@ -308,7 +308,7 @@ function Query(arg) {
308
308
  }
309
309
  catch (dbError) {
310
310
  // Attach SQL query (with placeholders) to error for debugging
311
- throw new errors_1.DatabaseError(dbError?.message || String(dbError), boundSql, dbError instanceof Error ? dbError : undefined);
311
+ throw new errors_1.DatabaseError(dbError?.message || String(dbError), boundSql, (0, run_1.isErrorLike)(dbError) ? dbError : undefined);
312
312
  }
313
313
  return out;
314
314
  };
@@ -439,7 +439,7 @@ function Query(arg) {
439
439
  out = tx ? await tx.query(boundSql, params) : await db.query(boundSql, params);
440
440
  }
441
441
  catch (dbError) {
442
- throw new errors_1.DatabaseError(dbError?.message || String(dbError), boundSql, dbError instanceof Error ? dbError : undefined);
442
+ throw new errors_1.DatabaseError(dbError?.message || String(dbError), boundSql, (0, run_1.isErrorLike)(dbError) ? dbError : undefined);
443
443
  }
444
444
  return finishResult(out, labels, this, prop);
445
445
  }
@@ -1 +1 @@
1
- {"version":3,"file":"query.js","sourceRoot":"","sources":["../../../src/decorators/query.ts"],"names":[],"mappings":";;AA6CA,sBA8YC;AA3bD,+CAAoF;AACpF,2CAAkI;AAClI,iDAAyE;AACzE,wCAA4F;AAE5F,oDAAmG;AACnG,2DAA6F;AAC7F,+CAAwG;AACxG,iDAA0E;AAE1E,kDAAuD;AACvD,gCAAsD;AACtD,gCAWgB;AAQhB;;;;;;;;;;;;;GAaG;AACH,SAAgB,KAAK,CAAC,GAA2B;IAC/C,OAAO,UAAU,OAAY,EAAE,IAAqB,EAAE,IAAwB;QAC5E,MAAM,OAAO,GAA6B,OAAO,GAAG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,MAAM,IAAI,uBAAc,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YAC3D,OAAO,IAAI,CAAC;QACd;YACE,OAAO,IAAI,CAAC;IAChB,CAAC;AACH,CAAC","sourcesContent":["import { getClassLabels, getMethodLabels, setMethodLabels } from '../core/metadata';\nimport { SqlStackError, ExactlyOneRowError, NoRowsError, RowsExistError, DatabaseError, ExpectedRowsError } from '../core/errors';\nimport { isValidationDisabled, validateOutput } from '../core/validator';\nimport { resolveExecution, resolveSqlResolver, isRegisteredDatabaseName } from '../runtime';\nimport type { SqlResolver } from '../core/resolver';\nimport { createSqliteBinder, createMysqlBinder, createPostgresBinder } from '../binders/sqlBinder';\nimport { coerceRootPath, resolveSqlFromFs, guessDecoratorDir } from '../core/fileResolution';\nimport { registerDecoratedMethod, recordQueryMethodOnClass, getActiveResolver } from '../core/resolver';\nimport { getResources, resolveSqlFromResources } from '../core/resources';\nimport type { MethodLabels } from '../core/metadata';\nimport { getTransactionTarget } from '../transactions';\nimport { SqlFragment, compileFragment } from '../sql';\nimport {\n runStorage,\n resolveRunTarget,\n executeOnTarget,\n toRunError,\n fragmentText,\n isRunDatabaseHandle,\n type RunContext,\n type RunDatabase,\n type RunInvocation,\n type RunTarget,\n} from '../run';\n\ntype QueryOptions = {\n sql?: string; // optional inline SQL for testing; otherwise, future: load from file\n db?: string; // optional override DB name\n dialect?: 'sqlite' | 'mysql' | 'postgres';\n};\n\n/**\n * Turn a method into a database query. The body calls `run(...)` (see `run`\n * for its forms); the wrapper resolves SQL, binds, executes, and applies the\n * shape/transform/validation decorators. A string argument is the root\n * directory holding the method's `.sql` file; `{ sql }` gives inline SQL,\n * `{ db }` pins a registered database, `{ dialect }` overrides binding style.\n *\n * The decorated method's promise rejects with:\n * @throws {DatabaseError} When the driver rejects the statement (original\n * error in `.cause`).\n * @throws {SqlStackError} For missing SQL sources, unresolvable databases,\n * and shape/validation failures (ExpectedRowsError, ExactlyOneRowError,\n * NoRowsError, RowsExistError, ValidationError).\n */\nexport function Query(arg?: string | QueryOptions) {\n return function (_target: any, prop: string | symbol, desc: PropertyDescriptor) {\n const options: QueryOptions | undefined = typeof arg === 'string' ? undefined : arg;\n const rootArg: string | undefined = typeof arg === 'string' ? arg : undefined;\n // Store method-level db override if provided\n if (options?.db) {\n setMethodLabels(_target, prop, { db: options.db });\n }\n // Store inline SQL if provided\n if (options?.sql) {\n setMethodLabels(_target, prop, { source: { kind: 'inline', sql: options.sql } });\n } else {\n // An EXPLICIT path argument pins a filesystem directory. Bare @Query()\n // records the directory of the decorating module (first non-sqlstack\n // stack frame at decoration time); at call time that directory is\n // resolved against the packaged resources map when one is installed\n // (SqlStack.useResources), else read from the filesystem. No tree scan.\n const { rootDir } = coerceRootPath(rootArg);\n if (rootDir) {\n setMethodLabels(_target, prop, { source: { kind: 'fs', rootDir } });\n } else {\n const dir = guessDecoratorDir();\n if (dir) setMethodLabels(_target, prop, { source: { kind: 'guess', dir } });\n }\n }\n\n // Record for resolver coverage checks: immutable class metadata (the\n // canonical, environment-local source) plus the deprecated global list\n // consulted by the legacy global-resolver path.\n const decoratedEntry = {\n className: _target?.constructor?.name ?? '<anonymous>',\n methodName: String(prop),\n inline: !!options?.sql,\n };\n recordQueryMethodOnClass(_target, decoratedEntry);\n registerDecoratedMethod(decoratedEntry);\n\n const original = desc.value;\n desc.value = async function (...callArgs: any[]) {\n const labels = getMethodLabels(this, prop);\n const classLabels = getClassLabels(this);\n\n // Resolve, bind, and execute the method's own SQL (inline, resolver,\n // or file) and return the adapter's raw result. `callArgs` is the\n // binding input: the method's own arguments for run() and the legacy\n // fallback, or the params given to run(db, params). `explicit` carries\n // the database chosen by run(db, params).\n const executeMethodSql = async (\n callArgs: any[],\n explicit: { target: RunTarget; resolver: SqlResolver | undefined } | undefined,\n onSql: (sqlText: string) => void\n ): Promise<unknown> => {\n // 1) prepare args with defaults\n const rawInput = callArgs.length === 1 ? callArgs[0] : callArgs; // object or positional array\n\n // 2) choose database and dialect via the active environment (or run's explicit database)\n let target: RunTarget;\n let activeResolver: SqlResolver | undefined;\n if (explicit) {\n target = explicit.target;\n activeResolver = explicit.resolver;\n } else {\n target = await contextTarget();\n activeResolver = target.resolver;\n }\n const db = target.db;\n const dialect = options?.dialect ?? db.dialect ?? 'sqlite';\n\n // 3) load SQL source: inline; else an installed resolver (the\n // instance's, else the process-global one — a build-time manifest\n // registered by a host runner applies even when the SqlStack itself\n // came from an IoC root); else the decorator's directory (explicit\n // path or guessed module dir) against the packaged resources /\n // filesystem.\n const className = this?.constructor?.name ?? '<anonymous>';\n const resolver = activeResolver ?? getActiveResolver();\n const sql = labels?.source?.kind === 'inline'\n ? labels.source.sql\n : (resolver?.resolve({\n className,\n methodName: String(prop),\n dialect,\n rootDir: labels?.source?.kind === 'fs' ? labels.source.rootDir : undefined,\n }) ?? resolveSourceSql(labels?.source, className, String(prop), dialect));\n if (!sql) {\n throw new SqlStackError(\n `No SQL source for ${className}.${String(prop)}: the decorating module's directory could not be ` +\n 'determined from the stack. Use @Query() with a file/folder path or inline sql.'\n );\n }\n onSql(sql);\n\n // 4) bind placeholders\n // Decide argument mode: positional if SQL contains :argN\n let workingSql = sql;\n const hasPositional = /:arg[1-9][0-9]*/.test(workingSql);\n\n // Prepare args for binder\n let args: any;\n if (hasPositional) {\n args = callArgs;\n } else {\n const namedBase = callArgs.length > 0 ? callArgs[0] : undefined;\n args = applyDefaults(labels.defaults, namedBase ?? {});\n }\n\n // Compute paging and inject :offset/:limit (named mode) or rewrite to positional\n const pageCfg = labels.page;\n if (pageCfg) {\n const { size, zeroBase } = pageCfg;\n const base = zeroBase ? 0 : 1;\n\n // Extract page number from input (object) or a trailing options object in positional mode\n const pageFromObject = (val: any): number | undefined => {\n if (val && typeof val === 'object' && !Array.isArray(val) && typeof (val as any).page !== 'undefined') {\n const p = (val as any).page;\n if (typeof p === 'number' && isFinite(p)) return p;\n }\n return undefined;\n };\n\n let pageNum: number | undefined;\n if (hasPositional) {\n // Variadic-style: only the LAST argument may carry `{ page }`\n if (callArgs.length > 0) {\n const last = callArgs[callArgs.length - 1];\n pageNum = pageFromObject(last);\n }\n } else {\n // Prefer last-arg options if provided; otherwise read from named object\n if (callArgs.length > 1) {\n const last = callArgs[callArgs.length - 1];\n pageNum = pageFromObject(last);\n }\n if (pageNum === undefined) {\n pageNum = pageFromObject(args);\n }\n }\n\n const effectivePage = typeof pageNum === 'number' ? pageNum : base;\n const offset = (effectivePage - base) * size;\n const limit = size;\n\n if (hasPositional) {\n // Replace occurrences of :offset and :limit with new :argN tokens appended to args\n const baseIndex = callArgs.length; // start numbering after user args\n let nextIndex = baseIndex + 1;\n const additions: unknown[] = [];\n\n const rewrite = (sqlText: string) => {\n const out: string[] = [];\n let i = 0;\n let inSQ = false, inDQ = false, inLC = false, inBC = false;\n const len = sqlText.length;\n while (i < len) {\n const ch = sqlText[i];\n const next = i + 1 < len ? sqlText[i + 1] : '';\n if (inLC) { out.push(ch); if (ch === '\\n') inLC = false; i++; continue; }\n if (inBC) { out.push(ch); if (ch === '*' && next === '/') { out.push(next); i++; inBC = false; } i++; continue; }\n if (inSQ) {\n out.push(ch);\n if (ch === \"'\" && next === \"'\") { out.push(next); i += 2; continue; }\n if (ch === \"'\") inSQ = false;\n i++;\n continue;\n }\n if (inDQ) {\n out.push(ch);\n if (ch === '\"' && next === '\"') { out.push(next); i += 2; continue; }\n if (ch === '\"') inDQ = false;\n i++;\n continue;\n }\n if (ch === '-' && next === '-') { out.push(ch, next); i += 2; inLC = true; continue; }\n if (ch === '/' && next === '*') { out.push(ch, next); i += 2; inBC = true; continue; }\n if (ch === '\"') { out.push(ch); inDQ = true; i++; continue; }\n if (ch === \"'\") { out.push(ch); inSQ = true; i++; continue; }\n if (ch === ':' && next === ':') { out.push('::'); i += 2; continue; }\n if (ch === ':') {\n // parse token\n let j = i + 1;\n const start = j;\n while (j < len) {\n const c = sqlText[j];\n if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c === '_') j++; else break;\n }\n const name = sqlText.slice(start, j);\n if (name === 'offset') {\n const token = `:arg${nextIndex++}`;\n out.push(token);\n additions.push(offset);\n i = j;\n continue;\n }\n if (name === 'limit') {\n const token = `:arg${nextIndex++}`;\n out.push(token);\n additions.push(limit);\n i = j;\n continue;\n }\n // otherwise leave untouched\n out.push(':');\n i++;\n continue;\n }\n out.push(ch);\n i++;\n }\n return out.join('');\n };\n\n const rewritten = rewrite(workingSql);\n if (rewritten !== workingSql) {\n workingSql = rewritten;\n // append values so :argK map correctly\n (args as unknown[]).push(...additions);\n }\n } else {\n // Named-mode: attach computed values (override any provided)\n args = { ...(args as Record<string, unknown>), offset, limit };\n }\n }\n const binder =\n dialect === 'postgres' ? createPostgresBinder() : dialect === 'mysql' ? createMysqlBinder() : createSqliteBinder();\n // Binding failures (missing :name, bad array value) surface as DatabaseError like every\n // other run() failure; the original error stays in `.cause`.\n let bound: { sql: string; params: unknown[] };\n try {\n bound = binder.bind(workingSql, args as any);\n } catch (bindError) {\n throw toRunError(bindError, workingSql);\n }\n const { sql: boundSql, params } = bound;\n onSql(boundSql);\n\n // 5) execute query (inside the active transaction on that database, if any)\n let out;\n try {\n out = target.tx ? await target.tx.query(boundSql, params) : await db.query(boundSql, params);\n } catch (dbError: any) {\n // Attach SQL query (with placeholders) to error for debugging\n throw new DatabaseError(\n dbError?.message || String(dbError),\n boundSql,\n dbError instanceof Error ? dbError : undefined\n );\n }\n return out;\n };\n\n // Database from the decorator context: @Query({ db }), @QueryBinder({ db }),\n // or the environment default.\n const contextTarget = async (): Promise<RunTarget> => {\n const dbName = labels.db ?? options?.db ?? classLabels?.db;\n const resolved = await resolveExecution(dbName);\n return {\n db: resolved.entry.db,\n tx: getTransactionTarget(resolved.entry),\n resolver: resolved.resolver,\n byName: true,\n };\n };\n\n // The method's own leading database argument: a handle (object with\n // query()) or a registered database name. It selects run()'s target\n // and is never bound as a value.\n const leadingDb = async (): Promise<RunDatabase | string | undefined> => {\n if (callArgs.length === 0) return undefined;\n const first = callArgs[0];\n if (isRunDatabaseHandle(first)) return first;\n if (typeof first === 'string' && first.length > 0 && (await isRegisteredDatabaseName(first))) return first;\n return undefined;\n };\n\n // A database chosen by run's argument or the method's leading argument.\n const explicitTarget = async (\n db: RunDatabase | string\n ): Promise<{ target: RunTarget; resolver: SqlResolver | undefined }> => {\n const target = await resolveRunTarget(db);\n // Inline SQL needs no resolver; only look one up for file-based SQL.\n const resolver = target.byName\n ? target.resolver\n : labels?.source?.kind === 'inline'\n ? undefined\n : await resolveSqlResolver();\n return { target, resolver };\n };\n\n // run() (and the legacy fallback): the method's arguments minus a\n // leading database, on that database or the decorator context.\n const executeDefault = async (onSql: (sqlText: string) => void): Promise<unknown> => {\n const lead = await leadingDb();\n if (lead === undefined) return executeMethodSql(callArgs, undefined, onSql);\n return executeMethodSql(callArgs.slice(1), await explicitTarget(lead), onSql);\n };\n\n // run's argument-taking forms: return the adapter's raw result.\n const executeInvocation = async (\n invocation: Exclude<RunInvocation, { kind: 'default' }>,\n onSql: (sqlText: string) => void\n ): Promise<unknown> => {\n if (invocation.kind === 'fragment') {\n // run(query) / run(db, query): the fragment replaces the method's SQL;\n // the method's arguments are not bound.\n const target = invocation.db !== undefined ? await resolveRunTarget(invocation.db) : await contextTarget();\n const dialect = options?.dialect ?? target.db.dialect ?? 'sqlite';\n const { sql: boundSql, params } = compileFragment(invocation.fragment, dialect);\n onSql(boundSql);\n return executeOnTarget(target, boundSql, params);\n }\n if (invocation.kind === 'db') {\n // run(db): the method's own SQL against db, bound from the method's\n // arguments minus a leading database argument.\n const lead = await leadingDb();\n const bindArgs = lead === undefined ? callArgs : callArgs.slice(1);\n return executeMethodSql(bindArgs, await explicitTarget(invocation.db), onSql);\n }\n // run(db, params) / run(params): the method's own SQL bound from params\n // only (an object for :named, an array for :argN), against run's db,\n // else the method's leading database, else the decorator context.\n const bindArgs = Array.isArray(invocation.params) ? [...invocation.params] : [invocation.params];\n const db = invocation.db ?? (await leadingDb());\n return executeMethodSql(bindArgs, db !== undefined ? await explicitTarget(db) : undefined, onSql);\n };\n\n // The full pipeline: execute, then — if rows were returned\n // (SELECT/CTE/RETURNING) — shape + transform + validate; a write result\n // is returned as-is (or fails if a shape was requested). Invoked by\n // run() from inside the method body, or directly as the legacy fallback\n // when the body throws. The zero-argument path is unchanged; run's\n // argument-taking forms get the unified error contract: any failure\n // before shaping that is not already a SqlStackError becomes a\n // DatabaseError with the original error in `.cause`.\n const pipeline = async (invocation?: RunInvocation): Promise<unknown> => {\n if (invocation === undefined || invocation.kind === 'default') {\n const out = await executeDefault(() => {});\n return finishResult(out, labels, this, prop);\n }\n let sqlText = invocation.kind === 'fragment' ? fragmentText(invocation.fragment) : '';\n let out: unknown;\n try {\n out = await executeInvocation(invocation, (s) => {\n sqlText = s;\n });\n } catch (err) {\n throw toRunError(err, sqlText);\n }\n return finishResult(out, labels, this, prop);\n };\n\n // 0) Invoke the method body inside a run() context. Three outcomes:\n // - body calls run(...): the pipeline executed inside the body; return\n // the body's result verbatim (it may have caught/transformed it).\n // - body returns a SqlFragment (deprecated template literal path):\n // execute it.\n // - body throws without calling run() (legacy placeholder throw):\n // fall through to the pipeline.\n const runCtx: RunContext = { ran: false, execute: pipeline, invocations: true };\n let fragmentResult: unknown;\n try {\n fragmentResult = await runStorage.run(runCtx, () => original.apply(this, callArgs));\n } catch (bodyError) {\n // A body that invoked run() is real logic — its errors propagate.\n if (runCtx.ran) throw bodyError;\n // Method body threw (e.g. placeholder `throw new Error('replaced')`) — fall through to file/inline SQL\n fragmentResult = undefined;\n }\n if (runCtx.ran) return fragmentResult;\n\n if (fragmentResult instanceof SqlFragment) {\n warnFragmentBodyDeprecated(this, prop);\n const { sql: boundSql, params } = fragmentResult.toSQL();\n\n const dbName = labels.db ?? options?.db ?? classLabels?.db;\n const { entry } = await resolveExecution(dbName);\n const db = entry.db;\n\n let out;\n try {\n const tx = getTransactionTarget(entry);\n out = tx ? await tx.query(boundSql, params) : await db.query(boundSql, params);\n } catch (dbError: any) {\n throw new DatabaseError(\n dbError?.message || String(dbError),\n boundSql,\n dbError instanceof Error ? dbError : undefined\n );\n }\n\n return finishResult(out, labels, this, prop);\n }\n\n return pipeline();\n };\n\n return desc;\n };\n}\n\n// Directory-based SQL for a decorated method. An explicit @Query('<path>')\n// is always the filesystem. A bare @Query() uses the packaged resources map\n// when one is installed (bundled/packaged runtimes), else the filesystem next\n// to the decorating module (tests, plain Node). Misses name every key tried.\nfunction resolveSourceSql(\n source: MethodLabels['source'],\n className: string,\n methodName: string,\n dialect: 'sqlite' | 'mysql' | 'postgres'\n): string | undefined {\n if (!source || source.kind === 'inline') return undefined;\n if (source.kind === 'fs') return resolveSqlFromFs(source.rootDir, methodName, dialect).sql;\n const packaged = getResources();\n const fromResources = packaged ? resolveSqlFromResources(source.dir, methodName, dialect) : undefined;\n if (fromResources?.sql !== undefined) return fromResources.sql;\n try {\n return resolveSqlFromFs(source.dir, methodName, dialect).sql;\n } catch (fsError) {\n const triedResources = fromResources ? `\\npackaged resources tried:\\n${fromResources.tried.join('\\n')}` : '';\n throw new SqlStackError(\n `sqlstack: no SQL for ${className}.${methodName}.${triedResources}\\n` +\n `${(fsError as Error)?.message ?? String(fsError)}`\n );\n }\n}\n\n// Deprecated (removal in the next major version): a @Query body that RETURNS\n// an sql`` fragment. It only type-checks when the method's declared return\n// type is bent to admit SqlFragment (an `as any`-style hole). One warning per\n// class.method per process.\nconst warnedFragmentBodies = new Set<string>();\n\nfunction warnFragmentBodyDeprecated(self: any, prop: string | symbol): void {\n const key = `${self?.constructor?.name ?? '<anonymous>'}.${String(prop)}`;\n if (warnedFragmentBodies.has(key)) return;\n warnedFragmentBodies.add(key);\n process.emitWarning(\n `@Query method ${key} returns an sql\\`\\` fragment from its body. This form is deprecated and will be ` +\n 'removed in the next major version. Use `return run(sql`...`)` (or `return run(db, sql`...`)`) instead.',\n { type: 'DeprecationWarning', code: 'SQLSTACK_FRAGMENT_BODY' }\n );\n}\n\nfunction applyDefaults(defaults: Record<string, unknown> | undefined, input: any) {\n if (!defaults) return input;\n if (Array.isArray(input)) return input; // defaults only apply to named-object args\n return { ...defaults, ...(input || {}) };\n}\n\n// Shared tail of both execution paths. Rows (any statement that produced a\n// result set) are shaped, transformed, and validated. A write result is\n// returned verbatim — unless a result-shape decorator was requested, in which\n// case the statement cannot satisfy it and we fail at the call site instead of\n// silently handing back a truthy `{ rowsAffected }` object.\nfunction finishResult(out: unknown, labels: any, self: any, prop: string | symbol): any {\n if (!Array.isArray(out)) {\n if (labels.shape) {\n throw new ExpectedRowsError(\n `${self?.constructor?.name ?? '<anonymous>'}.${String(prop)}`,\n labels.shape\n );\n }\n return out;\n }\n const shaped = applyShape(out, labels.shape);\n const transformed = labels.transform ? labels.transform(shaped) : shaped;\n\n if (labels.validateSchema && !isValidationDisabled()) {\n if (Array.isArray(transformed)) {\n for (const row of transformed) validateOutput(labels.validateSchema, row);\n } else if (transformed !== null && transformed !== undefined) {\n validateOutput(labels.validateSchema, transformed);\n }\n }\n return transformed;\n}\n\nfunction applyShape<T>(rows: T[], shape?: 'single' | 'only' | 'exist' | 'none'): any {\n switch (shape) {\n case 'single':\n return rows.length > 0 ? rows[0] : null;\n case 'only':\n if (rows.length !== 1) throw new ExactlyOneRowError(rows.length);\n return rows[0];\n case 'exist':\n if (rows.length < 1) throw new NoRowsError();\n return rows[0];\n case 'none':\n if (rows.length > 0) throw new RowsExistError(rows.length);\n return null;\n default:\n return rows;\n }\n}\n"]}
1
+ {"version":3,"file":"query.js","sourceRoot":"","sources":["../../../src/decorators/query.ts"],"names":[],"mappings":";;AA8CA,sBA8YC;AA5bD,+CAAoF;AACpF,2CAAkI;AAClI,iDAAyE;AACzE,wCAA4F;AAE5F,oDAAmG;AACnG,2DAA6F;AAC7F,+CAAwG;AACxG,iDAA0E;AAE1E,kDAAuD;AACvD,gCAAsD;AACtD,gCAYgB;AAQhB;;;;;;;;;;;;;GAaG;AACH,SAAgB,KAAK,CAAC,GAA2B;IAC/C,OAA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7C,OAAO,IAAI,CAAC,CAAC,CAAC,CAAC;QACjB,KAAK,MAAM;YACT,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC;gBAAE,MAAM,IAAI,uBAAc,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YAC3D,OAAO,IAAI,CAAC;QACd;YACE,OAAO,IAAI,CAAC;IAChB,CAAC;AACH,CAAC","sourcesContent":["import { getClassLabels, getMethodLabels, setMethodLabels } from '../core/metadata';\nimport { SqlStackError, ExactlyOneRowError, NoRowsError, RowsExistError, DatabaseError, ExpectedRowsError } from '../core/errors';\nimport { isValidationDisabled, validateOutput } from '../core/validator';\nimport { resolveExecution, resolveSqlResolver, isRegisteredDatabaseName } from '../runtime';\nimport type { SqlResolver } from '../core/resolver';\nimport { createSqliteBinder, createMysqlBinder, createPostgresBinder } from '../binders/sqlBinder';\nimport { coerceRootPath, resolveSqlFromFs, guessDecoratorDir } from '../core/fileResolution';\nimport { registerDecoratedMethod, recordQueryMethodOnClass, getActiveResolver } from '../core/resolver';\nimport { getResources, resolveSqlFromResources } from '../core/resources';\nimport type { MethodLabels } from '../core/metadata';\nimport { getTransactionTarget } from '../transactions';\nimport { SqlFragment, compileFragment } from '../sql';\nimport {\n runStorage,\n resolveRunTarget,\n executeOnTarget,\n toRunError,\n isErrorLike,\n fragmentText,\n isRunDatabaseHandle,\n type RunContext,\n type RunDatabase,\n type RunInvocation,\n type RunTarget,\n} from '../run';\n\ntype QueryOptions = {\n sql?: string; // optional inline SQL for testing; otherwise, future: load from file\n db?: string; // optional override DB name\n dialect?: 'sqlite' | 'mysql' | 'postgres';\n};\n\n/**\n * Turn a method into a database query. The body calls `run(...)` (see `run`\n * for its forms); the wrapper resolves SQL, binds, executes, and applies the\n * shape/transform/validation decorators. A string argument is the root\n * directory holding the method's `.sql` file; `{ sql }` gives inline SQL,\n * `{ db }` pins a registered database, `{ dialect }` overrides binding style.\n *\n * The decorated method's promise rejects with:\n * @throws {DatabaseError} When the driver rejects the statement (original\n * error in `.cause`).\n * @throws {SqlStackError} For missing SQL sources, unresolvable databases,\n * and shape/validation failures (ExpectedRowsError, ExactlyOneRowError,\n * NoRowsError, RowsExistError, ValidationError).\n */\nexport function Query(arg?: string | QueryOptions) {\n return function (_target: any, prop: string | symbol, desc: PropertyDescriptor) {\n const options: QueryOptions | undefined = typeof arg === 'string' ? undefined : arg;\n const rootArg: string | undefined = typeof arg === 'string' ? arg : undefined;\n // Store method-level db override if provided\n if (options?.db) {\n setMethodLabels(_target, prop, { db: options.db });\n }\n // Store inline SQL if provided\n if (options?.sql) {\n setMethodLabels(_target, prop, { source: { kind: 'inline', sql: options.sql } });\n } else {\n // An EXPLICIT path argument pins a filesystem directory. Bare @Query()\n // records the directory of the decorating module (first non-sqlstack\n // stack frame at decoration time); at call time that directory is\n // resolved against the packaged resources map when one is installed\n // (SqlStack.useResources), else read from the filesystem. No tree scan.\n const { rootDir } = coerceRootPath(rootArg);\n if (rootDir) {\n setMethodLabels(_target, prop, { source: { kind: 'fs', rootDir } });\n } else {\n const dir = guessDecoratorDir();\n if (dir) setMethodLabels(_target, prop, { source: { kind: 'guess', dir } });\n }\n }\n\n // Record for resolver coverage checks: immutable class metadata (the\n // canonical, environment-local source) plus the deprecated global list\n // consulted by the legacy global-resolver path.\n const decoratedEntry = {\n className: _target?.constructor?.name ?? '<anonymous>',\n methodName: String(prop),\n inline: !!options?.sql,\n };\n recordQueryMethodOnClass(_target, decoratedEntry);\n registerDecoratedMethod(decoratedEntry);\n\n const original = desc.value;\n desc.value = async function (...callArgs: any[]) {\n const labels = getMethodLabels(this, prop);\n const classLabels = getClassLabels(this);\n\n // Resolve, bind, and execute the method's own SQL (inline, resolver,\n // or file) and return the adapter's raw result. `callArgs` is the\n // binding input: the method's own arguments for run() and the legacy\n // fallback, or the params given to run(db, params). `explicit` carries\n // the database chosen by run(db, params).\n const executeMethodSql = async (\n callArgs: any[],\n explicit: { target: RunTarget; resolver: SqlResolver | undefined } | undefined,\n onSql: (sqlText: string) => void\n ): Promise<unknown> => {\n // 1) prepare args with defaults\n const rawInput = callArgs.length === 1 ? callArgs[0] : callArgs; // object or positional array\n\n // 2) choose database and dialect via the active environment (or run's explicit database)\n let target: RunTarget;\n let activeResolver: SqlResolver | undefined;\n if (explicit) {\n target = explicit.target;\n activeResolver = explicit.resolver;\n } else {\n target = await contextTarget();\n activeResolver = target.resolver;\n }\n const db = target.db;\n const dialect = options?.dialect ?? db.dialect ?? 'sqlite';\n\n // 3) load SQL source: inline; else an installed resolver (the\n // instance's, else the process-global one — a build-time manifest\n // registered by a host runner applies even when the SqlStack itself\n // came from an IoC root); else the decorator's directory (explicit\n // path or guessed module dir) against the packaged resources /\n // filesystem.\n const className = this?.constructor?.name ?? '<anonymous>';\n const resolver = activeResolver ?? getActiveResolver();\n const sql = labels?.source?.kind === 'inline'\n ? labels.source.sql\n : (resolver?.resolve({\n className,\n methodName: String(prop),\n dialect,\n rootDir: labels?.source?.kind === 'fs' ? labels.source.rootDir : undefined,\n }) ?? resolveSourceSql(labels?.source, className, String(prop), dialect));\n if (!sql) {\n throw new SqlStackError(\n `No SQL source for ${className}.${String(prop)}: the decorating module's directory could not be ` +\n 'determined from the stack. Use @Query() with a file/folder path or inline sql.'\n );\n }\n onSql(sql);\n\n // 4) bind placeholders\n // Decide argument mode: positional if SQL contains :argN\n let workingSql = sql;\n const hasPositional = /:arg[1-9][0-9]*/.test(workingSql);\n\n // Prepare args for binder\n let args: any;\n if (hasPositional) {\n args = callArgs;\n } else {\n const namedBase = callArgs.length > 0 ? callArgs[0] : undefined;\n args = applyDefaults(labels.defaults, namedBase ?? {});\n }\n\n // Compute paging and inject :offset/:limit (named mode) or rewrite to positional\n const pageCfg = labels.page;\n if (pageCfg) {\n const { size, zeroBase } = pageCfg;\n const base = zeroBase ? 0 : 1;\n\n // Extract page number from input (object) or a trailing options object in positional mode\n const pageFromObject = (val: any): number | undefined => {\n if (val && typeof val === 'object' && !Array.isArray(val) && typeof (val as any).page !== 'undefined') {\n const p = (val as any).page;\n if (typeof p === 'number' && isFinite(p)) return p;\n }\n return undefined;\n };\n\n let pageNum: number | undefined;\n if (hasPositional) {\n // Variadic-style: only the LAST argument may carry `{ page }`\n if (callArgs.length > 0) {\n const last = callArgs[callArgs.length - 1];\n pageNum = pageFromObject(last);\n }\n } else {\n // Prefer last-arg options if provided; otherwise read from named object\n if (callArgs.length > 1) {\n const last = callArgs[callArgs.length - 1];\n pageNum = pageFromObject(last);\n }\n if (pageNum === undefined) {\n pageNum = pageFromObject(args);\n }\n }\n\n const effectivePage = typeof pageNum === 'number' ? pageNum : base;\n const offset = (effectivePage - base) * size;\n const limit = size;\n\n if (hasPositional) {\n // Replace occurrences of :offset and :limit with new :argN tokens appended to args\n const baseIndex = callArgs.length; // start numbering after user args\n let nextIndex = baseIndex + 1;\n const additions: unknown[] = [];\n\n const rewrite = (sqlText: string) => {\n const out: string[] = [];\n let i = 0;\n let inSQ = false, inDQ = false, inLC = false, inBC = false;\n const len = sqlText.length;\n while (i < len) {\n const ch = sqlText[i];\n const next = i + 1 < len ? sqlText[i + 1] : '';\n if (inLC) { out.push(ch); if (ch === '\\n') inLC = false; i++; continue; }\n if (inBC) { out.push(ch); if (ch === '*' && next === '/') { out.push(next); i++; inBC = false; } i++; continue; }\n if (inSQ) {\n out.push(ch);\n if (ch === \"'\" && next === \"'\") { out.push(next); i += 2; continue; }\n if (ch === \"'\") inSQ = false;\n i++;\n continue;\n }\n if (inDQ) {\n out.push(ch);\n if (ch === '\"' && next === '\"') { out.push(next); i += 2; continue; }\n if (ch === '\"') inDQ = false;\n i++;\n continue;\n }\n if (ch === '-' && next === '-') { out.push(ch, next); i += 2; inLC = true; continue; }\n if (ch === '/' && next === '*') { out.push(ch, next); i += 2; inBC = true; continue; }\n if (ch === '\"') { out.push(ch); inDQ = true; i++; continue; }\n if (ch === \"'\") { out.push(ch); inSQ = true; i++; continue; }\n if (ch === ':' && next === ':') { out.push('::'); i += 2; continue; }\n if (ch === ':') {\n // parse token\n let j = i + 1;\n const start = j;\n while (j < len) {\n const c = sqlText[j];\n if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c === '_') j++; else break;\n }\n const name = sqlText.slice(start, j);\n if (name === 'offset') {\n const token = `:arg${nextIndex++}`;\n out.push(token);\n additions.push(offset);\n i = j;\n continue;\n }\n if (name === 'limit') {\n const token = `:arg${nextIndex++}`;\n out.push(token);\n additions.push(limit);\n i = j;\n continue;\n }\n // otherwise leave untouched\n out.push(':');\n i++;\n continue;\n }\n out.push(ch);\n i++;\n }\n return out.join('');\n };\n\n const rewritten = rewrite(workingSql);\n if (rewritten !== workingSql) {\n workingSql = rewritten;\n // append values so :argK map correctly\n (args as unknown[]).push(...additions);\n }\n } else {\n // Named-mode: attach computed values (override any provided)\n args = { ...(args as Record<string, unknown>), offset, limit };\n }\n }\n const binder =\n dialect === 'postgres' ? createPostgresBinder() : dialect === 'mysql' ? createMysqlBinder() : createSqliteBinder();\n // Binding failures (missing :name, bad array value) surface as DatabaseError like every\n // other run() failure; the original error stays in `.cause`.\n let bound: { sql: string; params: unknown[] };\n try {\n bound = binder.bind(workingSql, args as any);\n } catch (bindError) {\n throw toRunError(bindError, workingSql);\n }\n const { sql: boundSql, params } = bound;\n onSql(boundSql);\n\n // 5) execute query (inside the active transaction on that database, if any)\n let out;\n try {\n out = target.tx ? await target.tx.query(boundSql, params) : await db.query(boundSql, params);\n } catch (dbError: any) {\n // Attach SQL query (with placeholders) to error for debugging\n throw new DatabaseError(\n dbError?.message || String(dbError),\n boundSql,\n isErrorLike(dbError) ? dbError : undefined\n );\n }\n return out;\n };\n\n // Database from the decorator context: @Query({ db }), @QueryBinder({ db }),\n // or the environment default.\n const contextTarget = async (): Promise<RunTarget> => {\n const dbName = labels.db ?? options?.db ?? classLabels?.db;\n const resolved = await resolveExecution(dbName);\n return {\n db: resolved.entry.db,\n tx: getTransactionTarget(resolved.entry),\n resolver: resolved.resolver,\n byName: true,\n };\n };\n\n // The method's own leading database argument: a handle (object with\n // query()) or a registered database name. It selects run()'s target\n // and is never bound as a value.\n const leadingDb = async (): Promise<RunDatabase | string | undefined> => {\n if (callArgs.length === 0) return undefined;\n const first = callArgs[0];\n if (isRunDatabaseHandle(first)) return first;\n if (typeof first === 'string' && first.length > 0 && (await isRegisteredDatabaseName(first))) return first;\n return undefined;\n };\n\n // A database chosen by run's argument or the method's leading argument.\n const explicitTarget = async (\n db: RunDatabase | string\n ): Promise<{ target: RunTarget; resolver: SqlResolver | undefined }> => {\n const target = await resolveRunTarget(db);\n // Inline SQL needs no resolver; only look one up for file-based SQL.\n const resolver = target.byName\n ? target.resolver\n : labels?.source?.kind === 'inline'\n ? undefined\n : await resolveSqlResolver();\n return { target, resolver };\n };\n\n // run() (and the legacy fallback): the method's arguments minus a\n // leading database, on that database or the decorator context.\n const executeDefault = async (onSql: (sqlText: string) => void): Promise<unknown> => {\n const lead = await leadingDb();\n if (lead === undefined) return executeMethodSql(callArgs, undefined, onSql);\n return executeMethodSql(callArgs.slice(1), await explicitTarget(lead), onSql);\n };\n\n // run's argument-taking forms: return the adapter's raw result.\n const executeInvocation = async (\n invocation: Exclude<RunInvocation, { kind: 'default' }>,\n onSql: (sqlText: string) => void\n ): Promise<unknown> => {\n if (invocation.kind === 'fragment') {\n // run(query) / run(db, query): the fragment replaces the method's SQL;\n // the method's arguments are not bound.\n const target = invocation.db !== undefined ? await resolveRunTarget(invocation.db) : await contextTarget();\n const dialect = options?.dialect ?? target.db.dialect ?? 'sqlite';\n const { sql: boundSql, params } = compileFragment(invocation.fragment, dialect);\n onSql(boundSql);\n return executeOnTarget(target, boundSql, params);\n }\n if (invocation.kind === 'db') {\n // run(db): the method's own SQL against db, bound from the method's\n // arguments minus a leading database argument.\n const lead = await leadingDb();\n const bindArgs = lead === undefined ? callArgs : callArgs.slice(1);\n return executeMethodSql(bindArgs, await explicitTarget(invocation.db), onSql);\n }\n // run(db, params) / run(params): the method's own SQL bound from params\n // only (an object for :named, an array for :argN), against run's db,\n // else the method's leading database, else the decorator context.\n const bindArgs = Array.isArray(invocation.params) ? [...invocation.params] : [invocation.params];\n const db = invocation.db ?? (await leadingDb());\n return executeMethodSql(bindArgs, db !== undefined ? await explicitTarget(db) : undefined, onSql);\n };\n\n // The full pipeline: execute, then — if rows were returned\n // (SELECT/CTE/RETURNING) — shape + transform + validate; a write result\n // is returned as-is (or fails if a shape was requested). Invoked by\n // run() from inside the method body, or directly as the legacy fallback\n // when the body throws. The zero-argument path is unchanged; run's\n // argument-taking forms get the unified error contract: any failure\n // before shaping that is not already a SqlStackError becomes a\n // DatabaseError with the original error in `.cause`.\n const pipeline = async (invocation?: RunInvocation): Promise<unknown> => {\n if (invocation === undefined || invocation.kind === 'default') {\n const out = await executeDefault(() => {});\n return finishResult(out, labels, this, prop);\n }\n let sqlText = invocation.kind === 'fragment' ? fragmentText(invocation.fragment) : '';\n let out: unknown;\n try {\n out = await executeInvocation(invocation, (s) => {\n sqlText = s;\n });\n } catch (err) {\n throw toRunError(err, sqlText);\n }\n return finishResult(out, labels, this, prop);\n };\n\n // 0) Invoke the method body inside a run() context. Three outcomes:\n // - body calls run(...): the pipeline executed inside the body; return\n // the body's result verbatim (it may have caught/transformed it).\n // - body returns a SqlFragment (deprecated template literal path):\n // execute it.\n // - body throws without calling run() (legacy placeholder throw):\n // fall through to the pipeline.\n const runCtx: RunContext = { ran: false, execute: pipeline, invocations: true };\n let fragmentResult: unknown;\n try {\n fragmentResult = await runStorage.run(runCtx, () => original.apply(this, callArgs));\n } catch (bodyError) {\n // A body that invoked run() is real logic — its errors propagate.\n if (runCtx.ran) throw bodyError;\n // Method body threw (e.g. placeholder `throw new Error('replaced')`) — fall through to file/inline SQL\n fragmentResult = undefined;\n }\n if (runCtx.ran) return fragmentResult;\n\n if (fragmentResult instanceof SqlFragment) {\n warnFragmentBodyDeprecated(this, prop);\n const { sql: boundSql, params } = fragmentResult.toSQL();\n\n const dbName = labels.db ?? options?.db ?? classLabels?.db;\n const { entry } = await resolveExecution(dbName);\n const db = entry.db;\n\n let out;\n try {\n const tx = getTransactionTarget(entry);\n out = tx ? await tx.query(boundSql, params) : await db.query(boundSql, params);\n } catch (dbError: any) {\n throw new DatabaseError(\n dbError?.message || String(dbError),\n boundSql,\n isErrorLike(dbError) ? dbError : undefined\n );\n }\n\n return finishResult(out, labels, this, prop);\n }\n\n return pipeline();\n };\n\n return desc;\n };\n}\n\n// Directory-based SQL for a decorated method. An explicit @Query('<path>')\n// is always the filesystem. A bare @Query() uses the packaged resources map\n// when one is installed (bundled/packaged runtimes), else the filesystem next\n// to the decorating module (tests, plain Node). Misses name every key tried.\nfunction resolveSourceSql(\n source: MethodLabels['source'],\n className: string,\n methodName: string,\n dialect: 'sqlite' | 'mysql' | 'postgres'\n): string | undefined {\n if (!source || source.kind === 'inline') return undefined;\n if (source.kind === 'fs') return resolveSqlFromFs(source.rootDir, methodName, dialect).sql;\n const packaged = getResources();\n const fromResources = packaged ? resolveSqlFromResources(source.dir, methodName, dialect) : undefined;\n if (fromResources?.sql !== undefined) return fromResources.sql;\n try {\n return resolveSqlFromFs(source.dir, methodName, dialect).sql;\n } catch (fsError) {\n const triedResources = fromResources ? `\\npackaged resources tried:\\n${fromResources.tried.join('\\n')}` : '';\n throw new SqlStackError(\n `sqlstack: no SQL for ${className}.${methodName}.${triedResources}\\n` +\n `${(fsError as Error)?.message ?? String(fsError)}`\n );\n }\n}\n\n// Deprecated (removal in the next major version): a @Query body that RETURNS\n// an sql`` fragment. It only type-checks when the method's declared return\n// type is bent to admit SqlFragment (an `as any`-style hole). One warning per\n// class.method per process.\nconst warnedFragmentBodies = new Set<string>();\n\nfunction warnFragmentBodyDeprecated(self: any, prop: string | symbol): void {\n const key = `${self?.constructor?.name ?? '<anonymous>'}.${String(prop)}`;\n if (warnedFragmentBodies.has(key)) return;\n warnedFragmentBodies.add(key);\n process.emitWarning(\n `@Query method ${key} returns an sql\\`\\` fragment from its body. This form is deprecated and will be ` +\n 'removed in the next major version. Use `return run(sql`...`)` (or `return run(db, sql`...`)`) instead.',\n { type: 'DeprecationWarning', code: 'SQLSTACK_FRAGMENT_BODY' }\n );\n}\n\nfunction applyDefaults(defaults: Record<string, unknown> | undefined, input: any) {\n if (!defaults) return input;\n if (Array.isArray(input)) return input; // defaults only apply to named-object args\n return { ...defaults, ...(input || {}) };\n}\n\n// Shared tail of both execution paths. Rows (any statement that produced a\n// result set) are shaped, transformed, and validated. A write result is\n// returned verbatim — unless a result-shape decorator was requested, in which\n// case the statement cannot satisfy it and we fail at the call site instead of\n// silently handing back a truthy `{ rowsAffected }` object.\nfunction finishResult(out: unknown, labels: any, self: any, prop: string | symbol): any {\n if (!Array.isArray(out)) {\n if (labels.shape) {\n throw new ExpectedRowsError(\n `${self?.constructor?.name ?? '<anonymous>'}.${String(prop)}`,\n labels.shape\n );\n }\n return out;\n }\n const shaped = applyShape(out, labels.shape);\n const transformed = labels.transform ? labels.transform(shaped) : shaped;\n\n if (labels.validateSchema && !isValidationDisabled()) {\n if (Array.isArray(transformed)) {\n for (const row of transformed) validateOutput(labels.validateSchema, row);\n } else if (transformed !== null && transformed !== undefined) {\n validateOutput(labels.validateSchema, transformed);\n }\n }\n return transformed;\n}\n\nfunction applyShape<T>(rows: T[], shape?: 'single' | 'only' | 'exist' | 'none'): any {\n switch (shape) {\n case 'single':\n return rows.length > 0 ? rows[0] : null;\n case 'only':\n if (rows.length !== 1) throw new ExactlyOneRowError(rows.length);\n return rows[0];\n case 'exist':\n if (rows.length < 1) throw new NoRowsError();\n return rows[0];\n case 'none':\n if (rows.length > 0) throw new RowsExistError(rows.length);\n return null;\n default:\n return rows;\n }\n}\n"]}
package/dist/cjs/run.d.ts CHANGED
@@ -193,6 +193,16 @@ export declare function executeOnTarget(target: RunTarget, boundSql: string, par
193
193
  * through; anything else becomes DatabaseError with the original in `.cause`.
194
194
  */
195
195
  export declare function toRunError(err: unknown, sqlText: string): SqlStackError;
196
+ /**
197
+ * better-sqlite3 binds its SqliteError class once per process. When several
198
+ * realms share that process (vm contexts, e.g. jest --runInBand, which is
199
+ * jest's default on a single CPU), driver errors are Error subclasses of the
200
+ * first realm only: `instanceof Error` is false elsewhere and they carry no
201
+ * [[ErrorData]] slot. Recognise them by shape so `.cause`/`.code` survive.
202
+ *
203
+ * @internal Shared with decorators/query.ts.
204
+ */
205
+ export declare function isErrorLike(err: unknown): err is Error;
196
206
  /** @internal Raw template text of a fragment, for error messages. */
197
207
  export declare function fragmentText(fragment: SqlFragment): string;
198
208
  /** @internal Compile a fragment for the dialect, wrapping macro errors. */
@@ -1 +1 @@
1
- {"version":3,"file":"run.d.ts","sourceRoot":"","sources":["../../src/run.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,EAAE,aAAa,EAAiB,MAAM,eAAe,CAAC;AAC7D,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAC1C,OAAO,EAAE,WAAW,EAAkC,MAAM,OAAO,CAAC;AAEpE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAEnD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAExD;;;;;GAKG;AACH,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,OAAO,CAAC,EAAE,OAAO,CAAC;IAC3B,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;CACzD;AAED;;;;GAIG;AACH,MAAM,MAAM,iBAAiB,CAAC,CAAC,IAAI,CAAC,SAAS;IAAE,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,SAAS,OAAO,EAAE,CAAA;CAAE,GACtG,KAAK,GACL,OAAO,CAAC;AAEZ;;;GAGG;AACH,MAAM,MAAM,aAAa,GACrB;IAAE,QAAQ,CAAC,IAAI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B,QAAQ,CAAC,EAAE,EAAE,iBAAiB,GAAG,SAAS,CAAC;IAC3C,6EAA6E;IAC7E,QAAQ,CAAC,QAAQ,EAAE,WAAW,GAAG,SAAS,CAAC;IAC3C,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;CAC1B,CAAC;AAEF;;;;;;;;;GASG;AACH,wBAAsB,gBAAgB,CAAC,EAAE,EAAE,WAAW,GAAG,MAAM,GAAG,OAAO,CAAC,SAAS,CAAC,CAMnF;AAED,wFAAwF;AACxF,wBAAsB,eAAe,CAAC,MAAM,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC,OAAO,CAAC,CAM9G;AAED;;;;GAIG;AACH,wBAAgB,UAAU,CAAC,GAAG,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,GAAG,aAAa,CAEvE;AAWD;;;;;;;;GAQG;AACH,wBAAgB,WAAW,CAAC,GAAG,EAAE,OAAO,GAAG,GAAG,IAAI,KAAK,CAKtD;AAED,qEAAqE;AACrE,wBAAgB,YAAY,CAAC,QAAQ,EAAE,WAAW,GAAG,MAAM,CAE1D;AAED,2EAA2E;AAC3E,wBAAgB,aAAa,CAAC,QAAQ,EAAE,WAAW,EAAE,OAAO,EAAE,OAAO,GAAG;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,OAAO,EAAE,CAAA;CAAE,CAMzG"}
package/dist/cjs/run.js CHANGED
@@ -6,6 +6,7 @@ exports.isRunDatabaseHandle = isRunDatabaseHandle;
6
6
  exports.resolveRunTarget = resolveRunTarget;
7
7
  exports.executeOnTarget = executeOnTarget;
8
8
  exports.toRunError = toRunError;
9
+ exports.isErrorLike = isErrorLike;
9
10
  exports.fragmentText = fragmentText;
10
11
  exports.compileForRun = compileForRun;
11
12
  const node_async_hooks_1 = require("node:async_hooks");
@@ -150,7 +151,24 @@ function toRunError(err, sqlText) {
150
151
  }
151
152
  function toDatabaseError(err, sqlText) {
152
153
  const message = err?.message;
153
- return new errors_1.DatabaseError(typeof message === 'string' && message ? message : String(err), sqlText, err instanceof Error ? err : undefined);
154
+ return new errors_1.DatabaseError(typeof message === 'string' && message ? message : String(err), sqlText, isErrorLike(err) ? err : undefined);
155
+ }
156
+ /**
157
+ * better-sqlite3 binds its SqliteError class once per process. When several
158
+ * realms share that process (vm contexts, e.g. jest --runInBand, which is
159
+ * jest's default on a single CPU), driver errors are Error subclasses of the
160
+ * first realm only: `instanceof Error` is false elsewhere and they carry no
161
+ * [[ErrorData]] slot. Recognise them by shape so `.cause`/`.code` survive.
162
+ *
163
+ * @internal Shared with decorators/query.ts.
164
+ */
165
+ function isErrorLike(err) {
166
+ if (err instanceof Error)
167
+ return true;
168
+ if (typeof err !== 'object' || err === null)
169
+ return false;
170
+ const candidate = err;
171
+ return typeof candidate.message === 'string' && typeof candidate.stack === 'string';
154
172
  }
155
173
  /** @internal Raw template text of a fragment, for error messages. */
156
174
  function fragmentText(fragment) {
@@ -1 +1 @@
1
- {"version":3,"file":"run.js","sourceRoot":"","sources":["../../src/run.ts"],"names":[],"mappings":";;;AAsLA,kBA4CC;AAmDD,kDAEC;AA4CD,4CAMC;AAGD,0CAMC;AAOD,gCAEC;AAYD,oCAEC;AAGD,sCAMC;AAlXD,uDAAqD;AACrD,0CAA6D;AAE7D,+BAAoE;AACpE,uCAA6C;AAE7C,iDAAqF;AA0DrF,uEAAuE;AACvE,yEAAyE;AACzE,yCAAyC;AACzC,MAAM,WAAW,GAAG,MAAM,CAAC,GAAG,CAAC,2BAA2B,CAAC,CAAC;AAC5D,MAAM,MAAM,GAAG,UAA0C,CAAC;AAC1D,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,EAAE,CAAC;IACzB,MAAM,CAAC,WAAW,CAAC,GAAG,IAAI,oCAAiB,EAAc,CAAC;AAC5D,CAAC;AACY,QAAA,UAAU,GAAG,MAAM,CAAC,WAAW,CAAkC,CAAC;AA8GxE,KAAK,UAAU,G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AC,OAAO,GAAG,EAAE,CAAC;QACb,MAAM,UAAU,CAAC,GAAG,EAAE,YAAY,CAAC,QAAQ,CAAC,CAAC,CAAC;IAChD,CAAC;IACD,MAAM,EAAE,GAAG,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,aAAa,CAAC,QAAQ,EAAE,MAAM,CAAC,EAAE,CAAC,OAAO,IAAI,QAAQ,CAAC,CAAC;IACzF,OAAO,eAAe,CAAC,MAAM,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC;AACnD,CAAC","sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\nimport { SqlStackError, DatabaseError } from './core/errors';\nimport type { Dialect } from './registry';\nimport { SqlFragment, isSqlFragment, compileFragment } from './sql';\nimport { resolveExecution } from './runtime';\nimport type { SqlResolver } from './core/resolver';\nimport { getTransactionTarget, getTransactionTargetForHandle } from './transactions';\nimport type { ActiveTransaction } from './transactions';\n\n/**\n * Anything run(db, ...) can execute against: sqlstack's own `Database`\n * (from createSqliteDb/createPgDb/createMysqlDb), or any application handle\n * exposing `query(sql, params)`. `dialect` selects placeholder style and\n * defaults to `'sqlite'` when absent. run never opens databases by path.\n */\nexport interface RunDatabase {\n readonly dialect?: Dialect;\n query(sql: string, params: unknown[]): Promise<unknown>;\n}\n\n/**\n * Type-level guard for the params form of run: rejects the\n * `{ sql, params }` object returned by `fragment.toSQL()`. Pass the sql``\n * fragment itself instead, so run owns dialect binding and error handling.\n */\nexport type RejectCompiledSql<P> = P extends { readonly sql: string; readonly params: readonly unknown[] }\n ? never\n : unknown;\n\n/**\n * What a run(...) call made inside a @Query body asks of the wrapper's\n * pipeline. `default` is the zero-argument run().\n */\nexport type RunInvocation =\n | { readonly kind: 'default' }\n | { readonly kind: 'fragment'; readonly db?: RunDatabase | string; readonly fragment: SqlFragment }\n | { readonly kind: 'params'; readonly db?: RunDatabase | string; readonly params: object }\n | { readonly kind: 'db'; readonly db: RunDatabase | string };\n\n/**\n * Type-level guard for run(db) with a name: a string containing whitespace is\n * SQL text, never a database name. Build statements with the sql`` tag.\n */\nexport type RejectSqlText<D> = D extends string\n ? D extends `${string} ${string}` | `${string}\\n${string}` | `${string}\\t${string}`\n ? never\n : unknown\n : unknown;\n\n/**\n * Per-invocation context established by the @Query wrapper before the method\n * body executes. `execute` performs the full query pipeline (resolve SQL,\n * bind, execute, shape/transform/validate); `ran` records that the body\n * invoked run(), so the wrapper returns the body's result verbatim instead\n * of falling through to the legacy pipeline. `invocations` marks a wrapper\n * that understands the argument-taking run forms (an older duplicated copy\n * of the decorator would silently ignore them).\n */\nexport type RunContext = {\n execute: (invocation?: RunInvocation) => Promise<unknown>;\n ran: boolean;\n invocations?: true;\n};\n\n// Anchored on globalThis via Symbol.for so duplicated module instances\n// (npm link, dual ESM/CJS loads) share one channel between the decorator\n// and the run() the application imports.\nconst RUN_CHANNEL = Symbol.for('noego.sqlstack.runContext');\nconst anchor = globalThis as Record<PropertyKey, unknown>;\nif (!anchor[RUN_CHANNEL]) {\n anchor[RUN_CHANNEL] = new AsyncLocalStorage<RunContext>();\n}\nexport const runStorage = anchor[RUN_CHANNEL] as AsyncLocalStorage<RunContext>;\n\n/**\n * Execute the current @Query method's SQL and return the finished result.\n * Call it as the body of a @Query-decorated method:\n *\n * @Query()\n * async getUsers(active: boolean): Promise<User[]> {\n * return run();\n * }\n *\n * Takes no arguments — the method's own arguments, database, SQL source,\n * transaction, shaping, transform, and validation all come from the\n * decorator context — except that a leading method argument that is a\n * database handle (or a registered database name) selects the database and\n * is not bound. T is inferred from the method's declared return type.\n *\n * @throws {DatabaseError} When the driver rejects the statement (original\n * error in `.cause`).\n * @throws {SqlStackError} When called outside a @Query method, or for\n * shape/validation failures (ExactlyOneRowError, NoRowsError, ValidationError, ...).\n */\nexport function run<T = any>(): Promise<T>;\n/**\n * Inside a @Query method: execute this inline sql`` fragment instead of the\n * method's SQL file. The database comes from the method/class/registry\n * context (`@Query({ db })`, `@QueryBinder({ db })`, the default), the\n * active transaction on it is joined, and the method's shape/transform/\n * validation decorators apply. The method's arguments are not auto-bound —\n * the fragment's `${}` values are the parameters.\n *\n * @Single @Query()\n * async byEmail(email: string): Promise<User | null> {\n * return run(sql`SELECT * FROM users WHERE email = ${email}`);\n * }\n *\n * @throws {DatabaseError} When the fragment cannot be compiled (macro input\n * errors), the database cannot be resolved, or the driver rejects the\n * statement. The original error is in `.cause`.\n * @throws {SqlStackError} When called outside a @Query method (use\n * `run(db, query)` there), or for shape/validation failures.\n */\nexport function run<T = unknown>(query: SqlFragment): Promise<T>;\n/**\n * Execute an sql`` fragment against an explicit database: a handle\n * (anything with `query(sql, params)`) or the name of a database registered\n * with the active SqlStack / legacy registry. Usable anywhere.\n *\n * Binds for the database's dialect (`$1..` for Postgres, `?` otherwise;\n * default sqlite). Joins an active transaction opened on the same database\n * (same registered handle, or same name). Outside a @Query method the raw\n * result is returned (rows array, or `{ rowsAffected }` for writes); inside\n * one, the method's shape/transform/validation decorators apply.\n *\n * const rows = await run<Row[]>(accountsDb, sql`SELECT * FROM t WHERE id = ${id}`);\n *\n * @throws {DatabaseError} When the fragment cannot be compiled, a named\n * database cannot be resolved, or the driver rejects the statement. The\n * original error is in `.cause`, and its string `code` is copied to `.code`.\n * @throws {SqlStackError} For invalid arguments, or shape/validation failures.\n */\nexport function run<T = unknown>(db: RunDatabase | string, query: SqlFragment): Promise<T>;\n/**\n * Inside a @Query method: run the method's own SQL (its .sql file or inline\n * `@Query({ sql })`) against `db`, binding `params` (an object for `:named`\n * placeholders, an array for `:arg1..`). The method's raw arguments are NOT\n * auto-bound in this form — `params` is the whole binding input. @Defaults,\n * @Page, shaping, transform, and validation still apply.\n *\n * @Single @Query()\n * async byEmail(db: Database, p: { email: string }): Promise<User | null> {\n * return run(db, p);\n * }\n *\n * @throws {DatabaseError} When binding fails, a named database cannot be\n * resolved, or the driver rejects the statement. The original error is in\n * `.cause`.\n * @throws {SqlStackError} When called outside a @Query method, when passed\n * `.toSQL()` output, or for shape/validation failures.\n */\nexport function run<T = unknown, P extends object = object>(\n db: RunDatabase | string,\n params: P & RejectCompiledSql<P>\n): Promise<T>;\n/**\n * Inside a @Query method: run the method's own SQL against `db` (a handle or\n * a registered database name), binding the method's own arguments exactly as\n * run() does — except that a leading database handle/name argument of the\n * method is never bound.\n *\n * @throws {DatabaseError} When binding fails, a named database cannot be\n * resolved, or the driver rejects the statement.\n * @throws {SqlStackError} When called outside a @Query method, or for\n * shape/validation failures.\n */\nexport function run<T = unknown, D extends RunDatabase | string = RunDatabase | string>(\n db: D & RejectSqlText<D>\n): Promise<T>;\n/**\n * Inside a @Query method: run the method's own SQL binding only `params` (an\n * object for `:named`, an array for `:argN`) against the database run() would\n * use: the method's leading database handle/name argument, else the\n * decorator context.\n *\n * @throws {DatabaseError} When binding fails, the database cannot be\n * resolved, or the driver rejects the statement.\n * @throws {SqlStackError} When called outside a @Query method, when passed\n * `.toSQL()` output, or for shape/validation failures.\n */\nexport function run<T = unknown, P extends object = object>(params: P & RejectCompiledSql<P>): Promise<T>;\nexport async function run(...args: unknown[]): Promise<unknown> {\n const invocation = parseRunArgs(args);\n const ctx = runStorage.getStore();\n\n if (!ctx) {\n if (invocation.kind === 'fragment' && invocation.db !== undefined) {\n return executeFragment(invocation.db, invocation.fragment);\n }\n if (invocation.kind === 'default') {\n throw new SqlStackError(\n 'run() called outside a @Query method. It may only be invoked from the body of a @Query-decorated method.'\n );\n }\n if (invocation.kind === 'fragment') {\n throw new SqlStackError(\n 'run(query) called outside a @Query method has no database. Pass one explicitly: run(db, query).'\n );\n }\n if (invocation.kind === 'db') {\n throw new SqlStackError(\n 'run(db) called outside a @Query method has no SQL source. Pass an sql`` fragment instead: run(db, sql`...`).'\n );\n }\n if (invocation.db === undefined) {\n throw new SqlStackError(\n 'run(params) called outside a @Query method has no SQL source or database. ' +\n 'Pass a database and an sql`` fragment instead: run(db, sql`...`).'\n );\n }\n throw new SqlStackError(\n 'run(db, params) called outside a @Query method has no SQL source. ' +\n 'Pass an sql`` fragment instead: run(db, sql`...`).'\n );\n }\n\n if (invocation.kind !== 'default' && !ctx.invocations) {\n throw new SqlStackError(\n 'run(...) with arguments reached a @Query wrapper from an older sqlstack copy that cannot honour them. ' +\n 'Make sure a single sqlstack version is installed.'\n );\n }\n\n ctx.ran = true;\n return invocation.kind === 'default' ? ctx.execute() : ctx.execute(invocation);\n}\n\nfunction parseRunArgs(args: unknown[]): RunInvocation {\n if (args.length === 0) return { kind: 'default' };\n\n if (args.length === 1) {\n const [query] = args;\n if (isSqlFragment(query)) return { kind: 'fragment', fragment: query };\n if (typeof query === 'string') {\n // A whitespace-free string is a database name: run(db).\n if (isDatabaseNameText(query)) return { kind: 'db', db: query };\n throw new SqlStackError(\n 'run(query) does not accept SQL strings. Build the statement with the sql`` tag: run(sql`...`).'\n );\n }\n if (isRunDatabaseHandle(query)) return { kind: 'db', db: query };\n if (isCompiledSql(query)) {\n throw new SqlStackError(\n 'run(...) received the { sql, params } output of .toSQL(). Pass the sql`` fragment itself so run can ' +\n 'bind it for the target dialect: run(sql`...`).'\n );\n }\n if (typeof query === 'object' && query !== null) return { kind: 'params', params: query };\n throw new SqlStackError(\n 'run(x) requires an sql`` fragment, a params object/array, or a database handle/name.'\n );\n }\n\n if (args.length === 2) {\n const [db, second] = args;\n assertRunDatabase(db);\n if (isSqlFragment(second)) return { kind: 'fragment', db, fragment: second };\n if (typeof second === 'string') {\n throw new SqlStackError(\n 'run(db, query) does not accept SQL strings. Build the statement with the sql`` tag: run(db, sql`...`).'\n );\n }\n if (isCompiledSql(second)) {\n throw new SqlStackError(\n 'run(db, ...) received the { sql, params } output of .toSQL(). Pass the sql`` fragment itself so run can ' +\n 'bind it for the target dialect: run(db, sql`...`).'\n );\n }\n if (typeof second === 'object' && second !== null) return { kind: 'params', db, params: second };\n throw new SqlStackError('run(db, x) requires an sql`` fragment or a params object/array as its second argument.');\n }\n\n throw new SqlStackError(`run() accepts at most 2 arguments, got ${args.length}.`);\n}\n\n/** @internal A database handle: any object exposing query(sql, params). */\nexport function isRunDatabaseHandle(value: unknown): value is RunDatabase {\n return typeof value === 'object' && value !== null && typeof (value as { query?: unknown }).query === 'function';\n}\n\nfunction isDatabaseNameText(value: string): boolean {\n return value.length > 0 && !/\\s/.test(value);\n}\n\nfunction assertRunDatabase(db: unknown): asserts db is RunDatabase | string {\n if (typeof db === 'string' && db.length > 0) return;\n if (typeof db === 'object' && db !== null && typeof (db as { query?: unknown }).query === 'function') return;\n throw new SqlStackError(\n 'run(db, ...) requires a database handle with query(sql, params) or a registered database name as its first argument.'\n );\n}\n\nfunction isCompiledSql(value: unknown): boolean {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;\n const keys = Object.keys(value);\n const rec = value as { sql?: unknown; params?: unknown };\n return keys.length === 2 && typeof rec.sql === 'string' && Array.isArray(rec.params);\n}\n\n// ---------------------------------------------------------------------------\n// Shared execution helpers (also used by the @Query wrapper)\n// ---------------------------------------------------------------------------\n\n/** @internal A database chosen for one run, plus the transaction it joins. */\nexport type RunTarget = {\n readonly db: RunDatabase;\n readonly tx: ActiveTransaction | undefined;\n /** SQL resolver of the environment, when the target was resolved by name. */\n readonly resolver: SqlResolver | undefined;\n readonly byName: boolean;\n};\n\n/**\n * @internal Resolve run's database argument. A name goes through the active\n * SqlStack (or legacy registry) and joins that entry's transaction — or,\n * inside a @transaction scope with none open, opens one on first execution. A handle\n * is used as-is — no registry lookup, so it works without any SqlStack — and\n * behaves the same: it joins a transaction open in this flow on that same\n * object, or, inside a @transaction scope with none open, opens one on the\n * handle on first execution. Outside any scope a handle with no open\n * transaction runs directly.\n */\nexport async function resolveRunTarget(db: RunDatabase | string): Promise<RunTarget> {\n if (typeof db === 'string') {\n const { entry, resolver } = await resolveExecution(db);\n return { db: entry.db, tx: getTransactionTarget(entry), resolver, byName: true };\n }\n return { db, tx: getTransactionTargetForHandle(db), resolver: undefined, byName: false };\n}\n\n/** @internal Run one bound statement on the target (inside its transaction, if any). */\nexport async function executeOnTarget(target: RunTarget, boundSql: string, params: unknown[]): Promise<unknown> {\n try {\n return target.tx ? await target.tx.query(boundSql, params) : await target.db.query(boundSql, params);\n } catch (dbError) {\n throw toDatabaseError(dbError, boundSql);\n }\n}\n\n/**\n * @internal Normalize a failure from run's argument-taking forms: errors that\n * are already SqlStackError (DatabaseError, shape/validation errors) pass\n * through; anything else becomes DatabaseError with the original in `.cause`.\n */\nexport function toRunError(err: unknown, sqlText: string): SqlStackError {\n return err instanceof SqlStackError ? err : toDatabaseError(err, sqlText);\n}\n\nfunction toDatabaseError(err: unknown, sqlText: string): DatabaseError {\n const message = (err as { message?: unknown } | undefined)?.message;\n return new DatabaseError(\n typeof message === 'string' && message ? message : String(err),\n sqlText,\n err instanceof Error ? err : undefined\n );\n}\n\n/** @internal Raw template text of a fragment, for error messages. */\nexport function fragmentText(fragment: SqlFragment): string {\n return fragment.strings.join('?');\n}\n\n/** @internal Compile a fragment for the dialect, wrapping macro errors. */\nexport function compileForRun(fragment: SqlFragment, dialect: Dialect): { sql: string; params: unknown[] } {\n try {\n return compileFragment(fragment, dialect);\n } catch (err) {\n throw toRunError(err, fragmentText(fragment));\n }\n}\n\nasync function executeFragment(db: RunDatabase | string, fragment: SqlFragment): Promise<unknown> {\n let target: RunTarget;\n try {\n target = await resolveRunTarget(db);\n } catch (err) {\n throw toRunError(err, fragmentText(fragment));\n }\n const { sql: boundSql, params } = compileForRun(fragment, target.db.dialect ?? 'sqlite');\n return executeOnTarget(target, boundSql, params);\n}\n"]}
1
+ {"version":3,"file":"run.js","sourceRoot":"","sources":["../../src/run.ts"],"names":[],"mappings":";;;AAsLA,kBA4CC;AAmDD,kDAEC;AA4CD,4CAMC;AAGD,0CAMC;AAOD,gCAEC;AAoBD,kCAKC;AAGD,oCAEC;AAGD,sCAMC;AAlYD,uDAAqD;AACrD,0CAA6D;AAE7D,+BAAoE;AACpE,uCAA6C;AAE7C,iDAAqF;AA0DrF,uEAAuE;AACvE,yEAAyE;AACzE,yCAAyC;AACzC,MAAM,WAAW,G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AK,QAAQ,IAAI,OAAO,SAAS,CAAC,KAAK,KAAK,QAAQ,CAAC;AACtF,CAAC;AAED,qEAAqE;AACrE,SAAgB,YAAY,CAAC,QAAqB;IAChD,OAAO,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACpC,CAAC;AAED,2EAA2E;AAC3E,SAAgB,aAAa,CAAC,QAAqB,EAAE,OAAgB;IACnE,IAAI,CAAC;QACH,OAAO,IAAA,qBAAe,EAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;IAC5C,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,MAAM,UAAU,CAAC,GAAG,EAAE,YAAY,CAAC,QAAQ,CAAC,CAAC,CAAC;IAChD,CAAC;AACH,CAAC;AAED,KAAK,UAAU,eAAe,CAAC,EAAwB,EAAE,QAAqB;IAC5E,IAAI,MAAiB,CAAC;IACtB,IAAI,CAAC;QACH,MAAM,GAAG,MAAM,gBAAgB,CAAC,EAAE,CAAC,CAAC;IACtC,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,MAAM,UAAU,CAAC,GAAG,EAAE,YAAY,CAAC,QAAQ,CAAC,CAAC,CAAC;IAChD,CAAC;IACD,MAAM,EAAE,GAAG,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,aAAa,CAAC,QAAQ,EAAE,MAAM,CAAC,EAAE,CAAC,OAAO,IAAI,QAAQ,CAAC,CAAC;IACzF,OAAO,eAAe,CAAC,MAAM,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC;AACnD,CAAC","sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\nimport { SqlStackError, DatabaseError } from './core/errors';\nimport type { Dialect } from './registry';\nimport { SqlFragment, isSqlFragment, compileFragment } from './sql';\nimport { resolveExecution } from './runtime';\nimport type { SqlResolver } from './core/resolver';\nimport { getTransactionTarget, getTransactionTargetForHandle } from './transactions';\nimport type { ActiveTransaction } from './transactions';\n\n/**\n * Anything run(db, ...) can execute against: sqlstack's own `Database`\n * (from createSqliteDb/createPgDb/createMysqlDb), or any application handle\n * exposing `query(sql, params)`. `dialect` selects placeholder style and\n * defaults to `'sqlite'` when absent. run never opens databases by path.\n */\nexport interface RunDatabase {\n readonly dialect?: Dialect;\n query(sql: string, params: unknown[]): Promise<unknown>;\n}\n\n/**\n * Type-level guard for the params form of run: rejects the\n * `{ sql, params }` object returned by `fragment.toSQL()`. Pass the sql``\n * fragment itself instead, so run owns dialect binding and error handling.\n */\nexport type RejectCompiledSql<P> = P extends { readonly sql: string; readonly params: readonly unknown[] }\n ? never\n : unknown;\n\n/**\n * What a run(...) call made inside a @Query body asks of the wrapper's\n * pipeline. `default` is the zero-argument run().\n */\nexport type RunInvocation =\n | { readonly kind: 'default' }\n | { readonly kind: 'fragment'; readonly db?: RunDatabase | string; readonly fragment: SqlFragment }\n | { readonly kind: 'params'; readonly db?: RunDatabase | string; readonly params: object }\n | { readonly kind: 'db'; readonly db: RunDatabase | string };\n\n/**\n * Type-level guard for run(db) with a name: a string containing whitespace is\n * SQL text, never a database name. Build statements with the sql`` tag.\n */\nexport type RejectSqlText<D> = D extends string\n ? D extends `${string} ${string}` | `${string}\\n${string}` | `${string}\\t${string}`\n ? never\n : unknown\n : unknown;\n\n/**\n * Per-invocation context established by the @Query wrapper before the method\n * body executes. `execute` performs the full query pipeline (resolve SQL,\n * bind, execute, shape/transform/validate); `ran` records that the body\n * invoked run(), so the wrapper returns the body's result verbatim instead\n * of falling through to the legacy pipeline. `invocations` marks a wrapper\n * that understands the argument-taking run forms (an older duplicated copy\n * of the decorator would silently ignore them).\n */\nexport type RunContext = {\n execute: (invocation?: RunInvocation) => Promise<unknown>;\n ran: boolean;\n invocations?: true;\n};\n\n// Anchored on globalThis via Symbol.for so duplicated module instances\n// (npm link, dual ESM/CJS loads) share one channel between the decorator\n// and the run() the application imports.\nconst RUN_CHANNEL = Symbol.for('noego.sqlstack.runContext');\nconst anchor = globalThis as Record<PropertyKey, unknown>;\nif (!anchor[RUN_CHANNEL]) {\n anchor[RUN_CHANNEL] = new AsyncLocalStorage<RunContext>();\n}\nexport const runStorage = anchor[RUN_CHANNEL] as AsyncLocalStorage<RunContext>;\n\n/**\n * Execute the current @Query method's SQL and return the finished result.\n * Call it as the body of a @Query-decorated method:\n *\n * @Query()\n * async getUsers(active: boolean): Promise<User[]> {\n * return run();\n * }\n *\n * Takes no arguments — the method's own arguments, database, SQL source,\n * transaction, shaping, transform, and validation all come from the\n * decorator context — except that a leading method argument that is a\n * database handle (or a registered database name) selects the database and\n * is not bound. T is inferred from the method's declared return type.\n *\n * @throws {DatabaseError} When the driver rejects the statement (original\n * error in `.cause`).\n * @throws {SqlStackError} When called outside a @Query method, or for\n * shape/validation failures (ExactlyOneRowError, NoRowsError, ValidationError, ...).\n */\nexport function run<T = any>(): Promise<T>;\n/**\n * Inside a @Query method: execute this inline sql`` fragment instead of the\n * method's SQL file. The database comes from the method/class/registry\n * context (`@Query({ db })`, `@QueryBinder({ db })`, the default), the\n * active transaction on it is joined, and the method's shape/transform/\n * validation decorators apply. The method's arguments are not auto-bound —\n * the fragment's `${}` values are the parameters.\n *\n * @Single @Query()\n * async byEmail(email: string): Promise<User | null> {\n * return run(sql`SELECT * FROM users WHERE email = ${email}`);\n * }\n *\n * @throws {DatabaseError} When the fragment cannot be compiled (macro input\n * errors), the database cannot be resolved, or the driver rejects the\n * statement. The original error is in `.cause`.\n * @throws {SqlStackError} When called outside a @Query method (use\n * `run(db, query)` there), or for shape/validation failures.\n */\nexport function run<T = unknown>(query: SqlFragment): Promise<T>;\n/**\n * Execute an sql`` fragment against an explicit database: a handle\n * (anything with `query(sql, params)`) or the name of a database registered\n * with the active SqlStack / legacy registry. Usable anywhere.\n *\n * Binds for the database's dialect (`$1..` for Postgres, `?` otherwise;\n * default sqlite). Joins an active transaction opened on the same database\n * (same registered handle, or same name). Outside a @Query method the raw\n * result is returned (rows array, or `{ rowsAffected }` for writes); inside\n * one, the method's shape/transform/validation decorators apply.\n *\n * const rows = await run<Row[]>(accountsDb, sql`SELECT * FROM t WHERE id = ${id}`);\n *\n * @throws {DatabaseError} When the fragment cannot be compiled, a named\n * database cannot be resolved, or the driver rejects the statement. The\n * original error is in `.cause`, and its string `code` is copied to `.code`.\n * @throws {SqlStackError} For invalid arguments, or shape/validation failures.\n */\nexport function run<T = unknown>(db: RunDatabase | string, query: SqlFragment): Promise<T>;\n/**\n * Inside a @Query method: run the method's own SQL (its .sql file or inline\n * `@Query({ sql })`) against `db`, binding `params` (an object for `:named`\n * placeholders, an array for `:arg1..`). The method's raw arguments are NOT\n * auto-bound in this form — `params` is the whole binding input. @Defaults,\n * @Page, shaping, transform, and validation still apply.\n *\n * @Single @Query()\n * async byEmail(db: Database, p: { email: string }): Promise<User | null> {\n * return run(db, p);\n * }\n *\n * @throws {DatabaseError} When binding fails, a named database cannot be\n * resolved, or the driver rejects the statement. The original error is in\n * `.cause`.\n * @throws {SqlStackError} When called outside a @Query method, when passed\n * `.toSQL()` output, or for shape/validation failures.\n */\nexport function run<T = unknown, P extends object = object>(\n db: RunDatabase | string,\n params: P & RejectCompiledSql<P>\n): Promise<T>;\n/**\n * Inside a @Query method: run the method's own SQL against `db` (a handle or\n * a registered database name), binding the method's own arguments exactly as\n * run() does — except that a leading database handle/name argument of the\n * method is never bound.\n *\n * @throws {DatabaseError} When binding fails, a named database cannot be\n * resolved, or the driver rejects the statement.\n * @throws {SqlStackError} When called outside a @Query method, or for\n * shape/validation failures.\n */\nexport function run<T = unknown, D extends RunDatabase | string = RunDatabase | string>(\n db: D & RejectSqlText<D>\n): Promise<T>;\n/**\n * Inside a @Query method: run the method's own SQL binding only `params` (an\n * object for `:named`, an array for `:argN`) against the database run() would\n * use: the method's leading database handle/name argument, else the\n * decorator context.\n *\n * @throws {DatabaseError} When binding fails, the database cannot be\n * resolved, or the driver rejects the statement.\n * @throws {SqlStackError} When called outside a @Query method, when passed\n * `.toSQL()` output, or for shape/validation failures.\n */\nexport function run<T = unknown, P extends object = object>(params: P & RejectCompiledSql<P>): Promise<T>;\nexport async function run(...args: unknown[]): Promise<unknown> {\n const invocation = parseRunArgs(args);\n const ctx = runStorage.getStore();\n\n if (!ctx) {\n if (invocation.kind === 'fragment' && invocation.db !== undefined) {\n return executeFragment(invocation.db, invocation.fragment);\n }\n if (invocation.kind === 'default') {\n throw new SqlStackError(\n 'run() called outside a @Query method. It may only be invoked from the body of a @Query-decorated method.'\n );\n }\n if (invocation.kind === 'fragment') {\n throw new SqlStackError(\n 'run(query) called outside a @Query method has no database. Pass one explicitly: run(db, query).'\n );\n }\n if (invocation.kind === 'db') {\n throw new SqlStackError(\n 'run(db) called outside a @Query method has no SQL source. Pass an sql`` fragment instead: run(db, sql`...`).'\n );\n }\n if (invocation.db === undefined) {\n throw new SqlStackError(\n 'run(params) called outside a @Query method has no SQL source or database. ' +\n 'Pass a database and an sql`` fragment instead: run(db, sql`...`).'\n );\n }\n throw new SqlStackError(\n 'run(db, params) called outside a @Query method has no SQL source. ' +\n 'Pass an sql`` fragment instead: run(db, sql`...`).'\n );\n }\n\n if (invocation.kind !== 'default' && !ctx.invocations) {\n throw new SqlStackError(\n 'run(...) with arguments reached a @Query wrapper from an older sqlstack copy that cannot honour them. ' +\n 'Make sure a single sqlstack version is installed.'\n );\n }\n\n ctx.ran = true;\n return invocation.kind === 'default' ? ctx.execute() : ctx.execute(invocation);\n}\n\nfunction parseRunArgs(args: unknown[]): RunInvocation {\n if (args.length === 0) return { kind: 'default' };\n\n if (args.length === 1) {\n const [query] = args;\n if (isSqlFragment(query)) return { kind: 'fragment', fragment: query };\n if (typeof query === 'string') {\n // A whitespace-free string is a database name: run(db).\n if (isDatabaseNameText(query)) return { kind: 'db', db: query };\n throw new SqlStackError(\n 'run(query) does not accept SQL strings. Build the statement with the sql`` tag: run(sql`...`).'\n );\n }\n if (isRunDatabaseHandle(query)) return { kind: 'db', db: query };\n if (isCompiledSql(query)) {\n throw new SqlStackError(\n 'run(...) received the { sql, params } output of .toSQL(). Pass the sql`` fragment itself so run can ' +\n 'bind it for the target dialect: run(sql`...`).'\n );\n }\n if (typeof query === 'object' && query !== null) return { kind: 'params', params: query };\n throw new SqlStackError(\n 'run(x) requires an sql`` fragment, a params object/array, or a database handle/name.'\n );\n }\n\n if (args.length === 2) {\n const [db, second] = args;\n assertRunDatabase(db);\n if (isSqlFragment(second)) return { kind: 'fragment', db, fragment: second };\n if (typeof second === 'string') {\n throw new SqlStackError(\n 'run(db, query) does not accept SQL strings. Build the statement with the sql`` tag: run(db, sql`...`).'\n );\n }\n if (isCompiledSql(second)) {\n throw new SqlStackError(\n 'run(db, ...) received the { sql, params } output of .toSQL(). Pass the sql`` fragment itself so run can ' +\n 'bind it for the target dialect: run(db, sql`...`).'\n );\n }\n if (typeof second === 'object' && second !== null) return { kind: 'params', db, params: second };\n throw new SqlStackError('run(db, x) requires an sql`` fragment or a params object/array as its second argument.');\n }\n\n throw new SqlStackError(`run() accepts at most 2 arguments, got ${args.length}.`);\n}\n\n/** @internal A database handle: any object exposing query(sql, params). */\nexport function isRunDatabaseHandle(value: unknown): value is RunDatabase {\n return typeof value === 'object' && value !== null && typeof (value as { query?: unknown }).query === 'function';\n}\n\nfunction isDatabaseNameText(value: string): boolean {\n return value.length > 0 && !/\\s/.test(value);\n}\n\nfunction assertRunDatabase(db: unknown): asserts db is RunDatabase | string {\n if (typeof db === 'string' && db.length > 0) return;\n if (typeof db === 'object' && db !== null && typeof (db as { query?: unknown }).query === 'function') return;\n throw new SqlStackError(\n 'run(db, ...) requires a database handle with query(sql, params) or a registered database name as its first argument.'\n );\n}\n\nfunction isCompiledSql(value: unknown): boolean {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;\n const keys = Object.keys(value);\n const rec = value as { sql?: unknown; params?: unknown };\n return keys.length === 2 && typeof rec.sql === 'string' && Array.isArray(rec.params);\n}\n\n// ---------------------------------------------------------------------------\n// Shared execution helpers (also used by the @Query wrapper)\n// ---------------------------------------------------------------------------\n\n/** @internal A database chosen for one run, plus the transaction it joins. */\nexport type RunTarget = {\n readonly db: RunDatabase;\n readonly tx: ActiveTransaction | undefined;\n /** SQL resolver of the environment, when the target was resolved by name. */\n readonly resolver: SqlResolver | undefined;\n readonly byName: boolean;\n};\n\n/**\n * @internal Resolve run's database argument. A name goes through the active\n * SqlStack (or legacy registry) and joins that entry's transaction — or,\n * inside a @transaction scope with none open, opens one on first execution. A handle\n * is used as-is — no registry lookup, so it works without any SqlStack — and\n * behaves the same: it joins a transaction open in this flow on that same\n * object, or, inside a @transaction scope with none open, opens one on the\n * handle on first execution. Outside any scope a handle with no open\n * transaction runs directly.\n */\nexport async function resolveRunTarget(db: RunDatabase | string): Promise<RunTarget> {\n if (typeof db === 'string') {\n const { entry, resolver } = await resolveExecution(db);\n return { db: entry.db, tx: getTransactionTarget(entry), resolver, byName: true };\n }\n return { db, tx: getTransactionTargetForHandle(db), resolver: undefined, byName: false };\n}\n\n/** @internal Run one bound statement on the target (inside its transaction, if any). */\nexport async function executeOnTarget(target: RunTarget, boundSql: string, params: unknown[]): Promise<unknown> {\n try {\n return target.tx ? await target.tx.query(boundSql, params) : await target.db.query(boundSql, params);\n } catch (dbError) {\n throw toDatabaseError(dbError, boundSql);\n }\n}\n\n/**\n * @internal Normalize a failure from run's argument-taking forms: errors that\n * are already SqlStackError (DatabaseError, shape/validation errors) pass\n * through; anything else becomes DatabaseError with the original in `.cause`.\n */\nexport function toRunError(err: unknown, sqlText: string): SqlStackError {\n return err instanceof SqlStackError ? err : toDatabaseError(err, sqlText);\n}\n\nfunction toDatabaseError(err: unknown, sqlText: string): DatabaseError {\n const message = (err as { message?: unknown } | undefined)?.message;\n return new DatabaseError(\n typeof message === 'string' && message ? message : String(err),\n sqlText,\n isErrorLike(err) ? err : undefined\n );\n}\n\n/**\n * better-sqlite3 binds its SqliteError class once per process. When several\n * realms share that process (vm contexts, e.g. jest --runInBand, which is\n * jest's default on a single CPU), driver errors are Error subclasses of the\n * first realm only: `instanceof Error` is false elsewhere and they carry no\n * [[ErrorData]] slot. Recognise them by shape so `.cause`/`.code` survive.\n *\n * @internal Shared with decorators/query.ts.\n */\nexport function isErrorLike(err: unknown): err is Error {\n if (err instanceof Error) return true;\n if (typeof err !== 'object' || err === null) return false;\n const candidate = err as { message?: unknown; stack?: unknown };\n return typeof candidate.message === 'string' && typeof candidate.stack === 'string';\n}\n\n/** @internal Raw template text of a fragment, for error messages. */\nexport function fragmentText(fragment: SqlFragment): string {\n return fragment.strings.join('?');\n}\n\n/** @internal Compile a fragment for the dialect, wrapping macro errors. */\nexport function compileForRun(fragment: SqlFragment, dialect: Dialect): { sql: string; params: unknown[] } {\n try {\n return compileFragment(fragment, dialect);\n } catch (err) {\n throw toRunError(err, fragmentText(fragment));\n }\n}\n\nasync function executeFragment(db: RunDatabase | string, fragment: SqlFragment): Promise<unknown> {\n let target: RunTarget;\n try {\n target = await resolveRunTarget(db);\n } catch (err) {\n throw toRunError(err, fragmentText(fragment));\n }\n const { sql: boundSql, params } = compileForRun(fragment, target.db.dialect ?? 'sqlite');\n return executeOnTarget(target, boundSql, params);\n}\n"]}
@@ -54,12 +54,14 @@ export function coerceRootPath(input) {
54
54
  }
55
55
  export function guessDecoratorDir() {
56
56
  const err = new Error();
57
- const stack = (err.stack || '').split('\n').slice(2);
58
- const packageRoot = PACKAGE_ROOT_NORMALIZED;
59
- const codeRoot = SQLSTACK_CODE_ROOT;
60
- // DEBUG: Uncomment to trace issues
61
- // console.log('[guessDecoratorDir] packageRoot:', packageRoot);
62
- // console.log('[guessDecoratorDir] stack:', stack.slice(0, 5));
57
+ return decoratorDirFromStack((err.stack || '').split('\n').slice(2));
58
+ }
59
+ /**
60
+ * The directory of the first consumer frame in `stack` (stack lines below
61
+ * the Error header): the module that applied the decorator.
62
+ * @internal Exported for testing
63
+ */
64
+ export function decoratorDirFromStack(stack, packageRoot = PACKAGE_ROOT_NORMALIZED, codeRoot = SQLSTACK_CODE_ROOT) {
63
65
  for (const line of stack) {
64
66
  const m = line.match(/\((.*?):\d+:\d+\)/) || line.match(/at (.*?):\d+:\d+/);
65
67
  const file = m?.[1];
@@ -100,8 +102,11 @@ function toAbsolutePath(file) {
100
102
  if (file.startsWith('file://')) {
101
103
  return fileURLToPath(file);
102
104
  }
103
- // Skip Node.js internal modules and bundler internals
104
- if (file.startsWith('node:') || file.startsWith('webpack://')) {
105
+ // Skip Node.js internal modules and bundler internals. A NUL byte marks a
106
+ // Rollup/Vite virtual module (e.g. Vitest's oxc decorator helper, reported
107
+ // as `<cwd>/\0@oxc-project+runtime@x/helpers/esm/decorate.js`); it is never
108
+ // the decorating module and must not be mistaken for one.
109
+ if (file.includes('\0') || file.startsWith('node:') || file.startsWith('webpack://')) {
105
110
  return undefined;
106
111
  }
107
112
  if (!path.isAbsolute(file)) {
@@ -1 +1 @@
1
- {"version":3,"file":"fileResolution.js","sourceRoot":"","sources":["../../../src/core/fileResolution.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AAGpC,MAAM,WAAW,GAA4B;IAC3C,QAAQ,EAAE,IAAI;IACd,KAAK,EAAE,OAAO;IACd,MAAM,EAAE,QAAQ;CACjB,CAAC;AAEF,MAAM,YAAY,GAAG,IAAI,GAAG,EAAkB,CAAC;AAC/C,MAAM,SAAS,GAAG,IAAI,GAAG,EAAkB,CAAC;AAE5C,SAAS,GAAG,CAAC,IAAY,EAAE,MAAc,EAAE,OAAgB;IACzD,OAAO,GAAG,IAAI,KAAK,MAAM,KAAK,OAAO,EAAE,CAAC;AAC1C,CAAC;AAED,MAAM,UAAU,gBAAgB,CAAC,OAAe,EAAE,UAAkB,EAAE,OAAgB;IACpF,MAAM,CAAC,GAAG,GAAG,CAAC,OAAO,EAAE,UAAU,EAAE,OAAO,CAAC,CAAC;IAC5C,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,MAAM,GAA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C,CAAC;IAClD,IAAI,CAAC,OAAO;QAAE,OAAO,SAAS,CAAC;IAC/B,MAAM,IAAI,GAAG,aAAa,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC;IAClD,OAAO,IAAI,CAAC,CAAC,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;AACpD,CAAC;AAED,MAAM,kBAAkB,GAAG,eAAe,CAAC,GAAG,EAAE,CAAC,IAAI,KAAK,EAAE,CAAC,KAAK,IAAI,EAAE,CAAC,CAAC","sourcesContent":["import fs from 'fs';\nimport path from 'path';\nimport { fileURLToPath } from 'url';\nimport type { Dialect } from '../registry';\n\nconst DIALECT_EXT: Record<Dialect, string> = {\n postgres: 'pg',\n mysql: 'mysql',\n sqlite: 'sqlite',\n};\n\nconst contentCache = new Map<string, string>();\nconst pathCache = new Map<string, string>();\n\nfunction key(root: string, method: string, dialect: Dialect): string {\n return `${root}::${method}::${dialect}`;\n}\n\nexport function resolveSqlFromFs(rootDir: string, methodName: string, dialect: Dialect): { sql: string; tried: string[] } {\n const k = key(rootDir, methodName, dialect);\n const tried: string[] = [];\n const ext = DIALECT_EXT[dialect];\n const dialectPath = path.join(rootDir, `${methodName}.${ext}.sql`);\n const genericPath = path.join(rootDir, `${methodName}.sql`);\n\n // Cached path\n let chosen = pathCache.get(k);\n if (!chosen) {\n if (fs.existsSync(dialectPath)) {\n chosen = dialectPath;\n } else if (fs.existsSync(genericPath)) {\n chosen = genericPath;\n }\n if (chosen) pathCache.set(k, chosen);\n }\n\n if (!chosen) {\n tried.push(dialectPath, genericPath);\n throw new Error(\n `sqlstack: SQL file not found for ${methodName}\\ntried: ${tried.join(\"\\n\")}`\n );\n }\n\n // Cached content\n let sql = contentCache.get(chosen);\n if (!sql) {\n sql = fs.readFileSync(chosen, 'utf8');\n contentCache.set(chosen, sql);\n }\n return { sql, tried: [chosen] };\n}\n\nexport function coerceRootPath(input?: string): { rootDir?: string; from?: 'file' | 'folder' } {\n if (!input) return {};\n const stat = fs.existsSync(input) ? fs.statSync(input) : undefined;\n if (stat?.isDirectory()) return { rootDir: input, from: 'folder' };\n if (stat?.isFile()) return { rootDir: path.dirname(input), from: 'file' };\n // If not found, treat as folder hint anyway\n return { rootDir: input, from: 'folder' };\n}\n\nexport function guessDecoratorDir(): string | undefined {\n const err = new Error();\n const stack = (err.stack || '').split('\\n').slice(2);\n const packageRoot = PACKAGE_ROOT_NORMALIZED;\n const codeRoot = SQLSTACK_CODE_ROOT;\n\n // DEBUG: Uncomment to trace issues\n // console.log('[guessDecoratorDir] packageRoot:', packageRoot);\n // console.log('[guessDecoratorDir] stack:', stack.slice(0, 5));\n\n for (const line of stack) {\n const m = line.match(/\\((.*?):\\d+:\\d+\\)/) || line.match(/at (.*?):\\d+:\\d+/);\n const file = m?.[1];\n if (!file) continue;\n\n const resolved = toAbsolutePath(file);\n if (!resolved) continue;\n\n const normalized = safeNormalize(resolved);\n if (!normalized) continue;\n\n // Skip every node_modules frame (sqlstack as a dependency, decorator\n // helpers such as reflect-metadata, test runners) and sqlstack's own\n // src/ and dist/ under its package root (running from source or a linked\n // checkout). A consumer module under a node_modules-free path that merely\n // contains the word \"sqlstack\" — this package's own tests/fixtures — is\n // a consumer and is NOT skipped.\n if (normalized.includes(path.sep + 'node_modules' + path.sep)) continue;\n if (packageRoot && isSqlstackCodePath(normalized, packageRoot)) continue;\n // Filesystem-free: sqlstack's own code root (the directory holding\n // core/, decorators/, …) as the STACK names it — the only reliable\n // reference on hosts without fs (workerd) or with re-rooted trees.\n if (codeRoot && normalized.startsWith(codeRoot)) continue;\n\n // Return the first consumer frame - this is where @Query is applied\n return path.dirname(resolved);\n }\n return undefined;\n}\n\nfunction isSqlstackCodePath(normalized: string, packageRoot: string): boolean {\n const root = process.platform === 'win32' ? packageRoot.toLowerCase() : packageRoot;\n return normalized.startsWith(root + 'src' + path.sep) || normalized.startsWith(root + 'dist' + path.sep);\n}\n\nfunction toAbsolutePath(file: string): string | undefined {\n try {\n if (file.startsWith('file://')) {\n return fileURLToPath(file);\n }\n // Skip Node.js internal modules and bundler internals\n if (file.startsWith('node:') || file.startsWith('webpack://')) {\n return undefined;\n }\n if (!path.isAbsolute(file)) {\n return path.resolve(file);\n }\n return file;\n } catch {\n return undefined;\n }\n}\n\nfunction ensureTrailingSep(p: string): string {\n return p.endsWith(path.sep) ? p : p + path.sep;\n}\n\nfunction safeNormalize(p?: string): string | undefined {\n if (!p) return undefined;\n const normalized = path.normalize(p);\n return process.platform === 'win32' ? normalized.toLowerCase() : normalized;\n}\n\n/**\n * Finds the package root from a starting directory by walking up to find package.json.\n * @internal Exported for testing\n */\nexport function findPackageRoot(startDir: string): string | undefined {\n // The ESM build ships a nested dist/esm/package.json ({ type: module });\n // keep walking past any package.json that is not sqlstack's own so the\n // root is the real package directory (whose src/ and dist/ are skipped by\n // guessDecoratorDir). The first package.json found is the fallback.\n let current = startDir;\n let fallback: string | undefined;\n for (let i = 0; i < 8; i++) {\n const candidate = path.join(current, 'package.json');\n if (fs.existsSync(candidate)) {\n const root = path.dirname(candidate);\n const normalizedRoot = safeNormalize(root);\n const asRoot = normalizedRoot ? ensureTrailingSep(normalizedRoot) : ensureTrailingSep(root);\n if (packageNameOf(candidate) === 'sqlstack') return asRoot;\n fallback ??= asRoot;\n }\n const parent = path.dirname(current);\n if (parent === current) break;\n current = parent;\n }\n return fallback;\n}\n\nfunction packageNameOf(packageJsonPath: string): string | undefined {\n try {\n return JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'))?.name;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Detects if a path belongs to sqlstack package.\n * Handles both source paths (contains 'sqlstack') and node_modules paths.\n * @internal Exported for testing\n */\nexport function isSqlstackPath(filePath: string): boolean {\n const normalized = filePath.toLowerCase();\n // Check for source development path (e.g., /path/to/sqlstack/src/...)\n if (normalized.includes(path.sep + 'sqlstack' + path.sep)) return true;\n // Check for node_modules installation\n if (normalized.includes('node_modules' + path.sep + 'sqlstack' + path.sep)) return true;\n // Check for scoped package (@noego/sqlstack or similar)\n if (normalized.includes('node_modules' + path.sep + '@') && normalized.includes('sqlstack' + path.sep)) return true;\n return false;\n}\n\n/**\n * Extracts sqlstack's location from a stack trace.\n * Handles absolute paths, file:// URLs, and relative paths (Vitest uses relative paths).\n * @internal Exported for testing\n */\nexport function findSqlstackFromStack(stackString: string): string | undefined {\n const lines = stackString.split('\\n');\n for (const line of lines) {\n const m = line.match(/\\((.*?):\\d+:\\d+\\)/) || line.match(/at (.*?):\\d+:\\d+/);\n const file = m?.[1];\n if (!file) continue;\n try {\n let resolved: string | undefined;\n if (file.startsWith('file://')) {\n resolved = fileURLToPath(file);\n } else if (path.isAbsolute(file)) {\n resolved = file;\n } else if (!file.startsWith('node:') && !file.startsWith('webpack://')) {\n // Relative path - resolve it (Vitest uses relative paths in stack traces)\n resolved = path.resolve(file);\n }\n if (resolved && resolved.includes('fileResolution')) {\n return path.dirname(resolved);\n }\n } catch {\n // Skip invalid paths\n }\n }\n return undefined;\n}\n\n/**\n * Computes the sqlstack package root directory.\n * Handles both CJS (__dirname) and ESM (stack trace) detection.\n * Validates that __dirname actually points to sqlstack (guards against Vitest injection).\n * @internal Exported for testing\n */\nexport function computePackageRoot(\n dirnameValue: string | undefined,\n filenameValue: string | undefined,\n getStack: () => string\n): string | undefined {\n const candidates: string[] = [];\n\n // CJS: use __dirname/__filename, but validate they actually point to sqlstack\n // (Vitest can inject __dirname incorrectly when transforming CJS modules)\n if (typeof dirnameValue === 'string' && isSqlstackPath(dirnameValue)) {\n candidates.push(dirnameValue);\n }\n if (typeof filenameValue === 'string' && isSqlstackPath(filenameValue)) {\n candidates.push(path.dirname(filenameValue));\n }\n\n // ESM fallback or when __dirname was incorrectly injected: parse stack trace\n if (candidates.length === 0) {\n const stackDir = findSqlstackFromStack(getStack());\n if (stackDir) {\n candidates.push(stackDir);\n }\n }\n\n // Find the package root from the first valid candidate\n for (const base of candidates) {\n const root = findPackageRoot(base);\n if (root) return root;\n }\n return undefined;\n}\n\nconst PACKAGE_ROOT_NORMALIZED = computePackageRoot(\n typeof __dirname === 'string' ? __dirname : undefined,\n typeof __filename === 'string' ? __filename : undefined,\n () => new Error().stack || ''\n);\n\n/**\n * sqlstack's code root as the runtime names this module in stack traces:\n * the parent of this file's directory (`src/`, `dist/cjs/`, `dist/esm/`, or\n * a bundler's re-rooted copy). Needs no filesystem.\n * @internal Exported for testing\n */\nexport function computeCodeRoot(getStack: () => string): string | undefined {\n const coreDir = findSqlstackFromStack(getStack());\n if (!coreDir) return undefined;\n const root = safeNormalize(path.dirname(coreDir));\n return root ? ensureTrailingSep(root) : undefined;\n}\n\nconst SQLSTACK_CODE_ROOT = computeCodeRoot(() => new Error().stack || '');\n"]}
1
+ {"version":3,"file":"fileResolution.js","sourceRoot":"","sources":["../../../src/core/fileResolution.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AAGpC,MAAM,WAAW,GAA4B;IAC3C,QAAQ,EAAE,IAAI;IACd,KAAK,EAAE,OAAO;IACd,MAAM,EAAE,QAAQ;CACjB,CAAC;AAEF,MAAM,YAAY,GAAG,IAAI,GAAG,EAAkB,CAAC;AAC/C,MAAM,SAAS,GAAG,IAAI,GAAG,EAAkB,CAAC;AAE5C,SAAS,GAAG,CAAC,IAAY,EAAE,MAAc,EAAE,OAAgB;IACzD,OAAO,GAAG,IAAI,KAAK,MAAM,KAAK,OAAO,EAAE,CAAC;AAC1C,CAAC;AAED,MAAM,UAAU,gBAAgB,CAAC,OAAe,EAAE,UAAkB,EAAE,OAAgB;IACpF,MAAM,CAAC,GAAG,GAAG,CAAC,OAAO,EAAE,UAAU,EAAE,OAAO,CAAC,CAAC;IAC5C,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,MAAM,GAAG,GAAG,WAAW,CAAC,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AsB;IACpD,MAAM,OAAO,GAAG,qBAAqB,CAAC,QAAQ,EAAE,CAAC,CAAC;IAClD,IAAI,CAAC,OAAO;QAAE,OAAO,SAAS,CAAC;IAC/B,MAAM,IAAI,GAAG,aAAa,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC;IAClD,OAAO,IAAI,CAAC,CAAC,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;AACpD,CAAC;AAED,MAAM,kBAAkB,GAAG,eAAe,CAAC,GAAG,EAAE,CAAC,IAAI,KAAK,EAAE,CAAC,KAAK,IAAI,EAAE,CAAC,CAAC","sourcesContent":["import fs from 'fs';\nimport path from 'path';\nimport { fileURLToPath } from 'url';\nimport type { Dialect } from '../registry';\n\nconst DIALECT_EXT: Record<Dialect, string> = {\n postgres: 'pg',\n mysql: 'mysql',\n sqlite: 'sqlite',\n};\n\nconst contentCache = new Map<string, string>();\nconst pathCache = new Map<string, string>();\n\nfunction key(root: string, method: string, dialect: Dialect): string {\n return `${root}::${method}::${dialect}`;\n}\n\nexport function resolveSqlFromFs(rootDir: string, methodName: string, dialect: Dialect): { sql: string; tried: string[] } {\n const k = key(rootDir, methodName, dialect);\n const tried: string[] = [];\n const ext = DIALECT_EXT[dialect];\n const dialectPath = path.join(rootDir, `${methodName}.${ext}.sql`);\n const genericPath = path.join(rootDir, `${methodName}.sql`);\n\n // Cached path\n let chosen = pathCache.get(k);\n if (!chosen) {\n if (fs.existsSync(dialectPath)) {\n chosen = dialectPath;\n } else if (fs.existsSync(genericPath)) {\n chosen = genericPath;\n }\n if (chosen) pathCache.set(k, chosen);\n }\n\n if (!chosen) {\n tried.push(dialectPath, genericPath);\n throw new Error(\n `sqlstack: SQL file not found for ${methodName}\\ntried: ${tried.join(\"\\n\")}`\n );\n }\n\n // Cached content\n let sql = contentCache.get(chosen);\n if (!sql) {\n sql = fs.readFileSync(chosen, 'utf8');\n contentCache.set(chosen, sql);\n }\n return { sql, tried: [chosen] };\n}\n\nexport function coerceRootPath(input?: string): { rootDir?: string; from?: 'file' | 'folder' } {\n if (!input) return {};\n const stat = fs.existsSync(input) ? fs.statSync(input) : undefined;\n if (stat?.isDirectory()) return { rootDir: input, from: 'folder' };\n if (stat?.isFile()) return { rootDir: path.dirname(input), from: 'file' };\n // If not found, treat as folder hint anyway\n return { rootDir: input, from: 'folder' };\n}\n\nexport function guessDecoratorDir(): string | undefined {\n const err = new Error();\n return decoratorDirFromStack((err.stack || '').split('\\n').slice(2));\n}\n\n/**\n * The directory of the first consumer frame in `stack` (stack lines below\n * the Error header): the module that applied the decorator.\n * @internal Exported for testing\n */\nexport function decoratorDirFromStack(\n stack: string[],\n packageRoot: string | undefined = PACKAGE_ROOT_NORMALIZED,\n codeRoot: string | undefined = SQLSTACK_CODE_ROOT\n): string | undefined {\n for (const line of stack) {\n const m = line.match(/\\((.*?):\\d+:\\d+\\)/) || line.match(/at (.*?):\\d+:\\d+/);\n const file = m?.[1];\n if (!file) continue;\n\n const resolved = toAbsolutePath(file);\n if (!resolved) continue;\n\n const normalized = safeNormalize(resolved);\n if (!normalized) continue;\n\n // Skip every node_modules frame (sqlstack as a dependency, decorator\n // helpers such as reflect-metadata, test runners) and sqlstack's own\n // src/ and dist/ under its package root (running from source or a linked\n // checkout). A consumer module under a node_modules-free path that merely\n // contains the word \"sqlstack\" — this package's own tests/fixtures — is\n // a consumer and is NOT skipped.\n if (normalized.includes(path.sep + 'node_modules' + path.sep)) continue;\n if (packageRoot && isSqlstackCodePath(normalized, packageRoot)) continue;\n // Filesystem-free: sqlstack's own code root (the directory holding\n // core/, decorators/, …) as the STACK names it — the only reliable\n // reference on hosts without fs (workerd) or with re-rooted trees.\n if (codeRoot && normalized.startsWith(codeRoot)) continue;\n\n // Return the first consumer frame - this is where @Query is applied\n return path.dirname(resolved);\n }\n return undefined;\n}\n\nfunction isSqlstackCodePath(normalized: string, packageRoot: string): boolean {\n const root = process.platform === 'win32' ? packageRoot.toLowerCase() : packageRoot;\n return normalized.startsWith(root + 'src' + path.sep) || normalized.startsWith(root + 'dist' + path.sep);\n}\n\nfunction toAbsolutePath(file: string): string | undefined {\n try {\n if (file.startsWith('file://')) {\n return fileURLToPath(file);\n }\n // Skip Node.js internal modules and bundler internals. A NUL byte marks a\n // Rollup/Vite virtual module (e.g. Vitest's oxc decorator helper, reported\n // as `<cwd>/\\0@oxc-project+runtime@x/helpers/esm/decorate.js`); it is never\n // the decorating module and must not be mistaken for one.\n if (file.includes('\\0') || file.startsWith('node:') || file.startsWith('webpack://')) {\n return undefined;\n }\n if (!path.isAbsolute(file)) {\n return path.resolve(file);\n }\n return file;\n } catch {\n return undefined;\n }\n}\n\nfunction ensureTrailingSep(p: string): string {\n return p.endsWith(path.sep) ? p : p + path.sep;\n}\n\nfunction safeNormalize(p?: string): string | undefined {\n if (!p) return undefined;\n const normalized = path.normalize(p);\n return process.platform === 'win32' ? normalized.toLowerCase() : normalized;\n}\n\n/**\n * Finds the package root from a starting directory by walking up to find package.json.\n * @internal Exported for testing\n */\nexport function findPackageRoot(startDir: string): string | undefined {\n // The ESM build ships a nested dist/esm/package.json ({ type: module });\n // keep walking past any package.json that is not sqlstack's own so the\n // root is the real package directory (whose src/ and dist/ are skipped by\n // guessDecoratorDir). The first package.json found is the fallback.\n let current = startDir;\n let fallback: string | undefined;\n for (let i = 0; i < 8; i++) {\n const candidate = path.join(current, 'package.json');\n if (fs.existsSync(candidate)) {\n const root = path.dirname(candidate);\n const normalizedRoot = safeNormalize(root);\n const asRoot = normalizedRoot ? ensureTrailingSep(normalizedRoot) : ensureTrailingSep(root);\n if (packageNameOf(candidate) === 'sqlstack') return asRoot;\n fallback ??= asRoot;\n }\n const parent = path.dirname(current);\n if (parent === current) break;\n current = parent;\n }\n return fallback;\n}\n\nfunction packageNameOf(packageJsonPath: string): string | undefined {\n try {\n return JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'))?.name;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Detects if a path belongs to sqlstack package.\n * Handles both source paths (contains 'sqlstack') and node_modules paths.\n * @internal Exported for testing\n */\nexport function isSqlstackPath(filePath: string): boolean {\n const normalized = filePath.toLowerCase();\n // Check for source development path (e.g., /path/to/sqlstack/src/...)\n if (normalized.includes(path.sep + 'sqlstack' + path.sep)) return true;\n // Check for node_modules installation\n if (normalized.includes('node_modules' + path.sep + 'sqlstack' + path.sep)) return true;\n // Check for scoped package (@noego/sqlstack or similar)\n if (normalized.includes('node_modules' + path.sep + '@') && normalized.includes('sqlstack' + path.sep)) return true;\n return false;\n}\n\n/**\n * Extracts sqlstack's location from a stack trace.\n * Handles absolute paths, file:// URLs, and relative paths (Vitest uses relative paths).\n * @internal Exported for testing\n */\nexport function findSqlstackFromStack(stackString: string): string | undefined {\n const lines = stackString.split('\\n');\n for (const line of lines) {\n const m = line.match(/\\((.*?):\\d+:\\d+\\)/) || line.match(/at (.*?):\\d+:\\d+/);\n const file = m?.[1];\n if (!file) continue;\n try {\n let resolved: string | undefined;\n if (file.startsWith('file://')) {\n resolved = fileURLToPath(file);\n } else if (path.isAbsolute(file)) {\n resolved = file;\n } else if (!file.startsWith('node:') && !file.startsWith('webpack://')) {\n // Relative path - resolve it (Vitest uses relative paths in stack traces)\n resolved = path.resolve(file);\n }\n if (resolved && resolved.includes('fileResolution')) {\n return path.dirname(resolved);\n }\n } catch {\n // Skip invalid paths\n }\n }\n return undefined;\n}\n\n/**\n * Computes the sqlstack package root directory.\n * Handles both CJS (__dirname) and ESM (stack trace) detection.\n * Validates that __dirname actually points to sqlstack (guards against Vitest injection).\n * @internal Exported for testing\n */\nexport function computePackageRoot(\n dirnameValue: string | undefined,\n filenameValue: string | undefined,\n getStack: () => string\n): string | undefined {\n const candidates: string[] = [];\n\n // CJS: use __dirname/__filename, but validate they actually point to sqlstack\n // (Vitest can inject __dirname incorrectly when transforming CJS modules)\n if (typeof dirnameValue === 'string' && isSqlstackPath(dirnameValue)) {\n candidates.push(dirnameValue);\n }\n if (typeof filenameValue === 'string' && isSqlstackPath(filenameValue)) {\n candidates.push(path.dirname(filenameValue));\n }\n\n // ESM fallback or when __dirname was incorrectly injected: parse stack trace\n if (candidates.length === 0) {\n const stackDir = findSqlstackFromStack(getStack());\n if (stackDir) {\n candidates.push(stackDir);\n }\n }\n\n // Find the package root from the first valid candidate\n for (const base of candidates) {\n const root = findPackageRoot(base);\n if (root) return root;\n }\n return undefined;\n}\n\nconst PACKAGE_ROOT_NORMALIZED = computePackageRoot(\n typeof __dirname === 'string' ? __dirname : undefined,\n typeof __filename === 'string' ? __filename : undefined,\n () => new Error().stack || ''\n);\n\n/**\n * sqlstack's code root as the runtime names this module in stack traces:\n * the parent of this file's directory (`src/`, `dist/cjs/`, `dist/esm/`, or\n * a bundler's re-rooted copy). Needs no filesystem.\n * @internal Exported for testing\n */\nexport function computeCodeRoot(getStack: () => string): string | undefined {\n const coreDir = findSqlstackFromStack(getStack());\n if (!coreDir) return undefined;\n const root = safeNormalize(path.dirname(coreDir));\n return root ? ensureTrailingSep(root) : undefined;\n}\n\nconst SQLSTACK_CODE_ROOT = computeCodeRoot(() => new Error().stack || '');\n"]}
@@ -8,7 +8,7 @@ import { registerDecoratedMethod, recordQueryMethodOnClass, getActiveResolver }
8
8
  import { getResources, resolveSqlFromResources } from '../core/resources.js';
9
9
  import { getTransactionTarget } from '../transactions.js';
10
10
  import { SqlFragment, compileFragment } from '../sql.js';
11
- import { runStorage, resolveRunTarget, executeOnTarget, toRunError, fragmentText, isRunDatabaseHandle, } from '../run.js';
11
+ import { runStorage, resolveRunTarget, executeOnTarget, toRunError, isErrorLike, fragmentText, isRunDatabaseHandle, } from '../run.js';
12
12
  /**
13
13
  * Turn a method into a database query. The body calls `run(...)` (see `run`
14
14
  * for its forms); the wrapper resolves SQL, binds, executes, and applies the
@@ -305,7 +305,7 @@ export function Query(arg) {
305
305
  }
306
306
  catch (dbError) {
307
307
  // Attach SQL query (with placeholders) to error for debugging
308
- throw new DatabaseError(dbError?.message || String(dbError), boundSql, dbError instanceof Error ? dbError : undefined);
308
+ throw new DatabaseError(dbError?.message || String(dbError), boundSql, isErrorLike(dbError) ? dbError : undefined);
309
309
  }
310
310
  return out;
311
311
  };
@@ -436,7 +436,7 @@ export function Query(arg) {
436
436
  out = tx ? await tx.query(boundSql, params) : await db.query(boundSql, params);
437
437
  }
438
438
  catch (dbError) {
439
- throw new DatabaseError(dbError?.message || String(dbError), boundSql, dbError instanceof Error ? dbError : undefined);
439
+ throw new DatabaseError(dbError?.message || String(dbError), boundSql, isErrorLike(dbError) ? dbError : undefined);
440
440
  }
441
441
  return finishResult(out, labels, this, prop);
442
442
  }
@@ -1 +1 @@
1
- {"version":3,"file":"query.js","sourceRoot":"","sources":["../../../src/decorators/query.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AACpF,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,WAAW,EAAE,cAAc,EAAE,aAAa,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAClI,OAAO,EAAE,oBAAoB,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACzE,OAAO,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAC;AAE5F,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AACnG,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC7F,OAAO,EAAE,uBAAuB,EAAE,wBAAwB,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACxG,OAAO,EAAE,YAAY,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAE1E,OAAO,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AACvD,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,MA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,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC;gBAAE,MAAM,IAAI,cAAc,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YAC3D,OAAO,IAAI,CAAC;QACd;YACE,OAAO,IAAI,CAAC;IAChB,CAAC;AACH,CAAC","sourcesContent":["import { getClassLabels, getMethodLabels, setMethodLabels } from '../core/metadata';\nimport { SqlStackError, ExactlyOneRowError, NoRowsError, RowsExistError, DatabaseError, ExpectedRowsError } from '../core/errors';\nimport { isValidationDisabled, validateOutput } from '../core/validator';\nimport { resolveExecution, resolveSqlResolver, isRegisteredDatabaseName } from '../runtime';\nimport type { SqlResolver } from '../core/resolver';\nimport { createSqliteBinder, createMysqlBinder, createPostgresBinder } from '../binders/sqlBinder';\nimport { coerceRootPath, resolveSqlFromFs, guessDecoratorDir } from '../core/fileResolution';\nimport { registerDecoratedMethod, recordQueryMethodOnClass, getActiveResolver } from '../core/resolver';\nimport { getResources, resolveSqlFromResources } from '../core/resources';\nimport type { MethodLabels } from '../core/metadata';\nimport { getTransactionTarget } from '../transactions';\nimport { SqlFragment, compileFragment } from '../sql';\nimport {\n runStorage,\n resolveRunTarget,\n executeOnTarget,\n toRunError,\n fragmentText,\n isRunDatabaseHandle,\n type RunContext,\n type RunDatabase,\n type RunInvocation,\n type RunTarget,\n} from '../run';\n\ntype QueryOptions = {\n sql?: string; // optional inline SQL for testing; otherwise, future: load from file\n db?: string; // optional override DB name\n dialect?: 'sqlite' | 'mysql' | 'postgres';\n};\n\n/**\n * Turn a method into a database query. The body calls `run(...)` (see `run`\n * for its forms); the wrapper resolves SQL, binds, executes, and applies the\n * shape/transform/validation decorators. A string argument is the root\n * directory holding the method's `.sql` file; `{ sql }` gives inline SQL,\n * `{ db }` pins a registered database, `{ dialect }` overrides binding style.\n *\n * The decorated method's promise rejects with:\n * @throws {DatabaseError} When the driver rejects the statement (original\n * error in `.cause`).\n * @throws {SqlStackError} For missing SQL sources, unresolvable databases,\n * and shape/validation failures (ExpectedRowsError, ExactlyOneRowError,\n * NoRowsError, RowsExistError, ValidationError).\n */\nexport function Query(arg?: string | QueryOptions) {\n return function (_target: any, prop: string | symbol, desc: PropertyDescriptor) {\n const options: QueryOptions | undefined = typeof arg === 'string' ? undefined : arg;\n const rootArg: string | undefined = typeof arg === 'string' ? arg : undefined;\n // Store method-level db override if provided\n if (options?.db) {\n setMethodLabels(_target, prop, { db: options.db });\n }\n // Store inline SQL if provided\n if (options?.sql) {\n setMethodLabels(_target, prop, { source: { kind: 'inline', sql: options.sql } });\n } else {\n // An EXPLICIT path argument pins a filesystem directory. Bare @Query()\n // records the directory of the decorating module (first non-sqlstack\n // stack frame at decoration time); at call time that directory is\n // resolved against the packaged resources map when one is installed\n // (SqlStack.useResources), else read from the filesystem. No tree scan.\n const { rootDir } = coerceRootPath(rootArg);\n if (rootDir) {\n setMethodLabels(_target, prop, { source: { kind: 'fs', rootDir } });\n } else {\n const dir = guessDecoratorDir();\n if (dir) setMethodLabels(_target, prop, { source: { kind: 'guess', dir } });\n }\n }\n\n // Record for resolver coverage checks: immutable class metadata (the\n // canonical, environment-local source) plus the deprecated global list\n // consulted by the legacy global-resolver path.\n const decoratedEntry = {\n className: _target?.constructor?.name ?? '<anonymous>',\n methodName: String(prop),\n inline: !!options?.sql,\n };\n recordQueryMethodOnClass(_target, decoratedEntry);\n registerDecoratedMethod(decoratedEntry);\n\n const original = desc.value;\n desc.value = async function (...callArgs: any[]) {\n const labels = getMethodLabels(this, prop);\n const classLabels = getClassLabels(this);\n\n // Resolve, bind, and execute the method's own SQL (inline, resolver,\n // or file) and return the adapter's raw result. `callArgs` is the\n // binding input: the method's own arguments for run() and the legacy\n // fallback, or the params given to run(db, params). `explicit` carries\n // the database chosen by run(db, params).\n const executeMethodSql = async (\n callArgs: any[],\n explicit: { target: RunTarget; resolver: SqlResolver | undefined } | undefined,\n onSql: (sqlText: string) => void\n ): Promise<unknown> => {\n // 1) prepare args with defaults\n const rawInput = callArgs.length === 1 ? callArgs[0] : callArgs; // object or positional array\n\n // 2) choose database and dialect via the active environment (or run's explicit database)\n let target: RunTarget;\n let activeResolver: SqlResolver | undefined;\n if (explicit) {\n target = explicit.target;\n activeResolver = explicit.resolver;\n } else {\n target = await contextTarget();\n activeResolver = target.resolver;\n }\n const db = target.db;\n const dialect = options?.dialect ?? db.dialect ?? 'sqlite';\n\n // 3) load SQL source: inline; else an installed resolver (the\n // instance's, else the process-global one — a build-time manifest\n // registered by a host runner applies even when the SqlStack itself\n // came from an IoC root); else the decorator's directory (explicit\n // path or guessed module dir) against the packaged resources /\n // filesystem.\n const className = this?.constructor?.name ?? '<anonymous>';\n const resolver = activeResolver ?? getActiveResolver();\n const sql = labels?.source?.kind === 'inline'\n ? labels.source.sql\n : (resolver?.resolve({\n className,\n methodName: String(prop),\n dialect,\n rootDir: labels?.source?.kind === 'fs' ? labels.source.rootDir : undefined,\n }) ?? resolveSourceSql(labels?.source, className, String(prop), dialect));\n if (!sql) {\n throw new SqlStackError(\n `No SQL source for ${className}.${String(prop)}: the decorating module's directory could not be ` +\n 'determined from the stack. Use @Query() with a file/folder path or inline sql.'\n );\n }\n onSql(sql);\n\n // 4) bind placeholders\n // Decide argument mode: positional if SQL contains :argN\n let workingSql = sql;\n const hasPositional = /:arg[1-9][0-9]*/.test(workingSql);\n\n // Prepare args for binder\n let args: any;\n if (hasPositional) {\n args = callArgs;\n } else {\n const namedBase = callArgs.length > 0 ? callArgs[0] : undefined;\n args = applyDefaults(labels.defaults, namedBase ?? {});\n }\n\n // Compute paging and inject :offset/:limit (named mode) or rewrite to positional\n const pageCfg = labels.page;\n if (pageCfg) {\n const { size, zeroBase } = pageCfg;\n const base = zeroBase ? 0 : 1;\n\n // Extract page number from input (object) or a trailing options object in positional mode\n const pageFromObject = (val: any): number | undefined => {\n if (val && typeof val === 'object' && !Array.isArray(val) && typeof (val as any).page !== 'undefined') {\n const p = (val as any).page;\n if (typeof p === 'number' && isFinite(p)) return p;\n }\n return undefined;\n };\n\n let pageNum: number | undefined;\n if (hasPositional) {\n // Variadic-style: only the LAST argument may carry `{ page }`\n if (callArgs.length > 0) {\n const last = callArgs[callArgs.length - 1];\n pageNum = pageFromObject(last);\n }\n } else {\n // Prefer last-arg options if provided; otherwise read from named object\n if (callArgs.length > 1) {\n const last = callArgs[callArgs.length - 1];\n pageNum = pageFromObject(last);\n }\n if (pageNum === undefined) {\n pageNum = pageFromObject(args);\n }\n }\n\n const effectivePage = typeof pageNum === 'number' ? pageNum : base;\n const offset = (effectivePage - base) * size;\n const limit = size;\n\n if (hasPositional) {\n // Replace occurrences of :offset and :limit with new :argN tokens appended to args\n const baseIndex = callArgs.length; // start numbering after user args\n let nextIndex = baseIndex + 1;\n const additions: unknown[] = [];\n\n const rewrite = (sqlText: string) => {\n const out: string[] = [];\n let i = 0;\n let inSQ = false, inDQ = false, inLC = false, inBC = false;\n const len = sqlText.length;\n while (i < len) {\n const ch = sqlText[i];\n const next = i + 1 < len ? sqlText[i + 1] : '';\n if (inLC) { out.push(ch); if (ch === '\\n') inLC = false; i++; continue; }\n if (inBC) { out.push(ch); if (ch === '*' && next === '/') { out.push(next); i++; inBC = false; } i++; continue; }\n if (inSQ) {\n out.push(ch);\n if (ch === \"'\" && next === \"'\") { out.push(next); i += 2; continue; }\n if (ch === \"'\") inSQ = false;\n i++;\n continue;\n }\n if (inDQ) {\n out.push(ch);\n if (ch === '\"' && next === '\"') { out.push(next); i += 2; continue; }\n if (ch === '\"') inDQ = false;\n i++;\n continue;\n }\n if (ch === '-' && next === '-') { out.push(ch, next); i += 2; inLC = true; continue; }\n if (ch === '/' && next === '*') { out.push(ch, next); i += 2; inBC = true; continue; }\n if (ch === '\"') { out.push(ch); inDQ = true; i++; continue; }\n if (ch === \"'\") { out.push(ch); inSQ = true; i++; continue; }\n if (ch === ':' && next === ':') { out.push('::'); i += 2; continue; }\n if (ch === ':') {\n // parse token\n let j = i + 1;\n const start = j;\n while (j < len) {\n const c = sqlText[j];\n if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c === '_') j++; else break;\n }\n const name = sqlText.slice(start, j);\n if (name === 'offset') {\n const token = `:arg${nextIndex++}`;\n out.push(token);\n additions.push(offset);\n i = j;\n continue;\n }\n if (name === 'limit') {\n const token = `:arg${nextIndex++}`;\n out.push(token);\n additions.push(limit);\n i = j;\n continue;\n }\n // otherwise leave untouched\n out.push(':');\n i++;\n continue;\n }\n out.push(ch);\n i++;\n }\n return out.join('');\n };\n\n const rewritten = rewrite(workingSql);\n if (rewritten !== workingSql) {\n workingSql = rewritten;\n // append values so :argK map correctly\n (args as unknown[]).push(...additions);\n }\n } else {\n // Named-mode: attach computed values (override any provided)\n args = { ...(args as Record<string, unknown>), offset, limit };\n }\n }\n const binder =\n dialect === 'postgres' ? createPostgresBinder() : dialect === 'mysql' ? createMysqlBinder() : createSqliteBinder();\n // Binding failures (missing :name, bad array value) surface as DatabaseError like every\n // other run() failure; the original error stays in `.cause`.\n let bound: { sql: string; params: unknown[] };\n try {\n bound = binder.bind(workingSql, args as any);\n } catch (bindError) {\n throw toRunError(bindError, workingSql);\n }\n const { sql: boundSql, params } = bound;\n onSql(boundSql);\n\n // 5) execute query (inside the active transaction on that database, if any)\n let out;\n try {\n out = target.tx ? await target.tx.query(boundSql, params) : await db.query(boundSql, params);\n } catch (dbError: any) {\n // Attach SQL query (with placeholders) to error for debugging\n throw new DatabaseError(\n dbError?.message || String(dbError),\n boundSql,\n dbError instanceof Error ? dbError : undefined\n );\n }\n return out;\n };\n\n // Database from the decorator context: @Query({ db }), @QueryBinder({ db }),\n // or the environment default.\n const contextTarget = async (): Promise<RunTarget> => {\n const dbName = labels.db ?? options?.db ?? classLabels?.db;\n const resolved = await resolveExecution(dbName);\n return {\n db: resolved.entry.db,\n tx: getTransactionTarget(resolved.entry),\n resolver: resolved.resolver,\n byName: true,\n };\n };\n\n // The method's own leading database argument: a handle (object with\n // query()) or a registered database name. It selects run()'s target\n // and is never bound as a value.\n const leadingDb = async (): Promise<RunDatabase | string | undefined> => {\n if (callArgs.length === 0) return undefined;\n const first = callArgs[0];\n if (isRunDatabaseHandle(first)) return first;\n if (typeof first === 'string' && first.length > 0 && (await isRegisteredDatabaseName(first))) return first;\n return undefined;\n };\n\n // A database chosen by run's argument or the method's leading argument.\n const explicitTarget = async (\n db: RunDatabase | string\n ): Promise<{ target: RunTarget; resolver: SqlResolver | undefined }> => {\n const target = await resolveRunTarget(db);\n // Inline SQL needs no resolver; only look one up for file-based SQL.\n const resolver = target.byName\n ? target.resolver\n : labels?.source?.kind === 'inline'\n ? undefined\n : await resolveSqlResolver();\n return { target, resolver };\n };\n\n // run() (and the legacy fallback): the method's arguments minus a\n // leading database, on that database or the decorator context.\n const executeDefault = async (onSql: (sqlText: string) => void): Promise<unknown> => {\n const lead = await leadingDb();\n if (lead === undefined) return executeMethodSql(callArgs, undefined, onSql);\n return executeMethodSql(callArgs.slice(1), await explicitTarget(lead), onSql);\n };\n\n // run's argument-taking forms: return the adapter's raw result.\n const executeInvocation = async (\n invocation: Exclude<RunInvocation, { kind: 'default' }>,\n onSql: (sqlText: string) => void\n ): Promise<unknown> => {\n if (invocation.kind === 'fragment') {\n // run(query) / run(db, query): the fragment replaces the method's SQL;\n // the method's arguments are not bound.\n const target = invocation.db !== undefined ? await resolveRunTarget(invocation.db) : await contextTarget();\n const dialect = options?.dialect ?? target.db.dialect ?? 'sqlite';\n const { sql: boundSql, params } = compileFragment(invocation.fragment, dialect);\n onSql(boundSql);\n return executeOnTarget(target, boundSql, params);\n }\n if (invocation.kind === 'db') {\n // run(db): the method's own SQL against db, bound from the method's\n // arguments minus a leading database argument.\n const lead = await leadingDb();\n const bindArgs = lead === undefined ? callArgs : callArgs.slice(1);\n return executeMethodSql(bindArgs, await explicitTarget(invocation.db), onSql);\n }\n // run(db, params) / run(params): the method's own SQL bound from params\n // only (an object for :named, an array for :argN), against run's db,\n // else the method's leading database, else the decorator context.\n const bindArgs = Array.isArray(invocation.params) ? [...invocation.params] : [invocation.params];\n const db = invocation.db ?? (await leadingDb());\n return executeMethodSql(bindArgs, db !== undefined ? await explicitTarget(db) : undefined, onSql);\n };\n\n // The full pipeline: execute, then — if rows were returned\n // (SELECT/CTE/RETURNING) — shape + transform + validate; a write result\n // is returned as-is (or fails if a shape was requested). Invoked by\n // run() from inside the method body, or directly as the legacy fallback\n // when the body throws. The zero-argument path is unchanged; run's\n // argument-taking forms get the unified error contract: any failure\n // before shaping that is not already a SqlStackError becomes a\n // DatabaseError with the original error in `.cause`.\n const pipeline = async (invocation?: RunInvocation): Promise<unknown> => {\n if (invocation === undefined || invocation.kind === 'default') {\n const out = await executeDefault(() => {});\n return finishResult(out, labels, this, prop);\n }\n let sqlText = invocation.kind === 'fragment' ? fragmentText(invocation.fragment) : '';\n let out: unknown;\n try {\n out = await executeInvocation(invocation, (s) => {\n sqlText = s;\n });\n } catch (err) {\n throw toRunError(err, sqlText);\n }\n return finishResult(out, labels, this, prop);\n };\n\n // 0) Invoke the method body inside a run() context. Three outcomes:\n // - body calls run(...): the pipeline executed inside the body; return\n // the body's result verbatim (it may have caught/transformed it).\n // - body returns a SqlFragment (deprecated template literal path):\n // execute it.\n // - body throws without calling run() (legacy placeholder throw):\n // fall through to the pipeline.\n const runCtx: RunContext = { ran: false, execute: pipeline, invocations: true };\n let fragmentResult: unknown;\n try {\n fragmentResult = await runStorage.run(runCtx, () => original.apply(this, callArgs));\n } catch (bodyError) {\n // A body that invoked run() is real logic — its errors propagate.\n if (runCtx.ran) throw bodyError;\n // Method body threw (e.g. placeholder `throw new Error('replaced')`) — fall through to file/inline SQL\n fragmentResult = undefined;\n }\n if (runCtx.ran) return fragmentResult;\n\n if (fragmentResult instanceof SqlFragment) {\n warnFragmentBodyDeprecated(this, prop);\n const { sql: boundSql, params } = fragmentResult.toSQL();\n\n const dbName = labels.db ?? options?.db ?? classLabels?.db;\n const { entry } = await resolveExecution(dbName);\n const db = entry.db;\n\n let out;\n try {\n const tx = getTransactionTarget(entry);\n out = tx ? await tx.query(boundSql, params) : await db.query(boundSql, params);\n } catch (dbError: any) {\n throw new DatabaseError(\n dbError?.message || String(dbError),\n boundSql,\n dbError instanceof Error ? dbError : undefined\n );\n }\n\n return finishResult(out, labels, this, prop);\n }\n\n return pipeline();\n };\n\n return desc;\n };\n}\n\n// Directory-based SQL for a decorated method. An explicit @Query('<path>')\n// is always the filesystem. A bare @Query() uses the packaged resources map\n// when one is installed (bundled/packaged runtimes), else the filesystem next\n// to the decorating module (tests, plain Node). Misses name every key tried.\nfunction resolveSourceSql(\n source: MethodLabels['source'],\n className: string,\n methodName: string,\n dialect: 'sqlite' | 'mysql' | 'postgres'\n): string | undefined {\n if (!source || source.kind === 'inline') return undefined;\n if (source.kind === 'fs') return resolveSqlFromFs(source.rootDir, methodName, dialect).sql;\n const packaged = getResources();\n const fromResources = packaged ? resolveSqlFromResources(source.dir, methodName, dialect) : undefined;\n if (fromResources?.sql !== undefined) return fromResources.sql;\n try {\n return resolveSqlFromFs(source.dir, methodName, dialect).sql;\n } catch (fsError) {\n const triedResources = fromResources ? `\\npackaged resources tried:\\n${fromResources.tried.join('\\n')}` : '';\n throw new SqlStackError(\n `sqlstack: no SQL for ${className}.${methodName}.${triedResources}\\n` +\n `${(fsError as Error)?.message ?? String(fsError)}`\n );\n }\n}\n\n// Deprecated (removal in the next major version): a @Query body that RETURNS\n// an sql`` fragment. It only type-checks when the method's declared return\n// type is bent to admit SqlFragment (an `as any`-style hole). One warning per\n// class.method per process.\nconst warnedFragmentBodies = new Set<string>();\n\nfunction warnFragmentBodyDeprecated(self: any, prop: string | symbol): void {\n const key = `${self?.constructor?.name ?? '<anonymous>'}.${String(prop)}`;\n if (warnedFragmentBodies.has(key)) return;\n warnedFragmentBodies.add(key);\n process.emitWarning(\n `@Query method ${key} returns an sql\\`\\` fragment from its body. This form is deprecated and will be ` +\n 'removed in the next major version. Use `return run(sql`...`)` (or `return run(db, sql`...`)`) instead.',\n { type: 'DeprecationWarning', code: 'SQLSTACK_FRAGMENT_BODY' }\n );\n}\n\nfunction applyDefaults(defaults: Record<string, unknown> | undefined, input: any) {\n if (!defaults) return input;\n if (Array.isArray(input)) return input; // defaults only apply to named-object args\n return { ...defaults, ...(input || {}) };\n}\n\n// Shared tail of both execution paths. Rows (any statement that produced a\n// result set) are shaped, transformed, and validated. A write result is\n// returned verbatim — unless a result-shape decorator was requested, in which\n// case the statement cannot satisfy it and we fail at the call site instead of\n// silently handing back a truthy `{ rowsAffected }` object.\nfunction finishResult(out: unknown, labels: any, self: any, prop: string | symbol): any {\n if (!Array.isArray(out)) {\n if (labels.shape) {\n throw new ExpectedRowsError(\n `${self?.constructor?.name ?? '<anonymous>'}.${String(prop)}`,\n labels.shape\n );\n }\n return out;\n }\n const shaped = applyShape(out, labels.shape);\n const transformed = labels.transform ? labels.transform(shaped) : shaped;\n\n if (labels.validateSchema && !isValidationDisabled()) {\n if (Array.isArray(transformed)) {\n for (const row of transformed) validateOutput(labels.validateSchema, row);\n } else if (transformed !== null && transformed !== undefined) {\n validateOutput(labels.validateSchema, transformed);\n }\n }\n return transformed;\n}\n\nfunction applyShape<T>(rows: T[], shape?: 'single' | 'only' | 'exist' | 'none'): any {\n switch (shape) {\n case 'single':\n return rows.length > 0 ? rows[0] : null;\n case 'only':\n if (rows.length !== 1) throw new ExactlyOneRowError(rows.length);\n return rows[0];\n case 'exist':\n if (rows.length < 1) throw new NoRowsError();\n return rows[0];\n case 'none':\n if (rows.length > 0) throw new RowsExistError(rows.length);\n return null;\n default:\n return rows;\n }\n}\n"]}
1
+ {"version":3,"file":"query.js","sourceRoot":"","sources":["../../../src/decorators/query.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AACpF,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,WAAW,EAAE,cAAc,EAAE,aAAa,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAClI,OAAO,EAAE,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,WAAW,CAAC;AACrB,CAAC;AAED,SAAS,UAAU,CAAI,IAAS,EAAE,KAA4C;IAC5E,QAAQ,KAAK,EAAE,CAAC;QACd,KAAK,QAAQ;YACX,OAAO,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;QAC1C,KAAK,MAAM;YACT,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC;gBAAE,MAAM,IAAI,kBAAkB,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YACjE,OAAO,IAAI,CAAC,CAAC,CAAC,CAAC;QACjB,KAAK,OAAO;YACV,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC;gBAAE,MAAM,IAAI,WAAW,EAAE,CAAC;YAC7C,OAAO,IAAI,CAAC,CAAC,CAAC,CAAC;QACjB,KAAK,MAAM;YACT,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC;gBAAE,MAAM,IAAI,cAAc,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YAC3D,OAAO,IAAI,CAAC;QACd;YACE,OAAO,IAAI,CAAC;IAChB,CAAC;AACH,CAAC","sourcesContent":["import { getClassLabels, getMethodLabels, setMethodLabels } from '../core/metadata';\nimport { SqlStackError, ExactlyOneRowError, NoRowsError, RowsExistError, DatabaseError, ExpectedRowsError } from '../core/errors';\nimport { isValidationDisabled, validateOutput } from '../core/validator';\nimport { resolveExecution, resolveSqlResolver, isRegisteredDatabaseName } from '../runtime';\nimport type { SqlResolver } from '../core/resolver';\nimport { createSqliteBinder, createMysqlBinder, createPostgresBinder } from '../binders/sqlBinder';\nimport { coerceRootPath, resolveSqlFromFs, guessDecoratorDir } from '../core/fileResolution';\nimport { registerDecoratedMethod, recordQueryMethodOnClass, getActiveResolver } from '../core/resolver';\nimport { getResources, resolveSqlFromResources } from '../core/resources';\nimport type { MethodLabels } from '../core/metadata';\nimport { getTransactionTarget } from '../transactions';\nimport { SqlFragment, compileFragment } from '../sql';\nimport {\n runStorage,\n resolveRunTarget,\n executeOnTarget,\n toRunError,\n isErrorLike,\n fragmentText,\n isRunDatabaseHandle,\n type RunContext,\n type RunDatabase,\n type RunInvocation,\n type RunTarget,\n} from '../run';\n\ntype QueryOptions = {\n sql?: string; // optional inline SQL for testing; otherwise, future: load from file\n db?: string; // optional override DB name\n dialect?: 'sqlite' | 'mysql' | 'postgres';\n};\n\n/**\n * Turn a method into a database query. The body calls `run(...)` (see `run`\n * for its forms); the wrapper resolves SQL, binds, executes, and applies the\n * shape/transform/validation decorators. A string argument is the root\n * directory holding the method's `.sql` file; `{ sql }` gives inline SQL,\n * `{ db }` pins a registered database, `{ dialect }` overrides binding style.\n *\n * The decorated method's promise rejects with:\n * @throws {DatabaseError} When the driver rejects the statement (original\n * error in `.cause`).\n * @throws {SqlStackError} For missing SQL sources, unresolvable databases,\n * and shape/validation failures (ExpectedRowsError, ExactlyOneRowError,\n * NoRowsError, RowsExistError, ValidationError).\n */\nexport function Query(arg?: string | QueryOptions) {\n return function (_target: any, prop: string | symbol, desc: PropertyDescriptor) {\n const options: QueryOptions | undefined = typeof arg === 'string' ? undefined : arg;\n const rootArg: string | undefined = typeof arg === 'string' ? arg : undefined;\n // Store method-level db override if provided\n if (options?.db) {\n setMethodLabels(_target, prop, { db: options.db });\n }\n // Store inline SQL if provided\n if (options?.sql) {\n setMethodLabels(_target, prop, { source: { kind: 'inline', sql: options.sql } });\n } else {\n // An EXPLICIT path argument pins a filesystem directory. Bare @Query()\n // records the directory of the decorating module (first non-sqlstack\n // stack frame at decoration time); at call time that directory is\n // resolved against the packaged resources map when one is installed\n // (SqlStack.useResources), else read from the filesystem. No tree scan.\n const { rootDir } = coerceRootPath(rootArg);\n if (rootDir) {\n setMethodLabels(_target, prop, { source: { kind: 'fs', rootDir } });\n } else {\n const dir = guessDecoratorDir();\n if (dir) setMethodLabels(_target, prop, { source: { kind: 'guess', dir } });\n }\n }\n\n // Record for resolver coverage checks: immutable class metadata (the\n // canonical, environment-local source) plus the deprecated global list\n // consulted by the legacy global-resolver path.\n const decoratedEntry = {\n className: _target?.constructor?.name ?? '<anonymous>',\n methodName: String(prop),\n inline: !!options?.sql,\n };\n recordQueryMethodOnClass(_target, decoratedEntry);\n registerDecoratedMethod(decoratedEntry);\n\n const original = desc.value;\n desc.value = async function (...callArgs: any[]) {\n const labels = getMethodLabels(this, prop);\n const classLabels = getClassLabels(this);\n\n // Resolve, bind, and execute the method's own SQL (inline, resolver,\n // or file) and return the adapter's raw result. `callArgs` is the\n // binding input: the method's own arguments for run() and the legacy\n // fallback, or the params given to run(db, params). `explicit` carries\n // the database chosen by run(db, params).\n const executeMethodSql = async (\n callArgs: any[],\n explicit: { target: RunTarget; resolver: SqlResolver | undefined } | undefined,\n onSql: (sqlText: string) => void\n ): Promise<unknown> => {\n // 1) prepare args with defaults\n const rawInput = callArgs.length === 1 ? callArgs[0] : callArgs; // object or positional array\n\n // 2) choose database and dialect via the active environment (or run's explicit database)\n let target: RunTarget;\n let activeResolver: SqlResolver | undefined;\n if (explicit) {\n target = explicit.target;\n activeResolver = explicit.resolver;\n } else {\n target = await contextTarget();\n activeResolver = target.resolver;\n }\n const db = target.db;\n const dialect = options?.dialect ?? db.dialect ?? 'sqlite';\n\n // 3) load SQL source: inline; else an installed resolver (the\n // instance's, else the process-global one — a build-time manifest\n // registered by a host runner applies even when the SqlStack itself\n // came from an IoC root); else the decorator's directory (explicit\n // path or guessed module dir) against the packaged resources /\n // filesystem.\n const className = this?.constructor?.name ?? '<anonymous>';\n const resolver = activeResolver ?? getActiveResolver();\n const sql = labels?.source?.kind === 'inline'\n ? labels.source.sql\n : (resolver?.resolve({\n className,\n methodName: String(prop),\n dialect,\n rootDir: labels?.source?.kind === 'fs' ? labels.source.rootDir : undefined,\n }) ?? resolveSourceSql(labels?.source, className, String(prop), dialect));\n if (!sql) {\n throw new SqlStackError(\n `No SQL source for ${className}.${String(prop)}: the decorating module's directory could not be ` +\n 'determined from the stack. Use @Query() with a file/folder path or inline sql.'\n );\n }\n onSql(sql);\n\n // 4) bind placeholders\n // Decide argument mode: positional if SQL contains :argN\n let workingSql = sql;\n const hasPositional = /:arg[1-9][0-9]*/.test(workingSql);\n\n // Prepare args for binder\n let args: any;\n if (hasPositional) {\n args = callArgs;\n } else {\n const namedBase = callArgs.length > 0 ? callArgs[0] : undefined;\n args = applyDefaults(labels.defaults, namedBase ?? {});\n }\n\n // Compute paging and inject :offset/:limit (named mode) or rewrite to positional\n const pageCfg = labels.page;\n if (pageCfg) {\n const { size, zeroBase } = pageCfg;\n const base = zeroBase ? 0 : 1;\n\n // Extract page number from input (object) or a trailing options object in positional mode\n const pageFromObject = (val: any): number | undefined => {\n if (val && typeof val === 'object' && !Array.isArray(val) && typeof (val as any).page !== 'undefined') {\n const p = (val as any).page;\n if (typeof p === 'number' && isFinite(p)) return p;\n }\n return undefined;\n };\n\n let pageNum: number | undefined;\n if (hasPositional) {\n // Variadic-style: only the LAST argument may carry `{ page }`\n if (callArgs.length > 0) {\n const last = callArgs[callArgs.length - 1];\n pageNum = pageFromObject(last);\n }\n } else {\n // Prefer last-arg options if provided; otherwise read from named object\n if (callArgs.length > 1) {\n const last = callArgs[callArgs.length - 1];\n pageNum = pageFromObject(last);\n }\n if (pageNum === undefined) {\n pageNum = pageFromObject(args);\n }\n }\n\n const effectivePage = typeof pageNum === 'number' ? pageNum : base;\n const offset = (effectivePage - base) * size;\n const limit = size;\n\n if (hasPositional) {\n // Replace occurrences of :offset and :limit with new :argN tokens appended to args\n const baseIndex = callArgs.length; // start numbering after user args\n let nextIndex = baseIndex + 1;\n const additions: unknown[] = [];\n\n const rewrite = (sqlText: string) => {\n const out: string[] = [];\n let i = 0;\n let inSQ = false, inDQ = false, inLC = false, inBC = false;\n const len = sqlText.length;\n while (i < len) {\n const ch = sqlText[i];\n const next = i + 1 < len ? sqlText[i + 1] : '';\n if (inLC) { out.push(ch); if (ch === '\\n') inLC = false; i++; continue; }\n if (inBC) { out.push(ch); if (ch === '*' && next === '/') { out.push(next); i++; inBC = false; } i++; continue; }\n if (inSQ) {\n out.push(ch);\n if (ch === \"'\" && next === \"'\") { out.push(next); i += 2; continue; }\n if (ch === \"'\") inSQ = false;\n i++;\n continue;\n }\n if (inDQ) {\n out.push(ch);\n if (ch === '\"' && next === '\"') { out.push(next); i += 2; continue; }\n if (ch === '\"') inDQ = false;\n i++;\n continue;\n }\n if (ch === '-' && next === '-') { out.push(ch, next); i += 2; inLC = true; continue; }\n if (ch === '/' && next === '*') { out.push(ch, next); i += 2; inBC = true; continue; }\n if (ch === '\"') { out.push(ch); inDQ = true; i++; continue; }\n if (ch === \"'\") { out.push(ch); inSQ = true; i++; continue; }\n if (ch === ':' && next === ':') { out.push('::'); i += 2; continue; }\n if (ch === ':') {\n // parse token\n let j = i + 1;\n const start = j;\n while (j < len) {\n const c = sqlText[j];\n if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c === '_') j++; else break;\n }\n const name = sqlText.slice(start, j);\n if (name === 'offset') {\n const token = `:arg${nextIndex++}`;\n out.push(token);\n additions.push(offset);\n i = j;\n continue;\n }\n if (name === 'limit') {\n const token = `:arg${nextIndex++}`;\n out.push(token);\n additions.push(limit);\n i = j;\n continue;\n }\n // otherwise leave untouched\n out.push(':');\n i++;\n continue;\n }\n out.push(ch);\n i++;\n }\n return out.join('');\n };\n\n const rewritten = rewrite(workingSql);\n if (rewritten !== workingSql) {\n workingSql = rewritten;\n // append values so :argK map correctly\n (args as unknown[]).push(...additions);\n }\n } else {\n // Named-mode: attach computed values (override any provided)\n args = { ...(args as Record<string, unknown>), offset, limit };\n }\n }\n const binder =\n dialect === 'postgres' ? createPostgresBinder() : dialect === 'mysql' ? createMysqlBinder() : createSqliteBinder();\n // Binding failures (missing :name, bad array value) surface as DatabaseError like every\n // other run() failure; the original error stays in `.cause`.\n let bound: { sql: string; params: unknown[] };\n try {\n bound = binder.bind(workingSql, args as any);\n } catch (bindError) {\n throw toRunError(bindError, workingSql);\n }\n const { sql: boundSql, params } = bound;\n onSql(boundSql);\n\n // 5) execute query (inside the active transaction on that database, if any)\n let out;\n try {\n out = target.tx ? await target.tx.query(boundSql, params) : await db.query(boundSql, params);\n } catch (dbError: any) {\n // Attach SQL query (with placeholders) to error for debugging\n throw new DatabaseError(\n dbError?.message || String(dbError),\n boundSql,\n isErrorLike(dbError) ? dbError : undefined\n );\n }\n return out;\n };\n\n // Database from the decorator context: @Query({ db }), @QueryBinder({ db }),\n // or the environment default.\n const contextTarget = async (): Promise<RunTarget> => {\n const dbName = labels.db ?? options?.db ?? classLabels?.db;\n const resolved = await resolveExecution(dbName);\n return {\n db: resolved.entry.db,\n tx: getTransactionTarget(resolved.entry),\n resolver: resolved.resolver,\n byName: true,\n };\n };\n\n // The method's own leading database argument: a handle (object with\n // query()) or a registered database name. It selects run()'s target\n // and is never bound as a value.\n const leadingDb = async (): Promise<RunDatabase | string | undefined> => {\n if (callArgs.length === 0) return undefined;\n const first = callArgs[0];\n if (isRunDatabaseHandle(first)) return first;\n if (typeof first === 'string' && first.length > 0 && (await isRegisteredDatabaseName(first))) return first;\n return undefined;\n };\n\n // A database chosen by run's argument or the method's leading argument.\n const explicitTarget = async (\n db: RunDatabase | string\n ): Promise<{ target: RunTarget; resolver: SqlResolver | undefined }> => {\n const target = await resolveRunTarget(db);\n // Inline SQL needs no resolver; only look one up for file-based SQL.\n const resolver = target.byName\n ? target.resolver\n : labels?.source?.kind === 'inline'\n ? undefined\n : await resolveSqlResolver();\n return { target, resolver };\n };\n\n // run() (and the legacy fallback): the method's arguments minus a\n // leading database, on that database or the decorator context.\n const executeDefault = async (onSql: (sqlText: string) => void): Promise<unknown> => {\n const lead = await leadingDb();\n if (lead === undefined) return executeMethodSql(callArgs, undefined, onSql);\n return executeMethodSql(callArgs.slice(1), await explicitTarget(lead), onSql);\n };\n\n // run's argument-taking forms: return the adapter's raw result.\n const executeInvocation = async (\n invocation: Exclude<RunInvocation, { kind: 'default' }>,\n onSql: (sqlText: string) => void\n ): Promise<unknown> => {\n if (invocation.kind === 'fragment') {\n // run(query) / run(db, query): the fragment replaces the method's SQL;\n // the method's arguments are not bound.\n const target = invocation.db !== undefined ? await resolveRunTarget(invocation.db) : await contextTarget();\n const dialect = options?.dialect ?? target.db.dialect ?? 'sqlite';\n const { sql: boundSql, params } = compileFragment(invocation.fragment, dialect);\n onSql(boundSql);\n return executeOnTarget(target, boundSql, params);\n }\n if (invocation.kind === 'db') {\n // run(db): the method's own SQL against db, bound from the method's\n // arguments minus a leading database argument.\n const lead = await leadingDb();\n const bindArgs = lead === undefined ? callArgs : callArgs.slice(1);\n return executeMethodSql(bindArgs, await explicitTarget(invocation.db), onSql);\n }\n // run(db, params) / run(params): the method's own SQL bound from params\n // only (an object for :named, an array for :argN), against run's db,\n // else the method's leading database, else the decorator context.\n const bindArgs = Array.isArray(invocation.params) ? [...invocation.params] : [invocation.params];\n const db = invocation.db ?? (await leadingDb());\n return executeMethodSql(bindArgs, db !== undefined ? await explicitTarget(db) : undefined, onSql);\n };\n\n // The full pipeline: execute, then — if rows were returned\n // (SELECT/CTE/RETURNING) — shape + transform + validate; a write result\n // is returned as-is (or fails if a shape was requested). Invoked by\n // run() from inside the method body, or directly as the legacy fallback\n // when the body throws. The zero-argument path is unchanged; run's\n // argument-taking forms get the unified error contract: any failure\n // before shaping that is not already a SqlStackError becomes a\n // DatabaseError with the original error in `.cause`.\n const pipeline = async (invocation?: RunInvocation): Promise<unknown> => {\n if (invocation === undefined || invocation.kind === 'default') {\n const out = await executeDefault(() => {});\n return finishResult(out, labels, this, prop);\n }\n let sqlText = invocation.kind === 'fragment' ? fragmentText(invocation.fragment) : '';\n let out: unknown;\n try {\n out = await executeInvocation(invocation, (s) => {\n sqlText = s;\n });\n } catch (err) {\n throw toRunError(err, sqlText);\n }\n return finishResult(out, labels, this, prop);\n };\n\n // 0) Invoke the method body inside a run() context. Three outcomes:\n // - body calls run(...): the pipeline executed inside the body; return\n // the body's result verbatim (it may have caught/transformed it).\n // - body returns a SqlFragment (deprecated template literal path):\n // execute it.\n // - body throws without calling run() (legacy placeholder throw):\n // fall through to the pipeline.\n const runCtx: RunContext = { ran: false, execute: pipeline, invocations: true };\n let fragmentResult: unknown;\n try {\n fragmentResult = await runStorage.run(runCtx, () => original.apply(this, callArgs));\n } catch (bodyError) {\n // A body that invoked run() is real logic — its errors propagate.\n if (runCtx.ran) throw bodyError;\n // Method body threw (e.g. placeholder `throw new Error('replaced')`) — fall through to file/inline SQL\n fragmentResult = undefined;\n }\n if (runCtx.ran) return fragmentResult;\n\n if (fragmentResult instanceof SqlFragment) {\n warnFragmentBodyDeprecated(this, prop);\n const { sql: boundSql, params } = fragmentResult.toSQL();\n\n const dbName = labels.db ?? options?.db ?? classLabels?.db;\n const { entry } = await resolveExecution(dbName);\n const db = entry.db;\n\n let out;\n try {\n const tx = getTransactionTarget(entry);\n out = tx ? await tx.query(boundSql, params) : await db.query(boundSql, params);\n } catch (dbError: any) {\n throw new DatabaseError(\n dbError?.message || String(dbError),\n boundSql,\n isErrorLike(dbError) ? dbError : undefined\n );\n }\n\n return finishResult(out, labels, this, prop);\n }\n\n return pipeline();\n };\n\n return desc;\n };\n}\n\n// Directory-based SQL for a decorated method. An explicit @Query('<path>')\n// is always the filesystem. A bare @Query() uses the packaged resources map\n// when one is installed (bundled/packaged runtimes), else the filesystem next\n// to the decorating module (tests, plain Node). Misses name every key tried.\nfunction resolveSourceSql(\n source: MethodLabels['source'],\n className: string,\n methodName: string,\n dialect: 'sqlite' | 'mysql' | 'postgres'\n): string | undefined {\n if (!source || source.kind === 'inline') return undefined;\n if (source.kind === 'fs') return resolveSqlFromFs(source.rootDir, methodName, dialect).sql;\n const packaged = getResources();\n const fromResources = packaged ? resolveSqlFromResources(source.dir, methodName, dialect) : undefined;\n if (fromResources?.sql !== undefined) return fromResources.sql;\n try {\n return resolveSqlFromFs(source.dir, methodName, dialect).sql;\n } catch (fsError) {\n const triedResources = fromResources ? `\\npackaged resources tried:\\n${fromResources.tried.join('\\n')}` : '';\n throw new SqlStackError(\n `sqlstack: no SQL for ${className}.${methodName}.${triedResources}\\n` +\n `${(fsError as Error)?.message ?? String(fsError)}`\n );\n }\n}\n\n// Deprecated (removal in the next major version): a @Query body that RETURNS\n// an sql`` fragment. It only type-checks when the method's declared return\n// type is bent to admit SqlFragment (an `as any`-style hole). One warning per\n// class.method per process.\nconst warnedFragmentBodies = new Set<string>();\n\nfunction warnFragmentBodyDeprecated(self: any, prop: string | symbol): void {\n const key = `${self?.constructor?.name ?? '<anonymous>'}.${String(prop)}`;\n if (warnedFragmentBodies.has(key)) return;\n warnedFragmentBodies.add(key);\n process.emitWarning(\n `@Query method ${key} returns an sql\\`\\` fragment from its body. This form is deprecated and will be ` +\n 'removed in the next major version. Use `return run(sql`...`)` (or `return run(db, sql`...`)`) instead.',\n { type: 'DeprecationWarning', code: 'SQLSTACK_FRAGMENT_BODY' }\n );\n}\n\nfunction applyDefaults(defaults: Record<string, unknown> | undefined, input: any) {\n if (!defaults) return input;\n if (Array.isArray(input)) return input; // defaults only apply to named-object args\n return { ...defaults, ...(input || {}) };\n}\n\n// Shared tail of both execution paths. Rows (any statement that produced a\n// result set) are shaped, transformed, and validated. A write result is\n// returned verbatim — unless a result-shape decorator was requested, in which\n// case the statement cannot satisfy it and we fail at the call site instead of\n// silently handing back a truthy `{ rowsAffected }` object.\nfunction finishResult(out: unknown, labels: any, self: any, prop: string | symbol): any {\n if (!Array.isArray(out)) {\n if (labels.shape) {\n throw new ExpectedRowsError(\n `${self?.constructor?.name ?? '<anonymous>'}.${String(prop)}`,\n labels.shape\n );\n }\n return out;\n }\n const shaped = applyShape(out, labels.shape);\n const transformed = labels.transform ? labels.transform(shaped) : shaped;\n\n if (labels.validateSchema && !isValidationDisabled()) {\n if (Array.isArray(transformed)) {\n for (const row of transformed) validateOutput(labels.validateSchema, row);\n } else if (transformed !== null && transformed !== undefined) {\n validateOutput(labels.validateSchema, transformed);\n }\n }\n return transformed;\n}\n\nfunction applyShape<T>(rows: T[], shape?: 'single' | 'only' | 'exist' | 'none'): any {\n switch (shape) {\n case 'single':\n return rows.length > 0 ? rows[0] : null;\n case 'only':\n if (rows.length !== 1) throw new ExactlyOneRowError(rows.length);\n return rows[0];\n case 'exist':\n if (rows.length < 1) throw new NoRowsError();\n return rows[0];\n case 'none':\n if (rows.length > 0) throw new RowsExistError(rows.length);\n return null;\n default:\n return rows;\n }\n}\n"]}
package/dist/esm/run.js CHANGED
@@ -140,7 +140,24 @@ export function toRunError(err, sqlText) {
140
140
  }
141
141
  function toDatabaseError(err, sqlText) {
142
142
  const message = err?.message;
143
- return new DatabaseError(typeof message === 'string' && message ? message : String(err), sqlText, err instanceof Error ? err : undefined);
143
+ return new DatabaseError(typeof message === 'string' && message ? message : String(err), sqlText, isErrorLike(err) ? err : undefined);
144
+ }
145
+ /**
146
+ * better-sqlite3 binds its SqliteError class once per process. When several
147
+ * realms share that process (vm contexts, e.g. jest --runInBand, which is
148
+ * jest's default on a single CPU), driver errors are Error subclasses of the
149
+ * first realm only: `instanceof Error` is false elsewhere and they carry no
150
+ * [[ErrorData]] slot. Recognise them by shape so `.cause`/`.code` survive.
151
+ *
152
+ * @internal Shared with decorators/query.ts.
153
+ */
154
+ export function isErrorLike(err) {
155
+ if (err instanceof Error)
156
+ return true;
157
+ if (typeof err !== 'object' || err === null)
158
+ return false;
159
+ const candidate = err;
160
+ return typeof candidate.message === 'string' && typeof candidate.stack === 'string';
144
161
  }
145
162
  /** @internal Raw template text of a fragment, for error messages. */
146
163
  export function fragmentText(fragment) {
@@ -1 +1 @@
1
- {"version":3,"file":"run.js","sourceRoot":"","sources":["../../src/run.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAE7D,OAAO,EAAe,aAAa,EAAE,eAAe,EAAE,MAAM,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AAC,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACpC,CAAC;AAED,2EAA2E;AAC3E,MAAM,UAAU,aAAa,CAAC,QAAqB,EAAE,OAAgB;IACnE,IAAI,CAAC;QACH,OAAO,eAAe,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;IAC5C,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,MAAM,UAAU,CAAC,GAAG,EAAE,YAAY,CAAC,QAAQ,CAAC,CAAC,CAAC;IAChD,CAAC;AACH,CAAC;AAED,KAAK,UAAU,eAAe,CAAC,EAAwB,EAAE,QAAqB;IAC5E,IAAI,MAAiB,CAAC;IACtB,IAAI,CAAC;QACH,MAAM,GAAG,MAAM,gBAAgB,CAAC,EAAE,CAAC,CAAC;IACtC,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,MAAM,UAAU,CAAC,GAAG,EAAE,YAAY,CAAC,QAAQ,CAAC,CAAC,CAAC;IAChD,CAAC;IACD,MAAM,EAAE,GAAG,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,aAAa,CAAC,QAAQ,EAAE,MAAM,CAAC,EAAE,CAAC,OAAO,IAAI,QAAQ,CAAC,CAAC;IACzF,OAAO,eAAe,CAAC,MAAM,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC;AACnD,CAAC","sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\nimport { SqlStackError, DatabaseError } from './core/errors';\nimport type { Dialect } from './registry';\nimport { SqlFragment, isSqlFragment, compileFragment } from './sql';\nimport { resolveExecution } from './runtime';\nimport type { SqlResolver } from './core/resolver';\nimport { getTransactionTarget, getTransactionTargetForHandle } from './transactions';\nimport type { ActiveTransaction } from './transactions';\n\n/**\n * Anything run(db, ...) can execute against: sqlstack's own `Database`\n * (from createSqliteDb/createPgDb/createMysqlDb), or any application handle\n * exposing `query(sql, params)`. `dialect` selects placeholder style and\n * defaults to `'sqlite'` when absent. run never opens databases by path.\n */\nexport interface RunDatabase {\n readonly dialect?: Dialect;\n query(sql: string, params: unknown[]): Promise<unknown>;\n}\n\n/**\n * Type-level guard for the params form of run: rejects the\n * `{ sql, params }` object returned by `fragment.toSQL()`. Pass the sql``\n * fragment itself instead, so run owns dialect binding and error handling.\n */\nexport type RejectCompiledSql<P> = P extends { readonly sql: string; readonly params: readonly unknown[] }\n ? never\n : unknown;\n\n/**\n * What a run(...) call made inside a @Query body asks of the wrapper's\n * pipeline. `default` is the zero-argument run().\n */\nexport type RunInvocation =\n | { readonly kind: 'default' }\n | { readonly kind: 'fragment'; readonly db?: RunDatabase | string; readonly fragment: SqlFragment }\n | { readonly kind: 'params'; readonly db?: RunDatabase | string; readonly params: object }\n | { readonly kind: 'db'; readonly db: RunDatabase | string };\n\n/**\n * Type-level guard for run(db) with a name: a string containing whitespace is\n * SQL text, never a database name. Build statements with the sql`` tag.\n */\nexport type RejectSqlText<D> = D extends string\n ? D extends `${string} ${string}` | `${string}\\n${string}` | `${string}\\t${string}`\n ? never\n : unknown\n : unknown;\n\n/**\n * Per-invocation context established by the @Query wrapper before the method\n * body executes. `execute` performs the full query pipeline (resolve SQL,\n * bind, execute, shape/transform/validate); `ran` records that the body\n * invoked run(), so the wrapper returns the body's result verbatim instead\n * of falling through to the legacy pipeline. `invocations` marks a wrapper\n * that understands the argument-taking run forms (an older duplicated copy\n * of the decorator would silently ignore them).\n */\nexport type RunContext = {\n execute: (invocation?: RunInvocation) => Promise<unknown>;\n ran: boolean;\n invocations?: true;\n};\n\n// Anchored on globalThis via Symbol.for so duplicated module instances\n// (npm link, dual ESM/CJS loads) share one channel between the decorator\n// and the run() the application imports.\nconst RUN_CHANNEL = Symbol.for('noego.sqlstack.runContext');\nconst anchor = globalThis as Record<PropertyKey, unknown>;\nif (!anchor[RUN_CHANNEL]) {\n anchor[RUN_CHANNEL] = new AsyncLocalStorage<RunContext>();\n}\nexport const runStorage = anchor[RUN_CHANNEL] as AsyncLocalStorage<RunContext>;\n\n/**\n * Execute the current @Query method's SQL and return the finished result.\n * Call it as the body of a @Query-decorated method:\n *\n * @Query()\n * async getUsers(active: boolean): Promise<User[]> {\n * return run();\n * }\n *\n * Takes no arguments — the method's own arguments, database, SQL source,\n * transaction, shaping, transform, and validation all come from the\n * decorator context — except that a leading method argument that is a\n * database handle (or a registered database name) selects the database and\n * is not bound. T is inferred from the method's declared return type.\n *\n * @throws {DatabaseError} When the driver rejects the statement (original\n * error in `.cause`).\n * @throws {SqlStackError} When called outside a @Query method, or for\n * shape/validation failures (ExactlyOneRowError, NoRowsError, ValidationError, ...).\n */\nexport function run<T = any>(): Promise<T>;\n/**\n * Inside a @Query method: execute this inline sql`` fragment instead of the\n * method's SQL file. The database comes from the method/class/registry\n * context (`@Query({ db })`, `@QueryBinder({ db })`, the default), the\n * active transaction on it is joined, and the method's shape/transform/\n * validation decorators apply. The method's arguments are not auto-bound —\n * the fragment's `${}` values are the parameters.\n *\n * @Single @Query()\n * async byEmail(email: string): Promise<User | null> {\n * return run(sql`SELECT * FROM users WHERE email = ${email}`);\n * }\n *\n * @throws {DatabaseError} When the fragment cannot be compiled (macro input\n * errors), the database cannot be resolved, or the driver rejects the\n * statement. The original error is in `.cause`.\n * @throws {SqlStackError} When called outside a @Query method (use\n * `run(db, query)` there), or for shape/validation failures.\n */\nexport function run<T = unknown>(query: SqlFragment): Promise<T>;\n/**\n * Execute an sql`` fragment against an explicit database: a handle\n * (anything with `query(sql, params)`) or the name of a database registered\n * with the active SqlStack / legacy registry. Usable anywhere.\n *\n * Binds for the database's dialect (`$1..` for Postgres, `?` otherwise;\n * default sqlite). Joins an active transaction opened on the same database\n * (same registered handle, or same name). Outside a @Query method the raw\n * result is returned (rows array, or `{ rowsAffected }` for writes); inside\n * one, the method's shape/transform/validation decorators apply.\n *\n * const rows = await run<Row[]>(accountsDb, sql`SELECT * FROM t WHERE id = ${id}`);\n *\n * @throws {DatabaseError} When the fragment cannot be compiled, a named\n * database cannot be resolved, or the driver rejects the statement. The\n * original error is in `.cause`, and its string `code` is copied to `.code`.\n * @throws {SqlStackError} For invalid arguments, or shape/validation failures.\n */\nexport function run<T = unknown>(db: RunDatabase | string, query: SqlFragment): Promise<T>;\n/**\n * Inside a @Query method: run the method's own SQL (its .sql file or inline\n * `@Query({ sql })`) against `db`, binding `params` (an object for `:named`\n * placeholders, an array for `:arg1..`). The method's raw arguments are NOT\n * auto-bound in this form — `params` is the whole binding input. @Defaults,\n * @Page, shaping, transform, and validation still apply.\n *\n * @Single @Query()\n * async byEmail(db: Database, p: { email: string }): Promise<User | null> {\n * return run(db, p);\n * }\n *\n * @throws {DatabaseError} When binding fails, a named database cannot be\n * resolved, or the driver rejects the statement. The original error is in\n * `.cause`.\n * @throws {SqlStackError} When called outside a @Query method, when passed\n * `.toSQL()` output, or for shape/validation failures.\n */\nexport function run<T = unknown, P extends object = object>(\n db: RunDatabase | string,\n params: P & RejectCompiledSql<P>\n): Promise<T>;\n/**\n * Inside a @Query method: run the method's own SQL against `db` (a handle or\n * a registered database name), binding the method's own arguments exactly as\n * run() does — except that a leading database handle/name argument of the\n * method is never bound.\n *\n * @throws {DatabaseError} When binding fails, a named database cannot be\n * resolved, or the driver rejects the statement.\n * @throws {SqlStackError} When called outside a @Query method, or for\n * shape/validation failures.\n */\nexport function run<T = unknown, D extends RunDatabase | string = RunDatabase | string>(\n db: D & RejectSqlText<D>\n): Promise<T>;\n/**\n * Inside a @Query method: run the method's own SQL binding only `params` (an\n * object for `:named`, an array for `:argN`) against the database run() would\n * use: the method's leading database handle/name argument, else the\n * decorator context.\n *\n * @throws {DatabaseError} When binding fails, the database cannot be\n * resolved, or the driver rejects the statement.\n * @throws {SqlStackError} When called outside a @Query method, when passed\n * `.toSQL()` output, or for shape/validation failures.\n */\nexport function run<T = unknown, P extends object = object>(params: P & RejectCompiledSql<P>): Promise<T>;\nexport async function run(...args: unknown[]): Promise<unknown> {\n const invocation = parseRunArgs(args);\n const ctx = runStorage.getStore();\n\n if (!ctx) {\n if (invocation.kind === 'fragment' && invocation.db !== undefined) {\n return executeFragment(invocation.db, invocation.fragment);\n }\n if (invocation.kind === 'default') {\n throw new SqlStackError(\n 'run() called outside a @Query method. It may only be invoked from the body of a @Query-decorated method.'\n );\n }\n if (invocation.kind === 'fragment') {\n throw new SqlStackError(\n 'run(query) called outside a @Query method has no database. Pass one explicitly: run(db, query).'\n );\n }\n if (invocation.kind === 'db') {\n throw new SqlStackError(\n 'run(db) called outside a @Query method has no SQL source. Pass an sql`` fragment instead: run(db, sql`...`).'\n );\n }\n if (invocation.db === undefined) {\n throw new SqlStackError(\n 'run(params) called outside a @Query method has no SQL source or database. ' +\n 'Pass a database and an sql`` fragment instead: run(db, sql`...`).'\n );\n }\n throw new SqlStackError(\n 'run(db, params) called outside a @Query method has no SQL source. ' +\n 'Pass an sql`` fragment instead: run(db, sql`...`).'\n );\n }\n\n if (invocation.kind !== 'default' && !ctx.invocations) {\n throw new SqlStackError(\n 'run(...) with arguments reached a @Query wrapper from an older sqlstack copy that cannot honour them. ' +\n 'Make sure a single sqlstack version is installed.'\n );\n }\n\n ctx.ran = true;\n return invocation.kind === 'default' ? ctx.execute() : ctx.execute(invocation);\n}\n\nfunction parseRunArgs(args: unknown[]): RunInvocation {\n if (args.length === 0) return { kind: 'default' };\n\n if (args.length === 1) {\n const [query] = args;\n if (isSqlFragment(query)) return { kind: 'fragment', fragment: query };\n if (typeof query === 'string') {\n // A whitespace-free string is a database name: run(db).\n if (isDatabaseNameText(query)) return { kind: 'db', db: query };\n throw new SqlStackError(\n 'run(query) does not accept SQL strings. Build the statement with the sql`` tag: run(sql`...`).'\n );\n }\n if (isRunDatabaseHandle(query)) return { kind: 'db', db: query };\n if (isCompiledSql(query)) {\n throw new SqlStackError(\n 'run(...) received the { sql, params } output of .toSQL(). Pass the sql`` fragment itself so run can ' +\n 'bind it for the target dialect: run(sql`...`).'\n );\n }\n if (typeof query === 'object' && query !== null) return { kind: 'params', params: query };\n throw new SqlStackError(\n 'run(x) requires an sql`` fragment, a params object/array, or a database handle/name.'\n );\n }\n\n if (args.length === 2) {\n const [db, second] = args;\n assertRunDatabase(db);\n if (isSqlFragment(second)) return { kind: 'fragment', db, fragment: second };\n if (typeof second === 'string') {\n throw new SqlStackError(\n 'run(db, query) does not accept SQL strings. Build the statement with the sql`` tag: run(db, sql`...`).'\n );\n }\n if (isCompiledSql(second)) {\n throw new SqlStackError(\n 'run(db, ...) received the { sql, params } output of .toSQL(). Pass the sql`` fragment itself so run can ' +\n 'bind it for the target dialect: run(db, sql`...`).'\n );\n }\n if (typeof second === 'object' && second !== null) return { kind: 'params', db, params: second };\n throw new SqlStackError('run(db, x) requires an sql`` fragment or a params object/array as its second argument.');\n }\n\n throw new SqlStackError(`run() accepts at most 2 arguments, got ${args.length}.`);\n}\n\n/** @internal A database handle: any object exposing query(sql, params). */\nexport function isRunDatabaseHandle(value: unknown): value is RunDatabase {\n return typeof value === 'object' && value !== null && typeof (value as { query?: unknown }).query === 'function';\n}\n\nfunction isDatabaseNameText(value: string): boolean {\n return value.length > 0 && !/\\s/.test(value);\n}\n\nfunction assertRunDatabase(db: unknown): asserts db is RunDatabase | string {\n if (typeof db === 'string' && db.length > 0) return;\n if (typeof db === 'object' && db !== null && typeof (db as { query?: unknown }).query === 'function') return;\n throw new SqlStackError(\n 'run(db, ...) requires a database handle with query(sql, params) or a registered database name as its first argument.'\n );\n}\n\nfunction isCompiledSql(value: unknown): boolean {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;\n const keys = Object.keys(value);\n const rec = value as { sql?: unknown; params?: unknown };\n return keys.length === 2 && typeof rec.sql === 'string' && Array.isArray(rec.params);\n}\n\n// ---------------------------------------------------------------------------\n// Shared execution helpers (also used by the @Query wrapper)\n// ---------------------------------------------------------------------------\n\n/** @internal A database chosen for one run, plus the transaction it joins. */\nexport type RunTarget = {\n readonly db: RunDatabase;\n readonly tx: ActiveTransaction | undefined;\n /** SQL resolver of the environment, when the target was resolved by name. */\n readonly resolver: SqlResolver | undefined;\n readonly byName: boolean;\n};\n\n/**\n * @internal Resolve run's database argument. A name goes through the active\n * SqlStack (or legacy registry) and joins that entry's transaction — or,\n * inside a @transaction scope with none open, opens one on first execution. A handle\n * is used as-is — no registry lookup, so it works without any SqlStack — and\n * behaves the same: it joins a transaction open in this flow on that same\n * object, or, inside a @transaction scope with none open, opens one on the\n * handle on first execution. Outside any scope a handle with no open\n * transaction runs directly.\n */\nexport async function resolveRunTarget(db: RunDatabase | string): Promise<RunTarget> {\n if (typeof db === 'string') {\n const { entry, resolver } = await resolveExecution(db);\n return { db: entry.db, tx: getTransactionTarget(entry), resolver, byName: true };\n }\n return { db, tx: getTransactionTargetForHandle(db), resolver: undefined, byName: false };\n}\n\n/** @internal Run one bound statement on the target (inside its transaction, if any). */\nexport async function executeOnTarget(target: RunTarget, boundSql: string, params: unknown[]): Promise<unknown> {\n try {\n return target.tx ? await target.tx.query(boundSql, params) : await target.db.query(boundSql, params);\n } catch (dbError) {\n throw toDatabaseError(dbError, boundSql);\n }\n}\n\n/**\n * @internal Normalize a failure from run's argument-taking forms: errors that\n * are already SqlStackError (DatabaseError, shape/validation errors) pass\n * through; anything else becomes DatabaseError with the original in `.cause`.\n */\nexport function toRunError(err: unknown, sqlText: string): SqlStackError {\n return err instanceof SqlStackError ? err : toDatabaseError(err, sqlText);\n}\n\nfunction toDatabaseError(err: unknown, sqlText: string): DatabaseError {\n const message = (err as { message?: unknown } | undefined)?.message;\n return new DatabaseError(\n typeof message === 'string' && message ? message : String(err),\n sqlText,\n err instanceof Error ? err : undefined\n );\n}\n\n/** @internal Raw template text of a fragment, for error messages. */\nexport function fragmentText(fragment: SqlFragment): string {\n return fragment.strings.join('?');\n}\n\n/** @internal Compile a fragment for the dialect, wrapping macro errors. */\nexport function compileForRun(fragment: SqlFragment, dialect: Dialect): { sql: string; params: unknown[] } {\n try {\n return compileFragment(fragment, dialect);\n } catch (err) {\n throw toRunError(err, fragmentText(fragment));\n }\n}\n\nasync function executeFragment(db: RunDatabase | string, fragment: SqlFragment): Promise<unknown> {\n let target: RunTarget;\n try {\n target = await resolveRunTarget(db);\n } catch (err) {\n throw toRunError(err, fragmentText(fragment));\n }\n const { sql: boundSql, params } = compileForRun(fragment, target.db.dialect ?? 'sqlite');\n return executeOnTarget(target, boundSql, params);\n}\n"]}
1
+ {"version":3,"file":"run.js","sourceRoot":"","sources":["../../src/run.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAE7D,OAAO,EAAe,aAAa,EAAE,eAAe,EAAE,MAAM,OAAO,CAAC;AACpE,OAAO,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAE7C,OAAO,EAAE,oBAAoB,EAAE,6BAA6B,EAAE,MAAM,gBAAgB,CAAC;AA0DrF,uEAAuE;AACvE,yEAAyE;AACzE,yCAAyC;AACzC,MAAM,WAAW,GAAG,MAAM,CAAC,GAAG,CAAC,2BAA2B,CAAC,CAAC;AAC5D,MAAM,MAAM,GAAG,UAA0C,CAAC;AAC1D,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,EAAE,CAAC;IACzB,MAAM,CAAC,WAAW,CAAC,GAAG,IAAI,iBAAiB,EAAc,CAAC;AAC5D,CAAC;AACD,MAAM,CAAC,MAAM,UAAU,GAAG,MAAM,CAAC,WAAW,CAAkC,CAAC;AA8G/E,MAAM,CAAC,KAAK,UAAU,GAAG,CAAC,GAAG,IAAe;IAC1C,MAAM,UAAU,GAAG,YAAY,CAAC,IAAI,CAAC,CAAC;IACtC,MAAM,GAAG,GAAG,UAAU,CAAC,QAAQ,EAAE,CAAC;IAElC,IAAI,CAAC,GAAG,EAAE,CAAC;QACT,IAAI,UAAU,CAAC,IAAI,KAAK,UAAU,IAAI,UAAU,CAAC,EAAE,KAAK,SAAS,EAAE,CAAC;YAClE,OAAO,eAAe,CAAC,UAAU,CAAC,EAAE,EAAE,UAAU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CAAC;IACtC,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,MAAM,UAAU,CAAC,GAAG,EAAE,YAAY,CAAC,QAAQ,CAAC,CAAC,CAAC;IAChD,CAAC;IACD,MAAM,EAAE,GAAG,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,aAAa,CAAC,QAAQ,EAAE,MAAM,CAAC,EAAE,CAAC,OAAO,IAAI,QAAQ,CAAC,CAAC;IACzF,OAAO,eAAe,CAAC,MAAM,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC;AACnD,CAAC","sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\nimport { SqlStackError, DatabaseError } from './core/errors';\nimport type { Dialect } from './registry';\nimport { SqlFragment, isSqlFragment, compileFragment } from './sql';\nimport { resolveExecution } from './runtime';\nimport type { SqlResolver } from './core/resolver';\nimport { getTransactionTarget, getTransactionTargetForHandle } from './transactions';\nimport type { ActiveTransaction } from './transactions';\n\n/**\n * Anything run(db, ...) can execute against: sqlstack's own `Database`\n * (from createSqliteDb/createPgDb/createMysqlDb), or any application handle\n * exposing `query(sql, params)`. `dialect` selects placeholder style and\n * defaults to `'sqlite'` when absent. run never opens databases by path.\n */\nexport interface RunDatabase {\n readonly dialect?: Dialect;\n query(sql: string, params: unknown[]): Promise<unknown>;\n}\n\n/**\n * Type-level guard for the params form of run: rejects the\n * `{ sql, params }` object returned by `fragment.toSQL()`. Pass the sql``\n * fragment itself instead, so run owns dialect binding and error handling.\n */\nexport type RejectCompiledSql<P> = P extends { readonly sql: string; readonly params: readonly unknown[] }\n ? never\n : unknown;\n\n/**\n * What a run(...) call made inside a @Query body asks of the wrapper's\n * pipeline. `default` is the zero-argument run().\n */\nexport type RunInvocation =\n | { readonly kind: 'default' }\n | { readonly kind: 'fragment'; readonly db?: RunDatabase | string; readonly fragment: SqlFragment }\n | { readonly kind: 'params'; readonly db?: RunDatabase | string; readonly params: object }\n | { readonly kind: 'db'; readonly db: RunDatabase | string };\n\n/**\n * Type-level guard for run(db) with a name: a string containing whitespace is\n * SQL text, never a database name. Build statements with the sql`` tag.\n */\nexport type RejectSqlText<D> = D extends string\n ? D extends `${string} ${string}` | `${string}\\n${string}` | `${string}\\t${string}`\n ? never\n : unknown\n : unknown;\n\n/**\n * Per-invocation context established by the @Query wrapper before the method\n * body executes. `execute` performs the full query pipeline (resolve SQL,\n * bind, execute, shape/transform/validate); `ran` records that the body\n * invoked run(), so the wrapper returns the body's result verbatim instead\n * of falling through to the legacy pipeline. `invocations` marks a wrapper\n * that understands the argument-taking run forms (an older duplicated copy\n * of the decorator would silently ignore them).\n */\nexport type RunContext = {\n execute: (invocation?: RunInvocation) => Promise<unknown>;\n ran: boolean;\n invocations?: true;\n};\n\n// Anchored on globalThis via Symbol.for so duplicated module instances\n// (npm link, dual ESM/CJS loads) share one channel between the decorator\n// and the run() the application imports.\nconst RUN_CHANNEL = Symbol.for('noego.sqlstack.runContext');\nconst anchor = globalThis as Record<PropertyKey, unknown>;\nif (!anchor[RUN_CHANNEL]) {\n anchor[RUN_CHANNEL] = new AsyncLocalStorage<RunContext>();\n}\nexport const runStorage = anchor[RUN_CHANNEL] as AsyncLocalStorage<RunContext>;\n\n/**\n * Execute the current @Query method's SQL and return the finished result.\n * Call it as the body of a @Query-decorated method:\n *\n * @Query()\n * async getUsers(active: boolean): Promise<User[]> {\n * return run();\n * }\n *\n * Takes no arguments — the method's own arguments, database, SQL source,\n * transaction, shaping, transform, and validation all come from the\n * decorator context — except that a leading method argument that is a\n * database handle (or a registered database name) selects the database and\n * is not bound. T is inferred from the method's declared return type.\n *\n * @throws {DatabaseError} When the driver rejects the statement (original\n * error in `.cause`).\n * @throws {SqlStackError} When called outside a @Query method, or for\n * shape/validation failures (ExactlyOneRowError, NoRowsError, ValidationError, ...).\n */\nexport function run<T = any>(): Promise<T>;\n/**\n * Inside a @Query method: execute this inline sql`` fragment instead of the\n * method's SQL file. The database comes from the method/class/registry\n * context (`@Query({ db })`, `@QueryBinder({ db })`, the default), the\n * active transaction on it is joined, and the method's shape/transform/\n * validation decorators apply. The method's arguments are not auto-bound —\n * the fragment's `${}` values are the parameters.\n *\n * @Single @Query()\n * async byEmail(email: string): Promise<User | null> {\n * return run(sql`SELECT * FROM users WHERE email = ${email}`);\n * }\n *\n * @throws {DatabaseError} When the fragment cannot be compiled (macro input\n * errors), the database cannot be resolved, or the driver rejects the\n * statement. The original error is in `.cause`.\n * @throws {SqlStackError} When called outside a @Query method (use\n * `run(db, query)` there), or for shape/validation failures.\n */\nexport function run<T = unknown>(query: SqlFragment): Promise<T>;\n/**\n * Execute an sql`` fragment against an explicit database: a handle\n * (anything with `query(sql, params)`) or the name of a database registered\n * with the active SqlStack / legacy registry. Usable anywhere.\n *\n * Binds for the database's dialect (`$1..` for Postgres, `?` otherwise;\n * default sqlite). Joins an active transaction opened on the same database\n * (same registered handle, or same name). Outside a @Query method the raw\n * result is returned (rows array, or `{ rowsAffected }` for writes); inside\n * one, the method's shape/transform/validation decorators apply.\n *\n * const rows = await run<Row[]>(accountsDb, sql`SELECT * FROM t WHERE id = ${id}`);\n *\n * @throws {DatabaseError} When the fragment cannot be compiled, a named\n * database cannot be resolved, or the driver rejects the statement. The\n * original error is in `.cause`, and its string `code` is copied to `.code`.\n * @throws {SqlStackError} For invalid arguments, or shape/validation failures.\n */\nexport function run<T = unknown>(db: RunDatabase | string, query: SqlFragment): Promise<T>;\n/**\n * Inside a @Query method: run the method's own SQL (its .sql file or inline\n * `@Query({ sql })`) against `db`, binding `params` (an object for `:named`\n * placeholders, an array for `:arg1..`). The method's raw arguments are NOT\n * auto-bound in this form — `params` is the whole binding input. @Defaults,\n * @Page, shaping, transform, and validation still apply.\n *\n * @Single @Query()\n * async byEmail(db: Database, p: { email: string }): Promise<User | null> {\n * return run(db, p);\n * }\n *\n * @throws {DatabaseError} When binding fails, a named database cannot be\n * resolved, or the driver rejects the statement. The original error is in\n * `.cause`.\n * @throws {SqlStackError} When called outside a @Query method, when passed\n * `.toSQL()` output, or for shape/validation failures.\n */\nexport function run<T = unknown, P extends object = object>(\n db: RunDatabase | string,\n params: P & RejectCompiledSql<P>\n): Promise<T>;\n/**\n * Inside a @Query method: run the method's own SQL against `db` (a handle or\n * a registered database name), binding the method's own arguments exactly as\n * run() does — except that a leading database handle/name argument of the\n * method is never bound.\n *\n * @throws {DatabaseError} When binding fails, a named database cannot be\n * resolved, or the driver rejects the statement.\n * @throws {SqlStackError} When called outside a @Query method, or for\n * shape/validation failures.\n */\nexport function run<T = unknown, D extends RunDatabase | string = RunDatabase | string>(\n db: D & RejectSqlText<D>\n): Promise<T>;\n/**\n * Inside a @Query method: run the method's own SQL binding only `params` (an\n * object for `:named`, an array for `:argN`) against the database run() would\n * use: the method's leading database handle/name argument, else the\n * decorator context.\n *\n * @throws {DatabaseError} When binding fails, the database cannot be\n * resolved, or the driver rejects the statement.\n * @throws {SqlStackError} When called outside a @Query method, when passed\n * `.toSQL()` output, or for shape/validation failures.\n */\nexport function run<T = unknown, P extends object = object>(params: P & RejectCompiledSql<P>): Promise<T>;\nexport async function run(...args: unknown[]): Promise<unknown> {\n const invocation = parseRunArgs(args);\n const ctx = runStorage.getStore();\n\n if (!ctx) {\n if (invocation.kind === 'fragment' && invocation.db !== undefined) {\n return executeFragment(invocation.db, invocation.fragment);\n }\n if (invocation.kind === 'default') {\n throw new SqlStackError(\n 'run() called outside a @Query method. It may only be invoked from the body of a @Query-decorated method.'\n );\n }\n if (invocation.kind === 'fragment') {\n throw new SqlStackError(\n 'run(query) called outside a @Query method has no database. Pass one explicitly: run(db, query).'\n );\n }\n if (invocation.kind === 'db') {\n throw new SqlStackError(\n 'run(db) called outside a @Query method has no SQL source. Pass an sql`` fragment instead: run(db, sql`...`).'\n );\n }\n if (invocation.db === undefined) {\n throw new SqlStackError(\n 'run(params) called outside a @Query method has no SQL source or database. ' +\n 'Pass a database and an sql`` fragment instead: run(db, sql`...`).'\n );\n }\n throw new SqlStackError(\n 'run(db, params) called outside a @Query method has no SQL source. ' +\n 'Pass an sql`` fragment instead: run(db, sql`...`).'\n );\n }\n\n if (invocation.kind !== 'default' && !ctx.invocations) {\n throw new SqlStackError(\n 'run(...) with arguments reached a @Query wrapper from an older sqlstack copy that cannot honour them. ' +\n 'Make sure a single sqlstack version is installed.'\n );\n }\n\n ctx.ran = true;\n return invocation.kind === 'default' ? ctx.execute() : ctx.execute(invocation);\n}\n\nfunction parseRunArgs(args: unknown[]): RunInvocation {\n if (args.length === 0) return { kind: 'default' };\n\n if (args.length === 1) {\n const [query] = args;\n if (isSqlFragment(query)) return { kind: 'fragment', fragment: query };\n if (typeof query === 'string') {\n // A whitespace-free string is a database name: run(db).\n if (isDatabaseNameText(query)) return { kind: 'db', db: query };\n throw new SqlStackError(\n 'run(query) does not accept SQL strings. Build the statement with the sql`` tag: run(sql`...`).'\n );\n }\n if (isRunDatabaseHandle(query)) return { kind: 'db', db: query };\n if (isCompiledSql(query)) {\n throw new SqlStackError(\n 'run(...) received the { sql, params } output of .toSQL(). Pass the sql`` fragment itself so run can ' +\n 'bind it for the target dialect: run(sql`...`).'\n );\n }\n if (typeof query === 'object' && query !== null) return { kind: 'params', params: query };\n throw new SqlStackError(\n 'run(x) requires an sql`` fragment, a params object/array, or a database handle/name.'\n );\n }\n\n if (args.length === 2) {\n const [db, second] = args;\n assertRunDatabase(db);\n if (isSqlFragment(second)) return { kind: 'fragment', db, fragment: second };\n if (typeof second === 'string') {\n throw new SqlStackError(\n 'run(db, query) does not accept SQL strings. Build the statement with the sql`` tag: run(db, sql`...`).'\n );\n }\n if (isCompiledSql(second)) {\n throw new SqlStackError(\n 'run(db, ...) received the { sql, params } output of .toSQL(). Pass the sql`` fragment itself so run can ' +\n 'bind it for the target dialect: run(db, sql`...`).'\n );\n }\n if (typeof second === 'object' && second !== null) return { kind: 'params', db, params: second };\n throw new SqlStackError('run(db, x) requires an sql`` fragment or a params object/array as its second argument.');\n }\n\n throw new SqlStackError(`run() accepts at most 2 arguments, got ${args.length}.`);\n}\n\n/** @internal A database handle: any object exposing query(sql, params). */\nexport function isRunDatabaseHandle(value: unknown): value is RunDatabase {\n return typeof value === 'object' && value !== null && typeof (value as { query?: unknown }).query === 'function';\n}\n\nfunction isDatabaseNameText(value: string): boolean {\n return value.length > 0 && !/\\s/.test(value);\n}\n\nfunction assertRunDatabase(db: unknown): asserts db is RunDatabase | string {\n if (typeof db === 'string' && db.length > 0) return;\n if (typeof db === 'object' && db !== null && typeof (db as { query?: unknown }).query === 'function') return;\n throw new SqlStackError(\n 'run(db, ...) requires a database handle with query(sql, params) or a registered database name as its first argument.'\n );\n}\n\nfunction isCompiledSql(value: unknown): boolean {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;\n const keys = Object.keys(value);\n const rec = value as { sql?: unknown; params?: unknown };\n return keys.length === 2 && typeof rec.sql === 'string' && Array.isArray(rec.params);\n}\n\n// ---------------------------------------------------------------------------\n// Shared execution helpers (also used by the @Query wrapper)\n// ---------------------------------------------------------------------------\n\n/** @internal A database chosen for one run, plus the transaction it joins. */\nexport type RunTarget = {\n readonly db: RunDatabase;\n readonly tx: ActiveTransaction | undefined;\n /** SQL resolver of the environment, when the target was resolved by name. */\n readonly resolver: SqlResolver | undefined;\n readonly byName: boolean;\n};\n\n/**\n * @internal Resolve run's database argument. A name goes through the active\n * SqlStack (or legacy registry) and joins that entry's transaction — or,\n * inside a @transaction scope with none open, opens one on first execution. A handle\n * is used as-is — no registry lookup, so it works without any SqlStack — and\n * behaves the same: it joins a transaction open in this flow on that same\n * object, or, inside a @transaction scope with none open, opens one on the\n * handle on first execution. Outside any scope a handle with no open\n * transaction runs directly.\n */\nexport async function resolveRunTarget(db: RunDatabase | string): Promise<RunTarget> {\n if (typeof db === 'string') {\n const { entry, resolver } = await resolveExecution(db);\n return { db: entry.db, tx: getTransactionTarget(entry), resolver, byName: true };\n }\n return { db, tx: getTransactionTargetForHandle(db), resolver: undefined, byName: false };\n}\n\n/** @internal Run one bound statement on the target (inside its transaction, if any). */\nexport async function executeOnTarget(target: RunTarget, boundSql: string, params: unknown[]): Promise<unknown> {\n try {\n return target.tx ? await target.tx.query(boundSql, params) : await target.db.query(boundSql, params);\n } catch (dbError) {\n throw toDatabaseError(dbError, boundSql);\n }\n}\n\n/**\n * @internal Normalize a failure from run's argument-taking forms: errors that\n * are already SqlStackError (DatabaseError, shape/validation errors) pass\n * through; anything else becomes DatabaseError with the original in `.cause`.\n */\nexport function toRunError(err: unknown, sqlText: string): SqlStackError {\n return err instanceof SqlStackError ? err : toDatabaseError(err, sqlText);\n}\n\nfunction toDatabaseError(err: unknown, sqlText: string): DatabaseError {\n const message = (err as { message?: unknown } | undefined)?.message;\n return new DatabaseError(\n typeof message === 'string' && message ? message : String(err),\n sqlText,\n isErrorLike(err) ? err : undefined\n );\n}\n\n/**\n * better-sqlite3 binds its SqliteError class once per process. When several\n * realms share that process (vm contexts, e.g. jest --runInBand, which is\n * jest's default on a single CPU), driver errors are Error subclasses of the\n * first realm only: `instanceof Error` is false elsewhere and they carry no\n * [[ErrorData]] slot. Recognise them by shape so `.cause`/`.code` survive.\n *\n * @internal Shared with decorators/query.ts.\n */\nexport function isErrorLike(err: unknown): err is Error {\n if (err instanceof Error) return true;\n if (typeof err !== 'object' || err === null) return false;\n const candidate = err as { message?: unknown; stack?: unknown };\n return typeof candidate.message === 'string' && typeof candidate.stack === 'string';\n}\n\n/** @internal Raw template text of a fragment, for error messages. */\nexport function fragmentText(fragment: SqlFragment): string {\n return fragment.strings.join('?');\n}\n\n/** @internal Compile a fragment for the dialect, wrapping macro errors. */\nexport function compileForRun(fragment: SqlFragment, dialect: Dialect): { sql: string; params: unknown[] } {\n try {\n return compileFragment(fragment, dialect);\n } catch (err) {\n throw toRunError(err, fragmentText(fragment));\n }\n}\n\nasync function executeFragment(db: RunDatabase | string, fragment: SqlFragment): Promise<unknown> {\n let target: RunTarget;\n try {\n target = await resolveRunTarget(db);\n } catch (err) {\n throw toRunError(err, fragmentText(fragment));\n }\n const { sql: boundSql, params } = compileForRun(fragment, target.db.dialect ?? 'sqlite');\n return executeOnTarget(target, boundSql, params);\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sqlstack",
3
- "version": "3.7.0",
3
+ "version": "3.7.1",
4
4
  "description": "",
5
5
  "license": "ISC",
6
6
  "author": "",