@devwareng/vanilla-ts 1.1.10 → 1.1.11

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.cjs CHANGED
@@ -1,510 +1,2 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // index.ts
31
- var index_exports = {};
32
- __export(index_exports, {
33
- TSRouter: () => TSRouter,
34
- html: () => html,
35
- useAnchor: () => useAnchor,
36
- useAnchorSingle: () => useAnchorSingle,
37
- useInitialDOM: () => useInitialDOM,
38
- useTSAuth: () => useTSAuth,
39
- useTSComponent: () => useTSComponent,
40
- useTSElementEach: () => useTSElementEach,
41
- useTSElements: () => useTSElements,
42
- useTSEvent: () => useTSEvent,
43
- useTSEventAll: () => useTSEventAll,
44
- useTSExtractParams: () => useTSExtractParams,
45
- useTSParams: () => useTSParams,
46
- useTSPurifier: () => useTSPurifier,
47
- useTSSelect: () => useTSSelect
48
- });
49
- module.exports = __toCommonJS(index_exports);
50
-
51
- // src/define/html.ts
52
- function html(strings, ...values) {
53
- return strings.reduce((result, str, i) => {
54
- return result + str + (values[i] || "");
55
- }, "");
56
- }
57
-
58
- // src/hooks/useTSPurifier.ts
59
- var import_dompurify = __toESM(require("dompurify"), 1);
60
- var useTSPurifier = (input, config) => {
61
- const defaultConfig = {
62
- ADD_TAGS: ["my-custom-tag"]
63
- };
64
- const mergedConfig = { ...defaultConfig, ...config };
65
- if (typeof input === "string") {
66
- return import_dompurify.default.sanitize(input, mergedConfig);
67
- } else {
68
- return import_dompurify.default.sanitize(input.innerHTML, mergedConfig);
69
- }
70
- };
71
-
72
- // src/hooks/useTSEvent.ts
73
- var useTSEvent = (id, eventType, handler) => {
74
- const element = document.querySelector(`#${id}`);
75
- if (element) {
76
- element.addEventListener(
77
- eventType,
78
- handler
79
- );
80
- } else {
81
- console.warn(`Element with id '${id}' not found.`);
82
- }
83
- };
84
-
85
- // src/hooks/useTSParams.ts
86
- var import_vanilla = require("zustand/vanilla");
87
- var import_dompurify2 = __toESM(require("dompurify"), 1);
88
- function extractPatternParams(pattern, path) {
89
- const paramNames = [];
90
- const regexPattern = pattern.replace(/:[^/]+/g, (match2) => {
91
- paramNames.push(match2.slice(1));
92
- return "([^/]+)";
93
- });
94
- const regex = new RegExp(`^${regexPattern}$`);
95
- const match = path.match(regex);
96
- const result = {};
97
- if (match) {
98
- paramNames.forEach((name, i) => {
99
- result[name] = import_dompurify2.default.sanitize(match[i + 1] ?? "");
100
- });
101
- }
102
- return result;
103
- }
104
- function extractQueryParams(search) {
105
- const result = {};
106
- const urlSearchParams = new URLSearchParams(search);
107
- for (const [key, value] of urlSearchParams.entries()) {
108
- result[key] = import_dompurify2.default.sanitize(value);
109
- }
110
- return result;
111
- }
112
- var useTSParams = (0, import_vanilla.createStore)((set, get) => ({
113
- params: {},
114
- query: {},
115
- setFromPattern: (pattern) => {
116
- const path = window.location.pathname;
117
- const params = extractPatternParams(pattern, path);
118
- const query = extractQueryParams(window.location.search);
119
- set({ params, query });
120
- },
121
- getParam: (key) => get().params[key],
122
- getQuery: (key) => get().query[key]
123
- }));
124
-
125
- // src/hooks/useTSExtract.ts
126
- function useTSExtractParams(pattern) {
127
- const store = useTSParams.getState();
128
- store.setFromPattern(pattern);
129
- const params = store.params;
130
- const query = store.query;
131
- return { ...params, ...query };
132
- }
133
-
134
- // src/hooks/useTSAllElements.ts
135
- var useTSEventAll = (selector, eventType, handler) => {
136
- const elements = document.querySelectorAll(selector);
137
- elements.forEach((element) => {
138
- element.addEventListener(eventType, handler);
139
- });
140
- return () => {
141
- elements.forEach((element) => {
142
- element.removeEventListener(eventType, handler);
143
- });
144
- };
145
- };
146
-
147
- // src/hooks/useTSElements.ts
148
- var import_dompurify3 = __toESM(require("dompurify"), 1);
149
- var useTSElements = (htmlElement, element, config) => {
150
- const defaultConfig = {
151
- ALLOWED_TAGS: ["main", "div", "h1", "p", "button", "span", "a", "img", "input"],
152
- ALLOWED_ATTR: ["class", "id", "href", "style", "src", "alt"],
153
- ...config
154
- // allow user overrides
155
- };
156
- const sanitizedContent = import_dompurify3.default.sanitize(
157
- /*html*/
158
- element,
159
- defaultConfig
160
- );
161
- if (htmlElement.innerHTML !== String(sanitizedContent)) {
162
- return htmlElement.innerHTML = String(sanitizedContent);
163
- }
164
- };
165
-
166
- // src/hooks/useIntialDOM.ts
167
- var import_dompurify4 = __toESM(require("dompurify"), 1);
168
- var previousHTML = null;
169
- var useInitialDOM = (id, mount) => {
170
- if (typeof document === "undefined") return;
171
- const targetElement = document.getElementById(id);
172
- if (!targetElement) return;
173
- const currentHTML = targetElement.innerHTML;
174
- const sanitizedHTML = import_dompurify4.default.sanitize(currentHTML);
175
- if (previousHTML !== null && sanitizedHTML !== previousHTML) {
176
- const fallbackEl = document.createElement("div");
177
- mount(fallbackEl);
178
- targetElement.innerHTML = previousHTML;
179
- } else {
180
- previousHTML = sanitizedHTML;
181
- mount(targetElement);
182
- }
183
- };
184
-
185
- // src/hooks/useTSAnchorSingle.ts
186
- var sanitizeInput = (input) => {
187
- const element = document.createElement("div");
188
- element.innerText = input;
189
- return element.innerHTML;
190
- };
191
- var useAnchorSingle = (element, href, ariaLabel, className = "", childElement = null) => {
192
- if (!element) return;
193
- const sanitizedHref = sanitizeInput(href);
194
- const sanitizedAriaLabel = sanitizeInput(ariaLabel);
195
- const sanitizedClassName = className ? sanitizeInput(className) : void 0;
196
- element.setAttribute("href", sanitizedHref);
197
- element.setAttribute("aria-label", sanitizedAriaLabel);
198
- if (sanitizedClassName) {
199
- element.className = sanitizedClassName;
200
- }
201
- if (childElement) {
202
- element.innerHTML = "";
203
- element.appendChild(childElement);
204
- }
205
- element.addEventListener("click", (e) => {
206
- e.preventDefault();
207
- const target = e.currentTarget;
208
- const href2 = target.getAttribute("href");
209
- if (href2) {
210
- const scrollPosition = window.scrollY;
211
- window.scrollTo(0, 0);
212
- window.history.pushState({ scrollPosition }, "", href2);
213
- const navEvent = new PopStateEvent("popstate");
214
- dispatchEvent(navEvent);
215
- }
216
- });
217
- window.addEventListener("popstate", (e) => {
218
- const state = e.state;
219
- if (state && state.scrollPosition !== void 0) {
220
- window.scrollTo(0, state.scrollPosition);
221
- }
222
- });
223
- };
224
-
225
- // src/hooks/useTSAnchor.ts
226
- var import_lodash = __toESM(require("lodash"), 1);
227
- var sanitizeInput2 = (input) => input;
228
- if (typeof window !== "undefined" && typeof document !== "undefined") {
229
- sanitizeInput2 = (input) => {
230
- const element = document.createElement("div");
231
- element.innerText = input;
232
- return element.innerHTML;
233
- };
234
- }
235
- var useAnchor = typeof window !== "undefined" ? (0, import_lodash.default)((anchors) => {
236
- anchors.forEach((anchor) => {
237
- if (!anchor) return;
238
- const originalHref = anchor.getAttribute("href") || "#";
239
- const originalClassName = anchor.getAttribute("class") || "";
240
- const sanitizedHref = sanitizeInput2(originalHref);
241
- const sanitizedClassName = anchor.getAttribute("class") ? sanitizeInput2(anchor.getAttribute("class")) : originalClassName;
242
- anchor.setAttribute("href", sanitizedHref);
243
- anchor.setAttribute("class", sanitizedClassName);
244
- if (anchor.getAttribute("aria-label")) {
245
- anchor.setAttribute(
246
- "aria-label",
247
- sanitizeInput2(anchor.getAttribute("aria-label"))
248
- );
249
- }
250
- const childElement = anchor.querySelector(":scope > *");
251
- if (childElement) {
252
- anchor.innerHTML = "";
253
- anchor.appendChild(childElement);
254
- }
255
- anchor.addEventListener("click", (e) => {
256
- const target = e.currentTarget;
257
- const href = target.getAttribute("href");
258
- try {
259
- const url = new URL(href, window.location.href);
260
- if (url.origin !== window.location.origin) return;
261
- } catch (error) {
262
- console.error("Invalid URL:", error);
263
- return;
264
- }
265
- e.preventDefault();
266
- window.history.pushState({}, "", href);
267
- const navEvent = new PopStateEvent("popstate");
268
- window.dispatchEvent(navEvent);
269
- });
270
- });
271
- }) : () => {
272
- };
273
-
274
- // src/hooks/useTSMetaData.ts
275
- var import_dompurify5 = __toESM(require("dompurify"), 1);
276
-
277
- // src/hooks/useTSComponent.ts
278
- var import_dompurify6 = __toESM(require("dompurify"), 1);
279
- var useTSComponent = (id, DOM, element, params, params2) => {
280
- import_dompurify6.default.sanitize(DOM);
281
- element(DOM.querySelector(`#${id}`), params, params2);
282
- };
283
-
284
- // src/hooks/useTSSelect.ts
285
- var useTSSelect = (selector) => {
286
- const element = document.querySelector(selector);
287
- if (!element) {
288
- console.warn(`[useTSSelect] No element found for selector: '${selector}'`);
289
- return null;
290
- }
291
- return element;
292
- };
293
-
294
- // src/hooks/useTSAuth.ts
295
- var import_jwt_decode = require("jwt-decode");
296
- var useTSAuth = (_Component, loginUrl) => {
297
- const token = localStorage.getItem("token");
298
- if (!token) {
299
- window.location.href = loginUrl;
300
- return null;
301
- }
302
- try {
303
- const decodedToken = (0, import_jwt_decode.jwtDecode)(token);
304
- const currentTime = Date.now() / 1e3;
305
- if (decodedToken.exp && decodedToken.exp < currentTime) {
306
- console.error("Token has expired");
307
- window.localStorage.removeItem("token");
308
- window.location.href = loginUrl;
309
- return null;
310
- }
311
- return null;
312
- } catch (error) {
313
- console.error("Invalid token:", error);
314
- window.location.href = loginUrl;
315
- return null;
316
- }
317
- };
318
-
319
- // src/hooks/useTSForEach.ts
320
- var useTSElementEach = (elements, events, callback) => {
321
- elements.forEach((element) => {
322
- events.forEach((eventType) => {
323
- element.addEventListener(eventType, (event) => {
324
- callback(element, event);
325
- });
326
- });
327
- });
328
- };
329
-
330
- // src/routes/class/Router.class.ts
331
- var import_dompurify8 = __toESM(require("dompurify"), 1);
332
-
333
- // src/store/useTSParam.store.ts
334
- var import_vanilla2 = require("zustand/vanilla");
335
- var import_dompurify7 = __toESM(require("dompurify"), 1);
336
- var tsParamsStore = (0, import_vanilla2.createStore)((set) => ({
337
- params: {},
338
- query: {},
339
- setParams: (params) => set(() => ({
340
- params: sanitize(params)
341
- })),
342
- setQuery: (query) => set(() => ({
343
- query: sanitize(query)
344
- }))
345
- }));
346
- function sanitize(obj) {
347
- const output = {};
348
- for (const key in obj) {
349
- output[key] = import_dompurify7.default.sanitize(obj[key]);
350
- }
351
- return output;
352
- }
353
-
354
- // src/routes/class/Router.class.ts
355
- var TSRouter = class {
356
- constructor(routes, expectedParams) {
357
- this.routes = [];
358
- this.routes = routes;
359
- this.expectedParams = new Set(expectedParams);
360
- window.addEventListener("popstate", this.handlePopState.bind(this));
361
- this.handlePopState();
362
- }
363
- handlePopState() {
364
- const currentPath = window.location.pathname;
365
- const currentSearch = window.location.search;
366
- const queryParams = this.parseQueryParams(currentSearch);
367
- const matchingRoute = this.findMatchingRoute(currentPath, this.routes);
368
- if (matchingRoute) {
369
- if (matchingRoute.routeto) {
370
- this.navigate(matchingRoute.routeto);
371
- return;
372
- }
373
- const sanitizedParams = this.filterAndSanitizeParams(matchingRoute.params);
374
- tsParamsStore.getState().setParams(sanitizedParams);
375
- tsParamsStore.getState().setQuery(queryParams);
376
- const errorElement = document.createElement("div");
377
- matchingRoute.element?.(errorElement, sanitizedParams, queryParams);
378
- if (matchingRoute.children) {
379
- const nestedPath = currentPath.slice(matchingRoute.path.length);
380
- const childElement = errorElement.querySelector("#child");
381
- if (childElement) {
382
- this.renderChildren(
383
- matchingRoute.children,
384
- nestedPath,
385
- childElement,
386
- sanitizedParams,
387
- queryParams
388
- );
389
- }
390
- }
391
- } else {
392
- const notFoundRoute = this.findMatchingRoute("*", this.routes);
393
- if (notFoundRoute) {
394
- const fallbackParams = this.filterAndSanitizeParams(notFoundRoute.params);
395
- tsParamsStore.getState().setParams(fallbackParams);
396
- tsParamsStore.getState().setQuery(queryParams);
397
- const errorElement = document.createElement("div");
398
- notFoundRoute.element?.(errorElement, fallbackParams, queryParams);
399
- }
400
- }
401
- }
402
- renderChildren(children, nestedPath, parentElement, parentParams, queryParams) {
403
- if (!children || children.length === 0) {
404
- const childElement = parentElement.querySelector("#child");
405
- if (childElement) childElement.remove();
406
- return;
407
- }
408
- const matchingChild = this.findMatchingRoute(nestedPath, children);
409
- if (matchingChild) {
410
- const childElement = document.createElement("div");
411
- childElement.id = "child";
412
- const mergedParams = { ...parentParams, ...matchingChild.params };
413
- const sanitizedParams = this.filterAndSanitizeParams(mergedParams);
414
- tsParamsStore.getState().setParams(sanitizedParams);
415
- tsParamsStore.getState().setQuery(queryParams);
416
- matchingChild.element?.(childElement, sanitizedParams, queryParams);
417
- parentElement.appendChild(childElement);
418
- if (matchingChild.children) {
419
- const nextNestedPath = nestedPath.slice(matchingChild.path.length);
420
- this.renderChildren(
421
- matchingChild.children,
422
- nextNestedPath,
423
- childElement,
424
- sanitizedParams,
425
- queryParams
426
- );
427
- }
428
- }
429
- }
430
- parseQueryParams(search) {
431
- const queryParams = {};
432
- const urlSearchParams = new URLSearchParams(search);
433
- for (const [key, value] of urlSearchParams.entries()) {
434
- if (this.expectedParams.has(key)) {
435
- queryParams[key] = import_dompurify8.default.sanitize(value);
436
- }
437
- }
438
- return queryParams;
439
- }
440
- findMatchingRoute(path, routes, inheritedParams = {}) {
441
- for (const route of routes) {
442
- const routePath = route.path;
443
- const isDefaultRoute = routePath === "*";
444
- if (!isDefaultRoute) {
445
- const paramNames = [];
446
- const regexPattern = routePath.replace(/:[^\s/]+/g, (match2) => {
447
- paramNames.push(match2.substring(1));
448
- return "([^\\s/]+)";
449
- });
450
- const regex = new RegExp(`^${regexPattern}(?:/|$)`);
451
- const match = path.match(regex);
452
- if (match) {
453
- const params = { ...inheritedParams };
454
- paramNames.forEach((name, index) => {
455
- params[name] = match[index + 1] ?? "";
456
- });
457
- if (route.children) {
458
- const nestedPath = path.slice(match[0].length);
459
- const matchingChild = this.findMatchingRoute(
460
- nestedPath,
461
- route.children,
462
- params
463
- );
464
- if (matchingChild) return matchingChild;
465
- }
466
- return { ...route, params };
467
- }
468
- } else {
469
- return route;
470
- }
471
- }
472
- return void 0;
473
- }
474
- filterAndSanitizeParams(params) {
475
- if (!params) return {};
476
- const sanitizedParams = {};
477
- for (const key in params) {
478
- if (this.expectedParams.has(key)) {
479
- sanitizedParams[key] = import_dompurify8.default.sanitize(params[key] ?? "");
480
- }
481
- }
482
- return sanitizedParams;
483
- }
484
- navigate(path) {
485
- history.pushState(null, "", path);
486
- this.handlePopState();
487
- }
488
- addRoute(route) {
489
- this.routes.push(route);
490
- }
491
- };
492
- // Annotate the CommonJS export names for ESM import in node:
493
- 0 && (module.exports = {
494
- TSRouter,
495
- html,
496
- useAnchor,
497
- useAnchorSingle,
498
- useInitialDOM,
499
- useTSAuth,
500
- useTSComponent,
501
- useTSElementEach,
502
- useTSElements,
503
- useTSEvent,
504
- useTSEventAll,
505
- useTSExtractParams,
506
- useTSParams,
507
- useTSPurifier,
508
- useTSSelect
509
- });
1
+ "use strict";var Y=Object.create;var S=Object.defineProperty;var J=Object.getOwnPropertyDescriptor;var K=Object.getOwnPropertyNames;var V=Object.getPrototypeOf,X=Object.prototype.hasOwnProperty;var Z=(t,e)=>{for(var n in e)S(t,n,{get:e[n],enumerable:!0})},N=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of K(e))!X.call(t,o)&&o!==n&&S(t,o,{get:()=>e[o],enumerable:!(r=J(e,o))||r.enumerable});return t};var d=(t,e,n)=>(n=t!=null?Y(V(t)):{},N(e||!t||!t.__esModule?S(n,"default",{value:t,enumerable:!0}):n,t)),ee=t=>N(S({},"__esModule",{value:!0}),t);var oe={};Z(oe,{TSRouter:()=>v,html:()=>M,useAnchor:()=>O,useAnchorSingle:()=>D,useInitialDOM:()=>H,useTSAuth:()=>k,useTSComponent:()=>y,useTSElementEach:()=>q,useTSElements:()=>C,useTSEvent:()=>x,useTSEventAll:()=>w,useTSExtractParams:()=>A,useTSParams:()=>p,useTSPurifier:()=>P,useTSSelect:()=>z});module.exports=ee(oe);function M(t,...e){return t.reduce((n,r,o)=>n+r+(e[o]||""),"")}var L=d(require("dompurify"),1),P=(t,e)=>{let r={...{ADD_TAGS:["my-custom-tag"]},...e};return typeof t=="string"?L.default.sanitize(t,r):L.default.sanitize(t.innerHTML,r)};var x=(t,e,n)=>{let r=document.querySelector(`#${t}`);r?r.addEventListener(e,n):console.warn(`Element with id '${t}' not found.`)};var I=require("zustand/vanilla"),R=d(require("dompurify"),1);function te(t,e){let n=[],r=t.replace(/:[^/]+/g,i=>(n.push(i.slice(1)),"([^/]+)")),o=new RegExp(`^${r}$`),s=e.match(o),a={};return s&&n.forEach((i,c)=>{a[i]=R.default.sanitize(s[c+1]??"")}),a}function ne(t){let e={},n=new URLSearchParams(t);for(let[r,o]of n.entries())e[r]=R.default.sanitize(o);return e}var p=(0,I.createStore)((t,e)=>({params:{},query:{},setFromPattern:n=>{let r=window.location.pathname,o=te(n,r),s=ne(window.location.search);t({params:o,query:s})},getParam:n=>e().params[n],getQuery:n=>e().query[n]}));function A(t){let e=p.getState();e.setFromPattern(t);let n=e.params,r=e.query;return{...n,...r}}var w=(t,e,n)=>{let r=document.querySelectorAll(t);return r.forEach(o=>{o.addEventListener(e,n)}),()=>{r.forEach(o=>{o.removeEventListener(e,n)})}};var F=d(require("dompurify"),1),C=(t,e,n)=>{let r={ALLOWED_TAGS:["main","div","h1","p","button","span","a","img","input"],ALLOWED_ATTR:["class","id","href","style","src","alt"],...n},o=F.default.sanitize(e,r);if(t.innerHTML!==String(o))return t.innerHTML=String(o)};var U=d(require("dompurify"),1),T=null,H=(t,e)=>{if(typeof document>"u")return;let n=document.getElementById(t);if(!n)return;let r=n.innerHTML,o=U.default.sanitize(r);if(T!==null&&o!==T){let s=document.createElement("div");e(s),n.innerHTML=T}else T=o,e(n)};var b=t=>{let e=document.createElement("div");return e.innerText=t,e.innerHTML},D=(t,e,n,r="",o=null)=>{if(!t)return;let s=b(e),a=b(n),i=r?b(r):void 0;t.setAttribute("href",s),t.setAttribute("aria-label",a),i&&(t.className=i),o&&(t.innerHTML="",t.appendChild(o)),t.addEventListener("click",c=>{c.preventDefault();let u=c.currentTarget.getAttribute("href");if(u){let m=window.scrollY;window.scrollTo(0,0),window.history.pushState({scrollPosition:m},"",u);let f=new PopStateEvent("popstate");dispatchEvent(f)}}),window.addEventListener("popstate",c=>{let l=c.state;l&&l.scrollPosition!==void 0&&window.scrollTo(0,l.scrollPosition)})};var Q=d(require("lodash"),1),E=t=>t;typeof window<"u"&&typeof document<"u"&&(E=t=>{let e=document.createElement("div");return e.innerText=t,e.innerHTML});var O=typeof window<"u"?(0,Q.default)(t=>{t.forEach(e=>{if(!e)return;let n=e.getAttribute("href")||"#",r=e.getAttribute("class")||"",o=E(n),s=e.getAttribute("class")?E(e.getAttribute("class")):r;e.setAttribute("href",o),e.setAttribute("class",s),e.getAttribute("aria-label")&&e.setAttribute("aria-label",E(e.getAttribute("aria-label")));let a=e.querySelector(":scope > *");a&&(e.innerHTML="",e.appendChild(a)),e.addEventListener("click",i=>{let l=i.currentTarget.getAttribute("href");try{if(new URL(l,window.location.href).origin!==window.location.origin)return}catch(m){console.error("Invalid URL:",m);return}i.preventDefault(),window.history.pushState({},"",l);let u=new PopStateEvent("popstate");window.dispatchEvent(u)})})}):()=>{};var re=d(require("dompurify"),1);var _=d(require("dompurify"),1),y=(t,e,n,r,o)=>{_.default.sanitize(e),n(e.querySelector(`#${t}`),r,o)};var z=t=>{let e=document.querySelector(t);return e||(console.warn(`[useTSSelect] No element found for selector: '${t}'`),null)};var j=require("jwt-decode"),k=(t,e)=>{let n=localStorage.getItem("token");if(!n)return window.location.href=e,null;try{let r=(0,j.jwtDecode)(n),o=Date.now()/1e3;return r.exp&&r.exp<o&&(console.error("Token has expired"),window.localStorage.removeItem("token"),window.location.href=e),null}catch(r){return console.error("Invalid token:",r),window.location.href=e,null}};var q=(t,e,n)=>{t.forEach(r=>{e.forEach(o=>{r.addEventListener(o,s=>{n(r,s)})})})};var $=d(require("dompurify"),1);var G=require("zustand/vanilla"),W=d(require("dompurify"),1),g=(0,G.createStore)(t=>({params:{},query:{},setParams:e=>t(()=>({params:B(e)})),setQuery:e=>t(()=>({query:B(e)}))}));function B(t){let e={};for(let n in t)e[n]=W.default.sanitize(t[n]);return e}var v=class{constructor(e,n){this.routes=[];this.routes=e,this.expectedParams=new Set(n),window.addEventListener("popstate",this.handlePopState.bind(this)),this.handlePopState()}handlePopState(){let e=window.location.pathname,n=window.location.search,r=this.parseQueryParams(n),o=this.findMatchingRoute(e,this.routes);if(o){if(o.routeto){this.navigate(o.routeto);return}let s=this.filterAndSanitizeParams(o.params);g.getState().setParams(s),g.getState().setQuery(r);let a=document.createElement("div");if(o.element?.(a,s,r),o.children){let i=e.slice(o.path.length),c=a.querySelector("#child");c&&this.renderChildren(o.children,i,c,s,r)}}else{let s=this.findMatchingRoute("*",this.routes);if(s){let a=this.filterAndSanitizeParams(s.params);g.getState().setParams(a),g.getState().setQuery(r);let i=document.createElement("div");s.element?.(i,a,r)}}}renderChildren(e,n,r,o,s){if(!e||e.length===0){let i=r.querySelector("#child");i&&i.remove();return}let a=this.findMatchingRoute(n,e);if(a){let i=document.createElement("div");i.id="child";let c={...o,...a.params},l=this.filterAndSanitizeParams(c);if(g.getState().setParams(l),g.getState().setQuery(s),a.element?.(i,l,s),r.appendChild(i),a.children){let u=n.slice(a.path.length);this.renderChildren(a.children,u,i,l,s)}}}parseQueryParams(e){let n={},r=new URLSearchParams(e);for(let[o,s]of r.entries())this.expectedParams.has(o)&&(n[o]=$.default.sanitize(s));return n}findMatchingRoute(e,n,r={}){for(let o of n){let s=o.path;if(s==="*")return o;{let i=[],c=s.replace(/:[^\s/]+/g,m=>(i.push(m.substring(1)),"([^\\s/]+)")),l=new RegExp(`^${c}(?:/|$)`),u=e.match(l);if(u){let m={...r};if(i.forEach((f,h)=>{m[f]=u[h+1]??""}),o.children){let f=e.slice(u[0].length),h=this.findMatchingRoute(f,o.children,m);if(h)return h}return{...o,params:m}}}}}filterAndSanitizeParams(e){if(!e)return{};let n={};for(let r in e)this.expectedParams.has(r)&&(n[r]=$.default.sanitize(e[r]??""));return n}navigate(e){history.pushState(null,"",e),this.handlePopState()}addRoute(e){this.routes.push(e)}};0&&(module.exports={TSRouter,html,useAnchor,useAnchorSingle,useInitialDOM,useTSAuth,useTSComponent,useTSElementEach,useTSElements,useTSEvent,useTSEventAll,useTSExtractParams,useTSParams,useTSPurifier,useTSSelect});
510
2
  //# sourceMappingURL=index.cjs.map