import e from"./resolver.js";import{isString as t}from"../utils.js";const{pathToRegexp:r}=e,o=new Map;function cacheRoutes(e,t,r){const o=t.name||t.component;if(o&&(e.has(o)?e.get(o).push(t):e.set(o,[t])),Array.isArray(r))for(let o=0;o<r.length;o++){const n=r[o];n.parent=t,cacheRoutes(e,n,n.__children||n.children)}}function getRouteByName(e,t){const r=e.get(t);if(r&&r.length>1)throw new Error(`Duplicate route with name "${t}". Try seting unique 'name' route properties.`);return r&&r[0]}function getRoutePath(e){let t=e.path;return t=Array.isArray(t)?t[0]:t,void 0!==t?t:""}function generateUrls(n,a={}){if(!(n instanceof e))throw new TypeError("An instance of Resolver is expected");const s=new Map;return(e,c)=>{let u=getRouteByName(s,e);if(!u&&(s.clear(),cacheRoutes(s,n.root,n.root.__children),u=getRouteByName(s,e),!u))throw new Error(`Route "${e}" not found`);let i=o.get(u.fullPath);if(!i){let e=getRoutePath(u),n=u.parent;for(;n;){const t=getRoutePath(n);t&&(e=t.replace(/\/$/,"")+"/"+e.replace(/^\//,"")),n=n.parent}const a=r.parse(e),s=r.tokensToFunction(a),c=Object.create(null);for(let e=0;e<a.length;e++)t(a[e])||(c[a[e].name]=!0);i={toPath:s,keys:c},o.set(e,i),u.fullPath=e}let l=i.toPath(c,a)||"/";if(a.stringifyQueryParams&&c){const e={},t=Object.keys(c);for(let r=0;r<t.length;r++){const o=t[r];i.keys[o]||(e[o]=c[o])}const r=a.stringifyQueryParams(e);r&&(l+="?"===r.charAt(0)?r:`?${r}`)}return l}}export default generateUrls;