@uiwwsw/react-query-helper 1.3.0 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,2158 +1,758 @@
1
1
  #!/usr/bin/env node
2
- // node_modules/chokidar/esm/index.js
3
- import { stat as statcb } from "fs";
4
- import { stat as stat3, readdir as readdir2 } from "fs/promises";
5
- import { EventEmitter } from "events";
6
- import * as sysPath2 from "path";
7
2
 
8
- // node_modules/readdirp/esm/index.js
9
- import { stat, lstat, readdir, realpath } from "node:fs/promises";
10
- import { Readable } from "node:stream";
11
- import { resolve as presolve, relative as prelative, join as pjoin, sep as psep } from "node:path";
12
- var EntryTypes = {
13
- FILE_TYPE: "files",
14
- DIR_TYPE: "directories",
15
- FILE_DIR_TYPE: "files_directories",
16
- EVERYTHING_TYPE: "all"
17
- };
18
- var defaultOptions = {
19
- root: ".",
20
- fileFilter: (_entryInfo) => true,
21
- directoryFilter: (_entryInfo) => true,
22
- type: EntryTypes.FILE_TYPE,
23
- lstat: false,
24
- depth: 2147483648,
25
- alwaysStat: false,
26
- highWaterMark: 4096
27
- };
28
- Object.freeze(defaultOptions);
29
- var RECURSIVE_ERROR_CODE = "READDIRP_RECURSIVE_ERROR";
30
- var NORMAL_FLOW_ERRORS = new Set(["ENOENT", "EPERM", "EACCES", "ELOOP", RECURSIVE_ERROR_CODE]);
31
- var ALL_TYPES = [
32
- EntryTypes.DIR_TYPE,
33
- EntryTypes.EVERYTHING_TYPE,
34
- EntryTypes.FILE_DIR_TYPE,
35
- EntryTypes.FILE_TYPE
36
- ];
37
- var DIR_TYPES = new Set([
38
- EntryTypes.DIR_TYPE,
39
- EntryTypes.EVERYTHING_TYPE,
40
- EntryTypes.FILE_DIR_TYPE
41
- ]);
42
- var FILE_TYPES = new Set([
43
- EntryTypes.EVERYTHING_TYPE,
44
- EntryTypes.FILE_DIR_TYPE,
45
- EntryTypes.FILE_TYPE
46
- ]);
47
- var isNormalFlowError = (error) => NORMAL_FLOW_ERRORS.has(error.code);
48
- var wantBigintFsStats = process.platform === "win32";
49
- var emptyFn = (_entryInfo) => true;
50
- var normalizeFilter = (filter) => {
51
- if (filter === undefined)
52
- return emptyFn;
53
- if (typeof filter === "function")
54
- return filter;
55
- if (typeof filter === "string") {
56
- const fl = filter.trim();
57
- return (entry) => entry.basename === fl;
58
- }
59
- if (Array.isArray(filter)) {
60
- const trItems = filter.map((item) => item.trim());
61
- return (entry) => trItems.some((f) => entry.basename === f);
62
- }
63
- return emptyFn;
64
- };
3
+ // src/cli.ts
4
+ import { watch } from "chokidar";
5
+ import {
6
+ readdir,
7
+ readFile,
8
+ writeFile,
9
+ mkdir,
10
+ rename,
11
+ unlink,
12
+ stat,
13
+ realpath
14
+ } from "node:fs/promises";
15
+ import { existsSync as existsSync2 } from "node:fs";
16
+ import {
17
+ basename,
18
+ dirname as dirname2,
19
+ extname,
20
+ isAbsolute as isAbsolute2,
21
+ join as join2,
22
+ relative,
23
+ resolve as resolve2,
24
+ sep
25
+ } from "node:path";
26
+ import { randomUUID } from "node:crypto";
27
+ import picomatch from "picomatch";
28
+ import prettier from "prettier";
65
29
 
