@hypequery/cli 1.1.2 → 1.2.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.
Files changed (74) hide show
  1. package/README.md +26 -2
  2. package/dist/bin/cli.js +21 -81
  3. package/dist/cli.d.ts.map +1 -1
  4. package/dist/cli.js +72 -116
  5. package/dist/commands/dev.d.ts +1 -0
  6. package/dist/commands/dev.d.ts.map +1 -1
  7. package/dist/commands/dev.js +180 -255
  8. package/dist/commands/generate-datasets.d.ts +14 -0
  9. package/dist/commands/generate-datasets.d.ts.map +1 -0
  10. package/dist/commands/generate-datasets.js +96 -0
  11. package/dist/commands/generate.d.ts +2 -0
  12. package/dist/commands/generate.d.ts.map +1 -1
  13. package/dist/commands/generate.js +112 -167
  14. package/dist/commands/init.d.ts +7 -0
  15. package/dist/commands/init.d.ts.map +1 -1
  16. package/dist/commands/init.js +337 -370
  17. package/dist/generators/clickhouse.d.ts +1 -1
  18. package/dist/generators/clickhouse.d.ts.map +1 -1
  19. package/dist/generators/clickhouse.js +10 -269
  20. package/dist/generators/dataset-generator.d.ts +16 -0
  21. package/dist/generators/dataset-generator.d.ts.map +1 -0
  22. package/dist/generators/dataset-generator.js +246 -0
  23. package/dist/generators/index.js +3 -3
  24. package/dist/templates/api.d.ts +9 -0
  25. package/dist/templates/api.d.ts.map +1 -0
  26. package/dist/templates/api.js +26 -0
  27. package/dist/templates/auth-scaffold.d.ts +17 -0
  28. package/dist/templates/auth-scaffold.d.ts.map +1 -0
  29. package/dist/templates/auth-scaffold.js +41 -0
  30. package/dist/templates/client.js +10 -1
  31. package/dist/templates/datasets.d.ts +5 -0
  32. package/dist/templates/datasets.d.ts.map +1 -0
  33. package/dist/templates/datasets.js +23 -0
  34. package/dist/templates/env.js +19 -8
  35. package/dist/templates/gitignore.js +4 -1
  36. package/dist/templates/queries.d.ts +3 -0
  37. package/dist/templates/queries.d.ts.map +1 -1
  38. package/dist/templates/queries.js +66 -10
  39. package/dist/test-utils.d.ts +0 -71
  40. package/dist/test-utils.d.ts.map +1 -1
  41. package/dist/test-utils.js +12 -137
  42. package/dist/utils/clickhouse-client.js +10 -57
  43. package/dist/utils/clickhouse-sql.d.ts +6 -0
  44. package/dist/utils/clickhouse-sql.d.ts.map +1 -0
  45. package/dist/utils/clickhouse-sql.js +18 -0
  46. package/dist/utils/clickhouse-type-utils.d.ts +6 -0
  47. package/dist/utils/clickhouse-type-utils.d.ts.map +1 -0
  48. package/dist/utils/clickhouse-type-utils.js +59 -0
  49. package/dist/utils/dependency-installer.d.ts +4 -2
  50. package/dist/utils/dependency-installer.d.ts.map +1 -1
  51. package/dist/utils/dependency-installer.js +93 -170
  52. package/dist/utils/detect-database.js +84 -195
  53. package/dist/utils/find-files.d.ts +3 -1
  54. package/dist/utils/find-files.d.ts.map +1 -1
  55. package/dist/utils/find-files.js +82 -148
  56. package/dist/utils/load-api.d.ts.map +1 -1
  57. package/dist/utils/load-api.js +207 -396
  58. package/dist/utils/logger.js +38 -42
  59. package/dist/utils/prompts.d.ts +14 -0
  60. package/dist/utils/prompts.d.ts.map +1 -1
  61. package/dist/utils/prompts.js +170 -219
  62. package/dist/utils/runtime-guards.d.ts +4 -0
  63. package/dist/utils/runtime-guards.d.ts.map +1 -0
  64. package/dist/utils/runtime-guards.js +9 -0
  65. package/dist/utils/sha256.d.ts +2 -0
  66. package/dist/utils/sha256.d.ts.map +1 -0
  67. package/dist/utils/sha256.js +4 -0
  68. package/package.json +3 -8
  69. package/dist/utils/error-messages.d.ts +0 -6
  70. package/dist/utils/error-messages.d.ts.map +0 -1
  71. package/dist/utils/error-messages.js +0 -19
  72. package/dist/utils/load-hypequery-config.d.ts +0 -7
  73. package/dist/utils/load-hypequery-config.d.ts.map +0 -1
  74. package/dist/utils/load-hypequery-config.js +0 -89
