@ooneex/routing 0.10.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,35 +1,992 @@
1
1
  // @bun
2
- import{container as s,EContainerScope as f}from"@ooneex/container";import{Exception as p}from"@ooneex/exception";import{HttpStatus as n}from"@ooneex/http-status";class T extends p{constructor(t,w={}){super(t,{status:n.Code.InternalServerError,data:w});this.name="RouterException"}}class j{routes=new Map;addRoute(t){let w=t.name;for(let x of this.routes[Symbol.iterator]())if(x[1].find((M)=>M.name===w))throw new T(`Route with name '${w}' already exists`,t);let u=this.routes.get(t.path)??[];if(t.isSocket&&u.find((x)=>x.isSocket))throw new T(`Socket route with path '${t.path}' already exists`,t);if(!t.isSocket&&u.find((x)=>!x.isSocket&&x.method===t.method))throw new T(`Route with path '${t.path}' and method '${t.method}' already exists`,t);return u.push(t),this.routes.set(t.path,u),s.add(t.controller,f.Singleton),this}findRouteByPath(t){return this.routes.get(t)??null}findRouteByName(t){for(let w of this.routes[Symbol.iterator]()){let u=w[1].find((x)=>x.name===t);if(u)return u}return null}getRoutes(){return this.routes}getSocketRoutes(){let t=new Map;for(let[w,u]of this.routes){let x=u.find((R)=>R.isSocket);if(x)t.set(w,x)}return t}getHttpRoutes(){let t=new Map;for(let[w,u]of this.routes){let x=u.filter((R)=>!R.isSocket);if(x.length>0)t.set(w,x)}return t}generate(t,w){let u=this.findRouteByName(t);if(!u)throw new T(`Route with name '${t}' not found`);let x=u.path,R=x.match(/:[a-zA-Z0-9_]+/g)||[];if(R.length>0){if(!w||typeof w!=="object"||w===null)throw new T(`Route '${t}' requires parameters, but none were provided`);for(let M of R){let C=M.substring(1);if(!(C in w))throw new T(`Missing required parameter '${C}' for route '${t}'`);x=x.replace(M,String(w[C]))}}return x}}var _=new j;var k=(t)=>{return(w,u)=>{return(x)=>{let R={...u,path:w,method:t,isSocket:!1,controller:x};_.addRoute(R)}}},a=()=>{return(t,w)=>{return(u)=>{let x={...w,path:t,method:"GET",isSocket:!0,controller:u};_.addRoute(x)}}},g={get:k("GET"),post:k("POST"),put:k("PUT"),delete:k("DELETE"),patch:k("PATCH"),options:k("OPTIONS"),head:k("HEAD"),socket:a()};var dt=["api","client","admin","public","auth","webhook","internal","external","system","health","metrics","docs"],It=["list","show","read","create","update","delete","store","edit","index","search","filter","sort","export","import","upload","download","duplicate","clone","archive","restore","activate","deactivate","enable","disable","publish","unpublish","approve","reject","cancel","confirm","validate","verify","reset","refresh","sync","backup","migrate","seed","truncate","count","exists","find","aggregate","bulk","batch","preview","template","history","audit","log","track","monitor","health","status","ping","test","debug","info","stats","report","analytics","metrics","summary","detail","config","settings","preferences","profile","avatar","password","login","logout","register","unregister","subscribe","unsubscribe","follow","unfollow","like","unlike","share","comment","reply","rate","review","bookmark","favorite","tag","untag","assign","unassign","invite","revoke","grant","deny","lock","unlock","move","copy","rename","reorder","merge","split","convert","transform","process","queue","retry","skip","pause","resume","stop","start","restart","reload","clear","flush","purge","cleanup","optimize","compress","decompress","manage","administer","supervise","oversee","govern","control","execute","perform","run","operate","handle","maintain","service","support","assist","help","guide","instruct","teach","train","educate","inform","notify","alert","warn","remind","schedule","plan","organize","arrange","coordinate","integrate","connect","link","bind","attach","detach","separate","isolate","quarantine","protect","secure","encrypt","decrypt","encode","decode","format","parse","serialize","deserialize","marshal","unmarshal","package","unpack","bundle","unbundle","group","ungroup","categorize","classify","order","rank","prioritize","weight","score","evaluate","assess","measure","calculate","compute","analyze","examine","inspect","check","scan","detect","discover","explore","browse","navigate","travel","visit","access","enter","exit","leave","join","disconnect","reconnect","establish","initialize","setup","configure","customize","personalize","adapt","adjust","modify","change","alter","revise","amend","correct","fix","repair","recover","retrieve","fetch","get","obtain","acquire","receive","accept","take","capture","record","save","preserve","keep","retain","hold","sustain","continue","proceed","advance","progress","develop","evolve","grow","expand","extend","stretch","scale","resize","tune","calibrate","balance","stabilize","normalize","standardize","regulate","moderate","mediate","negotiate","compromise","resolve","solve","address","tackle","approach","deal","cope","direct","lead","command","instruct","order","request","ask","query","question","inquire","investigate","research","study","learn","understand","comprehend","grasp","realize","recognize","identify","determine","decide","choose","select","pick","opt","prefer","favor","recommend","suggest","propose","offer","provide","supply","deliver","send","transmit","transfer","forward","relay","redirect","route","dispatch","distribute","allocate","designate","appoint","nominate","elect","vote","poll","survey","interview","examine","trial","experiment","try","attempt","endeavor","strive","effort","work","labor","toil","struggle","fight","battle","compete","contest","challenge","oppose","resist","defend","guard","shield","cover","hide","conceal","mask","disguise","camouflage","cloak","wrap","enclose","contain","include","encompass","comprise","consist","compose","constitute","form","shape","mold","craft","build","construct","assemble","compile","gather","collect","accumulate","amass","pile","stack","heap","load","fill","populate","occupy","inhabit","reside","dwell","live","exist","become","turn","metamorphose","mutate","accommodate","conform","comply","obey","follow","adhere","stick","fasten","tie","unite","combine","mix","blend","fuse","incorporate","embed","insert","inject","introduce","bring","carry","transport","convey","spread","scatter","disperse","disseminate","broadcast","announce","declare","proclaim","state","express","voice","speak","say","tell","communicate","shift","relocate","journey","voyage","trip","tour","locate","position","place","put","set","lay","rest","sit","stand","rise","lift","raise","elevate","boost","enhance","improve","upgrade","renew","revive","mend","heal","cure","treat","remedy","settle","conclude","finish","complete","end","terminate","halt","break","interrupt","suspend","delay","postpone","defer","wait","uphold","safeguard","ensure","guarantee","warrant","promise","pledge","commit","dedicate","devote","consecrate","sacrifice","give","donate","contribute","furnish","equip","outfit","prepare","ready","design","make","produce","manufacture","fabricate","erect","found","institute","inaugurate","launch","begin","commence","initiate","trigger","turn-on","switch-on","power-on","boot","startup","function","act","behave","conduct","steer","pilot","drive","rule","manipulate","use","utilize","employ","apply","implement","deploy","install","refine","polish","perfect","finalize","close","shut","seal","watch","observe"];import{toPascalCase as W}from"@ooneex/utils";import{jsonSchemaToTypeString as v}from"@ooneex/validation";var Tt=(t)=>{if(!t.startsWith("/"))return!1;if(t.includes("//"))return!1;if(t.includes("::"))return!1;if(t.endsWith(":"))return!1;if(t.includes("/:")){let w=t.split("/");for(let u of w){if(u.startsWith(":")&&u.length===1)return!1;if(u.includes(":")&&!u.startsWith(":"))return!1}}return!0},c=(t)=>{let w=t.match(/:([^/]+)/g);return w?w.map((u)=>u.slice(1)):[]},K=(t)=>{if(!t.response&&!t.params&&!t.payload&&!t.queries)return"never";let w=[];if(t.response)try{let x=("getConstraint"in t.response?t.response.getConstraint():t.response).toJsonSchema(),R=v(x);if(R==="unknown"||R==="{ }"||R==="Record<string, unknown>")R="never";w.push(`response: ${R}`)}catch{w.push("response: never")}if(t.params){let u=[];for(let[x,R]of Object.entries(t.params))try{let C=("getConstraint"in R?R.getConstraint():R).toJsonSchema(),E=v(C);if(E==="unknown"||E==="{ }"||E==="Record<string, unknown>")E="never";u.push(`${x}: ${E}`)}catch{u.push(`${x}: never`)}if(u.length>0){let x=`{ ${u.join("; ")} }`;w.push(`params: ${x}`)}else w.push("params: never")}if(t.payload)try{let x=("getConstraint"in t.payload?t.payload.getConstraint():t.payload).toJsonSchema(),R=v(x);if(R==="unknown"||R==="{ }"||R==="Record<string, unknown>")R="never";w.push(`payload: ${R}`)}catch{w.push("payload: never")}if(t.queries)try{let x=("getConstraint"in t.queries?t.queries.getConstraint():t.queries).toJsonSchema(),R=v(x);if(R==="unknown"||R==="{ }"||R==="Record<string, unknown>")R="never";w.push(`queries: ${R}`)}catch{w.push("queries: never")}return`{
3
- ${w.join(`;
2
+ // src/Router.ts
3
+ import { container, EContainerScope } from "@ooneex/container";
4
+
5
+ // src/RouterException.ts
6
+ import { Exception } from "@ooneex/exception";
7
+ import { HttpStatus } from "@ooneex/http-status";
8
+
9
+ class RouterException extends Exception {
10
+ constructor(message, data = {}) {
11
+ super(message, {
12
+ status: HttpStatus.Code.InternalServerError,
13
+ data
14
+ });
15
+ this.name = "RouterException";
16
+ }
17
+ }
18
+
19
+ // src/Router.ts
20
+ class Router {
21
+ routes = new Map;
22
+ addRoute(route) {
23
+ const name = route.name;
24
+ for (const item of this.routes[Symbol.iterator]()) {
25
+ const existingRoute = item[1].find((r) => r.name === name);
26
+ if (existingRoute) {
27
+ throw new RouterException(`Route with name '${name}' already exists`, route);
28
+ }
29
+ }
30
+ const routes = this.routes.get(route.path) ?? [];
31
+ if (route.isSocket && routes.find((r) => r.isSocket)) {
32
+ throw new RouterException(`Socket route with path '${route.path}' already exists`, route);
33
+ }
34
+ if (!route.isSocket && routes.find((r) => !r.isSocket && r.method === route.method)) {
35
+ throw new RouterException(`Route with path '${route.path}' and method '${route.method}' already exists`, route);
36
+ }
37
+ routes.push(route);
38
+ this.routes.set(route.path, routes);
39
+ container.add(route.controller, EContainerScope.Singleton);
40
+ return this;
41
+ }
42
+ findRouteByPath(path) {
43
+ return this.routes.get(path) ?? null;
44
+ }
45
+ findRouteByName(name) {
46
+ for (const item of this.routes[Symbol.iterator]()) {
47
+ const existingRoute = item[1].find((r) => r.name === name);
48
+ if (existingRoute) {
49
+ return existingRoute;
50
+ }
51
+ }
52
+ return null;
53
+ }
54
+ getRoutes() {
55
+ return this.routes;
56
+ }
57
+ getSocketRoutes() {
58
+ const socketRoutes = new Map;
59
+ for (const [path, routes] of this.routes) {
60
+ const socketRoute = routes.find((route) => route.isSocket);
61
+ if (socketRoute) {
62
+ socketRoutes.set(path, socketRoute);
63
+ }
64
+ }
65
+ return socketRoutes;
66
+ }
67
+ getHttpRoutes() {
68
+ const httpRoutes = new Map;
69
+ for (const [path, routes] of this.routes) {
70
+ const filteredRoutes = routes.filter((route) => !route.isSocket);
71
+ if (filteredRoutes.length > 0) {
72
+ httpRoutes.set(path, filteredRoutes);
73
+ }
74
+ }
75
+ return httpRoutes;
76
+ }
77
+ generate(name, params) {
78
+ const route = this.findRouteByName(name);
79
+ if (!route) {
80
+ throw new RouterException(`Route with name '${name}' not found`);
81
+ }
82
+ let path = route.path;
83
+ const paramMatches = path.match(/:[a-zA-Z0-9_]+/g) || [];
84
+ if (paramMatches.length > 0) {
85
+ if (!params || typeof params !== "object" || params === null) {
86
+ throw new RouterException(`Route '${name}' requires parameters, but none were provided`);
87
+ }
88
+ for (const match of paramMatches) {
89
+ const paramName = match.substring(1);
90
+ if (!(paramName in params)) {
91
+ throw new RouterException(`Missing required parameter '${paramName}' for route '${name}'`);
92
+ }
93
+ path = path.replace(match, String(params[paramName]));
94
+ }
95
+ }
96
+ return path;
97
+ }
98
+ }
99
+ var router = new Router;
100
+
101
+ // src/decorators.ts
102
+ var createRouteDecorator = (method) => {
103
+ return (path, config) => {
104
+ return (target) => {
105
+ const route = {
106
+ ...config,
107
+ path,
108
+ method,
109
+ isSocket: false,
110
+ controller: target
111
+ };
112
+ router.addRoute(route);
113
+ };
114
+ };
115
+ };
116
+ var createSocketDecorator = () => {
117
+ return (path, config) => {
118
+ return (target) => {
119
+ const route = {
120
+ ...config,
121
+ path,
122
+ method: "GET",
123
+ isSocket: true,
124
+ controller: target
125
+ };
126
+ router.addRoute(route);
127
+ };
128
+ };
129
+ };
130
+ var Route = {
131
+ get: createRouteDecorator("GET"),
132
+ post: createRouteDecorator("POST"),
133
+ put: createRouteDecorator("PUT"),
134
+ delete: createRouteDecorator("DELETE"),
135
+ patch: createRouteDecorator("PATCH"),
136
+ options: createRouteDecorator("OPTIONS"),
137
+ head: createRouteDecorator("HEAD"),
138
+ socket: createSocketDecorator()
139
+ };
140
+ // src/types.ts
141
+ var VALID_NAMESPACES = [
142
+ "api",
143
+ "client",
144
+ "admin",
145
+ "public",
146
+ "auth",
147
+ "webhook",
148
+ "internal",
149
+ "external",
150
+ "system",
151
+ "health",
152
+ "metrics",
153
+ "docs"
154
+ ];
155
+ var VALID_ACTIONS = [
156
+ "list",
157
+ "show",
158
+ "read",
159
+ "create",
160
+ "update",
161
+ "delete",
162
+ "store",
163
+ "edit",
164
+ "index",
165
+ "search",
166
+ "filter",
167
+ "sort",
168
+ "export",
169
+ "import",
170
+ "upload",
171
+ "download",
172
+ "duplicate",
173
+ "clone",
174
+ "archive",
175
+ "restore",
176
+ "activate",
177
+ "deactivate",
178
+ "enable",
179
+ "disable",
180
+ "publish",
181
+ "unpublish",
182
+ "approve",
183
+ "reject",
184
+ "cancel",
185
+ "confirm",
186
+ "validate",
187
+ "verify",
188
+ "reset",
189
+ "refresh",
190
+ "sync",
191
+ "backup",
192
+ "migrate",
193
+ "seed",
194
+ "truncate",
195
+ "count",
196
+ "exists",
197
+ "find",
198
+ "aggregate",
199
+ "bulk",
200
+ "batch",
201
+ "preview",
202
+ "template",
203
+ "history",
204
+ "audit",
205
+ "log",
206
+ "track",
207
+ "monitor",
208
+ "health",
209
+ "status",
210
+ "ping",
211
+ "test",
212
+ "debug",
213
+ "info",
214
+ "stats",
215
+ "report",
216
+ "analytics",
217
+ "metrics",
218
+ "summary",
219
+ "detail",
220
+ "config",
221
+ "settings",
222
+ "preferences",
223
+ "profile",
224
+ "avatar",
225
+ "password",
226
+ "login",
227
+ "logout",
228
+ "register",
229
+ "unregister",
230
+ "subscribe",
231
+ "unsubscribe",
232
+ "follow",
233
+ "unfollow",
234
+ "like",
235
+ "unlike",
236
+ "share",
237
+ "comment",
238
+ "reply",
239
+ "rate",
240
+ "review",
241
+ "bookmark",
242
+ "favorite",
243
+ "tag",
244
+ "untag",
245
+ "assign",
246
+ "unassign",
247
+ "invite",
248
+ "revoke",
249
+ "grant",
250
+ "deny",
251
+ "lock",
252
+ "unlock",
253
+ "move",
254
+ "copy",
255
+ "rename",
256
+ "reorder",
257
+ "merge",
258
+ "split",
259
+ "convert",
260
+ "transform",
261
+ "process",
262
+ "queue",
263
+ "retry",
264
+ "skip",
265
+ "pause",
266
+ "resume",
267
+ "stop",
268
+ "start",
269
+ "restart",
270
+ "reload",
271
+ "clear",
272
+ "flush",
273
+ "purge",
274
+ "cleanup",
275
+ "optimize",
276
+ "compress",
277
+ "decompress",
278
+ "manage",
279
+ "administer",
280
+ "supervise",
281
+ "oversee",
282
+ "govern",
283
+ "control",
284
+ "execute",
285
+ "perform",
286
+ "run",
287
+ "operate",
288
+ "handle",
289
+ "maintain",
290
+ "service",
291
+ "support",
292
+ "assist",
293
+ "help",
294
+ "guide",
295
+ "instruct",
296
+ "teach",
297
+ "train",
298
+ "educate",
299
+ "inform",
300
+ "notify",
301
+ "alert",
302
+ "warn",
303
+ "remind",
304
+ "schedule",
305
+ "plan",
306
+ "organize",
307
+ "arrange",
308
+ "coordinate",
309
+ "integrate",
310
+ "connect",
311
+ "link",
312
+ "bind",
313
+ "attach",
314
+ "detach",
315
+ "separate",
316
+ "isolate",
317
+ "quarantine",
318
+ "protect",
319
+ "secure",
320
+ "encrypt",
321
+ "decrypt",
322
+ "encode",
323
+ "decode",
324
+ "format",
325
+ "parse",
326
+ "serialize",
327
+ "deserialize",
328
+ "marshal",
329
+ "unmarshal",
330
+ "package",
331
+ "unpack",
332
+ "bundle",
333
+ "unbundle",
334
+ "group",
335
+ "ungroup",
336
+ "categorize",
337
+ "classify",
338
+ "order",
339
+ "rank",
340
+ "prioritize",
341
+ "weight",
342
+ "score",
343
+ "evaluate",
344
+ "assess",
345
+ "measure",
346
+ "calculate",
347
+ "compute",
348
+ "analyze",
349
+ "examine",
350
+ "inspect",
351
+ "check",
352
+ "scan",
353
+ "detect",
354
+ "discover",
355
+ "explore",
356
+ "browse",
357
+ "navigate",
358
+ "travel",
359
+ "visit",
360
+ "access",
361
+ "enter",
362
+ "exit",
363
+ "leave",
364
+ "join",
365
+ "disconnect",
366
+ "reconnect",
367
+ "establish",
368
+ "initialize",
369
+ "setup",
370
+ "configure",
371
+ "customize",
372
+ "personalize",
373
+ "adapt",
374
+ "adjust",
375
+ "modify",
376
+ "change",
377
+ "alter",
378
+ "revise",
379
+ "amend",
380
+ "correct",
381
+ "fix",
382
+ "repair",
383
+ "recover",
384
+ "retrieve",
385
+ "fetch",
386
+ "get",
387
+ "obtain",
388
+ "acquire",
389
+ "receive",
390
+ "accept",
391
+ "take",
392
+ "capture",
393
+ "record",
394
+ "save",
395
+ "preserve",
396
+ "keep",
397
+ "retain",
398
+ "hold",
399
+ "sustain",
400
+ "continue",
401
+ "proceed",
402
+ "advance",
403
+ "progress",
404
+ "develop",
405
+ "evolve",
406
+ "grow",
407
+ "expand",
408
+ "extend",
409
+ "stretch",
410
+ "scale",
411
+ "resize",
412
+ "tune",
413
+ "calibrate",
414
+ "balance",
415
+ "stabilize",
416
+ "normalize",
417
+ "standardize",
418
+ "regulate",
419
+ "moderate",
420
+ "mediate",
421
+ "negotiate",
422
+ "compromise",
423
+ "resolve",
424
+ "solve",
425
+ "address",
426
+ "tackle",
427
+ "approach",
428
+ "deal",
429
+ "cope",
430
+ "direct",
431
+ "lead",
432
+ "command",
433
+ "instruct",
434
+ "order",
435
+ "request",
436
+ "ask",
437
+ "query",
438
+ "question",
439
+ "inquire",
440
+ "investigate",
441
+ "research",
442
+ "study",
443
+ "learn",
444
+ "understand",
445
+ "comprehend",
446
+ "grasp",
447
+ "realize",
448
+ "recognize",
449
+ "identify",
450
+ "determine",
451
+ "decide",
452
+ "choose",
453
+ "select",
454
+ "pick",
455
+ "opt",
456
+ "prefer",
457
+ "favor",
458
+ "recommend",
459
+ "suggest",
460
+ "propose",
461
+ "offer",
462
+ "provide",
463
+ "supply",
464
+ "deliver",
465
+ "send",
466
+ "transmit",
467
+ "transfer",
468
+ "forward",
469
+ "relay",
470
+ "redirect",
471
+ "route",
472
+ "dispatch",
473
+ "distribute",
474
+ "allocate",
475
+ "designate",
476
+ "appoint",
477
+ "nominate",
478
+ "elect",
479
+ "vote",
480
+ "poll",
481
+ "survey",
482
+ "interview",
483
+ "examine",
484
+ "trial",
485
+ "experiment",
486
+ "try",
487
+ "attempt",
488
+ "endeavor",
489
+ "strive",
490
+ "effort",
491
+ "work",
492
+ "labor",
493
+ "toil",
494
+ "struggle",
495
+ "fight",
496
+ "battle",
497
+ "compete",
498
+ "contest",
499
+ "challenge",
500
+ "oppose",
501
+ "resist",
502
+ "defend",
503
+ "guard",
504
+ "shield",
505
+ "cover",
506
+ "hide",
507
+ "conceal",
508
+ "mask",
509
+ "disguise",
510
+ "camouflage",
511
+ "cloak",
512
+ "wrap",
513
+ "enclose",
514
+ "contain",
515
+ "include",
516
+ "encompass",
517
+ "comprise",
518
+ "consist",
519
+ "compose",
520
+ "constitute",
521
+ "form",
522
+ "shape",
523
+ "mold",
524
+ "craft",
525
+ "build",
526
+ "construct",
527
+ "assemble",
528
+ "compile",
529
+ "gather",
530
+ "collect",
531
+ "accumulate",
532
+ "amass",
533
+ "pile",
534
+ "stack",
535
+ "heap",
536
+ "load",
537
+ "fill",
538
+ "populate",
539
+ "occupy",
540
+ "inhabit",
541
+ "reside",
542
+ "dwell",
543
+ "live",
544
+ "exist",
545
+ "become",
546
+ "turn",
547
+ "metamorphose",
548
+ "mutate",
549
+ "accommodate",
550
+ "conform",
551
+ "comply",
552
+ "obey",
553
+ "follow",
554
+ "adhere",
555
+ "stick",
556
+ "fasten",
557
+ "tie",
558
+ "unite",
559
+ "combine",
560
+ "mix",
561
+ "blend",
562
+ "fuse",
563
+ "incorporate",
564
+ "embed",
565
+ "insert",
566
+ "inject",
567
+ "introduce",
568
+ "bring",
569
+ "carry",
570
+ "transport",
571
+ "convey",
572
+ "spread",
573
+ "scatter",
574
+ "disperse",
575
+ "disseminate",
576
+ "broadcast",
577
+ "announce",
578
+ "declare",
579
+ "proclaim",
580
+ "state",
581
+ "express",
582
+ "voice",
583
+ "speak",
584
+ "say",
585
+ "tell",
586
+ "communicate",
587
+ "shift",
588
+ "relocate",
589
+ "journey",
590
+ "voyage",
591
+ "trip",
592
+ "tour",
593
+ "locate",
594
+ "position",
595
+ "place",
596
+ "put",
597
+ "set",
598
+ "lay",
599
+ "rest",
600
+ "sit",
601
+ "stand",
602
+ "rise",
603
+ "lift",
604
+ "raise",
605
+ "elevate",
606
+ "boost",
607
+ "enhance",
608
+ "improve",
609
+ "upgrade",
610
+ "renew",
611
+ "revive",
612
+ "mend",
613
+ "heal",
614
+ "cure",
615
+ "treat",
616
+ "remedy",
617
+ "settle",
618
+ "conclude",
619
+ "finish",
620
+ "complete",
621
+ "end",
622
+ "terminate",
623
+ "halt",
624
+ "break",
625
+ "interrupt",
626
+ "suspend",
627
+ "delay",
628
+ "postpone",
629
+ "defer",
630
+ "wait",
631
+ "uphold",
632
+ "safeguard",
633
+ "ensure",
634
+ "guarantee",
635
+ "warrant",
636
+ "promise",
637
+ "pledge",
638
+ "commit",
639
+ "dedicate",
640
+ "devote",
641
+ "consecrate",
642
+ "sacrifice",
643
+ "give",
644
+ "donate",
645
+ "contribute",
646
+ "furnish",
647
+ "equip",
648
+ "outfit",
649
+ "prepare",
650
+ "ready",
651
+ "design",
652
+ "make",
653
+ "produce",
654
+ "manufacture",
655
+ "fabricate",
656
+ "erect",
657
+ "found",
658
+ "institute",
659
+ "inaugurate",
660
+ "launch",
661
+ "begin",
662
+ "commence",
663
+ "initiate",
664
+ "trigger",
665
+ "turn-on",
666
+ "switch-on",
667
+ "power-on",
668
+ "boot",
669
+ "startup",
670
+ "function",
671
+ "act",
672
+ "behave",
673
+ "conduct",
674
+ "steer",
675
+ "pilot",
676
+ "drive",
677
+ "rule",
678
+ "manipulate",
679
+ "use",
680
+ "utilize",
681
+ "employ",
682
+ "apply",
683
+ "implement",
684
+ "deploy",
685
+ "install",
686
+ "refine",
687
+ "polish",
688
+ "perfect",
689
+ "finalize",
690
+ "close",
691
+ "shut",
692
+ "seal",
693
+ "watch",
694
+ "observe"
695
+ ];
696
+ // src/utils.ts
697
+ import { toPascalCase } from "@ooneex/utils";
698
+ import { jsonSchemaToTypeString } from "@ooneex/validation";
699
+ var isValidRoutePath = (path) => {
700
+ if (!path.startsWith("/"))
701
+ return false;
702
+ if (path.includes("//"))
703
+ return false;
704
+ if (path.includes("::"))
705
+ return false;
706
+ if (path.endsWith(":"))
707
+ return false;
708
+ if (path.includes("/:")) {
709
+ const segments = path.split("/");
710
+ for (const segment of segments) {
711
+ if (segment.startsWith(":") && segment.length === 1)
712
+ return false;
713
+ if (segment.includes(":") && !segment.startsWith(":"))
714
+ return false;
715
+ }
716
+ }
717
+ return true;
718
+ };
719
+ var extractParameterNames = (path) => {
720
+ const matches = path.match(/:([^/]+)/g);
721
+ return matches ? matches.map((match) => match.slice(1)) : [];
722
+ };
723
+ var routeConfigToTypeString = (config) => {
724
+ if (!config.response && !config.params && !config.payload && !config.queries) {
725
+ return "never";
726
+ }
727
+ const typeProperties = [];
728
+ if (config.response) {
729
+ try {
730
+ const constraint = "getConstraint" in config.response ? config.response.getConstraint() : config.response;
731
+ const schema = constraint.toJsonSchema();
732
+ let typeStr = jsonSchemaToTypeString(schema);
733
+ if (typeStr === "unknown" || typeStr === "{ }" || typeStr === "Record<string, unknown>") {
734
+ typeStr = "never";
735
+ }
736
+ typeProperties.push(`response: ${typeStr}`);
737
+ } catch {
738
+ typeProperties.push("response: never");
739
+ }
740
+ }
741
+ if (config.params) {
742
+ const paramProps = [];
743
+ for (const [key, assert] of Object.entries(config.params)) {
744
+ try {
745
+ const constraint = "getConstraint" in assert ? assert.getConstraint() : assert;
746
+ const schema = constraint.toJsonSchema();
747
+ let typeStr = jsonSchemaToTypeString(schema);
748
+ if (typeStr === "unknown" || typeStr === "{ }" || typeStr === "Record<string, unknown>") {
749
+ typeStr = "never";
750
+ }
751
+ paramProps.push(`${key}: ${typeStr}`);
752
+ } catch {
753
+ paramProps.push(`${key}: never`);
754
+ }
755
+ }
756
+ if (paramProps.length > 0) {
757
+ const paramsType = `{ ${paramProps.join("; ")} }`;
758
+ typeProperties.push(`params: ${paramsType}`);
759
+ } else {
760
+ typeProperties.push("params: never");
761
+ }
762
+ }
763
+ if (config.payload) {
764
+ try {
765
+ const constraint = "getConstraint" in config.payload ? config.payload.getConstraint() : config.payload;
766
+ const schema = constraint.toJsonSchema();
767
+ let typeStr = jsonSchemaToTypeString(schema);
768
+ if (typeStr === "unknown" || typeStr === "{ }" || typeStr === "Record<string, unknown>") {
769
+ typeStr = "never";
770
+ }
771
+ typeProperties.push(`payload: ${typeStr}`);
772
+ } catch {
773
+ typeProperties.push("payload: never");
774
+ }
775
+ }
776
+ if (config.queries) {
777
+ try {
778
+ const constraint = "getConstraint" in config.queries ? config.queries.getConstraint() : config.queries;
779
+ const schema = constraint.toJsonSchema();
780
+ let typeStr = jsonSchemaToTypeString(schema);
781
+ if (typeStr === "unknown" || typeStr === "{ }" || typeStr === "Record<string, unknown>") {
782
+ typeStr = "never";
783
+ }
784
+ typeProperties.push(`queries: ${typeStr}`);
785
+ } catch {
786
+ typeProperties.push("queries: never");
787
+ }
788
+ }
789
+ return `{
790
+ ${typeProperties.join(`;
4
791
  `)};
5
- }`},X=(t)=>{try{return(t&&typeof t==="object"&&"getConstraint"in t?t.getConstraint():t).toJsonSchema()}catch{return{type:"unknown"}}},Ot=(t)=>{let w={name:t.name,path:t.path,method:t.method,description:t.description,controller:t.controller.name,isSocket:t.isSocket,parameters:c(t.path)},u={};if(t.params){let R={type:"object",properties:{}};for(let[M,C]of Object.entries(t.params)){let E=X(C);delete E.$schema,E.required=!0,R.properties[M]=E}u.params=R}if(t.queries){let R=X(t.queries);if(delete R.$schema,R.type==="object"&&R.properties){let M=R.required||[],C=R.properties;for(let E of Object.keys(C)){let $=C[E];$.required=M.includes(E)}delete R.required}u.queries=R}if(t.payload){let R=X(t.payload);if(delete R.$schema,R.type==="object"&&R.properties){let M=R.required||[],C=R.properties;for(let E of Object.keys(C)){let $=C[E];$.required=M.includes(E)}delete R.required}u.payload=R}if(t.response){let R=X(t.response);if(delete R.$schema,R.type==="object"&&R.properties){let M=R.required||[],C=R.properties;for(let E of Object.keys(C)){let $=C[E];$.required=M.includes(E)}delete R.required}u.response=R}if(Object.keys(u).length>0)w.schemas=u;let x={};if(t.env&&t.env.length>0)x.environments=t.env;if(t.roles&&t.roles.length>0)x.roles=t.roles;if(t.ip&&t.ip.length>0)x.allowedIPs=t.ip;if(t.host&&t.host.length>0)x.allowedHosts=t.host;if(Object.keys(x).length>0)w.security=x;return w},l=(t)=>{let w=t.split(".");return w[w.length-1]||""},Y=(t,w=!0)=>{let u=w?"config.params":"params";return t.replace(/:(\w+)/g,(x,R)=>`\${${u}.${R}}`)},J=(t)=>{return`Object.entries(${t} || {}).reduce((params, [key, value]) => { params.append(key, String(value)); return params; }, new URLSearchParams()).toString()`},Gt=(t)=>{let w=l(t.name),u=`${w.charAt(0).toUpperCase()+w.slice(1)}RouteConfigType`,x=`${W(t.name)}Fetcher`,R=t.method.toLowerCase(),M=K(t),C=M==="never",E=C?"":`export type ${u} = ${M}`,$=[],A=t.params&&Object.keys(t.params).length>0,O=t.payload!==void 0,z=t.queries!==void 0,d=t.response?`${u}["response"]`:"never";if(A)$.push(`params: ${u}["params"]`);if(O)$.push(`payload: ${u}["payload"]`);if(z)$.push(`queries: ${u}["queries"]`);let I=$.length>0?`config: {
6
- ${$.join(`;
792
+ }`;
793
+ };
794
+ var assertToJsonSchema = (assert) => {
795
+ try {
796
+ const constraint = assert && typeof assert === "object" && "getConstraint" in assert ? assert.getConstraint() : assert;
797
+ return constraint.toJsonSchema();
798
+ } catch {
799
+ return { type: "unknown" };
800
+ }
801
+ };
802
+ var routeConfigToJsonDoc = (config) => {
803
+ const doc = {
804
+ name: config.name,
805
+ path: config.path,
806
+ method: config.method,
807
+ description: config.description,
808
+ controller: config.controller.name,
809
+ isSocket: config.isSocket,
810
+ parameters: extractParameterNames(config.path)
811
+ };
812
+ const schemas = {};
813
+ if (config.params) {
814
+ const paramsSchema = {
815
+ type: "object",
816
+ properties: {}
817
+ };
818
+ for (const [key, assert] of Object.entries(config.params)) {
819
+ const schema = assertToJsonSchema(assert);
820
+ delete schema.$schema;
821
+ schema.required = true;
822
+ paramsSchema.properties[key] = schema;
823
+ }
824
+ schemas.params = paramsSchema;
825
+ }
826
+ if (config.queries) {
827
+ const schema = assertToJsonSchema(config.queries);
828
+ delete schema.$schema;
829
+ if (schema.type === "object" && schema.properties) {
830
+ const requiredFields = schema.required || [];
831
+ const properties = schema.properties;
832
+ for (const key of Object.keys(properties)) {
833
+ const propSchema = properties[key];
834
+ propSchema.required = requiredFields.includes(key);
835
+ }
836
+ delete schema.required;
837
+ }
838
+ schemas.queries = schema;
839
+ }
840
+ if (config.payload) {
841
+ const schema = assertToJsonSchema(config.payload);
842
+ delete schema.$schema;
843
+ if (schema.type === "object" && schema.properties) {
844
+ const requiredFields = schema.required || [];
845
+ const properties = schema.properties;
846
+ for (const key of Object.keys(properties)) {
847
+ const propSchema = properties[key];
848
+ propSchema.required = requiredFields.includes(key);
849
+ }
850
+ delete schema.required;
851
+ }
852
+ schemas.payload = schema;
853
+ }
854
+ if (config.response) {
855
+ const schema = assertToJsonSchema(config.response);
856
+ delete schema.$schema;
857
+ if (schema.type === "object" && schema.properties) {
858
+ const requiredFields = schema.required || [];
859
+ const properties = schema.properties;
860
+ for (const key of Object.keys(properties)) {
861
+ const propSchema = properties[key];
862
+ propSchema.required = requiredFields.includes(key);
863
+ }
864
+ delete schema.required;
865
+ }
866
+ schemas.response = schema;
867
+ }
868
+ if (Object.keys(schemas).length > 0) {
869
+ doc.schemas = schemas;
870
+ }
871
+ const security = {};
872
+ if (config.env && config.env.length > 0) {
873
+ security.environments = config.env;
874
+ }
875
+ if (config.roles && config.roles.length > 0) {
876
+ security.roles = config.roles;
877
+ }
878
+ if (config.ip && config.ip.length > 0) {
879
+ security.allowedIPs = config.ip;
880
+ }
881
+ if (config.host && config.host.length > 0) {
882
+ security.allowedHosts = config.host;
883
+ }
884
+ if (Object.keys(security).length > 0) {
885
+ doc.security = security;
886
+ }
887
+ return doc;
888
+ };
889
+ var getRouteAction = (name) => {
890
+ const parts = name.split(".");
891
+ return parts[parts.length - 1] || "";
892
+ };
893
+ var buildPathWithParams = (path, useConfigPrefix = true) => {
894
+ const prefix = useConfigPrefix ? "config.params" : "params";
895
+ return path.replace(/:(\w+)/g, (_match, param) => `\${${prefix}.${param}}`);
896
+ };
897
+ var buildQueryString = (queriesSource) => {
898
+ return `Object.entries(${queriesSource} || {}).reduce((params, [key, value]) => { params.append(key, String(value)); return params; }, new URLSearchParams()).toString()`;
899
+ };
900
+ var routeConfigToFetcherString = (config) => {
901
+ const action = getRouteAction(config.name);
902
+ const typeName = `${action.charAt(0).toUpperCase() + action.slice(1)}RouteConfigType`;
903
+ const className = `${toPascalCase(config.name)}Fetcher`;
904
+ const method = config.method.toLowerCase();
905
+ const typeString = routeConfigToTypeString(config);
906
+ const isNeverType = typeString === "never";
907
+ const typeDefinition = isNeverType ? "" : `export type ${typeName} = ${typeString}`;
908
+ const configProps = [];
909
+ const hasParams = config.params && Object.keys(config.params).length > 0;
910
+ const hasPayload = config.payload !== undefined;
911
+ const hasQueries = config.queries !== undefined;
912
+ const responseType = config.response ? `${typeName}["response"]` : "never";
913
+ if (hasParams) {
914
+ configProps.push(`params: ${typeName}["params"]`);
915
+ }
916
+ if (hasPayload) {
917
+ configProps.push(`payload: ${typeName}["payload"]`);
918
+ }
919
+ if (hasQueries) {
920
+ configProps.push(`queries: ${typeName}["queries"]`);
921
+ }
922
+ const configType = configProps.length > 0 ? `config: {
923
+ ${configProps.join(`;
7
924
  `)};
8
- }`:"",H=Y(t.path),b=`\`${H}\``;if(z)b=`\`${H}?\${${J("config.queries")}}\``;let G=["post","put","patch"],F="";if(G.includes(R)&&O)F=`return await fetcher.${R}<${d}>(
9
- ${b},
925
+ }` : "";
926
+ const urlPath = buildPathWithParams(config.path);
927
+ let urlExpression = `\`${urlPath}\``;
928
+ if (hasQueries) {
929
+ urlExpression = `\`${urlPath}?\${${buildQueryString("config.queries")}}\``;
930
+ }
931
+ const methodsWithPayload = ["post", "put", "patch"];
932
+ let methodCall = "";
933
+ if (methodsWithPayload.includes(method) && hasPayload) {
934
+ methodCall = `return await fetcher.${method}<${responseType}>(
935
+ ${urlExpression},
10
936
  config.payload,
11
- );`;else F=`return await fetcher.${R}<${d}>(
12
- ${b},
13
- );`;let U=`export class ${x} {
14
- public async ${w}(${I}): Promise<ResponseDataType<${d}>> {
937
+ );`;
938
+ } else {
939
+ methodCall = `return await fetcher.${method}<${responseType}>(
940
+ ${urlExpression},
941
+ );`;
942
+ }
943
+ const classDefinition = `export class ${className} {
944
+ public async ${action}(${configType}): Promise<ResponseDataType<${responseType}>> {
15
945
 
16
946
  const fetcher = new Fetcher();
17
947
 
18
- ${F}
948
+ ${methodCall}
19
949
  }
20
- }`,B=`import { Fetcher } from "@ooneex/fetcher";
21
- import type { ResponseDataType } from "@ooneex/http-response";`;return C?`${B}
950
+ }`;
951
+ const imports = `import { Fetcher } from "@ooneex/fetcher";
952
+ import type { ResponseDataType } from "@ooneex/http-response";`;
953
+ return isNeverType ? `${imports}
22
954
 
23
- ${U}`:`${B}
955
+ ${classDefinition}` : `${imports}
24
956
 
25
- ${E}
957
+ ${typeDefinition}
26
958
 
27
- ${U}`},kt=(t)=>{let w=l(t.name),u=`${w.charAt(0).toUpperCase()+w.slice(1)}RouteConfigType`,x=`${W(t.name)}Socket`,R=K(t),M=R==="never",C=M?"":`export type ${u} = ${R}`,E=t.params&&Object.keys(t.params).length>0,$=t.payload&&Object.keys(t.payload).length>0,A=t.queries&&Object.keys(t.queries).length>0,O=E?`params: ${u}["params"]`:"",d=`\`${Y(t.path,!1)}\``,I=[];if($)I.push(`payload: ${u}["payload"]`);if(A)I.push(`queries: ${u}["queries"]`);I.push("language?: LocaleInfoType");let H=I.length>0?`{ ${I.join("; ")} }`:"Record<string, unknown>",b=t.response?`${u}["response"]`:"never",G=`export class ${x} {
28
- public ${w}(${O}): ISocket<${H}, ${b}> {
29
- const url = ${d};
30
- const socket = new Socket<${H}, ${b}>(url);
959
+ ${classDefinition}`;
960
+ };
961
+ var routeConfigToSocketString = (config) => {
962
+ const action = getRouteAction(config.name);
963
+ const typeName = `${action.charAt(0).toUpperCase() + action.slice(1)}RouteConfigType`;
964
+ const className = `${toPascalCase(config.name)}Socket`;
965
+ const typeString = routeConfigToTypeString(config);
966
+ const isNeverType = typeString === "never";
967
+ const typeDefinition = isNeverType ? "" : `export type ${typeName} = ${typeString}`;
968
+ const hasParams = config.params && Object.keys(config.params).length > 0;
969
+ const hasPayload = config.payload && Object.keys(config.payload).length > 0;
970
+ const hasQueries = config.queries && Object.keys(config.queries).length > 0;
971
+ const configType = hasParams ? `params: ${typeName}["params"]` : "";
972
+ const urlPath = buildPathWithParams(config.path, false);
973
+ const urlExpression = `\`${urlPath}\``;
974
+ const sendDataTypeProps = [];
975
+ if (hasPayload) {
976
+ sendDataTypeProps.push(`payload: ${typeName}["payload"]`);
977
+ }
978
+ if (hasQueries) {
979
+ sendDataTypeProps.push(`queries: ${typeName}["queries"]`);
980
+ }
981
+ sendDataTypeProps.push("language?: LocaleInfoType");
982
+ const sendDataType = sendDataTypeProps.length > 0 ? `{ ${sendDataTypeProps.join("; ")} }` : "Record<string, unknown>";
983
+ const responseType = config.response ? `${typeName}["response"]` : "never";
984
+ const classDefinition = `export class ${className} {
985
+ public ${action}(${configType}): ISocket<${sendDataType}, ${responseType}> {
986
+ const url = ${urlExpression};
987
+ const socket = new Socket<${sendDataType}, ${responseType}>(url);
31
988
 
32
- socket.onMessage((response: ResponseDataType<${b}>) => {
989
+ socket.onMessage((response: ResponseDataType<${responseType}>) => {
33
990
  // TODO: Handle socket message event
34
991
  });
35
992
 
@@ -41,61 +998,155 @@ ${U}`},kt=(t)=>{let w=l(t.name),u=`${w.charAt(0).toUpperCase()+w.slice(1)}RouteC
41
998
  // TODO: Handle socket close event
42
999
  });
43
1000
 
44
- socket.onError((event: Event, response?: ResponseDataType<${b}>) => {
1001
+ socket.onError((event: Event, response?: ResponseDataType<${responseType}>) => {
45
1002
  // TODO: Handle socket error event
46
1003
  });
47
1004
 
48
1005
  return socket;
49
1006
  }
50
- }`,F=`import type { ResponseDataType } from "@ooneex/http-response";
1007
+ }`;
1008
+ const imports = `import type { ResponseDataType } from "@ooneex/http-response";
51
1009
  import { type ISocket, Socket } from "@ooneex/socket/client";
52
- import type { LocaleInfoType } from "@ooneex/translation";`;return M?`${F}
1010
+ import type { LocaleInfoType } from "@ooneex/translation";`;
1011
+ return isNeverType ? `${imports}
53
1012
 
54
- ${G}`:`${F}
1013
+ ${classDefinition}` : `${imports}
55
1014
 
56
- ${C}
1015
+ ${typeDefinition}
57
1016
 
58
- ${G}`},zt=(t)=>{let w=l(t.name),u=`${w.charAt(0).toUpperCase()+w.slice(1)}RouteConfigType`,x=`use${W(t.name)}`,R=t.method.toUpperCase(),M=K(t),C=M==="never",E=C?"":`export type ${u} = ${M}`,A=["GET","HEAD","OPTIONS"].includes(R),O=t.params&&Object.keys(t.params).length>0,z=t.payload!==void 0,d=t.queries!==void 0,I=t.response?`${u}["response"]`:"never";if(A){let L=[];if(O)L.push(`params: ${u}["params"]`);if(d)L.push(`queries?: ${u}["queries"]`);let m=L.length>0?`config: {
59
- ${L.join(`;
1017
+ ${classDefinition}`;
1018
+ };
1019
+ var routeConfigToHookString = (config) => {
1020
+ const action = getRouteAction(config.name);
1021
+ const typeName = `${action.charAt(0).toUpperCase() + action.slice(1)}RouteConfigType`;
1022
+ const hookName = `use${toPascalCase(config.name)}`;
1023
+ const method = config.method.toUpperCase();
1024
+ const typeString = routeConfigToTypeString(config);
1025
+ const isNeverType = typeString === "never";
1026
+ const typeDefinition = isNeverType ? "" : `export type ${typeName} = ${typeString}`;
1027
+ const queryMethods = ["GET", "HEAD", "OPTIONS"];
1028
+ const isQuery = queryMethods.includes(method);
1029
+ const hasParams = config.params && Object.keys(config.params).length > 0;
1030
+ const hasPayload = config.payload !== undefined;
1031
+ const hasQueries = config.queries !== undefined;
1032
+ const responseType = config.response ? `${typeName}["response"]` : "never";
1033
+ if (isQuery) {
1034
+ const configProps2 = [];
1035
+ if (hasParams) {
1036
+ configProps2.push(`params: ${typeName}["params"]`);
1037
+ }
1038
+ if (hasQueries) {
1039
+ configProps2.push(`queries?: ${typeName}["queries"]`);
1040
+ }
1041
+ const configParam = configProps2.length > 0 ? `config: {
1042
+ ${configProps2.join(`;
60
1043
  `)};
61
- }`:"",Z=`[${t.name.split(".").map((D)=>`'${D}'`).join(", ")}`;if(O&&t.params){let D=Object.keys(t.params);for(let e of D)Z+=`, config.params.${e}`}if(d)Z+=", config.queries";Z+="]";let N=Y(t.path),S=`\`${N}\``;if(d)S=`\`${N}?\${${J("config.queries")}}\``;let h=R.toLowerCase(),y=`const fetcher = new Fetcher();
62
- const url = ${S};
1044
+ }` : "";
1045
+ const queryKeyParts = config.name.split(".");
1046
+ const queryKeyBase = queryKeyParts.map((part) => `'${part}'`).join(", ");
1047
+ let queryKey = `[${queryKeyBase}`;
1048
+ if (hasParams && config.params) {
1049
+ const paramKeys = Object.keys(config.params);
1050
+ for (const paramKey of paramKeys) {
1051
+ queryKey += `, config.params.${paramKey}`;
1052
+ }
1053
+ }
1054
+ if (hasQueries) {
1055
+ queryKey += ", config.queries";
1056
+ }
1057
+ queryKey += "]";
1058
+ const urlPath2 = buildPathWithParams(config.path);
1059
+ let urlExpression2 = `\`${urlPath2}\``;
1060
+ if (hasQueries) {
1061
+ urlExpression2 = `\`${urlPath2}?\${${buildQueryString("config.queries")}}\``;
1062
+ }
1063
+ const fetcherMethod2 = method.toLowerCase();
1064
+ const fetchCall2 = `const fetcher = new Fetcher();
1065
+ const url = ${urlExpression2};
63
1066
 
64
- return await fetcher.${h}<${I}>(url);`,P=`export const ${x} = (${m}) => {
1067
+ return await fetcher.${fetcherMethod2}<${responseType}>(url);`;
1068
+ const hookDefinition2 = `export const ${hookName} = (${configParam}) => {
65
1069
  return useQuery({
66
- queryKey: ${Z},
1070
+ queryKey: ${queryKey},
67
1071
  queryFn: async () => {
68
- ${y}
1072
+ ${fetchCall2}
69
1073
  },
70
1074
  });
71
- };`,o=`import { useQuery } from '@tanstack/react-query';
72
- import { Fetcher } from '@ooneex/fetcher';`;return C?`${o}
1075
+ };`;
1076
+ const imports2 = `import { useQuery } from '@tanstack/react-query';
1077
+ import { Fetcher } from '@ooneex/fetcher';`;
1078
+ return isNeverType ? `${imports2}
73
1079
 
74
- ${P}`:`${o}
1080
+ ${hookDefinition2}` : `${imports2}
75
1081
 
76
- ${E}
1082
+ ${typeDefinition}
77
1083
 
78
- ${P}`}let H=[];if(O)H.push(`params: ${u}["params"]`);if(z)H.push(`payload: ${u}["payload"]`);if(d)H.push(`queries?: ${u}["queries"]`);let b=H.length>0?`config: {
79
- ${H.join(`;
1084
+ ${hookDefinition2}`;
1085
+ }
1086
+ const configProps = [];
1087
+ if (hasParams) {
1088
+ configProps.push(`params: ${typeName}["params"]`);
1089
+ }
1090
+ if (hasPayload) {
1091
+ configProps.push(`payload: ${typeName}["payload"]`);
1092
+ }
1093
+ if (hasQueries) {
1094
+ configProps.push(`queries?: ${typeName}["queries"]`);
1095
+ }
1096
+ const mutationConfigType = configProps.length > 0 ? `config: {
1097
+ ${configProps.join(`;
80
1098
  `)};
81
- }`:"config?: Record<string, never>",G=Y(t.path),F=`\`${G}\``;if(d)F=`\`${G}\${config.queries ? \`?\${${J("config.queries")}}\` : ''}\``;let B=["POST","PUT","PATCH"].includes(R)&&z,q=R.toLowerCase(),V=`const fetcher = new Fetcher();
82
- const url = ${F};
1099
+ }` : "config?: Record<string, never>";
1100
+ const urlPath = buildPathWithParams(config.path);
1101
+ let urlExpression = `\`${urlPath}\``;
1102
+ if (hasQueries) {
1103
+ urlExpression = `\`${urlPath}\${config.queries ? \`?\${${buildQueryString("config.queries")}}\` : ''}\``;
1104
+ }
1105
+ const methodsWithPayload = ["POST", "PUT", "PATCH"];
1106
+ const hasFetchBody = methodsWithPayload.includes(method) && hasPayload;
1107
+ const fetcherMethod = method.toLowerCase();
1108
+ let fetchCall = `const fetcher = new Fetcher();
1109
+ const url = ${urlExpression};
83
1110
 
84
- `;if(B)V+=`return await fetcher.${q}<${I}>(url, config.payload);`;else V+=`return await fetcher.${q}<${I}>(url);`;let r=`export const ${x} = () => {
1111
+ `;
1112
+ if (hasFetchBody) {
1113
+ fetchCall += `return await fetcher.${fetcherMethod}<${responseType}>(url, config.payload);`;
1114
+ } else {
1115
+ fetchCall += `return await fetcher.${fetcherMethod}<${responseType}>(url);`;
1116
+ }
1117
+ const hookDefinition = `export const ${hookName} = () => {
85
1118
  const mutation = useMutation({
86
- mutationFn: async (${b}) => {
87
- ${V}
1119
+ mutationFn: async (${mutationConfigType}) => {
1120
+ ${fetchCall}
88
1121
  },
89
1122
  });
90
1123
 
91
1124
  return mutation;
92
- };`,Q=`import { useMutation } from '@tanstack/react-query';
93
- import { Fetcher } from '@ooneex/fetcher';`;return C?`${Q}
1125
+ };`;
1126
+ const imports = `import { useMutation } from '@tanstack/react-query';
1127
+ import { Fetcher } from '@ooneex/fetcher';`;
1128
+ return isNeverType ? `${imports}
94
1129
 
95
- ${r}`:`${Q}
1130
+ ${hookDefinition}` : `${imports}
96
1131
 
97
- ${E}
1132
+ ${typeDefinition}
98
1133
 
99
- ${r}`};export{_ as router,K as routeConfigToTypeString,kt as routeConfigToSocketString,Ot as routeConfigToJsonDoc,zt as routeConfigToHookString,Gt as routeConfigToFetcherString,Tt as isValidRoutePath,c as extractParameterNames,dt as VALID_NAMESPACES,It as VALID_ACTIONS,T as RouterException,j as Router,g as Route};
1134
+ ${hookDefinition}`;
1135
+ };
1136
+ export {
1137
+ router,
1138
+ routeConfigToTypeString,
1139
+ routeConfigToSocketString,
1140
+ routeConfigToJsonDoc,
1141
+ routeConfigToHookString,
1142
+ routeConfigToFetcherString,
1143
+ isValidRoutePath,
1144
+ extractParameterNames,
1145
+ VALID_NAMESPACES,
1146
+ VALID_ACTIONS,
1147
+ RouterException,
1148
+ Router,
1149
+ Route
1150
+ };
100
1151
 
101
- //# debugId=71957B2AF18D3E1B64756E2164756E21
1152
+ //# debugId=0A65C9B553EECFAD64756E2164756E21