66
- class ReaddirpStream extends Readable {
67
- constructor(options = {}) {
68
- super({
69
- objectMode: true,
70
- autoDestroy: true,
71
- highWaterMark: options.highWaterMark
72
- });
73
- const opts = { ...defaultOptions, ...options };
74
- const { root, type } = opts;
75
- this._fileFilter = normalizeFilter(opts.fileFilter);
76
- this._directoryFilter = normalizeFilter(opts.directoryFilter);
77
- const statMethod = opts.lstat ? lstat : stat;
78
- if (wantBigintFsStats) {
79
- this._stat = (path) => statMethod(path, { bigint: true });
80
- } else {
81
- this._stat = statMethod;
82
- }
83
- this._maxDepth = opts.depth ?? defaultOptions.depth;
84
- this._wantsDir = type ? DIR_TYPES.has(type) : false;
85
- this._wantsFile = type ? FILE_TYPES.has(type) : false;
86
- this._wantsEverything = type === EntryTypes.EVERYTHING_TYPE;
87
- this._root = presolve(root);
88
- this._isDirent = !opts.alwaysStat;
89
- this._statsProp = this._isDirent ? "dirent" : "stats";
90
- this._rdOptions = { encoding: "utf8", withFileTypes: this._isDirent };
91
- this.parents = [this._exploreDir(root, 1)];
92
- this.reading = false;
93
- this.parent = undefined;
94
- }
95
- async _read(batch) {
96
- if (this.reading)
97
- return;
98
- this.reading = true;
99
- try {
100
- while (!this.destroyed && batch > 0) {
101
- const par = this.parent;
102
- const fil = par && par.files;
103
- if (fil && fil.length > 0) {
104
- const { path, depth } = par;
105
- const slice = fil.splice(0, batch).map((dirent) => this._formatEntry(dirent, path));
106
- const awaited = await Promise.all(slice);
107
- for (const entry of awaited) {
108
- if (!entry)
109
- continue;
110
- if (this.destroyed)
111
- return;
112
- const entryType = await this._getEntryType(entry);
113
- if (entryType === "directory" && this._directoryFilter(entry)) {
114
- if (depth <= this._maxDepth) {
115
- this.parents.push(this._exploreDir(entry.fullPath, depth + 1));
116
- }
117
- if (this._wantsDir) {
118
- this.push(entry);
119
- batch--;
120
- }
121
- } else if ((entryType === "file" || this._includeAsFile(entry)) && this._fileFilter(entry)) {
122
- if (this._wantsFile) {
123
- this.push(entry);
124
- batch--;
125
- }
126
- }
127
- }
128
- } else {
129
- const parent = this.parents.pop();
130
- if (!parent) {
131
- this.push(null);
132
- break;
133
- }
134
- this.parent = await parent;
135
- if (this.destroyed)
136
- return;
137
- }
138
- }
139
- } catch (error) {
140
- this.destroy(error);
141
- } finally {
142
- this.reading = false;
143
- }
144
- }
145
- async _exploreDir(path, depth) {
146
- let files;
147
- try {
148
- files = await readdir(path, this._rdOptions);
149
- } catch (error) {
150
- this._onError(error);
151
- }
152
- return { files, depth, path };
153
- }
154
- async _formatEntry(dirent, path) {
155
- let entry;
156
- const basename = this._isDirent ? dirent.name : dirent;
157
- try {
158
- const fullPath = presolve(pjoin(path, basename));
159
- entry = { path: prelative(this._root, fullPath), fullPath, basename };
160
- entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
161
- } catch (err) {
162
- this._onError(err);
163
- return;
164
- }
165
- return entry;
166
- }
167
- _onError(err) {
168
- if (isNormalFlowError(err) && !this.destroyed) {
169
- this.emit("warn", err);
170
- } else {
171
- this.destroy(err);
172
- }
173
- }
174
- async _getEntryType(entry) {
175
- if (!entry && this._statsProp in entry) {
176
- return "";
177
- }
178
- const stats = entry[this._statsProp];
179
- if (stats.isFile())
180
- return "file";
181
- if (stats.isDirectory())
182
- return "directory";
183
- if (stats && stats.isSymbolicLink()) {
184
- const full = entry.fullPath;
185
- try {
186
- const entryRealPath = await realpath(full);
187
- const entryRealPathStats = await lstat(entryRealPath);
188
- if (entryRealPathStats.isFile()) {
189
- return "file";
190
- }
191
- if (entryRealPathStats.isDirectory()) {
192
- const len = entryRealPath.length;
193
- if (full.startsWith(entryRealPath) && full.substr(len, 1) === psep) {
194
- const recursiveError = new Error(`Circular symlink detected: "${full}" points to "${entryRealPath}"`);
195
- recursiveError.code = RECURSIVE_ERROR_CODE;
196
- return this._onError(recursiveError);
197
- }
198
- return "directory";
199
- }
200
- } catch (error) {
201
- this._onError(error);
202
- return "";
203
- }
204
- }
205
- }
206
- _includeAsFile(entry) {
207
- const stats = entry && entry[this._statsProp];
208
- return stats && this._wantsEverything && !stats.isDirectory();
209
- }
210
- }
211
- function readdirp(root, options = {}) {
212
- let type = options.entryType || options.type;
213
- if (type === "both")
214
- type = EntryTypes.FILE_DIR_TYPE;
215
- if (type)
216
- options.type = type;
217
- if (!root) {
218
- throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");
219
- } else if (typeof root !== "string") {
220
- throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");
221
- } else if (type && !ALL_TYPES.includes(type)) {
222
- throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(", ")}`);
30
+ // src/core/analyzer.ts
31
+ import ts from "typescript";
32
+ import { readFileSync } from "node:fs";
33
+ function unwrap(node) {
34
+ if (!node) return;
35
+ if (ts.isArrowFunction(node) || ts.isFunctionExpression(node)) return node;
36
+ if (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isTypeAssertionExpression(node) || ts.isSatisfiesExpression(node) || ts.isNonNullExpression(node)) {
37
+ return unwrap(node.expression);
223
38
  }
224
- options.root = root;
225
- return new ReaddirpStream(options);
226
39
  }
227
-
228
- // node_modules/chokidar/esm/handler.js
229
- import { watchFile, unwatchFile, watch as fs_watch } from "fs";
230
- import { open, stat as stat2, lstat as lstat2, realpath as fsrealpath } from "fs/promises";
231
- import * as sysPath from "path";
232
- import { type as osType } from "os";
233
- var STR_DATA = "data";
234
- var STR_END = "end";
235
- var STR_CLOSE = "close";
236
- var EMPTY_FN = () => {};
237
- var pl = process.platform;
238
- var isWindows = pl === "win32";
239
- var isMacos = pl === "darwin";
240
- var isLinux = pl === "linux";
241
- var isFreeBSD = pl === "freebsd";
242
- var isIBMi = osType() === "OS400";
243
- var EVENTS = {
244
- ALL: "all",
245
- READY: "ready",
246
- ADD: "add",
247
- CHANGE: "change",
248
- ADD_DIR: "addDir",
249
- UNLINK: "unlink",
250
- UNLINK_DIR: "unlinkDir",
251
- RAW: "raw",
252
- ERROR: "error"
253
- };
254
- var EV = EVENTS;
255
- var THROTTLE_MODE_WATCH = "watch";
256
- var statMethods = { lstat: lstat2, stat: stat2 };
257
- var KEY_LISTENERS = "listeners";
258
- var KEY_ERR = "errHandlers";
259
- var KEY_RAW = "rawEmitters";
260
- var HANDLER_KEYS = [KEY_LISTENERS, KEY_ERR, KEY_RAW];
261
- var binaryExtensions = new Set([
262
- "3dm",
263
- "3ds",
264
- "3g2",
265
- "3gp",
266
- "7z",
267
- "a",
268
- "aac",
269
- "adp",
270
- "afdesign",
271
- "afphoto",
272
- "afpub",
273
- "ai",
274
- "aif",
275
- "aiff",
276
- "alz",
277
- "ape",
278
- "apk",
279
- "appimage",
280
- "ar",
281
- "arj",
282
- "asf",
283
- "au",
284
- "avi",
285
- "bak",
286
- "baml",
287
- "bh",
288
- "bin",
289
- "bk",
290
- "bmp",
291
- "btif",
292
- "bz2",
293
- "bzip2",
294
- "cab",
295
- "caf",
296
- "cgm",
297
- "class",
298
- "cmx",
299
- "cpio",
300
- "cr2",
301
- "cur",
302
- "dat",
303
- "dcm",
304
- "deb",
305
- "dex",
306
- "djvu",
307
- "dll",
308
- "dmg",
309
- "dng",
310
- "doc",
311
- "docm",
312
- "docx",
313
- "dot",
314
- "dotm",
315
- "dra",
316
- "DS_Store",
317
- "dsk",
318
- "dts",
319
- "dtshd",
320
- "dvb",
321
- "dwg",
322
- "dxf",
323
- "ecelp4800",
324
- "ecelp7470",
325
- "ecelp9600",
326
- "egg",
327
- "eol",
328
- "eot",
329
- "epub",
330
- "exe",
331
- "f4v",
332
- "fbs",
333
- "fh",
334
- "fla",
335
- "flac",
336
- "flatpak",
337
- "fli",
338
- "flv",
339
- "fpx",
340
- "fst",
341
- "fvt",
342
- "g3",
343
- "gh",
344
- "gif",
345
- "graffle",
346
- "gz",
347
- "gzip",
348
- "h261",
349
- "h263",
350
- "h264",
351
- "icns",
352
- "ico",
353
- "ief",
354
- "img",
355
- "ipa",
356
- "iso",
357
- "jar",
358
- "jpeg",
359
- "jpg",
360
- "jpgv",
361
- "jpm",
362
- "jxr",
363
- "key",
364
- "ktx",
365
- "lha",
366
- "lib",
367
- "lvp",
368
- "lz",
369
- "lzh",
370
- "lzma",
371
- "lzo",
372
- "m3u",
373
- "m4a",
374
- "m4v",
375
- "mar",
376
- "mdi",
377
- "mht",
378
- "mid",
379
- "midi",
380
- "mj2",
381
- "mka",
382
- "mkv",
383
- "mmr",
384
- "mng",
385
- "mobi",
386
- "mov",
387
- "movie",
388
- "mp3",
389
- "mp4",
390
- "mp4a",
391
- "mpeg",
392
- "mpg",
393
- "mpga",
394
- "mxu",
395
- "nef",
396
- "npx",
397
- "numbers",
398
- "nupkg",
399
- "o",
400
- "odp",
401
- "ods",
402
- "odt",
403
- "oga",
404
- "ogg",
405
- "ogv",
406
- "otf",
407
- "ott",
408
- "pages",
409
- "pbm",
410
- "pcx",
411
- "pdb",
412
- "pdf",
413
- "pea",
414
- "pgm",
415
- "pic",
416
- "png",
417
- "pnm",
418
- "pot",
419
- "potm",
420
- "potx",
421
- "ppa",
422
- "ppam",
423
- "ppm",
424
- "pps",
425
- "ppsm",
426
- "ppsx",
427
- "ppt",
428
- "pptm",
429
- "pptx",
430
- "psd",
431
- "pya",
432
- "pyc",
433
- "pyo",
434
- "pyv",
435
- "qt",
436
- "rar",
437
- "ras",
438
- "raw",
439
- "resources",
440
- "rgb",
441
- "rip",
442
- "rlc",
443
- "rmf",
444
- "rmvb",
445
- "rpm",
446
- "rtf",
447
- "rz",
448
- "s3m",
449
- "s7z",
450
- "scpt",
451
- "sgi",
452
- "shar",
453
- "snap",
454
- "sil",
455
- "sketch",
456
- "slk",
457
- "smv",
458
- "snk",
459
- "so",
460
- "stl",
461
- "suo",
462
- "sub",
463
- "swf",
464
- "tar",
465
- "tbz",
466
- "tbz2",
467
- "tga",
468
- "tgz",
469
- "thmx",
470
- "tif",
471
- "tiff",
472
- "tlz",
473
- "ttc",
474
- "ttf",
475
- "txz",
476
- "udf",
477
- "uvh",
478
- "uvi",
479
- "uvm",
480
- "uvp",
481
- "uvs",
482
- "uvu",
483
- "viv",
484
- "vob",
485
- "war",
486
- "wav",
487
- "wax",
488
- "wbmp",
489
- "wdp",
490
- "weba",
491
- "webm",
492
- "webp",
493
- "whl",
494
- "wim",
495
- "wm",
496
- "wma",
497
- "wmv",
498
- "wmx",
499
- "woff",
500
- "woff2",
501
- "wrm",
502
- "wvx",
503
- "xbm",
504
- "xif",
505
- "xla",
506
- "xlam",
507
- "xls",
508
- "xlsb",
509
- "xlsm",
510
- "xlsx",
511
- "xlt",
512
- "xltm",
513
- "xltx",
514
- "xm",
515
- "xmind",
516
- "xpi",
517
- "xpm",
518
- "xwd",
519
- "xz",
520
- "z",
521
- "zip",
522
- "zipx"
523
- ]);
524
- var isBinaryPath = (filePath) => binaryExtensions.has(sysPath.extname(filePath).slice(1).toLowerCase());
525
- var foreach = (val, fn) => {
526
- if (val instanceof Set) {
527
- val.forEach(fn);
528
- } else {
529
- fn(val);
530
- }
531
- };
532
- var addAndConvert = (main, prop, item) => {
533
- let container = main[prop];
534
- if (!(container instanceof Set)) {
535
- main[prop] = container = new Set([container]);
536
- }
537
- container.add(item);
538
- };
539
- var clearItem = (cont) => (key) => {
540
- const set = cont[key];
541
- if (set instanceof Set) {
542
- set.clear();
543
- } else {
544
- delete cont[key];
545
- }
546
- };
547
- var delFromSet = (main, prop, item) => {
548
- const container = main[prop];
549
- if (container instanceof Set) {
550
- container.delete(item);
551
- } else if (container === item) {
552
- delete main[prop];
553
- }
554
- };
555
- var isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val;
556
- var FsWatchInstances = new Map;
557
- function createFsWatchInstance(path, options, listener, errHandler, emitRaw) {
558
- const handleEvent = (rawEvent, evPath) => {
559
- listener(path);
560
- emitRaw(rawEvent, evPath, { watchedPath: path });
561
- if (evPath && path !== evPath) {
562
- fsWatchBroadcast(sysPath.resolve(path, evPath), KEY_LISTENERS, sysPath.join(path, evPath));
563
- }
564
- };
565
- try {
566
- return fs_watch(path, {
567
- persistent: options.persistent
568
- }, handleEvent);
569
- } catch (error) {
570
- errHandler(error);
571
- return;
572
- }
40
+ function has(node, kind) {
41
+ return ts.canHaveModifiers(node) && ts.getModifiers(node)?.some((m) => m.kind === kind);
573
42
  }
574
- var fsWatchBroadcast = (fullPath, listenerType, val1, val2, val3) => {
575
- const cont = FsWatchInstances.get(fullPath);
576
- if (!cont)
577
- return;
578
- foreach(cont[listenerType], (listener) => {
579
- listener(val1, val2, val3);
580
- });
581
- };
582
- var setFsWatchListener = (path, fullPath, options, handlers) => {
583
- const { listener, errHandler, rawEmitter } = handlers;
584
- let cont = FsWatchInstances.get(fullPath);
585
- let watcher;
586
- if (!options.persistent) {
587
- watcher = createFsWatchInstance(path, options, listener, errHandler, rawEmitter);
588
- if (!watcher)
589
- return;
590
- return watcher.close.bind(watcher);
591
- }
592
- if (cont) {
593
- addAndConvert(cont, KEY_LISTENERS, listener);
594
- addAndConvert(cont, KEY_ERR, errHandler);
595
- addAndConvert(cont, KEY_RAW, rawEmitter);
596
- } else {
597
- watcher = createFsWatchInstance(path, options, fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS), errHandler, fsWatchBroadcast.bind(null, fullPath, KEY_RAW));
598
- if (!watcher)
599
- return;
600
- watcher.on(EV.ERROR, async (error) => {
601
- const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
602
- if (cont)
603
- cont.watcherUnusable = true;
604
- if (isWindows && error.code === "EPERM") {
605
- try {
606
- const fd = await open(path, "r");
607
- await fd.close();
608
- broadcastErr(error);
609
- } catch (err) {}
610
- } else {
611
- broadcastErr(error);
612
- }
613
- });
614
- cont = {
615
- listeners: listener,
616
- errHandlers: errHandler,
617
- rawEmitters: rawEmitter,
618
- watcher
619
- };
620
- FsWatchInstances.set(fullPath, cont);
621
- }
622
- return () => {
623
- delFromSet(cont, KEY_LISTENERS, listener);
624
- delFromSet(cont, KEY_ERR, errHandler);
625
- delFromSet(cont, KEY_RAW, rawEmitter);
626
- if (isEmptySet(cont.listeners)) {
627
- cont.watcher.close();
628
- FsWatchInstances.delete(fullPath);
629
- HANDLER_KEYS.forEach(clearItem(cont));
630
- cont.watcher = undefined;
631
- Object.freeze(cont);
632
- }
633
- };
634
- };
635
- var FsWatchFileInstances = new Map;
636
- var setFsWatchFileListener = (path, fullPath, options, handlers) => {
637
- const { listener, rawEmitter } = handlers;
638
- let cont = FsWatchFileInstances.get(fullPath);
639
- const copts = cont && cont.options;
640
- if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
641
- unwatchFile(fullPath);
642
- cont = undefined;
643
- }
644
- if (cont) {
645
- addAndConvert(cont, KEY_LISTENERS, listener);
646
- addAndConvert(cont, KEY_RAW, rawEmitter);
647
- } else {
648
- cont = {
649
- listeners: listener,
650
- rawEmitters: rawEmitter,
651
- options,
652
- watcher: watchFile(fullPath, options, (curr, prev) => {
653
- foreach(cont.rawEmitters, (rawEmitter2) => {
654
- rawEmitter2(EV.CHANGE, fullPath, { curr, prev });
655
- });
656
- const currmtime = curr.mtimeMs;
657
- if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {
658
- foreach(cont.listeners, (listener2) => listener2(path, curr));
659
- }
43
+ function analyzeFile(filePath, config = {}) {
44
+ const source = ts.createSourceFile(
45
+ filePath,
46
+ readFileSync(filePath, "utf8"),
47
+ ts.ScriptTarget.Latest,
48
+ true,
49
+ filePath.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS
50
+ );
51
+ const diagnostics = source.parseDiagnostics;
52
+ if (diagnostics.length)
53
+ throw new Error(
54
+ ts.formatDiagnosticsWithColorAndContext(diagnostics, {
55
+ getCanonicalFileName: (f) => f,
56
+ getCurrentDirectory: () => process.cwd(),
57
+ getNewLine: () => "\n"
660
58
  })
661
- };
662
- FsWatchFileInstances.set(fullPath, cont);
663
- }
664
- return () => {
665
- delFromSet(cont, KEY_LISTENERS, listener);
666
- delFromSet(cont, KEY_RAW, rawEmitter);
667
- if (isEmptySet(cont.listeners)) {
668
- FsWatchFileInstances.delete(fullPath);
669
- unwatchFile(fullPath);
670
- cont.options = cont.watcher = undefined;
671
- Object.freeze(cont);
672
- }
59
+ );
60
+ const functions = /* @__PURE__ */ new Map();
61
+ const exports = /* @__PURE__ */ new Map();
62
+ const identifiers = /* @__PURE__ */ new Set();
63
+ const collectIdentifiers = (node) => {
64
+ if (ts.isIdentifier(node)) identifiers.add(node.text);
65
+ ts.forEachChild(node, collectIdentifiers);
673
66
  };
674
- };
675
-
676
- class NodeFsHandler {
677
- constructor(fsW) {
678
- this.fsw = fsW;
679
- this._boundHandleError = (error) => fsW._handleError(error);
680
- }
681
- _watchWithNodeFs(path, listener) {
682
- const opts = this.fsw.options;
683
- const directory = sysPath.dirname(path);
684
- const basename2 = sysPath.basename(path);
685
- const parent = this.fsw._getWatchedDir(directory);
686
- parent.add(basename2);
687
- const absolutePath = sysPath.resolve(path);
688
- const options = {
689
- persistent: opts.persistent
690
- };
691
- if (!listener)
692
- listener = EMPTY_FN;
693
- let closer;
694
- if (opts.usePolling) {
695
- const enableBin = opts.interval !== opts.binaryInterval;
696
- options.interval = enableBin && isBinaryPath(basename2) ? opts.binaryInterval : opts.interval;
697
- closer = setFsWatchFileListener(path, absolutePath, options, {
698
- listener,
699
- rawEmitter: this.fsw._emitRaw
700
- });
701
- } else {
702
- closer = setFsWatchListener(path, absolutePath, options, {
703
- listener,
704
- errHandler: this._boundHandleError,
705
- rawEmitter: this.fsw._emitRaw
706
- });
707
- }
708
- return closer;
709
- }
710
- _handleFile(file, stats, initialAdd) {
711
- if (this.fsw.closed) {
712
- return;
713
- }
714
- const dirname2 = sysPath.dirname(file);
715
- const basename2 = sysPath.basename(file);
716
- const parent = this.fsw._getWatchedDir(dirname2);
717
- let prevStats = stats;
718
- if (parent.has(basename2))
719
- return;
720
- const listener = async (path, newStats) => {
721
- if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5))
722
- return;
723
- if (!newStats || newStats.mtimeMs === 0) {
724
- try {
725
- const newStats2 = await stat2(file);
726
- if (this.fsw.closed)
727
- return;
728
- const at = newStats2.atimeMs;
729
- const mt = newStats2.mtimeMs;
730
- if (!at || at <= mt || mt !== prevStats.mtimeMs) {
731
- this.fsw._emit(EV.CHANGE, file, newStats2);
732
- }
733
- if ((isMacos || isLinux || isFreeBSD) && prevStats.ino !== newStats2.ino) {
734
- this.fsw._closeFile(path);
735
- prevStats = newStats2;
736
- const closer2 = this._watchWithNodeFs(file, listener);
737
- if (closer2)
738
- this.fsw._addPathCloser(path, closer2);
739
- } else {
740
- prevStats = newStats2;
741
- }
742
- } catch (error) {
743
- this.fsw._remove(dirname2, basename2);
744
- }
745
- } else if (parent.has(basename2)) {
746
- const at = newStats.atimeMs;
747
- const mt = newStats.mtimeMs;
748
- if (!at || at <= mt || mt !== prevStats.mtimeMs) {
749
- this.fsw._emit(EV.CHANGE, file, newStats);
750
- }
751
- prevStats = newStats;
752
- }
753
- };
754
- const closer = this._watchWithNodeFs(file, listener);
755
- if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {
756
- if (!this.fsw._throttle(EV.ADD, file, 0))
757
- return;
758
- this.fsw._emit(EV.ADD, file, stats);
759
- }
760
- return closer;
761
- }
762
- async _handleSymlink(entry, directory, path, item) {
763
- if (this.fsw.closed) {
764
- return;
765
- }
766
- const full = entry.fullPath;
767
- const dir = this.fsw._getWatchedDir(directory);
768
- if (!this.fsw.options.followSymlinks) {
769
- this.fsw._incrReadyCount();
770
- let linkPath;
771
- try {
772
- linkPath = await fsrealpath(path);
773
- } catch (e) {
774
- this.fsw._emitReady();
775
- return true;
776
- }
777
- if (this.fsw.closed)
778
- return;
779
- if (dir.has(item)) {
780
- if (this.fsw._symlinkPaths.get(full) !== linkPath) {
781
- this.fsw._symlinkPaths.set(full, linkPath);
782
- this.fsw._emit(EV.CHANGE, path, entry.stats);
783
- }
784
- } else {
785
- dir.add(item);
786
- this.fsw._symlinkPaths.set(full, linkPath);
787
- this.fsw._emit(EV.ADD, path, entry.stats);
788
- }
789
- this.fsw._emitReady();
790
- return true;
791
- }
792
- if (this.fsw._symlinkPaths.has(full)) {
793
- return true;
794
- }
795
- this.fsw._symlinkPaths.set(full, true);
796
- }
797
- _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {
798
- directory = sysPath.join(directory, "");
799
- throttler = this.fsw._throttle("readdir", directory, 1000);
800
- if (!throttler)
801
- return;
802
- const previous = this.fsw._getWatchedDir(wh.path);
803
- const current = new Set;
804
- let stream = this.fsw._readdirp(directory, {
805
- fileFilter: (entry) => wh.filterPath(entry),
806
- directoryFilter: (entry) => wh.filterDir(entry)
807
- });
808
- if (!stream)
809
- return;
810
- stream.on(STR_DATA, async (entry) => {
811
- if (this.fsw.closed) {
812
- stream = undefined;
813
- return;
814
- }
815
- const item = entry.path;
816
- let path = sysPath.join(directory, item);
817
- current.add(item);
818
- if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path, item)) {
819
- return;
820
- }
821
- if (this.fsw.closed) {
822
- stream = undefined;
823
- return;
824
- }
825
- if (item === target || !target && !previous.has(item)) {
826
- this.fsw._incrReadyCount();
827
- path = sysPath.join(dir, sysPath.relative(dir, path));
828
- this._addToNodeFs(path, initialAdd, wh, depth + 1);
829
- }
830
- }).on(EV.ERROR, this._boundHandleError);
831
- return new Promise((resolve2, reject) => {
832
- if (!stream)
833
- return reject();
834
- stream.once(STR_END, () => {
835
- if (this.fsw.closed) {
836
- stream = undefined;
837
- return;
838
- }
839
- const wasThrottled = throttler ? throttler.clear() : false;
840
- resolve2(undefined);
841
- previous.getChildren().filter((item) => {
842
- return item !== directory && !current.has(item);
843
- }).forEach((item) => {
844
- this.fsw._remove(directory, item);
845
- });
846
- stream = undefined;
847
- if (wasThrottled)
848
- this._handleRead(directory, false, wh, target, dir, depth, throttler);
849
- });
850
- });
851
- }
852
- async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath2) {
853
- const parentDir = this.fsw._getWatchedDir(sysPath.dirname(dir));
854
- const tracked = parentDir.has(sysPath.basename(dir));
855
- if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {
856
- this.fsw._emit(EV.ADD_DIR, dir, stats);
857
- }
858
- parentDir.add(sysPath.basename(dir));
859
- this.fsw._getWatchedDir(dir);
860
- let throttler;
861
- let closer;
862
- const oDepth = this.fsw.options.depth;
863
- if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath2)) {
864
- if (!target) {
865
- await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
866
- if (this.fsw.closed)
867
- return;
868
- }
869
- closer = this._watchWithNodeFs(dir, (dirPath, stats2) => {
870
- if (stats2 && stats2.mtimeMs === 0)
871
- return;
872
- this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
873
- });
874
- }
875
- return closer;
876
- }
877
- async _addToNodeFs(path, initialAdd, priorWh, depth, target) {
878
- const ready = this.fsw._emitReady;
879
- if (this.fsw._isIgnored(path) || this.fsw.closed) {
880
- ready();
881
- return false;
882
- }
883
- const wh = this.fsw._getWatchHelpers(path);
884
- if (priorWh) {
885
- wh.filterPath = (entry) => priorWh.filterPath(entry);
886
- wh.filterDir = (entry) => priorWh.filterDir(entry);
887
- }
888
- try {
889
- const stats = await statMethods[wh.statMethod](wh.watchPath);
890
- if (this.fsw.closed)
891
- return;
892
- if (this.fsw._isIgnored(wh.watchPath, stats)) {
893
- ready();
894
- return false;
895
- }
896
- const follow = this.fsw.options.followSymlinks;
897
- let closer;
898
- if (stats.isDirectory()) {
899
- const absPath = sysPath.resolve(path);
900
- const targetPath = follow ? await fsrealpath(path) : path;
901
- if (this.fsw.closed)
902
- return;
903
- closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
904
- if (this.fsw.closed)
905
- return;
906
- if (absPath !== targetPath && targetPath !== undefined) {
907
- this.fsw._symlinkPaths.set(absPath, targetPath);
908
- }
909
- } else if (stats.isSymbolicLink()) {
910
- const targetPath = follow ? await fsrealpath(path) : path;
911
- if (this.fsw.closed)
912
- return;
913
- const parent = sysPath.dirname(wh.watchPath);
914
- this.fsw._getWatchedDir(parent).add(wh.watchPath);
915
- this.fsw._emit(EV.ADD, wh.watchPath, stats);
916
- closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath);
917
- if (this.fsw.closed)
918
- return;
919
- if (targetPath !== undefined) {
920
- this.fsw._symlinkPaths.set(sysPath.resolve(path), targetPath);
921
- }
922
- } else {
923
- closer = this._handleFile(wh.watchPath, stats, initialAdd);
924
- }
925
- ready();
926
- if (closer)
927
- this.fsw._addPathCloser(path, closer);
928
- return false;
929
- } catch (error) {
930
- if (this.fsw._handleError(error)) {
931
- ready();
932
- return path;
933
- }
934
- }
935
- }
936
- }
937
-
938
- // node_modules/chokidar/esm/index.js
939
- /*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) */
940
- var SLASH = "/";
941
- var SLASH_SLASH = "//";
942
- var ONE_DOT = ".";
943
- var TWO_DOTS = "..";
944
- var STRING_TYPE = "string";
945
- var BACK_SLASH_RE = /\\/g;
946
- var DOUBLE_SLASH_RE = /\/\//;
947
- var DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
948
- var REPLACER_RE = /^\.[/\\]/;
949
- function arrify(item) {
950
- return Array.isArray(item) ? item : [item];
951
- }
952
- var isMatcherObject = (matcher) => typeof matcher === "object" && matcher !== null && !(matcher instanceof RegExp);
953
- function createPattern(matcher) {
954
- if (typeof matcher === "function")
955
- return matcher;
956
- if (typeof matcher === "string")
957
- return (string) => matcher === string;
958
- if (matcher instanceof RegExp)
959
- return (string) => matcher.test(string);
960
- if (typeof matcher === "object" && matcher !== null) {
961
- return (string) => {
962
- if (matcher.path === string)
963
- return true;
964
- if (matcher.recursive) {
965
- const relative3 = sysPath2.relative(matcher.path, string);
966
- if (!relative3) {
967
- return false;
968
- }
969
- return !relative3.startsWith("..") && !sysPath2.isAbsolute(relative3);
970
- }
971
- return false;
972
- };
973
- }
974
- return () => false;
975
- }
976
- function normalizePath(path) {
977
- if (typeof path !== "string")
978
- throw new Error("string expected");
979
- path = sysPath2.normalize(path);
980
- path = path.replace(/\\/g, "/");
981
- let prepend = false;
982
- if (path.startsWith("//"))
983
- prepend = true;
984
- const DOUBLE_SLASH_RE2 = /\/\//;
985
- while (path.match(DOUBLE_SLASH_RE2))
986
- path = path.replace(DOUBLE_SLASH_RE2, "/");
987
- if (prepend)
988
- path = "/" + path;
989
- return path;
990
- }
991
- function matchPatterns(patterns, testString, stats) {
992
- const path = normalizePath(testString);
993
- for (let index = 0;index < patterns.length; index++) {
994
- const pattern = patterns[index];
995
- if (pattern(path, stats)) {
996
- return true;
997
- }
998
- }
999
- return false;
1000
- }
1001
- function anymatch(matchers, testString) {
1002
- if (matchers == null) {
1003
- throw new TypeError("anymatch: specify first argument");
1004
- }
1005
- const matchersArray = arrify(matchers);
1006
- const patterns = matchersArray.map((matcher) => createPattern(matcher));
1007
- if (testString == null) {
1008
- return (testString2, stats) => {
1009
- return matchPatterns(patterns, testString2, stats);
1010
- };
1011
- }
1012
- return matchPatterns(patterns, testString);
1013
- }
1014
- var unifyPaths = (paths_) => {
1015
- const paths = arrify(paths_).flat();
1016
- if (!paths.every((p) => typeof p === STRING_TYPE)) {
1017
- throw new TypeError(`Non-string provided as watch path: ${paths}`);
1018
- }
1019
- return paths.map(normalizePathToUnix);
1020
- };
1021
- var toUnix = (string) => {
1022
- let str = string.replace(BACK_SLASH_RE, SLASH);
1023
- let prepend = false;
1024
- if (str.startsWith(SLASH_SLASH)) {
1025
- prepend = true;
1026
- }
1027
- while (str.match(DOUBLE_SLASH_RE)) {
1028
- str = str.replace(DOUBLE_SLASH_RE, SLASH);
1029
- }
1030
- if (prepend) {
1031
- str = SLASH + str;
1032
- }
1033
- return str;
1034
- };
1035
- var normalizePathToUnix = (path) => toUnix(sysPath2.normalize(toUnix(path)));
1036
- var normalizeIgnored = (cwd = "") => (path) => {
1037
- if (typeof path === "string") {
1038
- return normalizePathToUnix(sysPath2.isAbsolute(path) ? path : sysPath2.join(cwd, path));
1039
- } else {
1040
- return path;
1041
- }
1042
- };
1043
- var getAbsolutePath = (path, cwd) => {
1044
- if (sysPath2.isAbsolute(path)) {
1045
- return path;
1046
- }
1047
- return sysPath2.join(cwd, path);
1048
- };
1049
- var EMPTY_SET = Object.freeze(new Set);
1050
-
1051
- class DirEntry {
1052
- constructor(dir, removeWatcher) {
1053
- this.path = dir;
1054
- this._removeWatcher = removeWatcher;
1055
- this.items = new Set;
1056
- }
1057
- add(item) {
1058
- const { items } = this;
1059
- if (!items)
1060
- return;
1061
- if (item !== ONE_DOT && item !== TWO_DOTS)
1062
- items.add(item);
1063
- }
1064
- async remove(item) {
1065
- const { items } = this;
1066
- if (!items)
1067
- return;
1068
- items.delete(item);
1069
- if (items.size > 0)
1070
- return;
1071
- const dir = this.path;
1072
- try {
1073
- await readdir2(dir);
1074
- } catch (err) {
1075
- if (this._removeWatcher) {
1076
- this._removeWatcher(sysPath2.dirname(dir), sysPath2.basename(dir));
1077
- }
1078
- }
1079
- }
1080
- has(item) {
1081
- const { items } = this;
1082
- if (!items)
1083
- return;
1084
- return items.has(item);
1085
- }
1086
- getChildren() {
1087
- const { items } = this;
1088
- if (!items)
1089
- return [];
1090
- return [...items.values()];
1091
- }
1092
- dispose() {
1093
- this.items.clear();
1094
- this.path = "";
1095
- this._removeWatcher = EMPTY_FN;
1096
- this.items = EMPTY_SET;
1097
- Object.freeze(this);
1098
- }
1099
- }
1100
- var STAT_METHOD_F = "stat";
1101
- var STAT_METHOD_L = "lstat";
1102
-
1103
- class WatchHelper {
1104
- constructor(path, follow, fsw) {
1105
- this.fsw = fsw;
1106
- const watchPath = path;
1107
- this.path = path = path.replace(REPLACER_RE, "");
1108
- this.watchPath = watchPath;
1109
- this.fullWatchPath = sysPath2.resolve(watchPath);
1110
- this.dirParts = [];
1111
- this.dirParts.forEach((parts) => {
1112
- if (parts.length > 1)
1113
- parts.pop();
67
+ collectIdentifiers(source);
68
+ const anonymousName = () => {
69
+ let name = "defaultExport";
70
+ while (identifiers.has(name)) name += "_";
71
+ identifiers.add(name);
72
+ return name;
73
+ };
74
+ function collect(name, fn) {
75
+ if (!fn.body) return;
76
+ functions.set(name, {
77
+ name,
78
+ parameters: fn.parameters.map((p) => p.name.getText(source)),
79
+ optionalParameters: fn.parameters.map(
80
+ (p) => !!(p.questionToken || p.initializer)
81
+ ),
82
+ restParameterIndex: fn.parameters.findIndex((p) => !!p.dotDotDotToken),
83
+ isAsync: !!has(fn, ts.SyntaxKind.AsyncKeyword),
84
+ isExported: false
1114
85
  });
1115
- this.followSymlinks = follow;
1116
- this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
1117
- }
1118
- entryPath(entry) {
1119
- return sysPath2.join(this.watchPath, sysPath2.relative(this.watchPath, entry.fullPath));
1120
- }
1121
- filterPath(entry) {
1122
- const { stats } = entry;
1123
- if (stats && stats.isSymbolicLink())
1124
- return this.filterDir(entry);
1125
- const resolvedPath = this.entryPath(entry);
1126
- return this.fsw._isntIgnored(resolvedPath, stats) && this.fsw._hasReadPermissions(stats);
1127
- }
1128
- filterDir(entry) {
1129
- return this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
1130
86
  }
1131
- }
1132
-
1133
- class FSWatcher extends EventEmitter {
1134
- constructor(_opts = {}) {
1135
- super();
1136
- this.closed = false;
1137
- this._closers = new Map;
1138
- this._ignoredPaths = new Set;
1139
- this._throttled = new Map;
1140
- this._streams = new Set;
1141
- this._symlinkPaths = new Map;
1142
- this._watched = new Map;
1143
- this._pendingWrites = new Map;
1144
- this._pendingUnlinks = new Map;
1145
- this._readyCount = 0;
1146
- this._readyEmitted = false;
1147
- const awf = _opts.awaitWriteFinish;
1148
- const DEF_AWF = { stabilityThreshold: 2000, pollInterval: 100 };
1149
- const opts = {
1150
- persistent: true,
1151
- ignoreInitial: false,
1152
- ignorePermissionErrors: false,
1153
- interval: 100,
1154
- binaryInterval: 300,
1155
- followSymlinks: true,
1156
- usePolling: false,
1157
- atomic: true,
1158
- ..._opts,
1159
- ignored: _opts.ignored ? arrify(_opts.ignored) : arrify([]),
1160
- awaitWriteFinish: awf === true ? DEF_AWF : typeof awf === "object" ? { ...DEF_AWF, ...awf } : false
1161
- };
1162
- if (isIBMi)
1163
- opts.usePolling = true;
1164
- if (opts.atomic === undefined)
1165
- opts.atomic = !opts.usePolling;
1166
- const envPoll = process.env.CHOKIDAR_USEPOLLING;
1167
- if (envPoll !== undefined) {
1168
- const envLower = envPoll.toLowerCase();
1169
- if (envLower === "false" || envLower === "0")
1170
- opts.usePolling = false;
1171
- else if (envLower === "true" || envLower === "1")
1172
- opts.usePolling = true;
1173
- else
1174
- opts.usePolling = !!envLower;
1175
- }
1176
- const envInterval = process.env.CHOKIDAR_INTERVAL;
1177
- if (envInterval)
1178
- opts.interval = Number.parseInt(envInterval, 10);
1179
- let readyCalls = 0;
1180
- this._emitReady = () => {
1181
- readyCalls++;
1182
- if (readyCalls >= this._readyCount) {
1183
- this._emitReady = EMPTY_FN;
1184
- this._readyEmitted = true;
1185
- process.nextTick(() => this.emit(EVENTS.READY));
87
+ for (const node of source.statements) {
88
+ if (has(node, ts.SyntaxKind.DeclareKeyword)) continue;
89
+ if (ts.isVariableStatement(node)) {
90
+ for (const decl of node.declarationList.declarations) {
91
+ const fn = unwrap(decl.initializer);
92
+ if (!ts.isIdentifier(decl.name) || !fn) continue;
93
+ collect(decl.name.text, fn);
94
+ if (has(node, ts.SyntaxKind.ExportKeyword))
95
+ exports.set(decl.name.text, decl.name.text);
1186
96
  }
1187
- };
1188
- this._emitRaw = (...args) => this.emit(EVENTS.RAW, ...args);
1189
- this._boundRemove = this._remove.bind(this);
1190
- this.options = opts;
1191
- this._nodeFsHandler = new NodeFsHandler(this);
1192
- Object.freeze(opts);
1193
- }
1194
- _addIgnoredPath(matcher) {
1195
- if (isMatcherObject(matcher)) {
1196
- for (const ignored of this._ignoredPaths) {
1197
- if (isMatcherObject(ignored) && ignored.path === matcher.path && ignored.recursive === matcher.recursive) {
1198
- return;
1199
- }
97
+ } else if (ts.isFunctionDeclaration(node) && node.body) {
98
+ const name = node.name?.text ?? anonymousName();
99
+ collect(name, node);
100
+ if (has(node, ts.SyntaxKind.ExportKeyword))
101
+ exports.set(
102
+ has(node, ts.SyntaxKind.DefaultKeyword) ? "default" : name,
103
+ name
104
+ );
105
+ } else if (ts.isExportDeclaration(node) && !node.moduleSpecifier && !node.isTypeOnly && node.exportClause && ts.isNamedExports(node.exportClause)) {
106
+ for (const item of node.exportClause.elements) {
107
+ if (!item.isTypeOnly)
108
+ exports.set(item.name.text, (item.propertyName ?? item.name).text);
1200
109
  }
1201
- }
1202
- this._ignoredPaths.add(matcher);
1203
- }
1204
- _removeIgnoredPath(matcher) {
1205
- this._ignoredPaths.delete(matcher);
1206
- if (typeof matcher === "string") {
1207
- for (const ignored of this._ignoredPaths) {
1208
- if (isMatcherObject(ignored) && ignored.path === matcher) {
1209
- this._ignoredPaths.delete(ignored);
110
+ } else if (ts.isExportAssignment(node)) {
111
+ if (node.isExportEquals)
112
+ throw new Error(
113
+ "CommonJS export assignment is not supported for API files."
114
+ );
115
+ if (ts.isIdentifier(node.expression))
116
+ exports.set("default", node.expression.text);
117
+ else {
118
+ const fn = unwrap(node.expression);
119
+ if (fn) {
120
+ const name = anonymousName();
121
+ collect(name, fn);
122
+ exports.set("default", name);
1210
123
  }
1211
124
  }
1212
125
  }
1213
126
  }
1214
- add(paths_, _origAdd, _internal) {
1215
- const { cwd } = this.options;
1216
- this.closed = false;
1217
- this._closePromise = undefined;
1218
- let paths = unifyPaths(paths_);
1219
- if (cwd) {
1220
- paths = paths.map((path) => {
1221
- const absPath = getAbsolutePath(path, cwd);
1222
- return absPath;
1223
- });
1224
- }
1225
- paths.forEach((path) => {
1226
- this._removeIgnoredPath(path);
1227
- });
1228
- this._userIgnored = undefined;
1229
- if (!this._readyCount)
1230
- this._readyCount = 0;
1231
- this._readyCount += paths.length;
1232
- Promise.all(paths.map(async (path) => {
1233
- const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, undefined, 0, _origAdd);
1234
- if (res)
1235
- this._emitReady();
1236
- return res;
1237
- })).then((results) => {
1238
- if (this.closed)
1239
- return;
1240
- results.forEach((item) => {
1241
- if (item)
1242
- this.add(sysPath2.dirname(item), sysPath2.basename(_origAdd || item));
1243
- });
1244
- });
1245
- return this;
1246
- }
1247
- unwatch(paths_) {
1248
- if (this.closed)
1249
- return this;
1250
- const paths = unifyPaths(paths_);
1251
- const { cwd } = this.options;
1252
- paths.forEach((path) => {
1253
- if (!sysPath2.isAbsolute(path) && !this._closers.has(path)) {
1254
- if (cwd)
1255
- path = sysPath2.join(cwd, path);
1256
- path = sysPath2.resolve(path);
1257
- }
1258
- this._closePath(path);
1259
- this._addIgnoredPath(path);
1260
- if (this._watched.has(path)) {
1261
- this._addIgnoredPath({
1262
- path,
1263
- recursive: true
1264
- });
127
+ const result = [];
128
+ const emitted = /* @__PURE__ */ new Map();
129
+ for (const [exportName, localName] of exports) {
130
+ const info = functions.get(localName);
131
+ if (info) {
132
+ const name = exportName === "default" ? localName : exportName;
133
+ if (emitted.has(name)) {
134
+ if (emitted.get(name) !== localName)
135
+ throw new Error("Conflicting exports; rename the default export.");
136
+ continue;
1265
137
  }
1266
- this._userIgnored = undefined;
1267
- });
1268
- return this;
1269
- }
1270
- close() {
1271
- if (this._closePromise) {
1272
- return this._closePromise;
1273
- }
1274
- this.closed = true;
1275
- this.removeAllListeners();
1276
- const closers = [];
1277
- this._closers.forEach((closerList) => closerList.forEach((closer) => {
1278
- const promise = closer();
1279
- if (promise instanceof Promise)
1280
- closers.push(promise);
1281
- }));
1282
- this._streams.forEach((stream) => stream.destroy());
1283
- this._userIgnored = undefined;
1284
- this._readyCount = 0;
1285
- this._readyEmitted = false;
1286
- this._watched.forEach((dirent) => dirent.dispose());
1287
- this._closers.clear();
1288
- this._watched.clear();
1289
- this._streams.clear();
1290
- this._symlinkPaths.clear();
1291
- this._throttled.clear();
1292
- this._closePromise = closers.length ? Promise.all(closers).then(() => {
1293
- return;
1294
- }) : Promise.resolve();
1295
- return this._closePromise;
1296
- }
1297
- getWatched() {
1298
- const watchList = {};
1299
- this._watched.forEach((entry, dir) => {
1300
- const key = this.options.cwd ? sysPath2.relative(this.options.cwd, dir) : dir;
1301
- const index = key || ONE_DOT;
1302
- watchList[index] = entry.getChildren().sort();
1303
- });
1304
- return watchList;
1305
- }
1306
- emitWithAll(event, args) {
1307
- this.emit(event, ...args);
1308
- if (event !== EVENTS.ERROR)
1309
- this.emit(EVENTS.ALL, event, ...args);
1310
- }
1311
- async _emit(event, path, stats) {
1312
- if (this.closed)
1313
- return;
1314
- const opts = this.options;
1315
- if (isWindows)
1316
- path = sysPath2.normalize(path);
1317
- if (opts.cwd)
1318
- path = sysPath2.relative(opts.cwd, path);
1319
- const args = [path];
1320
- if (stats != null)
1321
- args.push(stats);
1322
- const awf = opts.awaitWriteFinish;
1323
- let pw;
1324
- if (awf && (pw = this._pendingWrites.get(path))) {
1325
- pw.lastChange = new Date;
1326
- return this;
1327
- }
1328
- if (opts.atomic) {
1329
- if (event === EVENTS.UNLINK) {
1330
- this._pendingUnlinks.set(path, [event, ...args]);
1331
- setTimeout(() => {
1332
- this._pendingUnlinks.forEach((entry, path2) => {
1333
- this.emit(...entry);
1334
- this.emit(EVENTS.ALL, ...entry);
1335
- this._pendingUnlinks.delete(path2);
1336
- });
1337
- }, typeof opts.atomic === "number" ? opts.atomic : 100);
1338
- return this;
1339
- }
1340
- if (event === EVENTS.ADD && this._pendingUnlinks.has(path)) {
1341
- event = EVENTS.CHANGE;
1342
- this._pendingUnlinks.delete(path);
1343
- }
1344
- }
1345
- if (awf && (event === EVENTS.ADD || event === EVENTS.CHANGE) && this._readyEmitted) {
1346
- const awfEmit = (err, stats2) => {
1347
- if (err) {
1348
- event = EVENTS.ERROR;
1349
- args[0] = err;
1350
- this.emitWithAll(event, args);
1351
- } else if (stats2) {
1352
- if (args.length > 1) {
1353
- args[1] = stats2;
1354
- } else {
1355
- args.push(stats2);
1356
- }
1357
- this.emitWithAll(event, args);
1358
- }
1359
- };
1360
- this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);
1361
- return this;
1362
- }
1363
- if (event === EVENTS.CHANGE) {
1364
- const isThrottled = !this._throttle(EVENTS.CHANGE, path, 50);
1365
- if (isThrottled)
1366
- return this;
1367
- }
1368
- if (opts.alwaysStat && stats === undefined && (event === EVENTS.ADD || event === EVENTS.ADD_DIR || event === EVENTS.CHANGE)) {
1369
- const fullPath = opts.cwd ? sysPath2.join(opts.cwd, path) : path;
1370
- let stats2;
1371
- try {
1372
- stats2 = await stat3(fullPath);
1373
- } catch (err) {}
1374
- if (!stats2 || this.closed)
1375
- return;
1376
- args.push(stats2);
138
+ emitted.set(name, localName);
139
+ result.push({ ...info, name, importName: exportName, isExported: true });
1377
140
  }
1378
- this.emitWithAll(event, args);
1379
- return this;
1380
141
  }
1381
- _handleError(error) {
1382
- const code = error && error.code;
1383
- if (error && code !== "ENOENT" && code !== "ENOTDIR" && (!this.options.ignorePermissionErrors || code !== "EPERM" && code !== "EACCES")) {
1384
- this.emit(EVENTS.ERROR, error);
1385
- }
1386
- return error || this.closed;
1387
- }
1388
- _throttle(actionType, path, timeout) {
1389
- if (!this._throttled.has(actionType)) {
1390
- this._throttled.set(actionType, new Map);
1391
- }
1392
- const action = this._throttled.get(actionType);
1393
- if (!action)
1394
- throw new Error("invalid throttle");
1395
- const actionPath = action.get(path);
1396
- if (actionPath) {
1397
- actionPath.count++;
1398
- return false;
1399
- }
1400
- let timeoutObject;
1401
- const clear = () => {
1402
- const item = action.get(path);
1403
- const count = item ? item.count : 0;
1404
- action.delete(path);
1405
- clearTimeout(timeoutObject);
1406
- if (item)
1407
- clearTimeout(item.timeoutObject);
1408
- return count;
1409
- };
1410
- timeoutObject = setTimeout(clear, timeout);
1411
- const thr = { timeoutObject, clear, count: 0 };
1412
- action.set(path, thr);
1413
- return thr;
1414
- }
1415
- _incrReadyCount() {
1416
- return this._readyCount++;
1417
- }
1418
- _awaitWriteFinish(path, threshold, event, awfEmit) {
1419
- const awf = this.options.awaitWriteFinish;
1420
- if (typeof awf !== "object")
1421
- return;
1422
- const pollInterval = awf.pollInterval;
1423
- let timeoutHandler;
1424
- let fullPath = path;
1425
- if (this.options.cwd && !sysPath2.isAbsolute(path)) {
1426
- fullPath = sysPath2.join(this.options.cwd, path);
1427
- }
1428
- const now = new Date;
1429
- const writes = this._pendingWrites;
1430
- function awaitWriteFinishFn(prevStat) {
1431
- statcb(fullPath, (err, curStat) => {
1432
- if (err || !writes.has(path)) {
1433
- if (err && err.code !== "ENOENT")
1434
- awfEmit(err);
1435
- return;
1436
- }
1437
- const now2 = Number(new Date);
1438
- if (prevStat && curStat.size !== prevStat.size) {
1439
- writes.get(path).lastChange = now2;
1440
- }
1441
- const pw = writes.get(path);
1442
- const df = now2 - pw.lastChange;
1443
- if (df >= threshold) {
1444
- writes.delete(path);
1445
- awfEmit(undefined, curStat);
1446
- } else {
1447
- timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval, curStat);
1448
- }
1449
- });
1450
- }
1451
- if (!writes.has(path)) {
1452
- writes.set(path, {
1453
- lastChange: now,
1454
- cancelWait: () => {
1455
- writes.delete(path);
1456
- clearTimeout(timeoutHandler);
1457
- return event;
1458
- }
1459
- });
1460
- timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval);
1461
- }
1462
- }
1463
- _isIgnored(path, stats) {
1464
- if (this.options.atomic && DOT_RE.test(path))
1465
- return true;
1466
- if (!this._userIgnored) {
1467
- const { cwd } = this.options;
1468
- const ign = this.options.ignored;
1469
- const ignored = (ign || []).map(normalizeIgnored(cwd));
1470
- const ignoredPaths = [...this._ignoredPaths];
1471
- const list = [...ignoredPaths.map(normalizeIgnored(cwd)), ...ignored];
1472
- this._userIgnored = anymatch(list, undefined);
1473
- }
1474
- return this._userIgnored(path, stats);
1475
- }
1476
- _isntIgnored(path, stat4) {
1477
- return !this._isIgnored(path, stat4);
1478
- }
1479
- _getWatchHelpers(path) {
1480
- return new WatchHelper(path, this.options.followSymlinks, this);
1481
- }
1482
- _getWatchedDir(directory) {
1483
- const dir = sysPath2.resolve(directory);
1484
- if (!this._watched.has(dir))
1485
- this._watched.set(dir, new DirEntry(dir, this._boundRemove));
1486
- return this._watched.get(dir);
1487
- }
1488
- _hasReadPermissions(stats) {
1489
- if (this.options.ignorePermissionErrors)
1490
- return true;
1491
- return Boolean(Number(stats.mode) & 256);
1492
- }
1493
- _remove(directory, item, isDirectory) {
1494
- const path = sysPath2.join(directory, item);
1495
- const fullPath = sysPath2.resolve(path);
1496
- isDirectory = isDirectory != null ? isDirectory : this._watched.has(path) || this._watched.has(fullPath);
1497
- if (!this._throttle("remove", path, 100))
1498
- return;
1499
- if (!isDirectory && this._watched.size === 1) {
1500
- this.add(directory, item, true);
1501
- }
1502
- const wp = this._getWatchedDir(path);
1503
- const nestedDirectoryChildren = wp.getChildren();
1504
- nestedDirectoryChildren.forEach((nested) => this._remove(path, nested));
1505
- const parent = this._getWatchedDir(directory);
1506
- const wasTracked = parent.has(item);
1507
- parent.remove(item);
1508
- if (this._symlinkPaths.has(fullPath)) {
1509
- this._symlinkPaths.delete(fullPath);
1510
- }
1511
- let relPath = path;
1512
- if (this.options.cwd)
1513
- relPath = sysPath2.relative(this.options.cwd, path);
1514
- if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
1515
- const event = this._pendingWrites.get(relPath).cancelWait();
1516
- if (event === EVENTS.ADD)
1517
- return;
1518
- }
1519
- this._watched.delete(path);
1520
- this._watched.delete(fullPath);
1521
- const eventName = isDirectory ? EVENTS.UNLINK_DIR : EVENTS.UNLINK;
1522
- if (wasTracked && !this._isIgnored(path))
1523
- this._emit(eventName, path);
1524
- this._closePath(path);
1525
- }
1526
- _closePath(path) {
1527
- this._closeFile(path);
1528
- const dir = sysPath2.dirname(path);
1529
- this._getWatchedDir(dir).remove(sysPath2.basename(path));
1530
- }
1531
- _closeFile(path) {
1532
- const closers = this._closers.get(path);
1533
- if (!closers)
1534
- return;
1535
- closers.forEach((closer) => closer());
1536
- this._closers.delete(path);
1537
- }
1538
- _addPathCloser(path, closer) {
1539
- if (!closer)
1540
- return;
1541
- let list = this._closers.get(path);
1542
- if (!list) {
1543
- list = [];
1544
- this._closers.set(path, list);
1545
- }
1546
- list.push(closer);
1547
- }
1548
- _readdirp(root, opts) {
1549
- if (this.closed)
1550
- return;
1551
- const options = { type: EVENTS.ALL, alwaysStat: true, lstat: true, ...opts, depth: 0 };
1552
- let stream = readdirp(root, options);
1553
- this._streams.add(stream);
1554
- stream.once(STR_CLOSE, () => {
1555
- stream = undefined;
1556
- });
1557
- stream.once(STR_END, () => {
1558
- if (stream) {
1559
- this._streams.delete(stream);
1560
- stream = undefined;
1561
- }
1562
- });
1563
- return stream;
1564
- }
1565
- }
1566
- function watch(paths, options = {}) {
1567
- const watcher = new FSWatcher(options);
1568
- watcher.add(paths);
1569
- return watcher;
1570
- }
1571
-
1572
- // src/cli.ts
1573
- import {
1574
- basename as basename3,
1575
- dirname as dirname4,
1576
- extname as extname3,
1577
- join as join4,
1578
- relative as relative3,
1579
- resolve as resolve4,
1580
- sep
1581
- } from "path";
1582
- import { writeFileSync, existsSync as existsSync2, mkdirSync, unlinkSync } from "fs";
1583
- import { pathToFileURL as pathToFileURL2 } from "url";
1584
-
1585
- // src/core/analyzer.ts
1586
- import ts from "typescript";
1587
- import { readFileSync } from "fs";
1588
- function shouldIncludeFunction(info, config = {}) {
1589
- const exportFilter = config.exportFilter ?? "exported-only";
1590
- const functionMatchMode = config.functionMatchMode ?? "all";
1591
- if (exportFilter === "exported-only" && !info.isExported) {
1592
- return false;
1593
- }
1594
- if (functionMatchMode === "async-only" && !info.isAsync) {
1595
- return false;
1596
- }
1597
- if (functionMatchMode === "sync-only" && info.isAsync) {
1598
- return false;
1599
- }
1600
- if (config.includeNames?.length && !config.includeNames.includes(info.name)) {
1601
- return false;
1602
- }
1603
- if (config.excludeNames?.includes(info.name)) {
1604
- return false;
1605
- }
1606
- return true;
1607
- }
1608
- function unwrapFunctionLike(node) {
1609
- if (!node) {
1610
- return;
142
+ if (config.exportFilter === "all") {
143
+ for (const [name, info] of functions)
144
+ if (![...exports.values()].includes(name)) result.push(info);
1611
145
  }
1612
- if (ts.isArrowFunction(node) || ts.isFunctionExpression(node)) {
1613
- return node;
1614
- }
1615
- if (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isTypeAssertionExpression(node) || ts.isSatisfiesExpression(node) || ts.isNonNullExpression(node)) {
1616
- return unwrapFunctionLike(node.expression);
1617
- }
1618
- return;
1619
- }
1620
- function getFunctionInfo(name, parameters, isAsync, isExported, sourceFile) {
1621
- return {
1622
- name,
1623
- parameters: parameters.map((param) => param.name.getText(sourceFile)),
1624
- isAsync,
1625
- isExported
1626
- };
1627
- }
1628
- function analyzeFile(filePath, config = {}) {
1629
- const sourceCode = readFileSync(filePath, "utf8");
1630
- const scriptKind = filePath.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS;
1631
- const sourceFile = ts.createSourceFile(filePath, sourceCode, ts.ScriptTarget.Latest, true, scriptKind);
1632
- const functionInfos = [];
1633
- const hasExportModifier = (node) => ts.canHaveModifiers(node) && !!ts.getModifiers(node)?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword);
1634
- ts.forEachChild(sourceFile, (node) => {
1635
- if (ts.isVariableStatement(node)) {
1636
- const isExported = hasExportModifier(node);
1637
- node.declarationList.declarations.forEach((declaration) => {
1638
- if (ts.isVariableDeclaration(declaration) && ts.isIdentifier(declaration.name)) {
1639
- const initializer = unwrapFunctionLike(declaration.initializer);
1640
- if (initializer) {
1641
- functionInfos.push(getFunctionInfo(declaration.name.text, initializer.parameters, !!initializer.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword), isExported, sourceFile));
1642
- }
1643
- }
1644
- });
1645
- } else if (ts.isFunctionDeclaration(node) && node.name) {
1646
- functionInfos.push(getFunctionInfo(node.name.text, node.parameters, !!node.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword), hasExportModifier(node), sourceFile));
1647
- }
1648
- });
1649
- return functionInfos.filter((info) => shouldIncludeFunction(info, config));
146
+ return result.filter(
147
+ (info) => (config.functionMatchMode !== "async-only" || info.isAsync) && (config.functionMatchMode !== "sync-only" || !info.isAsync) && (!config.includeNames?.length || config.includeNames.includes(info.name)) && !config.excludeNames?.includes(info.name)
148
+ );
1650
149
  }
1651
150
 
1652
151
  // src/core/generator.ts
1653
- var DEFAULT_IMPORT_NAMES = {
152
+ import ts2 from "typescript";
153
+ var imports = {
1654
154
  query: "queryOption",
1655
155
  mutation: "mutationOption",
1656
156
  infinite: "infiniteOption"
1657
157
  };
1658
- var DEFAULT_OUTPUT_NAMES = {
158
+ var suffixes = {
1659
159
  query: "QueryOption",
1660
160
  mutation: "MutationOption",
1661
161
  infinite: "InfiniteQueryOption"
1662
162
  };
1663
- var MUTATION_NAME_PATTERN = /^(create|post|add|update|put|patch|delete|remove|set|send|upload|signIn|signOut|login|logout|mutate)/i;
1664
- var QUERY_NAME_PATTERN = /^(get|list|fetch|find|read|load|search|retrieve|detail|details)/i;
1665
- function isSimpleParameterName(name) {
1666
- return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name);
1667
- }
1668
- function getMutationVariablesTypeName(functionName) {
1669
- return `${functionName}MutationVariables`;
1670
- }
1671
- function buildMutationVariablesType(info) {
1672
- if (info.parameters.length <= 1 || !info.parameters.every(isSimpleParameterName)) {
1673
- return null;
1674
- }
1675
- const lines = info.parameters.map((parameterName, index) => ` ${parameterName}: Parameters<typeof ${info.name}>[${index}];`);
1676
- return `export type ${getMutationVariablesTypeName(info.name)} = {
1677
- ${lines.join(`
1678
- `)}
1679
- };
1680
- `;
1681
- }
1682
- function buildMutationOptionExpression(info, importName, keyName) {
1683
- if (info.parameters.length <= 1 || !info.parameters.every(isSimpleParameterName)) {
1684
- return `${importName}(${keyName}, ${info.name})`;
1685
- }
1686
- const variablesTypeName = getMutationVariablesTypeName(info.name);
1687
- const argumentMapping = info.parameters.map((parameterName) => `variables.${parameterName}`).join(", ");
1688
- return `${importName}<Parameters<typeof ${info.name}>, Awaited<ReturnType<typeof ${info.name}>>, ${variablesTypeName}>(${keyName}, ${info.name}, { mapVariablesToArgs: (variables) => [${argumentMapping}] })`;
1689
- }
1690
- function resolveArtifacts(info, enabledArtifacts, strategy) {
1691
- if (strategy === "all") {
1692
- return enabledArtifacts;
1693
- }
1694
- if (MUTATION_NAME_PATTERN.test(info.name)) {
1695
- return enabledArtifacts.filter((artifact) => artifact === "mutation");
1696
- }
1697
- if (QUERY_NAME_PATTERN.test(info.name)) {
1698
- return enabledArtifacts.filter((artifact) => artifact === "query" || artifact === "infinite");
1699
- }
1700
- return enabledArtifacts.filter((artifact) => artifact !== "infinite");
1701
- }
1702
- function getKeySegments(info, fileName, keySegments, keyStyle) {
1703
- switch (keyStyle) {
1704
- case "function-only":
1705
- return [info.name];
1706
- case "file-only":
1707
- return [fileName, info.name];
1708
- case "path":
1709
- default:
1710
- return [...keySegments, info.name];
1711
- }
1712
- }
1713
- function generateOptionsCode(functionInfos, importPath, { keySegments, fileName, templateImportPath, template }) {
1714
- if (functionInfos.length === 0) {
1715
- return "";
1716
- }
1717
- const enabledArtifacts = template?.enabledArtifacts?.length ? template.enabledArtifacts : ["query", "mutation", "infinite"];
1718
- const importNames = {
1719
- ...DEFAULT_IMPORT_NAMES,
1720
- ...template?.importNames
1721
- };
1722
- const outputNames = {
1723
- ...DEFAULT_OUTPUT_NAMES,
1724
- ...template?.outputNames
1725
- };
1726
- const artifactStrategy = template?.artifactStrategy ?? "smart";
1727
- const helperImports = [...new Set(enabledArtifacts.map((artifact) => importNames[artifact]))];
1728
- const functionNames = functionInfos.map((info) => info.name);
1729
- const keyStyle = template?.keyStyle ?? "path";
1730
- let newContent = `import { ${functionNames.join(", ")} } from "${importPath}";
163
+ var mutationPattern = /^(create|post|add|update|put|patch|delete|remove|set|send|upload|signIn|signOut|login|logout|mutate)(?=[A-Z_\d]|$)/;
164
+ var queryPattern = /^(get|list|fetch|find|read|load|search|retrieve|detail|details)(?=[A-Z_\d]|$)/;
165
+ function validIdentifier(name) {
166
+ const scanner = ts2.createScanner(
167
+ ts2.ScriptTarget.Latest,
168
+ false,
169
+ ts2.LanguageVariant.Standard,
170
+ name
171
+ );
172
+ const token = scanner.scan();
173
+ return (token === ts2.SyntaxKind.Identifier || token >= ts2.SyntaxKind.AbstractKeyword && token <= ts2.SyntaxKind.OfKeyword && token !== ts2.SyntaxKind.AwaitKeyword) && scanner.getTokenText() === name && scanner.scan() === ts2.SyntaxKind.EndOfFileToken;
174
+ }
175
+ function generateOptionsCode(functionInfos, importPath, {
176
+ keySegments,
177
+ fileName,
178
+ templateImportPath,
179
+ template = {}
180
+ }) {
181
+ const enabled = template.enabledArtifacts ?? [
182
+ "query",
183
+ "mutation",
184
+ "infinite"
185
+ ];
186
+ const strategy = template.artifactStrategy ?? "smart";
187
+ const rows = functionInfos.map((info) => {
188
+ let artifacts = template.artifactsByName?.[info.name] ?? enabled;
189
+ if (!template.artifactsByName?.[info.name] && strategy === "smart") {
190
+ artifacts = artifacts.filter(
191
+ (a) => mutationPattern.test(info.name) ? a === "mutation" : queryPattern.test(info.name) ? a !== "mutation" : a !== "infinite"
192
+ );
193
+ }
194
+ return {
195
+ info,
196
+ artifacts: [...new Set(artifacts.filter((a) => enabled.includes(a)))]
197
+ };
198
+ }).filter((row) => row.artifacts.length);
199
+ if (!rows.length) return "";
200
+ const occupied = /* @__PURE__ */ new Set();
201
+ function reserve(name) {
202
+ if (!validIdentifier(name) || occupied.has(name))
203
+ throw new Error(`Invalid or duplicate generated identifier: ${name}`);
204
+ occupied.add(name);
205
+ return name;
206
+ }
207
+ for (const { info } of rows) {
208
+ if (!info.isExported)
209
+ throw new Error(
210
+ `Cannot import private function ${info.name}. Export it or use a custom template.`
211
+ );
212
+ reserve(info.name);
213
+ }
214
+ for (const { info, artifacts } of rows) {
215
+ reserve(`${info.name}Key`);
216
+ for (const a of artifacts)
217
+ reserve(`${info.name}${template.outputNames?.[a] ?? suffixes[a]}`);
218
+ }
219
+ const helpers = /* @__PURE__ */ new Map();
220
+ const helperImports = [];
221
+ for (const a of new Set(rows.flatMap((row) => row.artifacts))) {
222
+ const name = template.importNames?.[a] ?? imports[a];
223
+ if (!validIdentifier(name))
224
+ throw new Error(`Invalid helper import: ${name}`);
225
+ let alias = `__rqh_${a}`;
226
+ while (occupied.has(alias)) alias += "_";
227
+ reserve(alias);
228
+ helpers.set(a, alias);
229
+ helperImports.push(`${name} as ${alias}`);
230
+ }
231
+ let code = `import { ${rows.map(
232
+ ({ info }) => info.importName && info.importName !== info.name ? `${info.importName === "default" ? "default" : JSON.stringify(info.importName)} as ${info.name}` : info.name
233
+ ).join(", ")} } from ${JSON.stringify(importPath)};
1731
234
  `;
1732
- newContent += `import { ${helperImports.join(", ")} } from "${templateImportPath}";
235
+ code += `import { ${helperImports.join(", ")} } from ${JSON.stringify(templateImportPath)};
1733
236
 
1734
237
  `;
1735
- functionInfos.forEach((info) => {
1736
- const resolvedArtifacts = resolveArtifacts(info, enabledArtifacts, artifactStrategy);
1737
- if (resolvedArtifacts.length === 0) {
1738
- return;
1739
- }
1740
- const keyArray = JSON.stringify(getKeySegments(info, fileName, keySegments, keyStyle));
238
+ for (const { info, artifacts } of rows) {
239
+ const base = template.keyStyle === "function-only" ? [] : template.keyStyle === "file-only" ? [fileName] : [...keySegments, fileName];
1741
240
  const keyName = `${info.name}Key`;
1742
- const mutationVariablesType = buildMutationVariablesType(info);
1743
- if (mutationVariablesType && resolvedArtifacts.includes("mutation")) {
1744
- newContent += mutationVariablesType;
1745
- }
1746
- newContent += `export const ${keyName} = ${keyArray} as const;
241
+ code += `export const ${keyName} = ${JSON.stringify([...base, info.name])} as const;
1747
242
  `;
1748
- resolvedArtifacts.forEach((artifact) => {
1749
- const optionExpression = artifact === "mutation" ? buildMutationOptionExpression(info, importNames[artifact], keyName) : `${importNames[artifact]}(${keyName}, ${info.name})`;
1750
- newContent += `export const ${info.name}${outputNames[artifact]} = ${optionExpression};
243
+ for (const artifact of artifacts) {
244
+ const helper = helpers.get(artifact);
245
+ let expression = `${helper}(${keyName}, ${info.name})`;
246
+ if (artifact === "mutation") {
247
+ const hasRest = info.restParameterIndex !== void 0 && info.restParameterIndex >= 0;
248
+ if (info.parameters.length > 1 && !hasRest && info.parameters.every(validIdentifier)) {
249
+ const typeName = reserve(`${info.name}MutationVariables`);
250
+ code += `export type ${typeName} = {
251
+ ${info.parameters.map(
252
+ (p, i) => ` ${p}${info.optionalParameters?.[i] ? "?" : ""}: Parameters<typeof ${info.name}>[${i}];`
253
+ ).join("\n")}
254
+ };
1751
255
  `;
1752
- });
1753
- newContent += `
256
+ expression = `${helper}<Parameters<typeof ${info.name}>, Awaited<ReturnType<typeof ${info.name}>>, ${typeName}>(${keyName}, ${info.name}, { mapVariablesToArgs: (variables) => [${info.parameters.map((p) => `variables.${p}`).join(", ")}] })`;
257
+ } else if (info.parameters.length > 1 || hasRest) {
258
+ expression = `${helper}(${keyName}, ${info.name}, { variablesMode: "tuple" })`;
259
+ }
260
+ }
261
+ code += `export const ${info.name}${template.outputNames?.[artifact] ?? suffixes[artifact]} = ${expression};
1754
262
  `;
1755
- });
1756
- return newContent;
263
+ }
264
+ code += "\n";
265
+ }
266
+ return code;
1757
267
  }