@@ -1,40 +1,3 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
- var __generator = (this && this.__generator) || function (thisArg, body) {
11
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
12
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
13
- function verb(n) { return function (v) { return step([n, v]); }; }
14
- function step(op) {
15
- if (f) throw new TypeError("Generator is already executing.");
16
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
17
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
18
- if (y = 0, t) op = [op[0] & 2, t.value];
19
- switch (op[0]) {
20
- case 0: case 1: t = op; break;
21
- case 4: _.label++; return { value: op[1], done: false };
22
- case 5: _.label++; y = op[1]; op = [0]; continue;
23
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
24
- default:
25
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
26
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
27
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
28
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
29
- if (t[2]) _.ops.pop();
30
- _.trys.pop(); continue;
31
- }
32
- op = body.call(thisArg, _);
33
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
34
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
35
- }
36
- };
37
- var _a, _b, _c, _d;
38
1
  import { pathToFileURL } from 'node:url';
39
2
  import { access, mkdtemp, rm, mkdir, writeFile } from 'node:fs/promises';
40
3
  import os from 'node:os';
@@ -43,129 +6,96 @@ import { build } from 'esbuild';
43
6
  if (typeof process.setMaxListeners === 'function') {
44
7
  process.setMaxListeners(0);
45
8
  }
46
- var TYPESCRIPT_EXTENSIONS = new Set(['.ts', '.tsx', '.mts', '.cts']);
47
- var tsconfigCache = new Map();
48
- export function loadApiModule(modulePath) {
49
- return __awaiter(this, void 0, void 0, function () {
50
- var resolved, mod, error_1, relativePath, api, relativePath, availableExports;
51
- var _a;
52
- return __generator(this, function (_b) {
53
- switch (_b.label) {
54
- case 0:
55
- resolved = path.resolve(process.cwd(), modulePath);
56
- _b.label = 1;
57
- case 1:
58
- _b.trys.push([1, 3, , 4]);
59
- return [4 /*yield*/, loadModule(modulePath)];
60
- case 2:
61
- mod = _b.sent();
62
- return [3 /*break*/, 4];
63
- case 3:
64
- error_1 = _b.sent();
65
- if (error_1 instanceof Error && error_1.message.startsWith('File not found:')) {
66
- relativePath = path.relative(process.cwd(), resolved);
67
- throw new Error("File not found: ".concat(relativePath, "\n\n") +
68
- "Make sure the file exists and the path is correct.\n" +
69
- "You can specify a different file with:\n" +
70
- " hypequery dev path/to/your/queries.ts");
71
- }
72
- throw error_1;
73
- case 4:
74
- api = (_a = mod.api) !== null && _a !== void 0 ? _a : mod.default;
75
- if (!api || typeof api.handler !== 'function') {
76
- relativePath = path.relative(process.cwd(), resolved);
77
- availableExports = Object.keys(mod).filter(function (key) { return key !== '__esModule'; });
78
- throw new Error("Invalid API module: ".concat(relativePath, "\n\n") +
79
- "The module must export a 'defineServe' result as 'api'.\n\n" +
80
- (availableExports.length > 0
81
- ? "Found exports: ".concat(availableExports.join(', '), "\n\n")
82
- : "No exports found in the module.\n\n") +
83
- "Expected format:\n\n" +
84
- " import { initServe } from '@hypequery/serve';\n" +
85
- " \n" +
86
- " const { define, queries, query } = initServe({\n" +
87
- " context: () => ({ db }),\n" +
88
- " });\n" +
89
- " \n" +
90
- " export const api = define({\n" +
91
- " queries: queries({\n" +
92
- " myQuery: query.query(async ({ ctx }) => {\n" +
93
- " // ...\n" +
94
- " }),\n" +
95
- " }),\n" +
96
- " });\n");
97
- }
98
- return [2 /*return*/, api];
99
- }
100
- });
101
- });
9
+ const TYPESCRIPT_EXTENSIONS = new Set(['.ts', '.tsx', '.mts', '.cts']);
10
+ const tsconfigCache = new Map();
11
+ export async function loadApiModule(modulePath) {
12
+ const resolved = path.resolve(process.cwd(), modulePath);
13
+ let mod;
14
+ try {
15
+ mod = await loadModule(modulePath);
16
+ }
17
+ catch (error) {
18
+ if (error instanceof Error && error.message.startsWith('File not found:')) {
19
+ const relativePath = path.relative(process.cwd(), resolved);
20
+ throw new Error(`File not found: ${relativePath}\n\n` +
21
+ `Make sure the file exists and the path is correct.\n` +
22
+ `You can specify a different file with:\n` +
23
+ ` hypequery dev path/to/your/queries.ts`);
24
+ }
25
+ throw error;
26
+ }
27
+ const api = mod.api ?? mod.default;
28
+ if (!api || typeof api.handler !== 'function') {
29
+ const relativePath = path.relative(process.cwd(), resolved);
30
+ const availableExports = Object.keys(mod).filter(key => key !== '__esModule');
31
+ throw new Error(`Invalid API module: ${relativePath}\n\n` +
32
+ `The module must export a hypequery API as 'api'.\n\n` +
33
+ (availableExports.length > 0
34
+ ? `Found exports: ${availableExports.join(', ')}\n\n`
35
+ : `No exports found in the module.\n\n`) +
36
+ `Expected format:\n\n` +
37
+ ` import { initServe } from '@hypequery/serve';\n` +
38
+ ` \n` +
39
+ ` const { query, serve } = initServe({\n` +
40
+ ` context: () => ({ db }),\n` +
41
+ ` });\n` +
42
+ ` \n` +
43
+ ` const myQuery = query({\n` +
44
+ ` query: async ({ ctx }) => ctx.db.table('events').select('*').limit(10).execute(),\n` +
45
+ ` });\n` +
46
+ ` \n` +
47
+ ` export const api = serve({\n` +
48
+ ` queries: { myQuery },\n` +
49
+ ` });\n\n` +
50
+ `Or the datasets semantic API:\n\n` +
51
+ ` import { createAPI } from '@hypequery/serve';\n` +
52
+ ` import { db } from './client.js';\n` +
53
+ ` import { datasets } from './datasets.js';\n` +
54
+ ` \n` +
55
+ ` export const api = createAPI({\n` +
56
+ ` queryBuilder: db,\n` +
57
+ ` datasets,\n` +
58
+ ` });\n`);
59
+ }
60
+ return api;
102
61
  }
103
- export function loadModule(modulePath) {
104
- return __awaiter(this, void 0, void 0, function () {
105
- var resolved, _a, relativePath, extension, isTypeScript, moduleUrl, _b, importOverride, _c, error_2, relativePath;
106
- return __generator(this, function (_d) {
107
- switch (_d.label) {
108
- case 0:
109
- resolved = path.resolve(process.cwd(), modulePath);
110
- _d.label = 1;
111
- case 1:
112
- _d.trys.push([1, 3, , 4]);
113
- return [4 /*yield*/, access(resolved)];
114
- case 2:
115
- _d.sent();
116
- return [3 /*break*/, 4];
117
- case 3:
118
- _a = _d.sent();
119
- relativePath = path.relative(process.cwd(), resolved);
120
- throw new Error("File not found: ".concat(relativePath));
121
- case 4:
122
- extension = path.extname(resolved).toLowerCase();
123
- isTypeScript = TYPESCRIPT_EXTENSIONS.has(extension);
124
- if (!isTypeScript) return [3 /*break*/, 6];
125
- return [4 /*yield*/, bundleTypeScriptModule(resolved)];
126
- case 5:
127
- _b = _d.sent();
128
- return [3 /*break*/, 7];
129
- case 6:
130
- _b = "".concat(pathToFileURL(resolved).href, "?t=").concat(Date.now());
131
- _d.label = 7;
132
- case 7:
133
- moduleUrl = _b;
134
- _d.label = 8;
135
- case 8:
136
- _d.trys.push([8, 13, , 14]);
137
- importOverride = globalState.__hypequeryCliImportOverride;
138
- if (!importOverride) return [3 /*break*/, 10];
139
- return [4 /*yield*/, importOverride(moduleUrl)];
140
- case 9:
141
- _c = _d.sent();
142
- return [3 /*break*/, 12];
143
- case 10: return [4 /*yield*/, import(/* @vite-ignore */ moduleUrl)];
144
- case 11:
145
- _c = _d.sent();
146
- _d.label = 12;
147
- case 12: return [2 /*return*/, _c];
148
- case 13:
149
- error_2 = _d.sent();
150
- relativePath = path.relative(process.cwd(), resolved);
151
- throw new Error("Failed to load module: ".concat(relativePath, "\n\n") +
152
- "Error: ".concat(error_2.message, "\n\n") +
153
- (error_2.code === 'ERR_MODULE_NOT_FOUND'
154
- ? "This usually means:\n" +
155
- " \u2022 A dependency is missing (run 'npm install')\n" +
156
- " \u2022 An import path is incorrect\n"
157
- : "") +
158
- (error_2.stack ? "\nStack trace:\n".concat(error_2.stack, "\n") : ''));
159
- case 14: return [2 /*return*/];
160
- }
161
- });
162
- });
62
+ export async function loadModule(modulePath) {
63
+ const resolved = path.resolve(process.cwd(), modulePath);
64
+ try {
65
+ await access(resolved);
66
+ }
67
+ catch {
68
+ const relativePath = path.relative(process.cwd(), resolved);
69
+ throw new Error(`File not found: ${relativePath}`);
70
+ }
71
+ const extension = path.extname(resolved).toLowerCase();
72
+ const isTypeScript = TYPESCRIPT_EXTENSIONS.has(extension);
73
+ const moduleUrl = isTypeScript
74
+ ? await bundleTypeScriptModule(resolved)
75
+ : `${pathToFileURL(resolved).href}?t=${Date.now()}`;
76
+ try {
77
+ const importOverride = globalState.__hypequeryCliImportOverride;
78
+ return importOverride
79
+ ? await importOverride(moduleUrl)
80
+ : await import(/* @vite-ignore */ moduleUrl);
81
+ }
82
+ catch (error) {
83
+ const relativePath = path.relative(process.cwd(), resolved);
84
+ throw new Error(`Failed to load module: ${relativePath}\n\n` +
85
+ `Error: ${error.message}\n\n` +
86
+ (error.code === 'ERR_MODULE_NOT_FOUND'
87
+ ? `This usually means:\n` +
88
+ ` • A dependency is missing (run 'npm install')\n` +
89
+ ` • An import path is incorrect\n`
90
+ : ``) +
91
+ (error.stack ? `\nStack trace:\n${error.stack}\n` : ''));
92
+ }
163
93
  }
164
- var globalState = globalThis;
165
- var tempDirPromise = (_a = globalState.__hypequeryCliTempDirPromise) !== null && _a !== void 0 ? _a : null;
166
- var tempFiles = (_b = globalState.__hypequeryCliTempFiles) !== null && _b !== void 0 ? _b : new Set();
167
- var tempDirs = (_c = globalState.__hypequeryCliTempDirs) !== null && _c !== void 0 ? _c : new Set();
168
- var cleanupHooksInstalled = (_d = globalState.__hypequeryCliCleanupInstalled) !== null && _d !== void 0 ? _d : false;
94
+ const globalState = globalThis;
95
+ let tempDirPromise = globalState.__hypequeryCliTempDirPromise ?? null;
96
+ const tempFiles = globalState.__hypequeryCliTempFiles ?? new Set();
97
+ const tempDirs = globalState.__hypequeryCliTempDirs ?? new Set();
98
+ let cleanupHooksInstalled = globalState.__hypequeryCliCleanupInstalled ?? false;
169
99
  if (!globalState.__hypequeryCliTempFiles) {
170
100
  globalState.__hypequeryCliTempFiles = tempFiles;
171
101
  }
@@ -173,264 +103,145 @@ if (!globalState.__hypequeryCliTempDirs) {
173
103
  globalState.__hypequeryCliTempDirs = tempDirs;
174
104
  }
175
105
  function ensureTempDir() {
176
- var _this = this;
177
106
  installCleanupHooks();
178
107
  if (!tempDirPromise) {
179
- tempDirPromise = (function () { return __awaiter(_this, void 0, void 0, function () {
180
- var projectTempRoot, dir, _a, fallbackDir;
181
- return __generator(this, function (_b) {
182
- switch (_b.label) {
183
- case 0:
184
- projectTempRoot = path.join(process.cwd(), '.hypequery', 'tmp');
185
- _b.label = 1;
186
- case 1:
187
- _b.trys.push([1, 4, , 6]);
188
- return [4 /*yield*/, mkdir(projectTempRoot, { recursive: true })];
189
- case 2:
190
- _b.sent();
191
- return [4 /*yield*/, mkdtemp(path.join(projectTempRoot, 'bundle-'))];
192
- case 3:
193
- dir = _b.sent();
194
- tempDirs.add(dir);
195
- return [2 /*return*/, dir];
196
- case 4:
197
- _a = _b.sent();
198
- return [4 /*yield*/, mkdtemp(path.join(os.tmpdir(), 'hypequery-cli-'))];
199
- case 5:
200
- fallbackDir = _b.sent();
201
- tempDirs.add(fallbackDir);
202
- return [2 /*return*/, fallbackDir];
203
- case 6: return [2 /*return*/];
204
- }
205
- });
206
- }); })();
108
+ tempDirPromise = (async () => {
109
+ const projectTempRoot = path.join(process.cwd(), '.hypequery', 'tmp');
110
+ try {
111
+ await mkdir(projectTempRoot, { recursive: true });
112
+ const dir = await mkdtemp(path.join(projectTempRoot, 'bundle-'));
113
+ tempDirs.add(dir);
114
+ return dir;
115
+ }
116
+ catch {
117
+ const fallbackDir = await mkdtemp(path.join(os.tmpdir(), 'hypequery-cli-'));
118
+ tempDirs.add(fallbackDir);
119
+ return fallbackDir;
120
+ }
121
+ })();
207
122
  globalState.__hypequeryCliTempDirPromise = tempDirPromise;
208
123
  }
209
124
  return tempDirPromise;
210
125
  }
211
- function cleanupTempFiles() {
212
- return __awaiter(this, void 0, void 0, function () {
213
- var _this = this;
214
- return __generator(this, function (_a) {
215
- switch (_a.label) {
216
- case 0:
217
- if (tempFiles.size === 0)
218
- return [2 /*return*/];
219
- return [4 /*yield*/, Promise.all(Array.from(tempFiles).map(function (file) { return __awaiter(_this, void 0, void 0, function () {
220
- var _a;
221
- return __generator(this, function (_b) {
222
- switch (_b.label) {
223
- case 0:
224
- _b.trys.push([0, 2, , 3]);
225
- return [4 /*yield*/, rm(file, { force: true })];
226
- case 1:
227
- _b.sent();
228
- return [3 /*break*/, 3];
229
- case 2:
230
- _a = _b.sent();
231
- return [3 /*break*/, 3];
232
- case 3: return [2 /*return*/];
233
- }
234
- });
235
- }); }))];
236
- case 1:
237
- _a.sent();
238
- tempFiles.clear();
239
- return [2 /*return*/];
240
- }
241
- });
242
- });
126
+ async function cleanupTempFiles() {
127
+ if (tempFiles.size === 0)
128
+ return;
129
+ await Promise.all(Array.from(tempFiles).map(async (file) => {
130
+ try {
131
+ await rm(file, { force: true });
132
+ }
133
+ catch {
134
+ // ignore cleanup failures
135
+ }
136
+ }));
137
+ tempFiles.clear();
243
138
  }
244
- function cleanupTempDirs() {
245
- return __awaiter(this, void 0, void 0, function () {
246
- var projectTempRoot, _a;
247
- var _this = this;
248
- return __generator(this, function (_b) {
249
- switch (_b.label) {
250
- case 0:
251
- if (tempDirs.size === 0)
252
- return [2 /*return*/];
253
- return [4 /*yield*/, Promise.all(Array.from(tempDirs).map(function (dir) { return __awaiter(_this, void 0, void 0, function () {
254
- var _a;
255
- return __generator(this, function (_b) {
256
- switch (_b.label) {
257
- case 0:
258
- _b.trys.push([0, 2, , 3]);
259
- return [4 /*yield*/, rm(dir, { recursive: true, force: true })];
260
- case 1:
261
- _b.sent();
262
- return [3 /*break*/, 3];
263
- case 2:
264
- _a = _b.sent();
265
- return [3 /*break*/, 3];
266
- case 3: return [2 /*return*/];
267
- }
268
- });
269
- }); }))];
270
- case 1:
271
- _b.sent();
272
- tempDirs.clear();
273
- projectTempRoot = path.join(process.cwd(), '.hypequery', 'tmp');
274
- _b.label = 2;
275
- case 2:
276
- _b.trys.push([2, 4, , 5]);
277
- return [4 /*yield*/, rm(projectTempRoot, { recursive: true, force: true })];
278
- case 3:
279
- _b.sent();
280
- return [3 /*break*/, 5];
281
- case 4:
282
- _a = _b.sent();
283
- return [3 /*break*/, 5];
284
- case 5: return [2 /*return*/];
285
- }
286
- });
287
- });
139
+ async function cleanupTempDirs() {
140
+ if (tempDirs.size === 0)
141
+ return;
142
+ await Promise.all(Array.from(tempDirs).map(async (dir) => {
143
+ try {
144
+ await rm(dir, { recursive: true, force: true });
145
+ }
146
+ catch {
147
+ // ignore cleanup failures
148
+ }
149
+ }));
150
+ tempDirs.clear();
151
+ const projectTempRoot = path.join(process.cwd(), '.hypequery', 'tmp');
152
+ try {
153
+ await rm(projectTempRoot, { recursive: true, force: true });
154
+ }
155
+ catch {
156
+ // ignore cleanup failures
157
+ }
288
158
  }
289
- function cleanupTempArtifacts() {
290
- return __awaiter(this, void 0, void 0, function () {
291
- return __generator(this, function (_a) {
292
- switch (_a.label) {
293
- case 0: return [4 /*yield*/, cleanupTempFiles()];
294
- case 1:
295
- _a.sent();
296
- return [4 /*yield*/, cleanupTempDirs()];
297
- case 2:
298
- _a.sent();
299
- return [2 /*return*/];
300
- }
301
- });
302
- });
159
+ async function cleanupTempArtifacts() {
160
+ await cleanupTempFiles();
161
+ await cleanupTempDirs();
303
162
  }
304
163
  function installCleanupHooks() {
305
164
  if (cleanupHooksInstalled)
306
165
  return;
307
166
  cleanupHooksInstalled = true;
308
167
  globalState.__hypequeryCliCleanupInstalled = true;
309
- process.once('exit', function () {
310
- cleanupTempArtifacts().catch(function () { return undefined; });
168
+ process.once('exit', () => {
169
+ cleanupTempArtifacts().catch(() => undefined);
311
170
  });
312
- ['SIGINT', 'SIGTERM'].forEach(function (signal) {
313
- process.once(signal, function () {
314
- cleanupTempArtifacts().catch(function () { return undefined; });
171
+ ['SIGINT', 'SIGTERM'].forEach(signal => {
172
+ process.once(signal, () => {
173
+ cleanupTempArtifacts().catch(() => undefined);
315
174
  process.exit();
316
175
  });
317
176
  });
318
177
  }
319
- function bundleTypeScriptModule(entryPath) {
320
- return __awaiter(this, void 0, void 0, function () {
321
- var relativePath, tsconfigPath, result, output, tempDir, timestamp, tempFile, contents, error_3;
322
- var _a, _b, _c, _d;
323
- return __generator(this, function (_e) {
324
- switch (_e.label) {
325
- case 0:
326
- relativePath = path.relative(process.cwd(), entryPath);
327
- return [4 /*yield*/, findNearestTsconfig(entryPath)];
328
- case 1:
329
- tsconfigPath = _e.sent();
330
- _e.label = 2;
331
- case 2:
332
- _e.trys.push([2, 6, , 7]);
333
- return [4 /*yield*/, build({
334
- entryPoints: [entryPath],
335
- bundle: true,
336
- format: 'esm',
337
- platform: 'node',
338
- target: ['node18'],
339
- sourcemap: 'inline',
340
- write: false,
341
- logLevel: 'silent',
342
- absWorkingDir: process.cwd(),
343
- packages: 'external',
344
- tsconfig: tsconfigPath !== null && tsconfigPath !== void 0 ? tsconfigPath : undefined,
345
- loader: {
346
- '.ts': 'ts',
347
- '.tsx': 'tsx',
348
- '.mts': 'ts',
349
- '.cts': 'ts',
350
- },
351
- })];
352
- case 3:
353
- result = _e.sent();
354
- output = (_b = (_a = result.outputFiles) === null || _a === void 0 ? void 0 : _a.find(function (file) { return file.path.endsWith('.js'); })) !== null && _b !== void 0 ? _b : (_c = result.outputFiles) === null || _c === void 0 ? void 0 : _c[0];
355
- if (!output) {
356
- throw new Error('esbuild produced no output');
357
- }
358
- return [4 /*yield*/, ensureTempDir()];
359
- case 4:
360
- tempDir = _e.sent();
361
- timestamp = Date.now();
362
- tempFile = path.join(tempDir, "".concat(path.basename(entryPath, path.extname(entryPath)), "-").concat(timestamp, ".mjs"));
363
- contents = "".concat(output.text, "\n") +
364
- "//# sourceURL=".concat(pathToFileURL(entryPath).href, "\n") +
365
- "//# hypequery-ts-bundle=".concat(timestamp);
366
- return [4 /*yield*/, writeFile(tempFile, contents, 'utf8')];
367
- case 5:
368
- _e.sent();
369
- tempFiles.add(tempFile);
370
- return [2 /*return*/, "".concat(pathToFileURL(tempFile).href, "?t=").concat(timestamp)];
371
- case 6:
372
- error_3 = _e.sent();
373
- throw new Error("Failed to compile ".concat(relativePath, " with esbuild.\n") +
374
- "Original error: ".concat((_d = error_3 === null || error_3 === void 0 ? void 0 : error_3.message) !== null && _d !== void 0 ? _d : error_3));
375
- case 7: return [2 /*return*/];
376
- }
178
+ async function bundleTypeScriptModule(entryPath) {
179
+ const relativePath = path.relative(process.cwd(), entryPath);
180
+ const tsconfigPath = await findNearestTsconfig(entryPath);
181
+ try {
182
+ const result = await build({
183
+ entryPoints: [entryPath],
184
+ bundle: true,
185
+ format: 'esm',
186
+ platform: 'node',
187
+ target: ['node18'],
188
+ sourcemap: 'inline',
189
+ write: false,
190
+ logLevel: 'silent',
191
+ absWorkingDir: process.cwd(),
192
+ packages: 'external',
193
+ tsconfig: tsconfigPath ?? undefined,
194
+ loader: {
195
+ '.ts': 'ts',
196
+ '.tsx': 'tsx',
197
+ '.mts': 'ts',
198
+ '.cts': 'ts',
199
+ },
377
200
  });
378
- });
201
+ const output = result.outputFiles?.find(file => file.path.endsWith('.js')) ?? result.outputFiles?.[0];
202
+ if (!output) {
203
+ throw new Error('esbuild produced no output');
204
+ }
205
+ const tempDir = await ensureTempDir();
206
+ const timestamp = Date.now();
207
+ const tempFile = path.join(tempDir, `${path.basename(entryPath, path.extname(entryPath))}-${timestamp}.mjs`);
208
+ const contents = `${output.text}\n` +
209
+ `//# sourceURL=${pathToFileURL(entryPath).href}\n` +
210
+ `//# hypequery-ts-bundle=${timestamp}`;
211
+ await writeFile(tempFile, contents, 'utf8');
212
+ tempFiles.add(tempFile);
213
+ return `${pathToFileURL(tempFile).href}?t=${timestamp}`;
214
+ }
215
+ catch (error) {
216
+ throw new Error(`Failed to compile ${relativePath} with esbuild.\n` +
217
+ `Original error: ${error?.message ?? error}`);
218
+ }
379
219
  }
380
- function findNearestTsconfig(filePath) {
381
- return __awaiter(this, void 0, void 0, function () {
382
- var dir, visited, _loop_1, state_1;
383
- var _a;
384
- return __generator(this, function (_b) {
385
- switch (_b.label) {
386
- case 0:
387
- dir = path.dirname(filePath);
388
- visited = [];
389
- _loop_1 = function () {
390
- var cached_1, candidate, _c, parent_1;
391
- return __generator(this, function (_d) {
392
- switch (_d.label) {
393
- case 0:
394
- if (tsconfigCache.has(dir)) {
395
- cached_1 = (_a = tsconfigCache.get(dir)) !== null && _a !== void 0 ? _a : null;
396
- visited.forEach(function (pathname) { return tsconfigCache.set(pathname, cached_1); });
397
- return [2 /*return*/, { value: cached_1 }];
398
- }
399
- visited.push(dir);
400
- candidate = path.join(dir, 'tsconfig.json');
401
- _d.label = 1;
402
- case 1:
403
- _d.trys.push([1, 3, , 4]);
404
- return [4 /*yield*/, access(candidate)];
405
- case 2:
406
- _d.sent();
407
- tsconfigCache.set(dir, candidate);
408
- visited.forEach(function (pathname) { return tsconfigCache.set(pathname, candidate); });
409
- return [2 /*return*/, { value: candidate }];
410
- case 3:
411
- _c = _d.sent();
412
- parent_1 = path.dirname(dir);
413
- if (parent_1 === dir) {
414
- visited.forEach(function (pathname) { return tsconfigCache.set(pathname, null); });
415
- return [2 /*return*/, { value: null }];
416
- }
417
- dir = parent_1;
418
- return [3 /*break*/, 4];
419
- case 4: return [2 /*return*/];
420
- }
421
- });
422
- };
423
- _b.label = 1;
424
- case 1:
425
- if (!dir) return [3 /*break*/, 3];
426
- return [5 /*yield**/, _loop_1()];
427
- case 2:
428
- state_1 = _b.sent();
429
- if (typeof state_1 === "object")
430
- return [2 /*return*/, state_1.value];
431
- return [3 /*break*/, 1];
432
- case 3: return [2 /*return*/, null];
220
+ async function findNearestTsconfig(filePath) {
221
+ let dir = path.dirname(filePath);
222
+ const visited = [];
223
+ while (dir) {
224
+ if (tsconfigCache.has(dir)) {
225
+ const cached = tsconfigCache.get(dir) ?? null;
226
+ visited.forEach(pathname => tsconfigCache.set(pathname, cached));
227
+ return cached;
228
+ }
229
+ visited.push(dir);
230
+ const candidate = path.join(dir, 'tsconfig.json');
231
+ try {
232
+ await access(candidate);
233
+ tsconfigCache.set(dir, candidate);
234
+ visited.forEach(pathname => tsconfigCache.set(pathname, candidate));
235
+ return candidate;
236
+ }
237
+ catch {
238
+ const parent = path.dirname(dir);
239
+ if (parent === dir) {
240
+ visited.forEach(pathname => tsconfigCache.set(pathname, null));
241
+ return null;
433
242
  }
434
- });
435
- });
243
+ dir = parent;
244
+ }
245
+ }
246
+ return null;
436
247
  }