1758
268
 
1759
269
  // src/config-loader.ts
1760
- import { existsSync } from "fs";
1761
- import { readFile, unlink, writeFile } from "fs/promises";
1762
- import { randomUUID } from "crypto";
1763
- import { dirname as dirname3, extname as extname2, join as join3, resolve as resolve3 } from "path";
1764
- import { pathToFileURL } from "url";
1765
- import ts2 from "typescript";
1766
-
1767
- class ConfigLoadError extends Error {
1768
- configPath;
1769
- cause;
270
+ import { existsSync } from "node:fs";
271
+ import { dirname, join, resolve, isAbsolute } from "node:path";
272
+ import { createJiti } from "jiti";
273
+ var ConfigLoadError = class extends Error {
1770
274
  constructor(message, configPath, cause) {
1771
275
  super(message);
1772
276
  this.configPath = configPath;
1773
277
  this.cause = cause;
1774
278
  this.name = "ConfigLoadError";
1775
279
  }
1776
- }
1777
- var defaultConfig = {
1778
- sourceDir: "./libs",
1779
- outputDir: "./src/options",
1780
- ignoredFiles: ["domain.ts", "adaptor.ts"],
1781
- templateDir: "@uiwwsw/react-query-helper"
280
+ configPath;
281
+ cause;
1782
282
  };
1783
- var CONFIG_FILE_NAMES = [
1784
- "rqh.config.ts",
1785
- "rqh.config.mts",
1786
- "rqh.config.cts",
1787
- "rqh.config.js",
1788
- "rqh.config.mjs",
1789
- "rqh.config.cjs"
1790
- ];
1791
- var TYPESCRIPT_CONFIG_EXTENSIONS = new Set([".ts", ".mts", ".cts"]);
1792
- async function importTypeScriptConfig(configPath) {
1793
- const source = await readFile(configPath, "utf8");
1794
- const transpiled = ts2.transpileModule(source, {
1795
- compilerOptions: {
1796
- module: ts2.ModuleKind.ESNext,
1797
- target: ts2.ScriptTarget.ES2020,
1798
- moduleResolution: ts2.ModuleResolutionKind.Bundler,
1799
- esModuleInterop: true
1800
- },
1801
- fileName: configPath
283
+ var configNames = ["ts", "mts", "cts", "js", "mjs", "cjs"].map(
284
+ (ext) => `rqh.config.${ext}`
285
+ );
286
+ function resolveConfigPath(cwd = process.cwd()) {
287
+ let dir = resolve(cwd);
288
+ while (true) {
289
+ const found = configNames.map((name) => join(dir, name)).filter(existsSync);
290
+ if (found.length > 1)
291
+ throw new ConfigLoadError(
292
+ `Multiple config files found: ${found.join(", ")}`
293
+ );
294
+ if (found[0]) return found[0];
295
+ const parent = dirname(dir);
296
+ if (parent === dir) return;
297
+ dir = parent;
298
+ }
299
+ }
300
+ async function loadModule(specifier, configDir) {
301
+ const jiti = createJiti(join(configDir, "rqh.loader.cjs"), {
302
+ interopDefault: false,
303
+ moduleCache: false,
304
+ fsCache: false
1802
305
  });
1803
- const tempFilePath = join3(dirname3(configPath), `.rqh.config.${randomUUID()}.mjs`);
1804
- await writeFile(tempFilePath, transpiled.outputText, "utf8");
1805
- try {
1806
- return await import(pathToFileURL(tempFilePath).href);
1807
- } finally {
1808
- await unlink(tempFilePath).catch(() => {
1809
- return;
1810
- });
1811
- }
1812
- }
1813
- async function importConfig(configPath) {
1814
- if (TYPESCRIPT_CONFIG_EXTENSIONS.has(extname2(configPath).toLowerCase())) {
1815
- return importTypeScriptConfig(configPath);
306
+ return await jiti.import(specifier);
307
+ }
308
+ function object(value, label) {
309
+ if (!value || typeof value !== "object" || Array.isArray(value))
310
+ throw new Error(`${label} must be an object.`);
311
+ }
312
+ function keys(value, allowed, label) {
313
+ for (const key of Object.keys(value))
314
+ if (!allowed.includes(key))
315
+ throw new Error(`Unknown ${label} option: ${key}`);
316
+ }
317
+ function string(value, label) {
318
+ if (typeof value !== "string" || !value.trim())
319
+ throw new Error(`${label} must be a non-empty string.`);
320
+ }
321
+ function strings(value, label) {
322
+ if (!Array.isArray(value) || value.some((v) => typeof v !== "string" || !v.trim()))
323
+ throw new Error(`${label} must be an array of non-empty strings.`);
324
+ }
325
+ function choice(value, allowed, label) {
326
+ if (!allowed.includes(value))
327
+ throw new Error(`${label} must be one of: ${allowed.join(", ")}`);
328
+ }
329
+ function validate(value) {
330
+ object(value, "Config");
331
+ keys(
332
+ value,
333
+ [
334
+ "sourceDir",
335
+ "outputDir",
336
+ "templateDir",
337
+ "sourceImportAlias",
338
+ "ignoredFiles",
339
+ "analyzer",
340
+ "template",
341
+ "customAnalyzerPath",
342
+ "customTemplatePath"
343
+ ],
344
+ "config"
345
+ );
346
+ for (const field of [
347
+ "sourceDir",
348
+ "outputDir",
349
+ "templateDir",
350
+ "sourceImportAlias",
351
+ "customAnalyzerPath",
352
+ "customTemplatePath"
353
+ ])
354
+ if (field in value) string(value[field], field);
355
+ if ("ignoredFiles" in value) strings(value.ignoredFiles, "ignoredFiles");
356
+ if (value.analyzer !== void 0) {
357
+ const a = value.analyzer;
358
+ object(a, "analyzer");
359
+ keys(
360
+ a,
361
+ ["exportFilter", "functionMatchMode", "includeNames", "excludeNames"],
362
+ "analyzer"
363
+ );
364
+ if (a.exportFilter !== void 0)
365
+ choice(a.exportFilter, ["exported-only", "all"], "exportFilter");
366
+ if (a.functionMatchMode !== void 0)
367
+ choice(
368
+ a.functionMatchMode,
369
+ ["all", "async-only", "sync-only"],
370
+ "functionMatchMode"
371
+ );
372
+ for (const field of ["includeNames", "excludeNames"])
373
+ if (a[field] !== void 0) strings(a[field], field);
374
+ }
375
+ if (value.template !== void 0) {
376
+ const t = value.template;
377
+ object(t, "template");
378
+ keys(
379
+ t,
380
+ [
381
+ "enabledArtifacts",
382
+ "artifactStrategy",
383
+ "keyStyle",
384
+ "importNames",
385
+ "outputNames",
386
+ "artifactsByName"
387
+ ],
388
+ "template"
389
+ );
390
+ const artifacts = ["query", "mutation", "infinite"];
391
+ const artifactList = (v) => {
392
+ strings(v, "artifacts");
393
+ v.forEach((a) => choice(a, artifacts, "artifact"));
394
+ };
395
+ if (t.enabledArtifacts !== void 0) artifactList(t.enabledArtifacts);
396
+ if (t.artifactStrategy !== void 0)
397
+ choice(t.artifactStrategy, ["all", "smart"], "artifactStrategy");
398
+ if (t.keyStyle !== void 0)
399
+ choice(t.keyStyle, ["path", "file-only", "function-only"], "keyStyle");
400
+ if (t.artifactsByName !== void 0) {
401
+ object(t.artifactsByName, "artifactsByName");
402
+ Object.values(t.artifactsByName).forEach(artifactList);
403
+ }
404
+ for (const field of ["importNames", "outputNames"])
405
+ if (t[field] !== void 0) {
406
+ object(t[field], field);
407
+ keys(t[field], artifacts, field);
408
+ for (const name of Object.values(t[field])) {
409
+ if (typeof name !== "string" || !validIdentifier(name))
410
+ throw new Error(`Invalid identifier in ${field}: ${name}`);
411
+ }
412
+ }
1816
413
  }
1817
- return import(pathToFileURL(configPath).href);
1818
- }
1819
- function resolveConfigPath(cwd = process.cwd()) {
1820
- return CONFIG_FILE_NAMES.map((fileName) => join3(cwd, fileName)).find((configPath) => existsSync(configPath));
1821
414
  }
1822
- async function loadConfig() {
1823
- const configPath = resolveConfigPath();
1824
- if (configPath) {
1825
- const importedConfig = await importConfig(configPath).catch((error) => {
1826
- throw new ConfigLoadError(`Failed to load config from ${configPath}.`, configPath, error);
1827
- });
1828
- const userConfig = importedConfig.default ?? importedConfig;
1829
- if (!userConfig || typeof userConfig !== "object") {
1830
- throw new ConfigLoadError(`Config at ${configPath} must export an object.`, configPath);
1831
- }
1832
- const mergedConfig = {
1833
- ...defaultConfig,
1834
- ...userConfig
415
+ async function loadConfig(options = {}) {
416
+ const cwd = resolve(options.cwd ?? process.cwd());
417
+ const configPath = options.configPath ? resolve(cwd, options.configPath) : resolveConfigPath(cwd);
418
+ try {
419
+ const mod = configPath ? await loadModule(configPath, dirname(configPath)) : { default: {} };
420
+ const user = configPath && /\.(cts|cjs|js)$/.test(configPath) ? mod?.default ?? mod : mod?.default;
421
+ validate(user);
422
+ const config = {
423
+ sourceDir: "./libs",
424
+ outputDir: "./src/options",
425
+ ignoredFiles: ["domain.ts", "adaptor.ts"],
426
+ templateDir: "@uiwwsw/react-query-helper",
427
+ ...user
1835
428
  };
1836
- const configDir2 = dirname3(configPath);
429
+ const configDir = configPath ? dirname(configPath) : cwd;
430
+ const modulePath2 = (path) => path?.startsWith(".") || path && isAbsolute(path) ? resolve(configDir, path) : path;
1837
431
  return {
1838
- ...mergedConfig,
432
+ ...config,
433
+ configDir,
1839
434
  configPath,
1840
- configDir: configDir2,
1841
- resolvedSourceDir: resolve3(configDir2, mergedConfig.sourceDir),
1842
- resolvedOutputDir: resolve3(configDir2, mergedConfig.outputDir),
1843
- resolvedTemplateDir: mergedConfig.templateDir && mergedConfig.templateDir.startsWith(".") ? resolve3(configDir2, mergedConfig.templateDir) : mergedConfig.templateDir,
1844
- resolvedCustomAnalyzerPath: mergedConfig.customAnalyzerPath && mergedConfig.customAnalyzerPath.startsWith(".") ? resolve3(configDir2, mergedConfig.customAnalyzerPath) : mergedConfig.customAnalyzerPath,
1845
- resolvedCustomTemplatePath: mergedConfig.customTemplatePath && mergedConfig.customTemplatePath.startsWith(".") ? resolve3(configDir2, mergedConfig.customTemplatePath) : mergedConfig.customTemplatePath
435
+ resolvedSourceDir: resolve(configDir, config.sourceDir),
436
+ resolvedOutputDir: resolve(configDir, config.outputDir),
437
+ resolvedTemplateDir: modulePath2(config.templateDir),
438
+ resolvedCustomAnalyzerPath: modulePath2(config.customAnalyzerPath),
439
+ resolvedCustomTemplatePath: modulePath2(config.customTemplatePath)
1846
440
  };
441
+ } catch (error) {
442
+ throw new ConfigLoadError(
443
+ `Invalid configuration ${configPath ?? "(defaults)"}: ${error instanceof Error ? error.message : String(error)}`,
444
+ configPath,
445
+ error
446
+ );
1847
447
  }
1848
- const configDir = process.cwd();
1849
- return {
1850
- ...defaultConfig,
1851
- configDir,
1852
- resolvedSourceDir: resolve3(configDir, defaultConfig.sourceDir),
1853
- resolvedOutputDir: resolve3(configDir, defaultConfig.outputDir),
1854
- resolvedTemplateDir: defaultConfig.templateDir,
1855
- resolvedCustomAnalyzerPath: undefined,
1856
- resolvedCustomTemplatePath: undefined
1857
- };
1858
448
  }
1859
449
 
1860
450
  // src/cli.ts
1861
- import prettier from "prettier";
1862
- var config;
1863
- var customAnalyzerModule = null;
1864
- var customTemplateModule = null;
1865
- var DEFAULT_CONFIG_FILE_NAME = "rqh.config.ts";
1866
- var DEFAULT_CONFIG_TEMPLATE = `import type { AutoQueryConfig } from "@uiwwsw/react-query-helper/config";
451
+ var marker = "// Generated by @uiwwsw/react-query-helper. DO NOT EDIT.";
452
+ var configTemplate = `import type { AutoQueryConfig } from "@uiwwsw/react-query-helper/config";
1867
453
 
1868
- const config: AutoQueryConfig = {
454
+ export default {
1869
455
  sourceDir: "./libs",
1870
456
  outputDir: "./src/options",
1871
- ignoredFiles: ["domain.ts", "adaptor.ts"],
1872
- templateDir: "@uiwwsw/react-query-helper",
1873
- sourceImportAlias: "@/libs",
1874
- analyzer: {
1875
- exportFilter: "exported-only",
1876
- functionMatchMode: "all",
1877
- includeNames: [],
1878
- excludeNames: [],
1879
- },
1880
- template: {
1881
- enabledArtifacts: ["query", "mutation", "infinite"],
1882
- artifactStrategy: "smart",
1883
- keyStyle: "path",
1884
- importNames: {
1885
- query: "queryOption",
1886
- mutation: "mutationOption",
1887
- infinite: "infiniteOption",
1888
- },
1889
- outputNames: {
1890
- query: "QueryOption",
1891
- mutation: "MutationOption",
1892
- infinite: "InfiniteQueryOption",
1893
- },
1894
- },
1895
- customAnalyzerPath: "./rqh.analyzer.ts",
1896
- customTemplatePath: "./rqh.template.ts",
1897
- };
1898
-
1899
- export default config;
457
+ ignoredFiles: ["domain.ts", "adaptor.ts", "**/*.test.ts", "**/*.spec.ts"],
458
+ template: { artifactStrategy: "smart" },
459
+ } satisfies AutoQueryConfig;
1900
460
  `;
1901
- function ensureDirectory(directory) {
1902
- if (!existsSync2(directory)) {
1903
- mkdirSync(directory, { recursive: true });
1904
- }
1905
- }
1906
- function normalizeModulePath(pathLike, forceRelativePrefix = false) {
1907
- const normalized = pathLike.split(sep).join("/");
1908
- if (forceRelativePrefix) {
1909
- if (!normalized.startsWith(".") && !normalized.startsWith("/")) {
1910
- return `./${normalized}`;
1911
- }
1912
- return normalized;
1913
- }
1914
- return normalized;
1915
- }
1916
- function shouldProcess(filePath) {
1917
- if (filePath.endsWith(".d.ts")) {
1918
- return false;
1919
- }
1920
- const extension = extname3(filePath).toLowerCase();
1921
- return extension === ".ts" || extension === ".tsx";
1922
- }
1923
- function escapeRegExp(value) {
1924
- return value.replace(/[|\\{}()[\]^$+?.]/g, "\\$&");
1925
- }
1926
- function globToRegExp(pattern) {
1927
- const normalized = normalizeModulePath(pattern);
1928
- const placeholder = "__DOUBLE_STAR__";
1929
- const escaped = escapeRegExp(normalized).replace(/\*\*/g, placeholder).replace(/\*/g, "[^/]*").replace(new RegExp(placeholder, "g"), ".*");
1930
- return new RegExp(`^${escaped}$`);
1931
- }
1932
- function isIgnoredFile(filePath) {
1933
- const relativePath = normalizeModulePath(relative3(config.resolvedSourceDir, filePath));
1934
- const fileName = basename3(filePath);
1935
- return config.ignoredFiles?.some((pattern) => {
1936
- const normalizedPattern = normalizeModulePath(pattern);
1937
- if (!normalizedPattern.includes("/") && !normalizedPattern.includes("*")) {
1938
- return fileName === normalizedPattern;
1939
- }
1940
- return globToRegExp(normalizedPattern).test(relativePath);
1941
- }) ?? false;
1942
- }
1943
- function printUsage() {
1944
- console.log("Usage: react-query-helper [init | generate | watch | help]");
1945
- console.log(" react-query-helper [--init | --generate | --watch | --help]");
1946
- }
1947
- function runInit() {
1948
- const existingConfigPath = resolveConfigPath();
1949
- if (existingConfigPath) {
1950
- console.log(`Config already exists at ${existingConfigPath}`);
1951
- return;
1952
- }
1953
- const configPath = resolve4(process.cwd(), DEFAULT_CONFIG_FILE_NAME);
1954
- writeFileSync(configPath, DEFAULT_CONFIG_TEMPLATE, "utf8");
1955
- console.log(`✅ Created ${configPath}`);
1956
- console.log("Next steps:");
1957
- console.log("1. Update sourceDir/outputDir if needed.");
1958
- console.log("2. Remove customAnalyzerPath/customTemplatePath if you don't need plugin hooks.");
1959
- console.log("3. Run `react-query-helper --generate`.");
1960
- }
1961
- async function loadConfigOrExit() {
461
+ var normalize = (path) => path.split(sep).join("/");
462
+ var within = (root, path) => {
463
+ const rel = relative(root, path);
464
+ return rel === "" || rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute2(rel);
465
+ };
466
+ var processable = (path) => /\.tsx?$/i.test(path) && !/\.d\.ts$/i.test(path);
467
+ async function physicalPath(path) {
468
+ if (existsSync2(path)) return realpath(path);
469
+ return join2(await physicalPath(dirname2(path)), basename(path));
470
+ }
471
+ function ignored(config, path) {
472
+ if ([
473
+ config.configPath,
474
+ config.resolvedCustomAnalyzerPath,
475
+ config.resolvedCustomTemplatePath
476
+ ].some((p) => p && isAbsolute2(p) && resolve2(p) === resolve2(path)))
477
+ return true;
478
+ if (within(config.resolvedOutputDir, path)) return true;
479
+ if (normalize(relative(config.resolvedSourceDir, path)).split("/").some((p) => p === "node_modules" || p === ".git"))
480
+ return true;
481
+ return (config.ignoredFiles ?? []).some(
482
+ (pattern) => picomatch(pattern, { dot: true, basename: !pattern.includes("/") })(
483
+ normalize(relative(config.resolvedSourceDir, path))
484
+ )
485
+ );
486
+ }
487
+ async function walk(root, skip = () => false) {
488
+ if (!existsSync2(root)) return [];
489
+ const result = [];
490
+ for (const entry of (await readdir(root, { withFileTypes: true })).sort(
491
+ (a, b) => a.name.localeCompare(b.name)
492
+ )) {
493
+ const path = join2(root, entry.name);
494
+ if (skip(path) || entry.isSymbolicLink()) continue;
495
+ if (entry.isDirectory()) result.push(...await walk(path, skip));
496
+ else if (entry.isFile()) result.push(path);
497
+ }
498
+ return result;
499
+ }
500
+ async function atomicWrite(path, content) {
501
+ await mkdir(dirname2(path), { recursive: true });
502
+ const temp = `${path}.${randomUUID()}.tmp`;
1962
503
  try {
1963
- return await loadConfig();
1964
- } catch (error) {
1965
- if (error instanceof ConfigLoadError) {
1966
- console.error(`❌ ${error.message}`);
1967
- if (error.cause) {
1968
- console.error(error.cause);
1969
- }
1970
- } else {
1971
- console.error("❌ Unexpected error while loading config:", error);
1972
- }
1973
- process.exitCode = 1;
1974
- return null;
1975
- }
1976
- }
1977
- async function loadPluginModules() {
1978
- customAnalyzerModule = null;
1979
- customTemplateModule = null;
1980
- if (config.resolvedCustomAnalyzerPath) {
1981
- const imported = await import(pathToFileURL2(config.resolvedCustomAnalyzerPath).href);
1982
- customAnalyzerModule = imported.default ?? imported;
1983
- }
1984
- if (config.resolvedCustomTemplatePath) {
1985
- const imported = await import(pathToFileURL2(config.resolvedCustomTemplatePath).href);
1986
- customTemplateModule = imported.default ?? imported;
1987
- }
1988
- }
1989
- async function collectFunctionInfos(filePath) {
1990
- if (customAnalyzerModule?.analyzeFile) {
1991
- const result = await customAnalyzerModule.analyzeFile(filePath, config);
1992
- return Array.isArray(result) ? result : [];
1993
- }
1994
- return analyzeFile(filePath, config.analyzer);
1995
- }
1996
- async function renderOptionsCode(params) {
1997
- if (customTemplateModule?.generateOptionsCode) {
1998
- return await customTemplateModule.generateOptionsCode({
1999
- ...params,
2000
- config
504
+ await writeFile(temp, content, { flag: "wx" });
505
+ await rename(temp, path);
506
+ } finally {
507
+ await unlink(temp).catch(() => {
2001
508
  });
2002
509
  }
2003
- return generateOptionsCode(params.functionInfos, params.importPath, {
2004
- keySegments: params.keySegments,
2005
- fileName: params.fileName,
2006
- templateImportPath: params.templateImportPath,
2007
- template: config.template
2008
- });
2009
510
  }
2010
- function stripTrailingIndex(modulePath) {
2011
- return modulePath.replace(/(?:\/index|^index)$/, "") || ".";
511
+ function modulePath(path, output) {
512
+ const rel = normalize(relative(dirname2(output), path));
513
+ return rel.startsWith(".") ? rel : `./${rel}`;
2012
514
  }
2013
- function resolveSourceImportPath(filePath, outputFile) {
2014
- const sourceModulePath = filePath.replace(new RegExp(`${extname3(filePath)}$`), "");
2015
- const relativeSourcePath = stripTrailingIndex(normalizeModulePath(relative3(config.resolvedSourceDir, sourceModulePath)));
515
+ function sourceImport(config, path, output) {
516
+ const withoutExtension = path.slice(0, -extname(path).length);
517
+ const stripIndex = (p) => p.replace(/(?:\/index|^index)$/, "") || ".";
2016
518
  if (config.sourceImportAlias) {
2017
- const aliasBase = config.sourceImportAlias.replace(/\/$/, "");
2018
- return relativeSourcePath === "." ? aliasBase : `${aliasBase}/${relativeSourcePath}`;
2019
- }
2020
- return stripTrailingIndex(normalizeModulePath(relative3(dirname4(outputFile), sourceModulePath) || ".", true));
2021
- }
2022
- async function processFile(filePath) {
2023
- if (!shouldProcess(filePath)) {
2024
- return;
2025
- }
2026
- const sourceRoot = config.resolvedSourceDir;
2027
- const outputRoot = config.resolvedOutputDir;
2028
- const relativePath = relative3(sourceRoot, filePath);
2029
- if (relativePath.startsWith("..")) {
2030
- console.warn(`Skipping file outside of sourceDir: ${filePath}`);
2031
- return;
2032
- }
2033
- const relativeDir = dirname4(relativePath);
2034
- const fileName = basename3(filePath, extname3(filePath));
2035
- if (isIgnoredFile(filePath)) {
2036
- console.log(`Skipping ignored file: ${filePath}`);
2037
- return;
2038
- }
2039
- try {
2040
- const functionInfos = await collectFunctionInfos(filePath);
2041
- if (functionInfos.length === 0) {
2042
- console.log(`No exported functions found in ${filePath}. Skipping code generation.`);
2043
- return;
2044
- }
2045
- const outputFolder = relativeDir === "." ? outputRoot : join4(outputRoot, relativeDir);
2046
- const outputFile = join4(outputFolder, `${fileName}Options.ts`);
2047
- const generatedCode = await renderOptionsCode({
2048
- functionInfos,
2049
- importPath: resolveSourceImportPath(filePath, outputFile),
2050
- keySegments: relativeDir === "." ? [fileName] : relativeDir.split(sep).filter(Boolean),
519
+ const rel = stripIndex(
520
+ normalize(relative(config.resolvedSourceDir, withoutExtension))
521
+ );
522
+ return config.sourceImportAlias.replace(/\/$/, "") + (rel === "." ? "" : `/${rel}`);
523
+ }
524
+ return stripIndex(modulePath(withoutExtension, output));
525
+ }
526
+ async function plugin(specifier, config, method) {
527
+ if (!specifier) return;
528
+ const mod = await loadModule(specifier, config.configDir);
529
+ const value = mod.default ?? mod;
530
+ if (!value || typeof value[method] !== "function")
531
+ throw new Error(`Plugin ${specifier} must export ${method}().`);
532
+ return value;
533
+ }
534
+ async function generate(config, check = false) {
535
+ if (!existsSync2(config.resolvedSourceDir) || !(await stat(config.resolvedSourceDir)).isDirectory())
536
+ throw new Error(
537
+ `sourceDir does not exist or is not a directory: ${config.resolvedSourceDir}`
538
+ );
539
+ const sourceRoot = await realpath(config.resolvedSourceDir);
540
+ const outputRoot = await physicalPath(config.resolvedOutputDir);
541
+ if (within(outputRoot, sourceRoot))
542
+ throw new Error("outputDir must not equal or contain sourceDir.");
543
+ config.resolvedSourceDir = sourceRoot;
544
+ config.resolvedOutputDir = outputRoot;
545
+ const analyzer = await plugin(
546
+ config.resolvedCustomAnalyzerPath,
547
+ config,
548
+ "analyzeFile"
549
+ );
550
+ const template = await plugin(
551
+ config.resolvedCustomTemplatePath,
552
+ config,
553
+ "generateOptionsCode"
554
+ );
555
+ const owner = `${marker}
556
+ // Source root: ${JSON.stringify(normalize(relative(config.resolvedOutputDir, config.resolvedSourceDir)))}
557
+ `;
558
+ const desired = /* @__PURE__ */ new Map();
559
+ const targets = /* @__PURE__ */ new Set();
560
+ for (const path of await walk(
561
+ config.resolvedSourceDir,
562
+ (p) => ignored(config, p)
563
+ )) {
564
+ if (!processable(path)) continue;
565
+ const rel = relative(config.resolvedSourceDir, path);
566
+ const fileName = basename(path, extname(path));
567
+ const output = join2(
568
+ config.resolvedOutputDir,
569
+ dirname2(rel),
570
+ `${fileName}Options.ts`
571
+ );
572
+ if (targets.has(output))
573
+ throw new Error(`Output collision between .ts/.tsx sources: ${output}`);
574
+ targets.add(output);
575
+ const infos = analyzer ? await analyzer.analyzeFile(path, config) : analyzeFile(path, config.analyzer);
576
+ if (!Array.isArray(infos) || infos.some(
577
+ (info) => !info || typeof info.name !== "string" || !Array.isArray(info.parameters) || info.parameters.some((p) => typeof p !== "string") || typeof info.isExported !== "boolean" || typeof info.isAsync !== "boolean"
578
+ ))
579
+ throw new Error(`Analyzer must return FunctionInfo[] for ${path}`);
580
+ const params = {
581
+ functionInfos: infos,
2051
582
  fileName,
2052
- templateImportPath: config.resolvedTemplateDir && config.templateDir?.startsWith(".") ? normalizeModulePath(relative3(dirname4(outputFile), config.resolvedTemplateDir) || ".", true) : config.resolvedTemplateDir ?? "@uiwwsw/react-query-helper"
583
+ importPath: sourceImport(config, path, output),
584
+ keySegments: dirname2(rel) === "." ? [] : dirname2(rel).split(sep),
585
+ templateImportPath: isAbsolute2(config.resolvedTemplateDir) ? modulePath(config.resolvedTemplateDir, output) : config.resolvedTemplateDir,
586
+ config
587
+ };
588
+ const code = template ? await template.generateOptionsCode(params) : generateOptionsCode(infos, params.importPath, {
589
+ ...params,
590
+ template: config.template
2053
591
  });
2054
- if (!existsSync2(outputFolder)) {
2055
- mkdirSync(outputFolder, { recursive: true });
592
+ if (typeof code !== "string")
593
+ throw new Error(`Template must return a string for ${path}`);
594
+ if (!code.trim()) continue;
595
+ const formatting = await prettier.resolveConfig(output);
596
+ desired.set(
597
+ output,
598
+ owner + await prettier.format(code, { ...formatting, parser: "typescript" })
599
+ );
600
+ }
601
+ const stale = [];
602
+ const existing = /* @__PURE__ */ new Map();
603
+ for (const path of await walk(config.resolvedOutputDir)) {
604
+ if (!path.endsWith("Options.ts")) continue;
605
+ const content = await readFile(path, "utf8");
606
+ existing.set(path, content);
607
+ if (content.startsWith(owner) && !desired.has(path)) stale.push(path);
608
+ }
609
+ for (const [path] of desired) {
610
+ const physical = await physicalPath(path);
611
+ if (!within(outputRoot, physical) || physical !== path)
612
+ throw new Error(`Output path contains a symlink: ${path}`);
613
+ const content = existing.get(path) ?? (existsSync2(path) ? await readFile(path, "utf8") : void 0);
614
+ if (content !== void 0 && !content.startsWith(owner))
615
+ throw new Error(
616
+ `Refusing to overwrite an unowned file: ${path}. Move legacy generated files before regenerating.`
617
+ );
618
+ }
619
+ const changed = [...desired].filter(
620
+ ([path, content]) => existing.get(path) !== content
621
+ );
622
+ if (check) {
623
+ if (changed.length || stale.length)
624
+ throw new Error(
625
+ `Generated files are out of date (${changed.length} changed, ${stale.length} stale).`
626
+ );
627
+ } else {
628
+ for (const [path, content] of changed) await atomicWrite(path, content);
629
+ for (const path of stale) await unlink(path);
630
+ }
631
+ console.log(
632
+ `${check ? "Checked" : "Generated"} ${desired.size} files; ${changed.length} changed; ${stale.length} stale.`
633
+ );
634
+ }
635
+ function usage() {
636
+ console.log(
637
+ "Usage: react-query-helper init|generate|watch [--config <path>] [--check]"
638
+ );
639
+ console.log(
640
+ "Aliases: --init, --generate, --watch, --help. --check is for generate only."
641
+ );
642
+ }
643
+ async function main() {
644
+ const args = process.argv.slice(2);
645
+ let command, configPath, check = false;
646
+ for (let i = 0; i < args.length; i++) {
647
+ const arg = args[i];
648
+ if (arg === "--help" || arg === "-h" || arg === "help") {
649
+ usage();
650
+ return;
2056
651
  }
2057
- const formattedCode = await prettier.format(generatedCode, {
2058
- parser: "typescript"
2059
- });
2060
- writeFileSync(outputFile, formattedCode, "utf8");
2061
- console.log(`✅ Generated options for ${filePath} -> ${outputFile}`);
2062
- } catch (error) {
2063
- console.error(`❌ Error processing file ${filePath}:`, error);
2064
- }
2065
- }
2066
- async function runGenerate() {
2067
- console.log("Generating options...");
2068
- const loadedConfig = await loadConfigOrExit();
2069
- if (!loadedConfig) {
652
+ if (arg === "--config") {
653
+ configPath = args[++i];
654
+ if (!configPath || configPath.startsWith("--"))
655
+ throw new Error("--config requires a path.");
656
+ } else if (arg === "--check") check = true;
657
+ else if (["init", "generate", "watch", "--init", "--generate", "--watch"].includes(
658
+ arg
659
+ ) && !command)
660
+ command = arg.replace(/^--/, "");
661
+ else throw new Error(`Unknown or conflicting argument: ${arg}`);
662
+ }
663
+ if (!command) {
664
+ if (args.length) throw new Error("Specify a command.");
665
+ usage();
2070
666
  return;
2071
667
  }
2072
- config = loadedConfig;
2073
- await loadPluginModules();
2074
- const sourcePath = config.resolvedSourceDir;
2075
- const outputRootPath = config.resolvedOutputDir;
2076
- ensureDirectory(outputRootPath);
2077
- console.log(`\uD83D\uDCC1 Ensured output directory exists at ${outputRootPath}`);
2078
- const files = await new Promise((resolve5, reject) => {
2079
- const results = [];
2080
- const watcher = watch(sourcePath, {
2081
- ignored: (watchedPath) => isIgnoredFile(String(watchedPath)),
2082
- ignoreInitial: false,
2083
- depth: 99
2084
- }).on("add", (path) => results.push(path)).on("ready", () => {
2085
- watcher.close();
2086
- resolve5(results);
2087
- }).on("error", (error) => {
2088
- watcher.close();
2089
- reject(error);
2090
- });
2091
- });
2092
- for (const file of files) {
2093
- await processFile(file);
2094
- }
2095
- console.log("✅ Options generation completed!");
2096
- }
2097
- async function runWatch() {
2098
- console.log("Watching for file changes...");
2099
- const loadedConfig = await loadConfigOrExit();
2100
- if (!loadedConfig) {
2101
- return;
2102
- }
2103
- config = loadedConfig;
2104
- await loadPluginModules();
2105
- const sourcePath = config.resolvedSourceDir;
2106
- const outputRootPath = config.resolvedOutputDir;
2107
- ensureDirectory(outputRootPath);
2108
- console.log(`\uD83D\uDCC1 Ensured output directory exists at ${outputRootPath}`);
2109
- watch(sourcePath, {
2110
- ignored: (watchedPath) => isIgnoredFile(String(watchedPath)),
2111
- ignoreInitial: false,
2112
- depth: 99
2113
- }).on("add", async (filePath) => {
2114
- if (!shouldProcess(filePath) || isIgnoredFile(filePath)) {
2115
- return;
2116
- }
2117
- console.log(`\uD83D\uDCC4 File added: ${filePath}`);
2118
- await processFile(filePath);
2119
- }).on("change", async (filePath) => {
2120
- if (!shouldProcess(filePath) || isIgnoredFile(filePath)) {
668
+ if (check && command !== "generate")
669
+ throw new Error("--check requires generate.");
670
+ if (command === "init") {
671
+ const path = resolve2(configPath ?? "rqh.config.ts");
672
+ if (existsSync2(path) || !configPath && resolveConfigPath()) {
673
+ console.log("Config already exists; nothing was overwritten.");
2121
674
  return;
2122
675
  }
2123
- console.log(`\uD83D\uDD04 File changed: ${filePath}`);
2124
- await processFile(filePath);
2125
- }).on("unlink", async (filePath) => {
2126
- if (!shouldProcess(filePath) || isIgnoredFile(filePath)) {
2127
- return;
2128
- }
2129
- console.log(`\uD83D\uDDD1️ File unlinked: ${filePath}`);
2130
- const sourceRoot = config.resolvedSourceDir;
2131
- const outputRoot = config.resolvedOutputDir;
2132
- const relativePath = relative3(sourceRoot, filePath);
2133
- if (relativePath.startsWith("..")) {
2134
- return;
2135
- }
2136
- const relativeDir = dirname4(relativePath);
2137
- const fileName = basename3(filePath, extname3(filePath));
2138
- const outputFile = join4(relativeDir === "." ? outputRoot : join4(outputRoot, relativeDir), `${fileName}Options.ts`);
2139
- if (existsSync2(outputFile)) {
2140
- unlinkSync(outputFile);
2141
- console.log(`\uD83D\uDDD1️ Deleted ${outputFile}`);
676
+ if (!/\.(ts|mts)$/.test(path))
677
+ throw new Error("init creates a .ts or .mts config.");
678
+ await mkdir(dirname2(path), { recursive: true });
679
+ await writeFile(path, configTemplate, { flag: "wx" });
680
+ console.log(
681
+ `Created ${path}. Set sourceDir, then run react-query-helper generate.`
682
+ );
683
+ return;
684
+ }
685
+ let config = await loadConfig({ configPath });
686
+ await generate(config, check);
687
+ if (command !== "watch") return;
688
+ const paths = (c) => [
689
+ c.resolvedSourceDir,
690
+ c.configPath,
691
+ c.resolvedCustomAnalyzerPath,
692
+ c.resolvedCustomTemplatePath
693
+ ].filter((p) => !!p && isAbsolute2(p));
694
+ const watcher = watch(paths(config), {
695
+ ignoreInitial: true,
696
+ followSymlinks: false,
697
+ ignored: (p) => within(config.resolvedOutputDir, resolve2(p)),
698
+ awaitWriteFinish: { stabilityThreshold: 100, pollInterval: 20 }
699
+ });
700
+ let pending = false, running = false, closing = false;
701
+ let timer;
702
+ let active = Promise.resolve();
703
+ async function drain() {
704
+ if (running || closing) return;
705
+ running = true;
706
+ try {
707
+ while (pending && !closing) {
708
+ pending = false;
709
+ try {
710
+ const next = await loadConfig({ configPath });
711
+ await generate(next);
712
+ const previous = paths(config);
713
+ config = next;
714
+ await watcher.unwatch(
715
+ previous.filter((p) => !paths(next).includes(p))
716
+ );
717
+ watcher.add(paths(next));
718
+ } catch (error) {
719
+ console.error(error instanceof Error ? error.message : error);
720
+ }
721
+ }
722
+ } finally {
723
+ running = false;
2142
724
  }
2143
- }).on("error", (error) => console.error(`❌ Watcher error: ${error}`));
2144
- console.log(`\uD83D\uDC40 Watching ${sourcePath} for changes.`);
2145
- }
2146
- var args = process.argv.slice(2);
2147
- var hasCommand = (...values) => values.some((value) => args.includes(value));
2148
- if (hasCommand("help", "--help")) {
2149
- printUsage();
2150
- } else if (hasCommand("init", "--init")) {
2151
- runInit();
2152
- } else if (hasCommand("watch", "--watch")) {
2153
- runWatch();
2154
- } else if (hasCommand("generate", "--generate")) {
2155
- runGenerate();
2156
- } else {
2157
- printUsage();
2158
- }
725
+ }
726
+ watcher.on("all", () => {
727
+ pending = true;
728
+ clearTimeout(timer);
729
+ timer = setTimeout(() => {
730
+ if (!running) active = drain();
731
+ }, 100);
732
+ });
733
+ watcher.on("error", (error) => {
734
+ console.error(error);
735
+ process.exitCode = 1;
736
+ void close();
737
+ });
738
+ const close = async () => {
739
+ closing = true;
740
+ clearTimeout(timer);
741
+ await watcher.close();
742
+ await active;
743
+ };
744
+ process.once("SIGINT", () => void close());
745
+ process.once("SIGTERM", () => void close());
746
+ await new Promise((resolve3, reject) => {
747
+ watcher.once("ready", resolve3);
748
+ watcher.once("error", reject);
749
+ });
750
+ pending = true;
751
+ if (!running) active = drain();
752
+ await active;
753
+ if (!closing) console.log(`Watching ${config.resolvedSourceDir}`);
754
+ }
755
+ main().catch((error) => {
756
+ console.error(error instanceof Error ? error.message : error);
757
+ process.exitCode = 1;
758
+ });