{"version":3,"sources":["../src/link-handler.ts","../src/browser-history.ts","../src/aurelia-history-browser.ts","../src/navigation-instruction.ts","../src/router-configuration.ts","../src/router.ts","../src/nav-model.ts","../src/util.ts","../src/next.ts","../src/pipeline.ts","../src/navigation-commands.ts","../src/navigation-plan.ts","../src/step-build-navigation-plan.ts","../src/utilities-route-loading.ts","../src/route-loader.ts","../src/step-load-route.ts","../src/step-commit-changes.ts","../src/activation-strategy.ts","../src/utilities-activation.ts","../src/step-activation.ts","../src/pipeline-provider.ts","../src/app-router.ts","../src/pipeline-status.ts","../src/router-event.ts","../src/pipeline-slot-name.ts","../src/router-view.ts","../src/route-href.ts","../src/aurelia-templating-router.ts"],"names":["Async","this","_customScheduler","tslib_1.__extends","_normalQueue","Queue","schedule","fn","receiver","arg","_lateQueue","push","_queueTick","AsyncSettlePromises","promise","_pushOne","queue","length","shift","Error","e","firstLineError","_dereq_","_schedule","hasCustomScheduler","haveItemsQueued","_isTickUsed","_haveDrainedQueues","fatalError","isNode","stderr","write","stack","exit","throwLater","setTimeout","invokeLater","AsyncInvokeLater","invoke","AsyncInvoke","settlePromises","_drainQueues","drainQueues","./schedule","2","module","exports","Promise","INTERNAL","tryConvertToPromise","debug","_","_reject","PLATFORM","context","bindingPromise","_then","rejectThis","thisArg","_bitField","_resolveCallback","target","promiseRejectionQueued","bind","prototype","_propagateFrom","propagateFromFunction","_boundValue","boundValueFunction","_target","maybePromise","ret","targetRejected","undefined","bindingRejected","_setBoundTo","obj","_boundTo","DOM","_isBound","value","resolve","bluebird","old","noConflict","4","PromiseArray","apiRejection","tryCatch","errorObj","_async","cancel","_warn","_cancelBy","child","_isFollowing","_followee","_cancelBranched","parent","_cancellationParent","_isCancellable","History","_setWillBeCancelled","_branchHasCancelled","_branchesRemainingToCancel","_enoughBranchesHaveCancelled","_invokeOnCancel","onCancelCallback","call","_resultCancelled","_onCancel","_invokeInternalOnCancel","_doInvokeOnCancel","_unsetOnCancel","5","NEXT_FILTER","predicateLoop","i","instances","item","cb","boundTo","matchesPredicate","util","isObject","keys","getKeys","j","key","./util","6","Context","CapturedTrace","peekContext","contextStack","lastIndex","_pushContext","_trace","_promiseCreated","trace","pop","createContext","Promise_peekContext","_peekContext","deactivateLongStackTraces","Promise_pushContext","_popContext","Promise_popContext","Promise_PeekContext","Promise_promiseCreated","ctx","name","executor","reject","onCancel","_attachCancellationCallback","previousOnCancel","isArray","_setOnCancel","cancellationSetOnCancel","flags","branchesRemainingToCancel","longStackTracesCaptureStackTrace","longStackTracesAttachExtraTrace","error","ignoreSelf","notEnumerableProp","parsed","message","join","returnValue","promiseCreated","_returnedNonUndefined","handlerLine","creatorLine","traceLines","split","cleanStack","line","nodeFramePattern","test","lineMatches","match","parseLinePattern","firstUserLine","msg","replacement","Warning","_attachExtraTrace","warning","longStackTraces","parseStackAndMessage","stacks","splice","current","currentLastIndex","commonRootMeetPoint","replace","stackFramePattern","slice","toString","stackFramesAsArray","title","isSoft","console","formatStack","String","printWarning","localHandler","reason","activeFireEvent","localEventFired","formatAndLogError","str","JSON","stringify","maxChars","captureStackTrace","parseLineInfoRegex","matches","parseInt","lastLineError","firstStackLines","parseLineInfo","firstFileName","result","fileName","firstIndex","lastStackLines","lastFileName","info","_length","uncycle","env","unhandledRejectionCheck","promises","_notifyUnhandledRejection","unhandledRejectionClear","suppressUnhandledRejections","_ensurePossibleRejectionHandled","_setRejectionIsUnhandled","fireRejectionEvent","_setReturnedNonUndefined","_isUnhandledRejectionNotified","_unsetUnhandledRejectionIsNotified","_notifyUnhandledRejectionIsHandled","_isRejectionUnhandled","shouldUseOwnTrace","warn","onPossiblyUnhandledRejection","_getContext","contextBind","onUnhandledRejectionHandled","config","longStackTracesIsSupported","Promise_captureStackTrace","_captureStackTrace","Promise_attachExtraTrace","Promise_dereferenceTrace","_dereferenceTrace","disableLongStackTraces","async","longStackTracesDereferenceTrace","activateLongStackTraces","legacyHandlers","unhandledrejection","global","onunhandledrejection","onrejectionhandled","legacy","dispatchEvent","eventData","detail","event","cancelable","dispatch","domEvent","initCustomEvent","toLowerCase","methodName","generatePromiseLifecycleEventObject","fireDomEvent","eventToObjectGenerator","apply","arguments","globalEventFired","opts","hasLongStackTraces","warningsOption","warnings","wForgottenReturn","cancellation","cancellationPropagateFrom","_execute","cancellationExecute","monitoring","_fireEvent","defaultFireEvent","prev","cur","asyncHooks","disableAsyncHooks","handler","_clearCancellationData","bindingPropagateFrom","node","_parent","nodes","stackToIndex","currentStack","index","cycleEdgeNode","currentChildLength","attachExtraTrace","__stackCleaned__","reconstructStack","v8stackFramePattern","v8stackFormatter","formatNonError","ignoreUntil","stackTraceLimit","err","indexOf","hasStackAfterThrow","color","deprecated","thrower","thenReturn","thenThrow","catchThrow","_reason","caught","catchReturn","_value","defaultMessage","SubError","nameProperty","constructor","OperationalError","_RangeError","inherits","subError","TimeoutError","AggregateError","methods","Array","level","indent","lines","errorTypes","RejectionError","defineProperty","writable","_TypeError","CancellationError","10","isES5","Object","freeze","getOwnPropertyDescriptor","getOwnPropertyNames","getPrototypeOf","prop","descriptor","set","hasOwnProperty","proto","ObjectKeys","o","has","ObjectGetDescriptor","ArrayIsArray","ObjectDefineProperty","getDescriptor","ObjectFreeze","ObjectGetPrototypeOf","type","cancelPromise","FinallyHandlerCancelReaction","finallyHandler","_cancel","_settledValue","reasonOrValue","isPending","succeed","fail","isFinallyHandler","then","success","PassThroughHandlerContext","_passThrough","tapCatch","handlerOrPredicate","len","catchInstances","TypeError","classString","12","canEvaluate","last","args","spread","checkForgottenReturns","attempt","14","es5","isUntypedError","nodebackForPromise","multiArgs","wrapped","wrapAsOperationalError","maybeWrapAsError","_fulfill","errors","./es5","15","self","_receiver0","PromiseInspection","reflectHandler","domain","process","getDomain","AsyncResource","getContext","getContextDomain","RangeError","Proxyable","create","LogManager.getLogger","catchFilter","reflect","didFulfill","didReject","done","all","APPLY","originatesFromRejection","val","fromCallback","rejected","setScheduler","internalData","haveInternalData","settler","_settlePromiseCtx","_rejectionHandler0","bitField","_fulfillmentHandler0","_unsetRejectionIsUnhandled","_settlePromiseLateCancellationObserver","_isFateSealed","_setLength","_setFulfilled","_setRejected","_setFollowing","_isFinal","_unsetCancelled","_setCancelled","_setAsyncGuaranteed","_setNoAsyncGuarantee","_receiverAt","UNDEFINED_BINDING","_promiseAt","_fulfillmentHandlerAt","_migrateCallback0","follower","PipelineStatus","_promise0","_migrateCallbackAt","fulfill","_rejectionHandlerAt","RouterEvent","base","PipelineSlotName","normalize","baseName","applyMap","mapValue","nameParts","nameSegment","foundMap","foundI","foundStarMap","starI","normalizedBaseParts","baseParts","map","concat","trimDots","starMap","getOwn","outerLoop","each","scripts","scriptNode","getAttribute","contextName","parentNode","removeChild","pathConfig","paths","id","require","undef","makeRequire","skipMap","splitPrefix","substring","prefix","parentModuleMap","isNormalized","pluginModule","suffix","ShadowDOM","requireCounter","parentName","normalizedName","url","nameToUrl","unnormalizedCounter","parentMap","originalName","isDefine","depMap","mod","registry","Module","hasProp","defined","defineEmitComplete","on","errback","requireModules","ids","emit","notified","req","onError","takeGlobalQueue","globalDefQueue","queueItem","defQueueMap","defQueue","cleanRegistry","enabledRegistry","breakCycle","traced","processed","depMaps","dep","depId","depMatched","defineDep","check","usingPathFallback","waitInterval","waitSeconds","expired","startTime","Date","getTime","noLoads","reqCalls","stillLoading","needCycleCheck","inCheckLoaded","RouteLoader","eachProp","Router","handlers","customElement","usingExports","useView","uri"],"mappings":"0tIAmBAA,KAAAC,KAACC,kBAAA,2BAMuCC,WAAAA,GAAAA,GAAAA,SAUtCC,aAAA,GAAAC,GAAA,6BACE,QAEAJ,sBACM,4CAIFK,aA6EHC,EAAAC,EAAAC,QACFC,WAAAC,KAAAJ,EAAAC,EAAAC,QAQMG,wBAIGL,EAAAC,EAAYC,qBAClBE,KAAAJ,EAAYC,EAAaC,6BA7GSI,GAgHvCC,GAEDb,KAAMG,aAAYW,SAAGD,gCC/FZE,UACDC,SAAC,mBAUGD,SACPA,EAAAE,WAEG,kBAAJX,+BAIAC,GAAI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,KACAC,GAAW,EACLC,GAAA,CAjBZ,KAAAC,EAAA,OCFeC,EAObC,SAAOvB,EAAuB,SAACwB,GAChC,GAAAlF,GAAAsC,EAAAtC,ojCbiFDmF,IACQnE,QAAO,SAAAsB,GAEb,MAAAA,GAAAtB,QAAAsB,EAAAtB,QAIEsB,EAAAtB,QAAAjc,EAAAmc,YAAKoB,EAAmBtC,MAG1Bzb,QAAA,SAAC+d,GAED8C,GAFC9C,EAAA+C,cAAA,EAEDD,EAAAA,IAAAA,SACAE,MAAAA,GAAAA,QAEoB5C,EAAAJ,EAAAtC,IAAAe,IAAAuB,EAAA/d,qDYtGtB,MAAA+d,GAAAhe,OAkDIge,EAAAhe,OAIege,EAAAhe,QACVyc,GAASuB,EAAGtC,IAAOe,GACzBwE,IAAAjD,EAAAtC,IAAA+B,sBArDD,MAAA3B,QAAA9O,EAAAA,OAAAgR,EAAAtC,IAAAe,SAECxc,QAAA+d,EAAA/d,UAAA+d,EAAA/d","file":"vendor-bundle.js","sourceRoot":"..","sourcesContent":["import { DOM, PLATFORM } from 'aurelia-pal';\nimport { BrowserHistory } from './browser-history';\nimport { AnchorEventInfo } from './interfaces';\n\n/**\n * Class responsible for handling interactions that should trigger browser history navigations.\n */\nexport class LinkHandler {\n /**\n * Activate the instance.\n *\n * @param history The BrowserHistory instance that navigations should be dispatched to.\n */\n activate(history: BrowserHistory): void {/**/}\n\n /**\n * Deactivate the instance. Event handlers and other resources should be cleaned up here.\n */\n deactivate(): void {/**/}\n}\n\n/**\n * The default LinkHandler implementation. Navigations are triggered by click events on\n * anchor elements with relative hrefs when the history instance is using pushstate.\n */\nexport class DefaultLinkHandler extends LinkHandler {\n\n /**@internal */\n handler: (e: Event) => void;\n\n /**@internal */\n history: BrowserHistory;\n /**\n * Creates an instance of DefaultLinkHandler.\n */\n constructor() {\n super();\n\n this.handler = (e) => {\n let { shouldHandleEvent, href } = DefaultLinkHandler.getEventInfo(e);\n\n if (shouldHandleEvent) {\n e.preventDefault();\n this.history.navigate(href);\n }\n };\n }\n\n /**\n * Activate the instance.\n *\n * @param history The BrowserHistory instance that navigations should be dispatched to.\n */\n activate(history: BrowserHistory): void {\n if (history._hasPushState) {\n this.history = history;\n DOM.addEventListener('click', this.handler, true);\n }\n }\n\n /**\n * Deactivate the instance. Event handlers and other resources should be cleaned up here.\n */\n deactivate(): void {\n DOM.removeEventListener('click', this.handler, true);\n }\n\n /**\n * Gets the href and a \"should handle\" recommendation, given an Event.\n *\n * @param event The Event to inspect for target anchor and href.\n */\n static getEventInfo(event: Event): AnchorEventInfo {\n let $event = event as MouseEvent;\n let info = {\n shouldHandleEvent: false,\n href: null,\n anchor: null\n };\n\n let target = DefaultLinkHandler.findClosestAnchor($event.target as Element);\n if (!target || !DefaultLinkHandler.targetIsThisWindow(target)) {\n return info;\n }\n\n if (hasAttribute(target, 'download')\n || hasAttribute(target, 'router-ignore')\n || hasAttribute(target, 'data-router-ignore')\n ) {\n return info;\n }\n\n if ($event.altKey || $event.ctrlKey || $event.metaKey || $event.shiftKey) {\n return info;\n }\n\n let href = target.getAttribute('href');\n info.anchor = target;\n info.href = href;\n\n let leftButtonClicked = $event.which === 1;\n let isRelative = href && !(href.charAt(0) === '#' || (/^[a-z]+:/i).test(href));\n\n info.shouldHandleEvent = leftButtonClicked && isRelative;\n return info;\n }\n\n /**\n * Finds the closest ancestor that's an anchor element.\n *\n * @param el The element to search upward from.\n * @returns The link element that is the closest ancestor.\n */\n static findClosestAnchor(el: Element): Element {\n while (el) {\n if (el.tagName === 'A') {\n return el;\n }\n\n el = el.parentNode as Element;\n }\n }\n\n /**\n * Gets a value indicating whether or not an anchor targets the current window.\n *\n * @param target The anchor element whose target should be inspected.\n * @returns True if the target of the link element is this window; false otherwise.\n */\n static targetIsThisWindow(target: Element): boolean {\n let targetWindow = target.getAttribute('target');\n let win = PLATFORM.global;\n\n return !targetWindow ||\n targetWindow === win.name ||\n targetWindow === '_self';\n }\n}\n\nconst hasAttribute = (el: Element, attr: string) => el.hasAttribute(attr);\n","import { DOM, PLATFORM } from 'aurelia-pal';\nimport { LinkHandler } from './link-handler';\nimport { History } from 'aurelia-history';\n\n/**\n * An implementation of the basic history API.\n */\nexport class BrowserHistory extends History {\n /**@internal */\n static inject = [LinkHandler];\n\n /**@internal */\n _isActive: boolean;\n\n /**@internal*/\n _checkUrlCallback: any;\n /**@internal*/\n location: Location;\n /**@internal*/\n history: typeof PLATFORM['history'];\n /**@internal*/\n linkHandler: LinkHandler;\n /**@internal*/\n options: any;\n /**@internal*/\n root: string;\n /**@internal*/\n _wantsHashChange: boolean;\n /**@internal*/\n _hasPushState: boolean;\n /**@internal*/\n fragment: string;\n\n /**\n * Creates an instance of BrowserHistory\n * @param linkHandler An instance of LinkHandler.\n */\n constructor(linkHandler: LinkHandler) {\n super();\n\n this._isActive = false;\n this._checkUrlCallback = this._checkUrl.bind(this);\n\n this.location = PLATFORM.location;\n this.history = PLATFORM.history;\n this.linkHandler = linkHandler;\n }\n\n /**\n * Activates the history object.\n * @param options The set of options to activate history with.\n * @returns Whether or not activation occurred.\n */\n activate(options?: Object): boolean {\n if (this._isActive) {\n throw new Error('History has already been activated.');\n }\n\n let $history = this.history;\n let wantsPushState = !!(options as any).pushState;\n\n this._isActive = true;\n let normalizedOptions = this.options = Object.assign({}, { root: '/' }, this.options, options);\n\n // Normalize root to always include a leading and trailing slash.\n let rootUrl = this.root = ('/' + normalizedOptions.root + '/').replace(rootStripper, '/');\n\n let wantsHashChange = this._wantsHashChange = normalizedOptions.hashChange !== false;\n let hasPushState = this._hasPushState = !!(normalizedOptions.pushState && $history && $history.pushState);\n\n // Determine how we check the URL state.\n let eventName: string;\n if (hasPushState) {\n eventName = 'popstate';\n } else if (wantsHashChange) {\n eventName = 'hashchange';\n }\n\n PLATFORM.addEventListener(eventName, this._checkUrlCallback);\n\n // Determine if we need to change the base url, for a pushState link\n // opened by a non-pushState browser.\n if (wantsHashChange && wantsPushState) {\n // Transition from hashChange to pushState or vice versa if both are requested.\n let $location = this.location;\n let atRoot = $location.pathname.replace(/[^\\/]$/, '$&/') === rootUrl;\n\n // If we've started off with a route from a `pushState`-enabled\n // browser, but we're currently in a browser that doesn't support it...\n if (!hasPushState && !atRoot) {\n let fragment = this.fragment = this._getFragment(null, true);\n $location.replace(rootUrl + $location.search + '#' + fragment);\n // Return immediately as browser will do redirect to new url\n return true;\n\n // Or if we've started out with a hash-based route, but we're currently\n // in a browser where it could be `pushState`-based instead...\n } else if (hasPushState && atRoot && $location.hash) {\n let fragment = this.fragment = this._getHash().replace(routeStripper, '');\n $history.replaceState({}, DOM.title, rootUrl + fragment + $location.search);\n }\n }\n\n if (!this.fragment) {\n this.fragment = this._getFragment('');\n }\n\n this.linkHandler.activate(this);\n\n if (!normalizedOptions.silent) {\n return this._loadUrl('');\n }\n }\n\n /**\n * Deactivates the history object.\n */\n deactivate(): void {\n const handler = this._checkUrlCallback;\n PLATFORM.removeEventListener('popstate', handler);\n PLATFORM.removeEventListener('hashchange', handler);\n this._isActive = false;\n this.linkHandler.deactivate();\n }\n\n /**\n * Returns the fully-qualified root of the current history object.\n * @returns The absolute root of the application.\n */\n getAbsoluteRoot(): string {\n let $location = this.location;\n let origin = createOrigin($location.protocol, $location.hostname, $location.port);\n return `${origin}${this.root}`;\n }\n\n /**\n * Causes a history navigation to occur.\n *\n * @param fragment The history fragment to navigate to.\n * @param options The set of options that specify how the navigation should occur.\n * @return Promise if triggering navigation, otherwise true/false indicating if navigation occurred.\n */\n navigate(fragment?: string, {trigger = true, replace = false} = {}): boolean {\n let location = this.location;\n if (fragment && absoluteUrl.test(fragment)) {\n location.href = fragment;\n return true;\n }\n\n if (!this._isActive) {\n return false;\n }\n\n fragment = this._getFragment(fragment || '');\n\n if (this.fragment === fragment && !replace) {\n return false;\n }\n\n this.fragment = fragment;\n\n let url = this.root + fragment;\n\n // Don't include a trailing slash on the root.\n if (fragment === '' && url !== '/') {\n url = url.slice(0, -1);\n }\n\n // If pushState is available, we use it to set the fragment as a real URL.\n if (this._hasPushState) {\n url = url.replace('//', '/');\n this.history[replace ? 'replaceState' : 'pushState']({}, DOM.title, url);\n } else if (this._wantsHashChange) {\n // If hash changes haven't been explicitly disabled, update the hash\n // fragment to store history.\n updateHash(location, fragment, replace);\n } else {\n // If you've told us that you explicitly don't want fallback hashchange-\n // based history, then `navigate` becomes a page refresh.\n location.assign(url);\n }\n\n if (trigger) {\n return this._loadUrl(fragment);\n }\n\n return true;\n }\n\n /**\n * Causes the history state to navigate back.\n */\n navigateBack(): void {\n this.history.back();\n }\n\n /**\n * Sets the document title.\n */\n setTitle(title: string): void {\n DOM.title = title;\n }\n\n /**\n * Sets a key in the history page state.\n * @param key The key for the value.\n * @param value The value to set.\n */\n setState(key: string, value: any): void {\n let $history = this.history;\n let state = Object.assign({}, $history.state);\n let { pathname, search, hash } = this.location;\n state[key] = value;\n $history.replaceState(state, null, `${pathname}${search}${hash}`);\n }\n\n /**\n * Gets a key in the history page state.\n * @param key The key for the value.\n * @return The value for the key.\n */\n getState(key: string): any {\n let state = Object.assign({}, this.history.state);\n return state[key];\n }\n\n /**\n * Returns the current index in the navigation history.\n * @returns The current index.\n */\n getHistoryIndex(): number {\n let historyIndex = this.getState('HistoryIndex');\n if (historyIndex === undefined) {\n historyIndex = this.history.length - 1;\n this.setState('HistoryIndex', historyIndex);\n }\n return historyIndex;\n }\n\n /**\n * Move to a specific position in the navigation history.\n * @param movement The amount of steps, positive or negative, to move.\n */\n go(movement: number): void {\n this.history.go(movement);\n }\n\n /**\n * @internal\n */\n _getHash(): string {\n return this.location.hash.substr(1);\n }\n\n /**\n * @internal\n */\n _getFragment(fragment: string, forcePushState?: boolean): string {\n let rootUrl: string;\n\n if (!fragment) {\n if (this._hasPushState || !this._wantsHashChange || forcePushState) {\n let location = this.location;\n fragment = location.pathname + location.search;\n rootUrl = this.root.replace(trailingSlash, '');\n if (!fragment.indexOf(rootUrl)) {\n fragment = fragment.substr(rootUrl.length);\n }\n } else {\n fragment = this._getHash();\n }\n }\n\n return '/' + fragment.replace(routeStripper, '');\n }\n\n /**\n * Url change handler.\n * Invoked when current fragment is different with previous fragment\n * @internal\n */\n _checkUrl(): void {\n let current = this._getFragment('');\n if (current !== this.fragment) {\n this._loadUrl('');\n }\n }\n\n /**\n * invoke routeHandler\n * @internal\n */\n _loadUrl(fragmentOverride: string): boolean {\n let fragment = this.fragment = this._getFragment(fragmentOverride);\n\n return this.options.routeHandler ?\n this.options.routeHandler(fragment) :\n false;\n }\n}\n\n// Cached regex for stripping a leading hash/slash and trailing space.\nconst routeStripper = /^#?\\/*|\\s+$/g;\n\n// Cached regex for stripping leading and trailing slashes.\nconst rootStripper = /^\\/+|\\/+$/g;\n\n// Cached regex for removing a trailing slash.\nconst trailingSlash = /\\/$/;\n\n// Cached regex for detecting if a URL is absolute,\n// i.e., starts with a scheme or is scheme-relative.\n// See http://www.ietf.org/rfc/rfc2396.txt section 3.1 for valid scheme format\nconst absoluteUrl = /^([a-z][a-z0-9+\\-.]*:)?\\/\\//i;\n\n// Update the hash location, either replacing the current entry, or adding\n// a new one to the browser history.\nfunction updateHash($location: Location, fragment: string, replace: boolean) {\n if (replace) {\n let href = $location.href.replace(/(javascript:|#).*$/, '');\n $location.replace(href + '#' + fragment);\n } else {\n // Some browsers require that `hash` contains a leading #.\n $location.hash = '#' + fragment;\n }\n}\n\nfunction createOrigin(protocol: string, hostname: string, port: string) {\n return `${protocol}//${hostname}${port ? ':' + port : ''}`;\n}\n","import {History} from 'aurelia-history';\nimport {LinkHandler, DefaultLinkHandler} from './link-handler';\nimport { BrowserHistory } from './browser-history';\n\n/**\n * Configures the plugin by registering BrowserHistory as the implementation of History in the DI container.\n * @param config The FrameworkConfiguration object provided by Aurelia.\n */\nexport function configure(config: Object): void {\n // work around for converting to TS without breaking compat\n const $config = config as any;\n $config.singleton(History, BrowserHistory);\n $config.transient(LinkHandler, DefaultLinkHandler);\n}\n\nexport {\n LinkHandler,\n DefaultLinkHandler,\n BrowserHistory\n};\n","import { ViewPortInstruction, RouteConfig, ViewPort, LifecycleArguments, ViewPortComponent } from './interfaces';\nimport { Router } from './router';\nimport { ActivationStrategyType, InternalActivationStrategy } from './activation-strategy';\n\n/**\n * Initialization options for a navigation instruction\n */\nexport interface NavigationInstructionInit {\n fragment: string;\n queryString?: string;\n params?: Record;\n queryParams?: Record;\n config: RouteConfig;\n parentInstruction?: NavigationInstruction;\n previousInstruction?: NavigationInstruction;\n router: Router;\n options?: Object;\n plan?: Record;\n}\n\nexport interface ViewPortInstructionInit {\n name: string;\n strategy: ActivationStrategyType;\n moduleId: string;\n component: ViewPortComponent;\n}\n\n/**\n * Class used to represent an instruction during a navigation.\n */\nexport class NavigationInstruction {\n /**\n * The URL fragment.\n */\n fragment: string;\n\n /**\n * The query string.\n */\n queryString: string;\n\n /**\n * Parameters extracted from the route pattern.\n */\n params: any;\n\n /**\n * Parameters extracted from the query string.\n */\n queryParams: any;\n\n /**\n * The route config for the route matching this instruction.\n */\n config: RouteConfig;\n\n /**\n * The parent instruction, if this instruction was created by a child router.\n */\n parentInstruction: NavigationInstruction;\n\n parentCatchHandler: any;\n\n /**\n * The instruction being replaced by this instruction in the current router.\n */\n previousInstruction: NavigationInstruction;\n\n /**\n * viewPort instructions to used activation.\n */\n viewPortInstructions: Record;\n\n /**\n * The router instance.\n */\n router: Router;\n\n /**\n * Current built viewport plan of this nav instruction\n */\n plan: Record = null;\n\n options: Record = {};\n\n /**@internal */\n lifecycleArgs: LifecycleArguments;\n /**@internal */\n resolve?: (val?: any) => void;\n\n constructor(init: NavigationInstructionInit) {\n Object.assign(this, init);\n\n this.params = this.params || {};\n this.viewPortInstructions = {};\n\n let ancestorParams = [];\n let current: NavigationInstruction = this;\n do {\n let currentParams = Object.assign({}, current.params);\n if (current.config && current.config.hasChildRouter) {\n // remove the param for the injected child route segment\n delete currentParams[current.getWildCardName()];\n }\n\n ancestorParams.unshift(currentParams);\n current = current.parentInstruction;\n } while (current);\n\n let allParams = Object.assign({}, this.queryParams, ...ancestorParams);\n this.lifecycleArgs = [allParams, this.config, this];\n }\n\n /**\n * Gets an array containing this instruction and all child instructions for the current navigation.\n */\n getAllInstructions(): Array {\n let instructions: NavigationInstruction[] = [this];\n let viewPortInstructions: Record = this.viewPortInstructions;\n\n for (let key in viewPortInstructions) {\n let childInstruction = viewPortInstructions[key].childNavigationInstruction;\n if (childInstruction) {\n instructions.push(...childInstruction.getAllInstructions());\n }\n }\n\n return instructions;\n }\n\n /**\n * Gets an array containing the instruction and all child instructions for the previous navigation.\n * Previous instructions are no longer available after navigation completes.\n */\n getAllPreviousInstructions(): Array {\n return this.getAllInstructions().map(c => c.previousInstruction).filter(c => c);\n }\n\n /**\n * Adds a viewPort instruction. Returns the newly created instruction based on parameters\n */\n addViewPortInstruction(initOptions: ViewPortInstructionInit): /*ViewPortInstruction*/ any;\n addViewPortInstruction(viewPortName: string, strategy: ActivationStrategyType, moduleId: string, component: any): /*ViewPortInstruction*/ any;\n addViewPortInstruction(\n nameOrInitOptions: string | ViewPortInstructionInit,\n strategy?: ActivationStrategyType,\n moduleId?: string,\n component?: any\n ): /*ViewPortInstruction*/ any {\n\n let viewPortInstruction: ViewPortInstruction;\n let viewPortName = typeof nameOrInitOptions === 'string' ? nameOrInitOptions : nameOrInitOptions.name;\n const lifecycleArgs = this.lifecycleArgs;\n const config: RouteConfig = Object.assign({}, lifecycleArgs[1], { currentViewPort: viewPortName });\n\n if (typeof nameOrInitOptions === 'string') {\n viewPortInstruction = {\n name: nameOrInitOptions,\n strategy: strategy,\n moduleId: moduleId,\n component: component,\n childRouter: component.childRouter,\n lifecycleArgs: [lifecycleArgs[0], config, lifecycleArgs[2]] as LifecycleArguments\n };\n } else {\n viewPortInstruction = {\n name: viewPortName,\n strategy: nameOrInitOptions.strategy,\n component: nameOrInitOptions.component,\n moduleId: nameOrInitOptions.moduleId,\n childRouter: nameOrInitOptions.component.childRouter,\n lifecycleArgs: [lifecycleArgs[0], config, lifecycleArgs[2]] as LifecycleArguments\n };\n }\n\n return this.viewPortInstructions[viewPortName] = viewPortInstruction;\n }\n\n /**\n * Gets the name of the route pattern's wildcard parameter, if applicable.\n */\n getWildCardName(): string {\n // todo: potential issue, or at least unsafe typings\n let configRoute = this.config.route as string;\n let wildcardIndex = configRoute.lastIndexOf('*');\n return configRoute.substr(wildcardIndex + 1);\n }\n\n /**\n * Gets the path and query string created by filling the route\n * pattern's wildcard parameter with the matching param.\n */\n getWildcardPath(): string {\n let wildcardName = this.getWildCardName();\n let path = this.params[wildcardName] || '';\n let queryString = this.queryString;\n\n if (queryString) {\n path += '?' + queryString;\n }\n\n return path;\n }\n\n /**\n * Gets the instruction's base URL, accounting for wildcard route parameters.\n */\n getBaseUrl(): string {\n let $encodeURI = encodeURI;\n let fragment = decodeURI(this.fragment);\n\n if (fragment === '') {\n let nonEmptyRoute = this.router.routes.find(route => {\n return route.name === this.config.name &&\n route.route !== '';\n });\n if (nonEmptyRoute) {\n fragment = nonEmptyRoute.route as any;\n }\n }\n\n if (!this.params) {\n return $encodeURI(fragment);\n }\n\n let wildcardName = this.getWildCardName();\n let path = this.params[wildcardName] || '';\n\n if (!path) {\n return $encodeURI(fragment);\n }\n\n return $encodeURI(fragment.substr(0, fragment.lastIndexOf(path)));\n }\n\n /**\n * Finalize a viewport instruction\n * @internal\n */\n _commitChanges(waitToSwap: boolean): Promise {\n let router = this.router;\n router.currentInstruction = this;\n\n const previousInstruction = this.previousInstruction;\n if (previousInstruction) {\n previousInstruction.config.navModel.isActive = false;\n }\n\n this.config.navModel.isActive = true;\n\n router.refreshNavigation();\n\n let loads: Promise[] = [];\n let delaySwaps: ISwapPlan[] = [];\n let viewPortInstructions: Record = this.viewPortInstructions;\n\n for (let viewPortName in viewPortInstructions) {\n let viewPortInstruction = viewPortInstructions[viewPortName];\n let viewPort = router.viewPorts[viewPortName];\n\n if (!viewPort) {\n throw new Error(`There was no router-view found in the view for ${viewPortInstruction.moduleId}.`);\n }\n\n let childNavInstruction = viewPortInstruction.childNavigationInstruction;\n if (viewPortInstruction.strategy === InternalActivationStrategy.Replace) {\n if (childNavInstruction && childNavInstruction.parentCatchHandler) {\n loads.push(childNavInstruction._commitChanges(waitToSwap));\n } else {\n if (waitToSwap) {\n delaySwaps.push({ viewPort, viewPortInstruction });\n }\n loads.push(\n viewPort\n .process(viewPortInstruction, waitToSwap)\n .then(() => childNavInstruction\n ? childNavInstruction._commitChanges(waitToSwap)\n : Promise.resolve()\n )\n );\n }\n } else {\n if (childNavInstruction) {\n loads.push(childNavInstruction._commitChanges(waitToSwap));\n }\n }\n }\n\n return Promise\n .all(loads)\n .then(() => {\n delaySwaps.forEach(x => x.viewPort.swap(x.viewPortInstruction));\n return null;\n })\n .then(() => prune(this));\n }\n\n /**@internal */\n _updateTitle(): void {\n let router = this.router;\n let title = this._buildTitle(router.titleSeparator);\n if (title) {\n router.history.setTitle(title);\n }\n }\n\n /**@internal */\n _buildTitle(separator: string = ' | '): string {\n let title = '';\n let childTitles = [];\n let navModelTitle = this.config.navModel.title;\n let instructionRouter = this.router;\n let viewPortInstructions: Record = this.viewPortInstructions;\n\n if (navModelTitle) {\n title = instructionRouter.transformTitle(navModelTitle);\n }\n\n for (let viewPortName in viewPortInstructions) {\n let viewPortInstruction = viewPortInstructions[viewPortName];\n let child_nav_instruction = viewPortInstruction.childNavigationInstruction;\n\n if (child_nav_instruction) {\n let childTitle = child_nav_instruction._buildTitle(separator);\n if (childTitle) {\n childTitles.push(childTitle);\n }\n }\n }\n\n if (childTitles.length) {\n title = childTitles.join(separator) + (title ? separator : '') + title;\n }\n\n if (instructionRouter.title) {\n title += (title ? separator : '') + instructionRouter.transformTitle(instructionRouter.title);\n }\n\n return title;\n }\n}\n\nconst prune = (instruction: NavigationInstruction): void => {\n instruction.previousInstruction = null;\n instruction.plan = null;\n};\n\ninterface ISwapPlan {\n viewPort: ViewPort;\n viewPortInstruction: ViewPortInstruction;\n}\n","import { RouteConfig, PipelineStep, RouteConfigSpecifier } from './interfaces';\nimport { _ensureArrayWithSingleRoutePerConfig } from './util';\nimport { Router } from './router';\nimport { NavigationInstruction } from './navigation-instruction';\nimport { PipelineSlotName } from './pipeline-slot-name';\n\n/**\n * Class used to configure a [[Router]] instance.\n *\n * @constructor\n */\nexport class RouterConfiguration {\n instructions: Array<(router: Router) => void> = [];\n options: {\n [key: string]: any;\n compareQueryParams?: boolean;\n root?: string;\n pushState?: boolean;\n hashChange?: boolean;\n silent?: boolean;\n } = {};\n pipelineSteps: Array<{ name: string, step: Function | PipelineStep }> = [];\n title: string;\n titleSeparator: string;\n unknownRouteConfig: RouteConfigSpecifier;\n viewPortDefaults: Record;\n\n /**@internal */\n _fallbackRoute: string;\n\n /**\n * Adds a step to be run during the [[Router]]'s navigation pipeline.\n *\n * @param name The name of the pipeline slot to insert the step into.\n * @param step The pipeline step.\n * @chainable\n */\n addPipelineStep(name: string, step: Function | PipelineStep): RouterConfiguration {\n if (step === null || step === undefined) {\n throw new Error('Pipeline step cannot be null or undefined.');\n }\n this.pipelineSteps.push({ name, step });\n return this;\n }\n\n /**\n * Adds a step to be run during the [[Router]]'s authorize pipeline slot.\n *\n * @param step The pipeline step.\n * @chainable\n */\n addAuthorizeStep(step: Function | PipelineStep): RouterConfiguration {\n return this.addPipelineStep(PipelineSlotName.Authorize, step);\n }\n\n /**\n * Adds a step to be run during the [[Router]]'s preActivate pipeline slot.\n *\n * @param step The pipeline step.\n * @chainable\n */\n addPreActivateStep(step: Function | PipelineStep): RouterConfiguration {\n return this.addPipelineStep(PipelineSlotName.PreActivate, step);\n }\n\n /**\n * Adds a step to be run during the [[Router]]'s preRender pipeline slot.\n *\n * @param step The pipeline step.\n * @chainable\n */\n addPreRenderStep(step: Function | PipelineStep): RouterConfiguration {\n return this.addPipelineStep(PipelineSlotName.PreRender, step);\n }\n\n /**\n * Adds a step to be run during the [[Router]]'s postRender pipeline slot.\n *\n * @param step The pipeline step.\n * @chainable\n */\n addPostRenderStep(step: Function | PipelineStep): RouterConfiguration {\n return this.addPipelineStep(PipelineSlotName.PostRender, step);\n }\n\n /**\n * Configures a route that will be used if there is no previous location available on navigation cancellation.\n *\n * @param fragment The URL fragment to use as the navigation destination.\n * @chainable\n */\n fallbackRoute(fragment: string): RouterConfiguration {\n this._fallbackRoute = fragment;\n return this;\n }\n\n /**\n * Maps one or more routes to be registered with the router.\n *\n * @param route The [[RouteConfig]] to map, or an array of [[RouteConfig]] to map.\n * @chainable\n */\n map(route: RouteConfig | RouteConfig[]): RouterConfiguration {\n if (Array.isArray(route)) {\n route.forEach(r => this.map(r));\n return this;\n }\n\n return this.mapRoute(route);\n }\n\n /**\n * Configures defaults to use for any view ports.\n *\n * @param viewPortConfig a view port configuration object to use as a\n * default, of the form { viewPortName: { moduleId } }.\n * @chainable\n */\n useViewPortDefaults(viewPortConfig: Record): RouterConfiguration {\n this.viewPortDefaults = viewPortConfig;\n return this;\n }\n\n /**\n * Maps a single route to be registered with the router.\n *\n * @param route The [[RouteConfig]] to map.\n * @chainable\n */\n mapRoute(config: RouteConfig): RouterConfiguration {\n this.instructions.push(router => {\n let routeConfigs = _ensureArrayWithSingleRoutePerConfig(config);\n\n let navModel;\n for (let i = 0, ii = routeConfigs.length; i < ii; ++i) {\n let routeConfig = routeConfigs[i];\n routeConfig.settings = routeConfig.settings || {};\n if (!navModel) {\n navModel = router.createNavModel(routeConfig);\n }\n\n router.addRoute(routeConfig, navModel);\n }\n });\n\n return this;\n }\n\n /**\n * Registers an unknown route handler to be run when the URL fragment doesn't match any registered routes.\n *\n * @param config A string containing a moduleId to load, or a [[RouteConfig]], or a function that takes the\n * [[NavigationInstruction]] and selects a moduleId to load.\n * @chainable\n */\n mapUnknownRoutes(config: RouteConfigSpecifier): RouterConfiguration {\n this.unknownRouteConfig = config;\n return this;\n }\n\n /**\n * Applies the current configuration to the specified [[Router]].\n *\n * @param router The [[Router]] to apply the configuration to.\n */\n exportToRouter(router: Router): void {\n let instructions = this.instructions;\n for (let i = 0, ii = instructions.length; i < ii; ++i) {\n instructions[i](router);\n }\n\n let { title, titleSeparator, unknownRouteConfig, _fallbackRoute, viewPortDefaults } = this;\n\n if (title) {\n router.title = title;\n }\n\n if (titleSeparator) {\n router.titleSeparator = titleSeparator;\n }\n\n if (unknownRouteConfig) {\n router.handleUnknownRoutes(unknownRouteConfig);\n }\n\n if (_fallbackRoute) {\n router.fallbackRoute = _fallbackRoute;\n }\n\n if (viewPortDefaults) {\n router.useViewPortDefaults(viewPortDefaults);\n }\n\n Object.assign(router.options, this.options);\n\n let pipelineSteps = this.pipelineSteps;\n let pipelineStepCount = pipelineSteps.length;\n if (pipelineStepCount) {\n if (!router.isRoot) {\n throw new Error('Pipeline steps can only be added to the root router');\n }\n\n let pipelineProvider = router.pipelineProvider;\n for (let i = 0, ii = pipelineStepCount; i < ii; ++i) {\n let { name, step } = pipelineSteps[i];\n pipelineProvider.addStep(name, step);\n }\n }\n }\n}\n","import { RouteRecognizer, RouteHandler, ConfigurableRoute, State, RecognizedRoute } from 'aurelia-route-recognizer';\nimport { Container } from 'aurelia-dependency-injection';\nimport { History, NavigationOptions } from 'aurelia-history';\nimport { NavigationInstruction, NavigationInstructionInit } from './navigation-instruction';\nimport { NavModel } from './nav-model';\nimport { RouterConfiguration } from './router-configuration';\nimport {\n _ensureArrayWithSingleRoutePerConfig,\n _normalizeAbsolutePath,\n _createRootedPath,\n _resolveUrl\n} from './util';\nimport { RouteConfig, RouteConfigSpecifier, ViewPortInstruction } from './interfaces';\nimport { PipelineProvider } from './pipeline-provider';\n\n/**@internal */\ndeclare module 'aurelia-history' {\n interface History {\n // This is wrong, as it's an implementation detail from aurelia-history-browser\n // but we are poking it in here so probably will need to make it official in `aurelia-history`\n /**\n * A private flag of Aurelia History implementation to indicate if push state should be used\n */\n _hasPushState: boolean;\n\n previousLocation: string;\n }\n}\n\n/**@internal */\ndeclare module 'aurelia-route-recognizer' {\n interface State {\n types: {\n dynamics: DynamicSegment;\n stars: StarSegment;\n };\n }\n\n interface RouteHandler {\n navigationStrategy?: (instruction: NavigationInstruction) => any;\n }\n\n interface RecognizedRoute {\n config?: RouteConfig;\n queryParams?: Record;\n }\n}\n\ntype RouterConfigurationResolution = RouterConfiguration | ((cfg: RouterConfiguration) => void | RouterConfiguration | Promise);\n\n/**\n * The primary class responsible for handling routing and navigation.\n */\nexport class Router {\n\n /**\n * Container associated with this router. Also used to create child container for creating child router.\n */\n container: Container;\n\n /**\n * History instance of Aurelia abstract class for wrapping platform history global object\n */\n history: History;\n\n /**\n * A registry of registered viewport. Will be used to handle process navigation instruction route loading\n * and dom swapping\n */\n viewPorts: Record;\n\n /**\n * List of route configs registered with this router\n */\n routes: RouteConfig[];\n\n /**\n * The [[Router]]'s current base URL, typically based on the [[Router.currentInstruction]].\n */\n baseUrl: string;\n\n /**\n * If defined, used in generation of document title for [[Router]]'s routes.\n */\n title: string | undefined;\n\n /**\n * The separator used in the document title between [[Router]]'s routes.\n */\n titleSeparator: string | undefined;\n\n /**\n * True if the [[Router]] has been configured.\n */\n isConfigured: boolean;\n\n /**\n * True if the [[Router]] is currently processing a navigation.\n */\n isNavigating: boolean;\n\n /**\n * True if the [[Router]] is navigating due to explicit call to navigate function(s).\n */\n isExplicitNavigation: boolean;\n\n /**\n * True if the [[Router]] is navigating due to explicit call to navigateBack function.\n */\n isExplicitNavigationBack: boolean;\n\n /**\n * True if the [[Router]] is navigating into the app for the first time in the browser session.\n */\n isNavigatingFirst: boolean;\n\n /**\n * True if the [[Router]] is navigating to a page instance not in the browser session history.\n */\n isNavigatingNew: boolean;\n\n /**\n * True if the [[Router]] is navigating forward in the browser session history.\n */\n isNavigatingForward: boolean;\n\n /**\n * True if the [[Router]] is navigating back in the browser session history.\n */\n isNavigatingBack: boolean;\n\n /**\n * True if the [[Router]] is navigating due to a browser refresh.\n */\n isNavigatingRefresh: boolean;\n\n /**\n * True if the previous instruction successfully completed the CanDeactivatePreviousStep in the current navigation.\n */\n couldDeactivate: boolean;\n\n /**\n * The currently active navigation tracker.\n */\n currentNavigationTracker: number;\n\n /**\n * The navigation models for routes that specified [[RouteConfig.nav]].\n */\n navigation: NavModel[];\n\n /**\n * The currently active navigation instruction.\n */\n currentInstruction: NavigationInstruction;\n\n /**\n * The parent router, or null if this instance is not a child router.\n */\n parent: Router = null;\n\n options: any = {};\n\n /**\n * The defaults used when a viewport lacks specified content\n */\n viewPortDefaults: Record = {};\n\n /**@internal */\n catchAllHandler: (instruction: NavigationInstruction) => NavigationInstruction | Promise;\n /**@internal */\n fallbackRoute: string;\n /**@internal */\n pipelineProvider: PipelineProvider;\n /**@internal */\n _fallbackOrder: number;\n /**@internal */\n _recognizer: RouteRecognizer;\n /**@internal */\n _childRecognizer: RouteRecognizer;\n /**@internal */\n _configuredPromise: Promise;\n /**@internal */\n _resolveConfiguredPromise: (value?: any) => void;\n\n /**\n * Extension point to transform the document title before it is built and displayed.\n * By default, child routers delegate to the parent router, and the app router\n * returns the title unchanged.\n */\n transformTitle: (title: string) => string = (title: string) => {\n if (this.parent) {\n return this.parent.transformTitle(title);\n }\n return title;\n }\n\n /**\n * @param container The [[Container]] to use when child routers.\n * @param history The [[History]] implementation to delegate navigation requests to.\n */\n constructor(container: Container, history: History) {\n this.container = container;\n this.history = history;\n this.reset();\n }\n\n /**\n * Fully resets the router's internal state. Primarily used internally by the framework when multiple calls to setRoot are made.\n * Use with caution (actually, avoid using this). Do not use this to simply change your navigation model.\n */\n reset() {\n this.viewPorts = {};\n this.routes = [];\n this.baseUrl = '';\n this.isConfigured = false;\n this.isNavigating = false;\n this.isExplicitNavigation = false;\n this.isExplicitNavigationBack = false;\n this.isNavigatingFirst = false;\n this.isNavigatingNew = false;\n this.isNavigatingRefresh = false;\n this.isNavigatingForward = false;\n this.isNavigatingBack = false;\n this.couldDeactivate = false;\n this.navigation = [];\n this.currentInstruction = null;\n this.viewPortDefaults = {};\n this._fallbackOrder = 100;\n this._recognizer = new RouteRecognizer();\n this._childRecognizer = new RouteRecognizer();\n this._configuredPromise = new Promise(resolve => {\n this._resolveConfiguredPromise = resolve;\n });\n }\n\n /**\n * Gets a value indicating whether or not this [[Router]] is the root in the router tree. I.e., it has no parent.\n */\n get isRoot(): boolean {\n return !this.parent;\n }\n\n /**\n * Registers a viewPort to be used as a rendering target for activated routes.\n *\n * @param viewPort The viewPort.\n * @param name The name of the viewPort. 'default' if unspecified.\n */\n registerViewPort(viewPort: /*ViewPort*/any, name?: string): void {\n name = name || 'default';\n this.viewPorts[name] = viewPort;\n }\n\n /**\n * Returns a Promise that resolves when the router is configured.\n */\n ensureConfigured(): Promise {\n return this._configuredPromise;\n }\n\n /**\n * Configures the router.\n *\n * @param callbackOrConfig The [[RouterConfiguration]] or a callback that takes a [[RouterConfiguration]].\n */\n configure(callbackOrConfig: RouterConfiguration | ((config: RouterConfiguration) => RouterConfiguration)): Promise {\n this.isConfigured = true;\n\n let result: RouterConfigurationResolution = callbackOrConfig as RouterConfiguration;\n let config: RouterConfiguration;\n if (typeof callbackOrConfig === 'function') {\n config = new RouterConfiguration();\n result = callbackOrConfig(config);\n }\n\n return Promise\n .resolve(result)\n .then((c) => {\n if (c && (c as RouterConfiguration).exportToRouter) {\n config = c;\n }\n\n config.exportToRouter(this);\n this.isConfigured = true;\n this._resolveConfiguredPromise();\n });\n }\n\n /**\n * Navigates to a new location.\n *\n * @param fragment The URL fragment to use as the navigation destination.\n * @param options The navigation options.\n */\n navigate(fragment: string, options?: NavigationOptions): boolean {\n if (!this.isConfigured && this.parent) {\n return this.parent.navigate(fragment, options);\n }\n\n this.isExplicitNavigation = true;\n return this.history.navigate(_resolveUrl(fragment, this.baseUrl, this.history._hasPushState), options);\n }\n\n /**\n * Navigates to a new location corresponding to the route and params specified. Equivallent to [[Router.generate]] followed\n * by [[Router.navigate]].\n *\n * @param route The name of the route to use when generating the navigation location.\n * @param params The route parameters to be used when populating the route pattern.\n * @param options The navigation options.\n */\n navigateToRoute(route: string, params?: any, options?: NavigationOptions): boolean {\n let path = this.generate(route, params);\n return this.navigate(path, options);\n }\n\n /**\n * Navigates back to the most recent location in history.\n */\n navigateBack(): void {\n this.isExplicitNavigationBack = true;\n this.history.navigateBack();\n }\n\n /**\n * Creates a child router of the current router.\n *\n * @param container The [[Container]] to provide to the child router. Uses the current [[Router]]'s [[Container]] if unspecified.\n * @returns {Router} The new child Router.\n */\n createChild(container?: Container): Router {\n let childRouter = new Router(container || this.container.createChild(), this.history);\n childRouter.parent = this;\n return childRouter;\n }\n\n /**\n * Generates a URL fragment matching the specified route pattern.\n *\n * @param name The name of the route whose pattern should be used to generate the fragment.\n * @param params The route params to be used to populate the route pattern.\n * @param options If options.absolute = true, then absolute url will be generated; otherwise, it will be relative url.\n * @returns {string} A string containing the generated URL fragment.\n */\n generate(nameOrRoute: string | RouteConfig, params: any = {}, options: any = {}): string {\n // A child recognizer generates routes for potential child routes. Any potential child route is added\n // to the childRoute property of params for the childRouter to recognize. When generating routes, we\n // use the childRecognizer when childRoute params are available to generate a child router enabled route.\n let recognizer = 'childRoute' in params ? this._childRecognizer : this._recognizer;\n let hasRoute = recognizer.hasRoute(nameOrRoute as string | RouteHandler);\n if (!hasRoute) {\n if (this.parent) {\n return this.parent.generate(nameOrRoute, params, options);\n }\n throw new Error(`A route with name '${nameOrRoute}' could not be found. Check that \\`name: '${nameOrRoute}'\\` was specified in the route's config.`);\n }\n let path = recognizer.generate(nameOrRoute as string | RouteHandler, params);\n let rootedPath = _createRootedPath(path, this.baseUrl, this.history._hasPushState, options.absolute);\n return options.absolute ? `${this.history.getAbsoluteRoot()}${rootedPath}` : rootedPath;\n }\n\n /**\n * Creates a [[NavModel]] for the specified route config.\n *\n * @param config The route config.\n */\n createNavModel(config: RouteConfig): NavModel {\n let navModel = new NavModel(\n this,\n 'href' in config\n ? config.href\n // potential error when config.route is a string[] ?\n : config.route as string);\n navModel.title = config.title;\n navModel.order = config.nav;\n navModel.href = config.href;\n navModel.settings = config.settings;\n navModel.config = config;\n\n return navModel;\n }\n\n /**\n * Registers a new route with the router.\n *\n * @param config The [[RouteConfig]].\n * @param navModel The [[NavModel]] to use for the route. May be omitted for single-pattern routes.\n */\n addRoute(config: RouteConfig, navModel?: NavModel): void {\n if (Array.isArray(config.route)) {\n let routeConfigs = _ensureArrayWithSingleRoutePerConfig(config);\n // the following is wrong. todo: fix this after TS refactoring release\n routeConfigs.forEach(this.addRoute.bind(this));\n return;\n }\n\n validateRouteConfig(config);\n\n if (!('viewPorts' in config) && !config.navigationStrategy) {\n config.viewPorts = {\n 'default': {\n moduleId: config.moduleId,\n view: config.view\n }\n };\n }\n\n if (!navModel) {\n navModel = this.createNavModel(config);\n }\n\n this.routes.push(config);\n\n let path = config.route;\n if (path.charAt(0) === '/') {\n path = path.substr(1);\n }\n let caseSensitive = config.caseSensitive === true;\n let state: State = this._recognizer.add({\n path: path,\n handler: config as RouteHandler,\n caseSensitive: caseSensitive\n } as ConfigurableRoute);\n\n if (path) {\n let settings = config.settings;\n delete config.settings;\n let withChild = JSON.parse(JSON.stringify(config));\n config.settings = settings;\n withChild.route = `${path}/*childRoute`;\n withChild.hasChildRouter = true;\n this._childRecognizer.add({\n path: withChild.route,\n handler: withChild,\n caseSensitive: caseSensitive\n });\n\n withChild.navModel = navModel;\n withChild.settings = config.settings;\n withChild.navigationStrategy = config.navigationStrategy;\n }\n\n config.navModel = navModel;\n\n let navigation = this.navigation;\n\n if ((navModel.order || navModel.order === 0) && navigation.indexOf(navModel) === -1) {\n if ((!navModel.href && navModel.href !== '') && (state.types.dynamics || state.types.stars)) {\n throw new Error('Invalid route config for \"' + config.route + '\" : dynamic routes must specify an \"href:\" to be included in the navigation model.');\n }\n\n if (typeof navModel.order !== 'number') {\n navModel.order = ++this._fallbackOrder;\n }\n\n navigation.push(navModel);\n // this is a potential error / inconsistency between browsers\n //\n // MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort\n // If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other,\n // but sorted with respect to all different elements.\n // Note: the ECMAscript standard does not guarantee this behaviour,\n // and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.\n navigation.sort((a, b) => a.order - b.order);\n }\n }\n\n /**\n * Gets a value indicating whether or not this [[Router]] or one of its ancestors has a route registered with the specified name.\n *\n * @param name The name of the route to check.\n */\n hasRoute(name: string): boolean {\n return !!(this._recognizer.hasRoute(name) || this.parent && this.parent.hasRoute(name));\n }\n\n /**\n * Gets a value indicating whether or not this [[Router]] has a route registered with the specified name.\n *\n * @param name The name of the route to check.\n */\n hasOwnRoute(name: string): boolean {\n return this._recognizer.hasRoute(name);\n }\n\n /**\n * Register a handler to use when the incoming URL fragment doesn't match any registered routes.\n *\n * @param config The moduleId, or a function that selects the moduleId, or a [[RouteConfig]].\n */\n handleUnknownRoutes(config?: RouteConfigSpecifier): void {\n if (!config) {\n throw new Error('Invalid unknown route handler');\n }\n\n this.catchAllHandler = instruction => {\n return this\n ._createRouteConfig(config, instruction)\n .then(c => {\n instruction.config = c;\n return instruction;\n });\n };\n }\n\n /**\n * Updates the document title using the current navigation instruction.\n */\n updateTitle(): void {\n let parentRouter = this.parent;\n if (parentRouter) {\n return parentRouter.updateTitle();\n }\n\n let currentInstruction = this.currentInstruction;\n if (currentInstruction) {\n currentInstruction._updateTitle();\n }\n return undefined;\n }\n\n /**\n * Updates the navigation routes with hrefs relative to the current location.\n * Note: This method will likely move to a plugin in a future release.\n */\n refreshNavigation(): void {\n let nav = this.navigation;\n\n for (let i = 0, length = nav.length; i < length; i++) {\n let current = nav[i];\n if (!current.config.href) {\n current.href = _createRootedPath(current.relativeHref, this.baseUrl, this.history._hasPushState);\n } else {\n current.href = _normalizeAbsolutePath(current.config.href, this.history._hasPushState);\n }\n }\n }\n\n /**\n * Sets the default configuration for the view ports. This specifies how to\n * populate a view port for which no module is specified. The default is\n * an empty view/view-model pair.\n */\n useViewPortDefaults($viewPortDefaults: Record): void {\n // a workaround to have strong typings while not requiring to expose interface ViewPortInstruction\n let viewPortDefaults: Record = $viewPortDefaults;\n for (let viewPortName in viewPortDefaults) {\n let viewPortConfig = viewPortDefaults[viewPortName];\n this.viewPortDefaults[viewPortName] = {\n moduleId: viewPortConfig.moduleId\n };\n }\n }\n\n /**@internal */\n _refreshBaseUrl(): void {\n let parentRouter = this.parent;\n if (parentRouter) {\n this.baseUrl = generateBaseUrl(parentRouter, parentRouter.currentInstruction);\n }\n }\n\n /**@internal */\n _createNavigationInstruction(url: string = '', parentInstruction: NavigationInstruction = null): Promise {\n let fragment = url;\n let queryString = '';\n\n let queryIndex = url.indexOf('?');\n if (queryIndex !== -1) {\n fragment = url.substr(0, queryIndex);\n queryString = url.substr(queryIndex + 1);\n }\n\n let urlRecognizationResults = this._recognizer.recognize(url) as IRouteRecognizationResults;\n if (!urlRecognizationResults || !urlRecognizationResults.length) {\n urlRecognizationResults = this._childRecognizer.recognize(url) as IRouteRecognizationResults;\n }\n\n let instructionInit: NavigationInstructionInit = {\n fragment,\n queryString,\n config: null,\n parentInstruction,\n previousInstruction: this.currentInstruction,\n router: this,\n options: {\n compareQueryParams: this.options.compareQueryParams\n }\n };\n\n let result: Promise;\n\n if (urlRecognizationResults && urlRecognizationResults.length) {\n let first = urlRecognizationResults[0];\n let instruction = new NavigationInstruction(Object.assign({}, instructionInit, {\n params: first.params,\n queryParams: first.queryParams || urlRecognizationResults.queryParams,\n config: first.config || first.handler\n }));\n\n if (typeof first.handler === 'function') {\n result = evaluateNavigationStrategy(instruction, first.handler, first);\n } else if (first.handler && typeof first.handler.navigationStrategy === 'function') {\n result = evaluateNavigationStrategy(instruction, first.handler.navigationStrategy, first.handler);\n } else {\n result = Promise.resolve(instruction);\n }\n } else if (this.catchAllHandler) {\n let instruction = new NavigationInstruction(Object.assign({}, instructionInit, {\n params: { path: fragment },\n queryParams: urlRecognizationResults ? urlRecognizationResults.queryParams : {},\n config: null // config will be created by the catchAllHandler\n }));\n\n result = evaluateNavigationStrategy(instruction, this.catchAllHandler);\n } else if (this.parent) {\n let router = this._parentCatchAllHandler(this.parent);\n\n if (router) {\n let newParentInstruction = this._findParentInstructionFromRouter(router, parentInstruction);\n\n let instruction = new NavigationInstruction(Object.assign({}, instructionInit, {\n params: { path: fragment },\n queryParams: urlRecognizationResults ? urlRecognizationResults.queryParams : {},\n router: router,\n parentInstruction: newParentInstruction,\n parentCatchHandler: true,\n config: null // config will be created by the chained parent catchAllHandler\n }));\n\n result = evaluateNavigationStrategy(instruction, router.catchAllHandler);\n }\n }\n\n if (result && parentInstruction) {\n this.baseUrl = generateBaseUrl(this.parent, parentInstruction);\n }\n\n return result || Promise.reject(new Error(`Route not found: ${url}`));\n }\n\n /**@internal */\n _findParentInstructionFromRouter(router: Router, instruction: NavigationInstruction): NavigationInstruction {\n if (instruction.router === router) {\n instruction.fragment = router.baseUrl; // need to change the fragment in case of a redirect instead of moduleId\n return instruction;\n } else if (instruction.parentInstruction) {\n return this._findParentInstructionFromRouter(router, instruction.parentInstruction);\n }\n return undefined;\n }\n\n /**@internal */\n _parentCatchAllHandler(router: Router): Router | false {\n if (router.catchAllHandler) {\n return router;\n } else if (router.parent) {\n return this._parentCatchAllHandler(router.parent);\n }\n return false;\n }\n\n /**\n * @internal\n */\n _createRouteConfig(config: RouteConfigSpecifier, instruction: NavigationInstruction): Promise {\n return Promise\n .resolve(config)\n .then((c: any) => {\n if (typeof c === 'string') {\n return { moduleId: c } as RouteConfig;\n } else if (typeof c === 'function') {\n return c(instruction);\n }\n\n return c;\n })\n // typing here could be either RouteConfig or RedirectConfig\n // but temporarily treat both as RouteConfig\n // todo: improve typings precision\n .then((c: string | RouteConfig) => typeof c === 'string' ? { moduleId: c } as RouteConfig : c)\n .then((c: RouteConfig) => {\n c.route = instruction.params.path;\n validateRouteConfig(c);\n\n if (!c.navModel) {\n c.navModel = this.createNavModel(c);\n }\n\n return c;\n });\n }\n}\n\n/* @internal exported for unit testing */\nexport const generateBaseUrl = (router: Router, instruction: NavigationInstruction): string => {\n return `${router.baseUrl || ''}${instruction.getBaseUrl() || ''}`;\n};\n\n/* @internal exported for unit testing */\nexport const validateRouteConfig = (config: RouteConfig): void => {\n if (typeof config !== 'object') {\n throw new Error('Invalid Route Config');\n }\n\n if (typeof config.route !== 'string') {\n let name = config.name || '(no name)';\n throw new Error('Invalid Route Config for \"' + name + '\": You must specify a \"route:\" pattern.');\n }\n\n if (!('redirect' in config || config.moduleId || config.navigationStrategy || config.viewPorts)) {\n throw new Error('Invalid Route Config for \"' + config.route + '\": You must specify a \"moduleId:\", \"redirect:\", \"navigationStrategy:\", or \"viewPorts:\".');\n }\n};\n\n/* @internal exported for unit testing */\nexport const evaluateNavigationStrategy = (\n instruction: NavigationInstruction,\n evaluator: Function,\n context?: any\n): Promise => {\n return Promise\n .resolve(evaluator.call(context, instruction))\n .then(() => {\n if (!('viewPorts' in instruction.config)) {\n instruction.config.viewPorts = {\n 'default': {\n moduleId: instruction.config.moduleId\n }\n };\n }\n\n return instruction;\n });\n};\n\ninterface IRouteRecognizationResults extends Array {\n queryParams: Record;\n}\n","import { Router } from './router';\nimport { RouteConfig } from './interfaces';\n\n/**\n* Class for storing and interacting with a route's navigation settings.\n*/\nexport class NavModel {\n\n /**\n * True if this nav item is currently active.\n */\n isActive: boolean = false;\n\n /**\n * The title.\n */\n title: string = null;\n\n /**\n * This nav item's absolute href.\n */\n href: string = null;\n\n /**\n * This nav item's relative href.\n */\n relativeHref: string = null;\n\n /**\n * Data attached to the route at configuration time.\n */\n settings: any = {};\n\n /**\n * The route config.\n */\n config: RouteConfig = null;\n\n /**\n * The router associated with this navigation model.\n */\n router: Router;\n\n order: number | boolean;\n\n constructor(router: Router, relativeHref: string) {\n this.router = router;\n this.relativeHref = relativeHref;\n }\n\n /**\n * Sets the route's title and updates document.title.\n * If the a navigation is in progress, the change will be applied\n * to document.title when the navigation completes.\n *\n * @param title The new title.\n */\n setTitle(title: string): void {\n this.title = title;\n\n if (this.isActive) {\n this.router.updateTitle();\n }\n }\n}\n","import { RouteConfig } from './interfaces';\n\nexport function _normalizeAbsolutePath(path: string, hasPushState: boolean, absolute: boolean = false) {\n if (!hasPushState && path[0] !== '#') {\n path = '#' + path;\n }\n\n if (hasPushState && absolute) {\n path = path.substring(1, path.length);\n }\n\n return path;\n}\n\nexport function _createRootedPath(fragment: string, baseUrl: string, hasPushState: boolean, absolute?: boolean) {\n if (isAbsoluteUrl.test(fragment)) {\n return fragment;\n }\n\n let path = '';\n\n if (baseUrl.length && baseUrl[0] !== '/') {\n path += '/';\n }\n\n path += baseUrl;\n\n if ((!path.length || path[path.length - 1] !== '/') && fragment[0] !== '/') {\n path += '/';\n }\n\n if (path.length && path[path.length - 1] === '/' && fragment[0] === '/') {\n path = path.substring(0, path.length - 1);\n }\n\n return _normalizeAbsolutePath(path + fragment, hasPushState, absolute);\n}\n\nexport function _resolveUrl(fragment: string, baseUrl: string, hasPushState?: boolean) {\n if (isRootedPath.test(fragment)) {\n return _normalizeAbsolutePath(fragment, hasPushState);\n }\n\n return _createRootedPath(fragment, baseUrl, hasPushState);\n}\n\nexport function _ensureArrayWithSingleRoutePerConfig(config: RouteConfig) {\n let routeConfigs = [];\n\n if (Array.isArray(config.route)) {\n for (let i = 0, ii = config.route.length; i < ii; ++i) {\n let current = Object.assign({}, config);\n current.route = config.route[i];\n routeConfigs.push(current);\n }\n } else {\n routeConfigs.push(Object.assign({}, config));\n }\n\n return routeConfigs;\n}\n\nconst isRootedPath = /^#?\\//;\nconst isAbsoluteUrl = /^([a-z][a-z0-9+\\-.]*:)?\\/\\//i;\n","import { PipelineStatus } from './pipeline-status';\nimport { NavigationInstruction } from './navigation-instruction';\nimport { Next, StepRunnerFunction, NextCompletionHandler } from './interfaces';\n\n/**@internal exported for unit testing */\nexport const createNextFn = (instruction: NavigationInstruction, steps: StepRunnerFunction[]): Next => {\n let index = -1;\n const next: Next = function() {\n index++;\n\n if (index < steps.length) {\n let currentStep = steps[index];\n\n try {\n return currentStep(instruction, next);\n } catch (e) {\n return next.reject(e);\n }\n } else {\n return next.complete();\n }\n } as Next;\n\n next.complete = createCompletionHandler(next, PipelineStatus.Completed);\n next.cancel = createCompletionHandler(next, PipelineStatus.Canceled);\n next.reject = createCompletionHandler(next, PipelineStatus.Rejected);\n\n return next;\n};\n\n/**@internal exported for unit testing */\nexport const createCompletionHandler = (next: Next, status: PipelineStatus): NextCompletionHandler => {\n return (output: any) => Promise\n .resolve({\n status,\n output,\n completed: status === PipelineStatus.Completed\n });\n};\n","import { PipelineStep, PipelineResult, Next, StepRunnerFunction, IPipelineSlot } from './interfaces';\nimport { NavigationInstruction } from './navigation-instruction';\nimport { createNextFn } from './next';\n\n/**\n * The class responsible for managing and processing the navigation pipeline.\n */\nexport class Pipeline {\n /**\n * The pipeline steps. And steps added via addStep will be converted to a function\n * The actualy running functions with correct step contexts of this pipeline\n */\n steps: StepRunnerFunction[] = [];\n\n /**\n * Adds a step to the pipeline.\n *\n * @param step The pipeline step.\n */\n addStep(step: StepRunnerFunction | PipelineStep | IPipelineSlot): Pipeline {\n let run;\n\n if (typeof step === 'function') {\n run = step;\n } else if (typeof step.getSteps === 'function') {\n // getSteps is to enable support open slots\n // where devs can add multiple steps into the same slot name\n let steps = step.getSteps();\n for (let i = 0, l = steps.length; i < l; i++) {\n this.addStep(steps[i]);\n }\n\n return this;\n } else {\n run = (step as PipelineStep).run.bind(step);\n }\n\n this.steps.push(run);\n\n return this;\n }\n\n /**\n * Runs the pipeline.\n *\n * @param instruction The navigation instruction to process.\n */\n run(instruction: NavigationInstruction): Promise {\n const nextFn = createNextFn(instruction, this.steps);\n return nextFn();\n }\n}\n","import { NavigationOptions } from 'aurelia-history';\nimport { Router } from './router';\n\n/**@internal */\ndeclare module 'aurelia-history' {\n interface NavigationOptions {\n useAppRouter?: boolean;\n }\n}\n\n/**\n* When a navigation command is encountered, the current navigation\n* will be cancelled and control will be passed to the navigation\n* command so it can determine the correct action.\n*/\nexport interface NavigationCommand {\n navigate: (router: Router) => void;\n /**@internal */\n shouldContinueProcessing?: boolean;\n /**@internal */\n setRouter?: (router: Router) => void;\n}\n\n/**\n* Determines if the provided object is a navigation command.\n* A navigation command is anything with a navigate method.\n*\n* @param obj The object to check.\n*/\nexport function isNavigationCommand(obj: any): obj is NavigationCommand {\n return obj && typeof obj.navigate === 'function';\n}\n\n/**\n* Used during the activation lifecycle to cause a redirect.\n*/\nexport class Redirect implements NavigationCommand {\n\n url: string;\n /**@internal */\n options: NavigationOptions;\n /**@internal */\n shouldContinueProcessing: boolean;\n\n private router: Router;\n\n /**\n * @param url The URL fragment to use as the navigation destination.\n * @param options The navigation options.\n */\n constructor(url: string, options: NavigationOptions = {}) {\n this.url = url;\n this.options = Object.assign({ trigger: true, replace: true }, options);\n this.shouldContinueProcessing = false;\n }\n\n /**\n * Called by the activation system to set the child router.\n *\n * @param router The router.\n */\n setRouter(router: Router): void {\n this.router = router;\n }\n\n /**\n * Called by the navigation pipeline to navigate.\n *\n * @param appRouter The router to be redirected.\n */\n navigate(appRouter: Router): void {\n let navigatingRouter = this.options.useAppRouter ? appRouter : (this.router || appRouter);\n navigatingRouter.navigate(this.url, this.options);\n }\n}\n\n/**\n * Used during the activation lifecycle to cause a redirect to a named route.\n */\nexport class RedirectToRoute implements NavigationCommand {\n\n route: string;\n params: any;\n /**@internal */\n options: NavigationOptions;\n\n /**@internal */\n shouldContinueProcessing: boolean;\n\n /**@internal */\n router: Router;\n\n /**\n * @param route The name of the route.\n * @param params The parameters to be sent to the activation method.\n * @param options The options to use for navigation.\n */\n constructor(route: string, params: any = {}, options: NavigationOptions = {}) {\n this.route = route;\n this.params = params;\n this.options = Object.assign({ trigger: true, replace: true }, options);\n this.shouldContinueProcessing = false;\n }\n\n /**\n * Called by the activation system to set the child router.\n *\n * @param router The router.\n */\n setRouter(router: Router): void {\n this.router = router;\n }\n\n /**\n * Called by the navigation pipeline to navigate.\n *\n * @param appRouter The router to be redirected.\n */\n navigate(appRouter: Router): void {\n let navigatingRouter = this.options.useAppRouter ? appRouter : (this.router || appRouter);\n navigatingRouter.navigateToRoute(this.route, this.params, this.options);\n }\n}\n","import { ViewPortPlan, ViewPortInstruction, RouteConfig, ViewPort } from './interfaces';\nimport { Redirect } from './navigation-commands';\nimport { NavigationInstruction } from './navigation-instruction';\nimport { InternalActivationStrategy, ActivationStrategyType } from './activation-strategy';\n\ntype ViewPortPlansRecord = Record;\n\n/**\n * @internal exported for unit testing\n */\nexport function _buildNavigationPlan(\n instruction: NavigationInstruction,\n forceLifecycleMinimum?: boolean\n): Promise {\n let config = instruction.config;\n\n if ('redirect' in config) {\n return buildRedirectPlan(instruction);\n }\n\n const prevInstruction = instruction.previousInstruction;\n const defaultViewPortConfigs = instruction.router.viewPortDefaults;\n\n if (prevInstruction) {\n return buildTransitionPlans(instruction, prevInstruction, defaultViewPortConfigs, forceLifecycleMinimum);\n }\n\n // first navigation, only need to prepare a few information for each viewport plan\n const viewPortPlans: ViewPortPlansRecord = {};\n let viewPortConfigs = config.viewPorts;\n for (let viewPortName in viewPortConfigs) {\n let viewPortConfig = viewPortConfigs[viewPortName];\n if (viewPortConfig.moduleId === null && viewPortName in defaultViewPortConfigs) {\n viewPortConfig = defaultViewPortConfigs[viewPortName];\n }\n viewPortPlans[viewPortName] = {\n name: viewPortName,\n strategy: InternalActivationStrategy.Replace,\n config: viewPortConfig\n };\n }\n\n return Promise.resolve(viewPortPlans);\n}\n\n/**\n * Build redirect plan based on config of a navigation instruction\n * @internal exported for unit testing\n */\nexport const buildRedirectPlan = (instruction: NavigationInstruction) => {\n const config = instruction.config;\n const router = instruction.router;\n return router\n ._createNavigationInstruction(config.redirect)\n .then(redirectInstruction => {\n\n const params: Record = {};\n const originalInstructionParams = instruction.params;\n const redirectInstructionParams = redirectInstruction.params;\n\n for (let key in redirectInstructionParams) {\n // If the param on the redirect points to another param, e.g. { route: first/:this, redirect: second/:this }\n let val = redirectInstructionParams[key];\n if (typeof val === 'string' && val[0] === ':') {\n val = val.slice(1);\n // And if that param is found on the original instruction then use it\n if (val in originalInstructionParams) {\n params[key] = originalInstructionParams[val];\n }\n } else {\n params[key] = redirectInstructionParams[key];\n }\n }\n let redirectLocation = router.generate(redirectInstruction.config, params, instruction.options);\n\n // Special handling for child routes\n for (let key in originalInstructionParams) {\n redirectLocation = redirectLocation.replace(`:${key}`, originalInstructionParams[key]);\n }\n\n let queryString = instruction.queryString;\n if (queryString) {\n redirectLocation += '?' + queryString;\n }\n\n return Promise.resolve(new Redirect(redirectLocation));\n });\n};\n\n/**\n * @param viewPortPlans the Plan record that holds information about built plans\n * @internal exported for unit testing\n */\nexport const buildTransitionPlans = (\n currentInstruction: NavigationInstruction,\n previousInstruction: NavigationInstruction,\n defaultViewPortConfigs: Record,\n forceLifecycleMinimum?: boolean\n): Promise => {\n\n let viewPortPlans: ViewPortPlansRecord = {};\n let newInstructionConfig = currentInstruction.config;\n let hasNewParams = hasDifferentParameterValues(previousInstruction, currentInstruction);\n let pending: Promise[] = [];\n let previousViewPortInstructions = previousInstruction.viewPortInstructions as Record;\n\n for (let viewPortName in previousViewPortInstructions) {\n\n const prevViewPortInstruction = previousViewPortInstructions[viewPortName];\n const prevViewPortComponent = prevViewPortInstruction.component;\n const newInstructionViewPortConfigs = newInstructionConfig.viewPorts as Record;\n\n // if this is invoked on a viewport without any changes, based on new url,\n // newViewPortConfig will be the existing viewport instruction\n let nextViewPortConfig = viewPortName in newInstructionViewPortConfigs\n ? newInstructionViewPortConfigs[viewPortName]\n : prevViewPortInstruction;\n\n if (nextViewPortConfig.moduleId === null && viewPortName in defaultViewPortConfigs) {\n nextViewPortConfig = defaultViewPortConfigs[viewPortName];\n }\n\n const viewPortActivationStrategy = determineActivationStrategy(\n currentInstruction,\n prevViewPortInstruction,\n nextViewPortConfig,\n hasNewParams,\n forceLifecycleMinimum\n );\n const viewPortPlan = viewPortPlans[viewPortName] = {\n name: viewPortName,\n // ViewPortInstruction can quack like a RouteConfig\n config: nextViewPortConfig as RouteConfig,\n prevComponent: prevViewPortComponent,\n prevModuleId: prevViewPortInstruction.moduleId,\n strategy: viewPortActivationStrategy\n } as ViewPortPlan;\n\n // recursively build nav plans for all existing child routers/viewports of this viewport\n // this is possible because existing child viewports and routers already have necessary information\n // to process the wildcard path from parent instruction\n if (viewPortActivationStrategy !== InternalActivationStrategy.Replace && prevViewPortInstruction.childRouter) {\n const path = currentInstruction.getWildcardPath();\n const task: Promise = prevViewPortInstruction\n .childRouter\n ._createNavigationInstruction(path, currentInstruction)\n .then((childInstruction: NavigationInstruction) => {\n viewPortPlan.childNavigationInstruction = childInstruction;\n\n return _buildNavigationPlan(\n childInstruction,\n // is it safe to assume viewPortPlan has not been changed from previous assignment?\n // if so, can just use local variable viewPortPlanStrategy\n // there could be user code modifying viewport plan during _createNavigationInstruction?\n viewPortPlan.strategy === InternalActivationStrategy.InvokeLifecycle\n )\n .then(childPlan => {\n if (childPlan instanceof Redirect) {\n return Promise.reject(childPlan);\n }\n childInstruction.plan = childPlan;\n // for bluebird ?\n return null;\n });\n });\n\n pending.push(task);\n }\n }\n\n return Promise.all(pending).then(() => viewPortPlans);\n};\n\n/**\n * @param newViewPortConfig if this is invoked on a viewport without any changes, based on new url, newViewPortConfig will be the existing viewport instruction\n * @internal exported for unit testing\n */\nexport const determineActivationStrategy = (\n currentNavInstruction: NavigationInstruction,\n prevViewPortInstruction: ViewPortInstruction,\n newViewPortConfig: RouteConfig | ViewPortInstruction,\n // indicates whether there is difference between old and new url params\n hasNewParams: boolean,\n forceLifecycleMinimum?: boolean\n): ActivationStrategyType => {\n\n let newInstructionConfig = currentNavInstruction.config;\n let prevViewPortViewModel = prevViewPortInstruction.component.viewModel;\n let viewPortPlanStrategy: ActivationStrategyType;\n\n if (prevViewPortInstruction.moduleId !== newViewPortConfig.moduleId) {\n viewPortPlanStrategy = InternalActivationStrategy.Replace;\n } else if ('determineActivationStrategy' in prevViewPortViewModel) {\n viewPortPlanStrategy = prevViewPortViewModel.determineActivationStrategy(...currentNavInstruction.lifecycleArgs);\n } else if (newInstructionConfig.activationStrategy) {\n viewPortPlanStrategy = newInstructionConfig.activationStrategy;\n } else if (hasNewParams || forceLifecycleMinimum) {\n viewPortPlanStrategy = InternalActivationStrategy.InvokeLifecycle;\n } else {\n viewPortPlanStrategy = InternalActivationStrategy.NoChange;\n }\n return viewPortPlanStrategy;\n};\n\n/**@internal exported for unit testing */\nexport const hasDifferentParameterValues = (prev: NavigationInstruction, next: NavigationInstruction): boolean => {\n let prevParams = prev.params;\n let nextParams = next.params;\n let nextWildCardName = next.config.hasChildRouter ? next.getWildCardName() : null;\n\n for (let key in nextParams) {\n if (key === nextWildCardName) {\n continue;\n }\n\n if (prevParams[key] !== nextParams[key]) {\n return true;\n }\n }\n\n for (let key in prevParams) {\n if (key === nextWildCardName) {\n continue;\n }\n\n if (prevParams[key] !== nextParams[key]) {\n return true;\n }\n }\n\n if (!next.options.compareQueryParams) {\n return false;\n }\n\n let prevQueryParams = prev.queryParams;\n let nextQueryParams = next.queryParams;\n for (let key in nextQueryParams) {\n if (prevQueryParams[key] !== nextQueryParams[key]) {\n return true;\n }\n }\n\n for (let key in prevQueryParams) {\n if (prevQueryParams[key] !== nextQueryParams[key]) {\n return true;\n }\n }\n\n return false;\n};\n","import { Next } from './interfaces';\nimport { Redirect } from './navigation-commands';\nimport { NavigationInstruction } from './navigation-instruction';\nimport { _buildNavigationPlan } from './navigation-plan';\n\n/**\n * Transform a navigation instruction into viewport plan record object,\n * or a redirect request if user viewmodel demands\n */\nexport class BuildNavigationPlanStep {\n run(navigationInstruction: NavigationInstruction, next: Next): Promise {\n return _buildNavigationPlan(navigationInstruction)\n .then(plan => {\n if (plan instanceof Redirect) {\n return next.cancel(plan);\n }\n navigationInstruction.plan = plan;\n return next();\n })\n .catch(next.cancel);\n }\n}\n","import { RouteConfig, ViewPortComponent, ViewPortPlan, ViewPortInstruction } from './interfaces';\nimport { Redirect } from './navigation-commands';\nimport { NavigationInstruction } from './navigation-instruction';\nimport { _buildNavigationPlan } from './navigation-plan';\nimport { InternalActivationStrategy } from './activation-strategy';\nimport { RouteLoader } from './route-loader';\n\n/**\n * Loading plan calculated based on a navigration-instruction and a viewport plan\n */\ninterface ILoadingPlan {\n viewPortPlan: ViewPortPlan;\n navigationInstruction: NavigationInstruction;\n}\n\n/**\n * @internal Exported for unit testing\n */\nexport const loadNewRoute = (\n routeLoader: RouteLoader,\n navigationInstruction: NavigationInstruction\n): Promise => {\n let loadingPlans = determineLoadingPlans(navigationInstruction);\n let loadPromises = loadingPlans.map((loadingPlan: ILoadingPlan) => loadRoute(\n routeLoader,\n loadingPlan.navigationInstruction,\n loadingPlan.viewPortPlan\n ));\n\n return Promise.all(loadPromises);\n};\n\n/**\n * @internal Exported for unit testing\n */\nexport const determineLoadingPlans = (\n navigationInstruction: NavigationInstruction,\n loadingPlans: ILoadingPlan[] = []\n): ILoadingPlan[] => {\n let viewPortPlans: Record = navigationInstruction.plan;\n\n for (let viewPortName in viewPortPlans) {\n let viewPortPlan = viewPortPlans[viewPortName];\n let childNavInstruction = viewPortPlan.childNavigationInstruction;\n\n if (viewPortPlan.strategy === InternalActivationStrategy.Replace) {\n loadingPlans.push({ viewPortPlan, navigationInstruction } as ILoadingPlan);\n\n if (childNavInstruction) {\n determineLoadingPlans(childNavInstruction, loadingPlans);\n }\n } else {\n let viewPortInstruction = navigationInstruction.addViewPortInstruction({\n name: viewPortName,\n strategy: viewPortPlan.strategy,\n moduleId: viewPortPlan.prevModuleId,\n component: viewPortPlan.prevComponent\n }) as ViewPortInstruction;\n\n if (childNavInstruction) {\n viewPortInstruction.childNavigationInstruction = childNavInstruction;\n determineLoadingPlans(childNavInstruction, loadingPlans);\n }\n }\n }\n\n return loadingPlans;\n};\n\n/**\n * @internal Exported for unit testing\n */\nexport const loadRoute = (\n routeLoader: RouteLoader,\n navigationInstruction: NavigationInstruction,\n viewPortPlan: ViewPortPlan\n): Promise => {\n let planConfig = viewPortPlan.config;\n let moduleId = planConfig ? planConfig.moduleId : null;\n\n return loadComponent(routeLoader, navigationInstruction, planConfig)\n .then((component) => {\n let viewPortInstruction = navigationInstruction.addViewPortInstruction({\n name: viewPortPlan.name,\n strategy: viewPortPlan.strategy,\n moduleId: moduleId,\n component: component\n }) as ViewPortInstruction;\n\n let childRouter = component.childRouter;\n if (childRouter) {\n let path = navigationInstruction.getWildcardPath();\n\n return childRouter\n ._createNavigationInstruction(path, navigationInstruction)\n .then((childInstruction) => {\n viewPortPlan.childNavigationInstruction = childInstruction;\n\n return _buildNavigationPlan(childInstruction)\n .then((childPlan) => {\n if (childPlan instanceof Redirect) {\n return Promise.reject(childPlan);\n }\n childInstruction.plan = childPlan;\n viewPortInstruction.childNavigationInstruction = childInstruction;\n\n return loadNewRoute(routeLoader, childInstruction);\n });\n });\n }\n // ts complains without this, though they are same\n return void 0;\n });\n};\n\n/**\n * Load a routed-component based on navigation instruction and route config\n * @internal exported for unit testing only\n */\nexport const loadComponent = (\n routeLoader: RouteLoader,\n navigationInstruction: NavigationInstruction,\n config: RouteConfig\n): Promise => {\n let router = navigationInstruction.router;\n let lifecycleArgs = navigationInstruction.lifecycleArgs;\n\n return Promise.resolve()\n .then(() => routeLoader.loadRoute(router, config, navigationInstruction))\n .then(\n /**\n * @param component an object carrying information about loaded route\n * typically contains information about view model, childContainer, view and router\n */\n (component: ViewPortComponent) => {\n let { viewModel, childContainer } = component;\n component.router = router;\n component.config = config;\n\n if ('configureRouter' in viewModel) {\n let childRouter = childContainer.getChildRouter();\n component.childRouter = childRouter;\n\n return childRouter\n .configure(c => viewModel.configureRouter(c, childRouter, lifecycleArgs[0], lifecycleArgs[1], lifecycleArgs[2]))\n .then(() => component);\n }\n\n return component;\n }\n );\n};\n","import { Origin } from 'aurelia-metadata';\nimport { relativeToFile } from 'aurelia-path';\nimport { NavigationInstruction, RouteConfig, RouteLoader, Router } from 'aurelia-router';\nimport { CompositionEngine, customElement, inlineView, useView, CompositionContext } from 'aurelia-templating';\nimport { RouterViewLocator } from './router-view';\nimport { Container } from 'aurelia-dependency-injection';\n\n/**@internal exported for unit testing */\nexport class EmptyClass { }\ninlineView('')(EmptyClass);\n\n/**\n * Default implementation of `RouteLoader` used for loading component based on a route config\n */\nexport class TemplatingRouteLoader extends RouteLoader {\n\n /**@internal */\n static inject = [CompositionEngine];\n\n /**@internal */\n compositionEngine: CompositionEngine;\n\n constructor(\n compositionEngine: CompositionEngine\n ) {\n super();\n this.compositionEngine = compositionEngine;\n }\n\n /**\n * Resolve a view model from a RouteConfig\n * Throws when there is neither \"moduleId\" nor \"viewModel\" property\n * @internal\n */\n resolveViewModel(router: Router, config: RouteConfig): Promise {\n return new Promise((resolve, reject) => {\n let viewModel: string | null | Function;\n if ('moduleId' in config) {\n let moduleId = config.moduleId;\n if (moduleId === null) {\n viewModel = EmptyClass;\n } else {\n // this requires container of router has passes a certain point\n // where a view model has been setup on the container\n // it will fail in enhance scenario because no viewport has been registered\n moduleId = relativeToFile(moduleId, Origin.get(router.container.viewModel.constructor).moduleId);\n if (/\\.html/i.test(moduleId)) {\n viewModel = createDynamicClass(moduleId);\n } else {\n viewModel = moduleId;\n }\n }\n return resolve(viewModel);\n }\n // todo: add if ('viewModel' in config) to support static view model resolution\n reject(new Error('Invalid route config. No \"moduleId\" found.'));\n });\n }\n\n /**\n * Create child container based on a router container\n * Also ensures that child router are properly constructed in the newly created child container\n * @internal\n */\n createChildContainer(router: Router): Container {\n const childContainer = router.container.createChild();\n\n childContainer.registerSingleton(RouterViewLocator);\n childContainer.getChildRouter = function() {\n let childRouter: Router;\n\n childContainer.registerHandler(\n Router,\n () => childRouter || (childRouter = router.createChild(childContainer))\n );\n\n return childContainer.get(Router);\n };\n return childContainer;\n }\n\n /**\n * Load corresponding component of a route config of a navigation instruction\n */\n loadRoute(router: Router, config: RouteConfig, _navInstruction: NavigationInstruction): Promise {\n return this\n .resolveViewModel(router, config)\n .then(viewModel => this.compositionEngine.ensureViewModel({\n viewModel: viewModel,\n childContainer: this.createChildContainer(router),\n view: config.view || config.viewStrategy,\n router: router\n } as CompositionContext));\n }\n}\n\n/**@internal exported for unit testing */\nexport function createDynamicClass(moduleId: string) {\n const name = /([^\\/^\\?]+)\\.html/i.exec(moduleId)[1];\n\n class DynamicClass {\n\n $parent: any;\n\n bind(bindingContext: any) {\n this.$parent = bindingContext;\n }\n }\n\n customElement(name)(DynamicClass);\n useView(moduleId)(DynamicClass);\n\n return DynamicClass;\n}\n","import { Next } from './interfaces';\nimport { NavigationInstruction } from './navigation-instruction';\nimport { loadNewRoute } from './utilities-route-loading';\nimport { RouteLoader } from './route-loader';\n/**\n * A pipeline step responsible for loading a route config of a navigation instruction\n */\nexport class LoadRouteStep {\n /**@internal */\n static inject() { return [RouteLoader]; }\n /**\n * Route loader isntance that will handle loading route config\n * @internal\n */\n routeLoader: RouteLoader;\n constructor(routeLoader: RouteLoader) {\n this.routeLoader = routeLoader;\n }\n /**\n * Run the internal to load route config of a navigation instruction to prepare for next steps in the pipeline\n */\n run(navigationInstruction: NavigationInstruction, next: Next): Promise {\n return loadNewRoute(this.routeLoader, navigationInstruction)\n .then(next, next.cancel);\n }\n}\n","import { NavigationInstruction } from './navigation-instruction';\n\n/**\n * A pipeline step for instructing a piepline to commit changes on a navigation instruction\n */\nexport class CommitChangesStep {\n run(navigationInstruction: NavigationInstruction, next: Function): Promise {\n return navigationInstruction\n ._commitChanges(/*wait to swap?*/ true)\n .then(() => {\n navigationInstruction._updateTitle();\n return next();\n });\n }\n}\n","/**\n * An optional interface describing the available activation strategies.\n * @internal Used internally.\n */\nexport const enum InternalActivationStrategy {\n /**\n * Reuse the existing view model, without invoking Router lifecycle hooks.\n */\n NoChange = 'no-change',\n /**\n * Reuse the existing view model, invoking Router lifecycle hooks.\n */\n InvokeLifecycle = 'invoke-lifecycle',\n /**\n * Replace the existing view model, invoking Router lifecycle hooks.\n */\n Replace = 'replace'\n}\n\n/**\n * The strategy to use when activating modules during navigation.\n */\n// kept for compat reason\nexport const activationStrategy: ActivationStrategy = {\n noChange: InternalActivationStrategy.NoChange,\n invokeLifecycle: InternalActivationStrategy.InvokeLifecycle,\n replace: InternalActivationStrategy.Replace\n};\n\n/**\n * An optional interface describing the available activation strategies.\n */\nexport interface ActivationStrategy {\n /**\n * Reuse the existing view model, without invoking Router lifecycle hooks.\n */\n noChange: 'no-change';\n /**\n * Reuse the existing view model, invoking Router lifecycle hooks.\n */\n invokeLifecycle: 'invoke-lifecycle';\n /**\n * Replace the existing view model, invoking Router lifecycle hooks.\n */\n replace: 'replace';\n}\n\n/**\n * Enum like type for activation strategy built-in values\n */\nexport type ActivationStrategyType = ActivationStrategy[keyof ActivationStrategy];\n","import { Next, ViewPortComponent, ViewPortPlan, ViewPortInstruction, LifecycleArguments } from './interfaces';\nimport { isNavigationCommand } from './navigation-commands';\nimport { NavigationInstruction } from './navigation-instruction';\nimport { activationStrategy } from './activation-strategy';\nimport { Router } from './router';\n\n/**\n * Recursively find list of deactivate-able view models\n * and invoke the either 'canDeactivate' or 'deactivate' on each\n * @internal exported for unit testing\n */\nexport const processDeactivatable = (\n navigationInstruction: NavigationInstruction,\n callbackName: 'canDeactivate' | 'deactivate',\n next: Next,\n ignoreResult?: boolean\n): Promise => {\n let plan: Record = navigationInstruction.plan;\n let infos = findDeactivatable(plan, callbackName);\n let i = infos.length; // query from inside out\n\n function inspect(val: any): Promise {\n if (ignoreResult || shouldContinue(val)) {\n return iterate();\n }\n\n return next.cancel(val);\n }\n\n function iterate(): Promise {\n if (i--) {\n try {\n let viewModel = infos[i];\n let result = viewModel[callbackName](navigationInstruction);\n return processPotential(result, inspect, next.cancel);\n } catch (error) {\n return next.cancel(error);\n }\n }\n\n navigationInstruction.router.couldDeactivate = true;\n\n return next();\n }\n\n return iterate();\n};\n\n/**\n * Recursively find and returns a list of deactivate-able view models\n * @internal exported for unit testing\n */\nexport const findDeactivatable = (\n plan: Record,\n callbackName: string,\n list: IActivatableInfo[] = []\n): any[] => {\n for (let viewPortName in plan) {\n let viewPortPlan = plan[viewPortName];\n let prevComponent = viewPortPlan.prevComponent;\n\n if ((viewPortPlan.strategy === activationStrategy.invokeLifecycle || viewPortPlan.strategy === activationStrategy.replace)\n && prevComponent\n ) {\n let viewModel = prevComponent.viewModel;\n\n if (callbackName in viewModel) {\n list.push(viewModel);\n }\n }\n\n if (viewPortPlan.strategy === activationStrategy.replace && prevComponent) {\n addPreviousDeactivatable(prevComponent, callbackName, list);\n } else if (viewPortPlan.childNavigationInstruction) {\n findDeactivatable(viewPortPlan.childNavigationInstruction.plan, callbackName, list);\n }\n }\n\n return list;\n};\n\n/**\n * @internal exported for unit testing\n */\nexport const addPreviousDeactivatable = (\n component: ViewPortComponent,\n callbackName: string,\n list: IActivatableInfo[]\n): void => {\n let childRouter = component.childRouter;\n\n if (childRouter && childRouter.currentInstruction) {\n let viewPortInstructions = childRouter.currentInstruction.viewPortInstructions;\n\n for (let viewPortName in viewPortInstructions) {\n let viewPortInstruction = viewPortInstructions[viewPortName];\n let prevComponent = viewPortInstruction.component;\n let prevViewModel = prevComponent.viewModel;\n\n if (callbackName in prevViewModel) {\n list.push(prevViewModel);\n }\n\n addPreviousDeactivatable(prevComponent, callbackName, list);\n }\n }\n};\n\n/**\n * @internal exported for unit testing\n */\nexport const processActivatable = (\n navigationInstruction: NavigationInstruction,\n callbackName: 'canActivate' | 'activate',\n next: Next,\n ignoreResult?: boolean\n): Promise => {\n let infos = findActivatable(navigationInstruction, callbackName);\n let length = infos.length;\n let i = -1; // query from top down\n\n function inspect(val: any, router: Router): Promise {\n if (ignoreResult || shouldContinue(val, router)) {\n return iterate();\n }\n\n return next.cancel(val);\n }\n\n function iterate(): Promise {\n i++;\n\n if (i < length) {\n try {\n let current = infos[i];\n let result = current.viewModel[callbackName](...current.lifecycleArgs);\n return processPotential(result, (val: any) => inspect(val, current.router), next.cancel);\n } catch (error) {\n return next.cancel(error);\n }\n }\n\n return next();\n }\n\n return iterate();\n};\n\ninterface IActivatableInfo {\n viewModel: any;\n lifecycleArgs: LifecycleArguments;\n router: Router;\n}\n\n/**\n * Find list of activatable view model and add to list (3rd parameter)\n * @internal exported for unit testing\n */\nexport const findActivatable = (\n navigationInstruction: NavigationInstruction,\n callbackName: 'canActivate' | 'activate',\n list: IActivatableInfo[] = [],\n router?: Router\n): IActivatableInfo[] => {\n let plan: Record = navigationInstruction.plan;\n\n Object\n .keys(plan)\n .forEach((viewPortName) => {\n let viewPortPlan = plan[viewPortName];\n let viewPortInstruction = navigationInstruction.viewPortInstructions[viewPortName] as ViewPortInstruction;\n let viewPortComponent = viewPortInstruction.component;\n let viewModel = viewPortComponent.viewModel;\n\n if (\n (viewPortPlan.strategy === activationStrategy.invokeLifecycle\n || viewPortPlan.strategy === activationStrategy.replace\n )\n && callbackName in viewModel\n ) {\n list.push({\n viewModel,\n lifecycleArgs: viewPortInstruction.lifecycleArgs,\n router\n });\n }\n\n let childNavInstruction = viewPortPlan.childNavigationInstruction;\n\n if (childNavInstruction) {\n findActivatable(\n childNavInstruction,\n callbackName,\n list,\n viewPortComponent.childRouter || router\n );\n }\n });\n\n return list;\n};\n\nconst shouldContinue = (output: T, router?: Router): boolean | T => {\n if (output instanceof Error) {\n return false;\n }\n\n if (isNavigationCommand(output)) {\n if (typeof output.setRouter === 'function') {\n output.setRouter(router);\n }\n\n return !!output.shouldContinueProcessing;\n }\n\n if (output === undefined) {\n return true;\n }\n\n return output;\n};\n\n/**\n * A basic interface for an Observable type\n */\nexport interface IObservable {\n subscribe(sub?: IObservableConfig): ISubscription;\n}\n\nexport interface IObservableConfig {\n next(): void;\n error(err?: any): void;\n complete(): void;\n}\n\n/**\n * A basic interface for a Subscription to an Observable\n */\ninterface ISubscription {\n unsubscribe(): void;\n}\n\ntype SafeSubscriptionFunc = (sub: SafeSubscription) => ISubscription;\n\n/**\n * wraps a subscription, allowing unsubscribe calls even if\n * the first value comes synchronously\n */\nclass SafeSubscription {\n\n private _subscribed: boolean;\n private _subscription: ISubscription;\n\n constructor(subscriptionFunc: SafeSubscriptionFunc) {\n this._subscribed = true;\n this._subscription = subscriptionFunc(this);\n\n if (!this._subscribed) {\n this.unsubscribe();\n }\n }\n\n get subscribed(): boolean {\n return this._subscribed;\n }\n\n unsubscribe(): void {\n if (this._subscribed && this._subscription) {\n this._subscription.unsubscribe();\n }\n\n this._subscribed = false;\n }\n}\n\n/**\n * A function to process return value from `activate`/`canActivate` steps\n * Supports observable/promise\n *\n * For observable, resolve at first next() or on complete()\n */\nconst processPotential = (obj: any, resolve: (val?: any) => any, reject: (err?: any) => any): any => {\n // if promise like\n if (obj && typeof obj.then === 'function') {\n return Promise.resolve(obj).then(resolve).catch(reject);\n }\n\n // if observable\n if (obj && typeof obj.subscribe === 'function') {\n let obs: IObservable = obj;\n return new SafeSubscription(sub => obs.subscribe({\n next() {\n if (sub.subscribed) {\n sub.unsubscribe();\n resolve(obj);\n }\n },\n error(error) {\n if (sub.subscribed) {\n sub.unsubscribe();\n reject(error);\n }\n },\n complete() {\n if (sub.subscribed) {\n sub.unsubscribe();\n resolve(obj);\n }\n }\n }));\n }\n\n // else just resolve\n try {\n return resolve(obj);\n } catch (error) {\n return reject(error);\n }\n};\n","import { Next } from './interfaces';\nimport { NavigationInstruction } from './navigation-instruction';\nimport { processDeactivatable, processActivatable } from './utilities-activation';\n\n/**\n * A pipeline step responsible for finding and activating method `canDeactivate` on a view model of a route\n */\nexport class CanDeactivatePreviousStep {\n run(navigationInstruction: NavigationInstruction, next: Next): Promise {\n return processDeactivatable(navigationInstruction, 'canDeactivate', next);\n }\n}\n\n/**\n * A pipeline step responsible for finding and activating method `canActivate` on a view model of a route\n */\nexport class CanActivateNextStep {\n run(navigationInstruction: NavigationInstruction, next: Next): Promise {\n return processActivatable(navigationInstruction, 'canActivate', next);\n }\n}\n\n/**\n * A pipeline step responsible for finding and activating method `deactivate` on a view model of a route\n */\nexport class DeactivatePreviousStep {\n run(navigationInstruction: NavigationInstruction, next: Next): Promise {\n return processDeactivatable(navigationInstruction, 'deactivate', next, true);\n }\n}\n\n/**\n * A pipeline step responsible for finding and activating method `activate` on a view model of a route\n */\nexport class ActivateNextStep {\n run(navigationInstruction: NavigationInstruction, next: Next): Promise {\n return processActivatable(navigationInstruction, 'activate', next, true);\n }\n}\n","import { Container } from 'aurelia-dependency-injection';\nimport { Pipeline } from './pipeline';\nimport { BuildNavigationPlanStep } from './step-build-navigation-plan';\nimport { LoadRouteStep } from './step-load-route';\nimport { CommitChangesStep } from './step-commit-changes';\nimport { CanDeactivatePreviousStep, CanActivateNextStep, DeactivatePreviousStep, ActivateNextStep } from './step-activation';\nimport { PipelineStep, StepRunnerFunction, IPipelineSlot } from './interfaces';\nimport { PipelineSlotName } from './pipeline-slot-name';\n\n/**\n * A multi-slots Pipeline Placeholder Step for hooking into a pipeline execution\n */\nclass PipelineSlot implements IPipelineSlot {\n\n /**@internal */\n container: Container;\n /**@internal */\n slotName: string;\n /**@internal */\n slotAlias?: string;\n\n steps: (Function | PipelineStep)[] = [];\n\n constructor(container: Container, name: string, alias?: string) {\n this.container = container;\n this.slotName = name;\n this.slotAlias = alias;\n }\n\n getSteps(): (StepRunnerFunction | IPipelineSlot | PipelineStep)[] {\n return this.steps.map(x => this.container.get(x));\n }\n}\n\n/**\n * Class responsible for creating the navigation pipeline.\n */\nexport class PipelineProvider {\n\n /**@internal */\n static inject() { return [Container]; }\n /**@internal */\n container: Container;\n /**@internal */\n steps: (Function | PipelineSlot)[];\n\n constructor(container: Container) {\n this.container = container;\n this.steps = [\n BuildNavigationPlanStep,\n CanDeactivatePreviousStep, // optional\n LoadRouteStep,\n createPipelineSlot(container, PipelineSlotName.Authorize),\n CanActivateNextStep, // optional\n createPipelineSlot(container, PipelineSlotName.PreActivate, 'modelbind'),\n // NOTE: app state changes start below - point of no return\n DeactivatePreviousStep, // optional\n ActivateNextStep, // optional\n createPipelineSlot(container, PipelineSlotName.PreRender, 'precommit'),\n CommitChangesStep,\n createPipelineSlot(container, PipelineSlotName.PostRender, 'postcomplete')\n ];\n }\n\n /**\n * Create the navigation pipeline.\n */\n createPipeline(useCanDeactivateStep: boolean = true): Pipeline {\n let pipeline = new Pipeline();\n this.steps.forEach(step => {\n if (useCanDeactivateStep || step !== CanDeactivatePreviousStep) {\n pipeline.addStep(this.container.get(step));\n }\n });\n return pipeline;\n }\n\n /**@internal */\n _findStep(name: string): PipelineSlot {\n // Steps that are not PipelineSlots are constructor functions, and they will automatically fail. Probably.\n return this.steps.find(x => (x as PipelineSlot).slotName === name || (x as PipelineSlot).slotAlias === name) as PipelineSlot;\n }\n\n /**\n * Adds a step into the pipeline at a known slot location.\n */\n addStep(name: string, step: PipelineStep | Function): void {\n let found = this._findStep(name);\n if (found) {\n let slotSteps = found.steps;\n // prevent duplicates\n if (!slotSteps.includes(step)) {\n slotSteps.push(step);\n }\n } else {\n throw new Error(`Invalid pipeline slot name: ${name}.`);\n }\n }\n\n /**\n * Removes a step from a slot in the pipeline\n */\n removeStep(name: string, step: PipelineStep): void {\n let slot = this._findStep(name);\n if (slot) {\n let slotSteps = slot.steps;\n slotSteps.splice(slotSteps.indexOf(step), 1);\n }\n }\n\n /**\n * Clears all steps from a slot in the pipeline\n * @internal\n */\n _clearSteps(name: string = ''): void {\n let slot = this._findStep(name);\n if (slot) {\n slot.steps = [];\n }\n }\n\n /**\n * Resets all pipeline slots\n */\n reset(): void {\n this._clearSteps(PipelineSlotName.Authorize);\n this._clearSteps(PipelineSlotName.PreActivate);\n this._clearSteps(PipelineSlotName.PreRender);\n this._clearSteps(PipelineSlotName.PostRender);\n }\n}\n\n/**@internal */\nconst createPipelineSlot = (container: Container, name: PipelineSlotName, alias?: string): PipelineSlot => {\n return new PipelineSlot(container, name, alias);\n};\n","import * as LogManager from 'aurelia-logging';\nimport { Container } from 'aurelia-dependency-injection';\nimport { History, NavigationOptions } from 'aurelia-history';\nimport { Router } from './router';\nimport { PipelineProvider } from './pipeline-provider';\nimport { isNavigationCommand } from './navigation-commands';\nimport { EventAggregator } from 'aurelia-event-aggregator';\nimport { NavigationInstruction } from './navigation-instruction';\nimport { ViewPort, ConfiguresRouter, PipelineResult } from './interfaces';\nimport { RouterEvent } from './router-event';\nimport { RouterConfiguration } from './router-configuration';\n\n/**@internal */\ndeclare module 'aurelia-dependency-injection' {\n interface Container {\n viewModel?: any;\n }\n}\n\nconst logger = LogManager.getLogger('app-router');\n\n/**\n * The main application router.\n */\nexport class AppRouter extends Router {\n\n /**@internal */\n static inject() { return [Container, History, PipelineProvider, EventAggregator]; }\n\n events: EventAggregator;\n /**@internal */\n maxInstructionCount: number;\n /**@internal */\n _queue: NavigationInstruction[];\n /**@internal */\n isActive: boolean;\n\n constructor(container: Container, history: History, pipelineProvider: PipelineProvider, events: EventAggregator) {\n super(container, history); // Note the super will call reset internally.\n this.pipelineProvider = pipelineProvider;\n this.events = events;\n }\n\n /**\n * Fully resets the router's internal state. Primarily used internally by the framework when multiple calls to setRoot are made.\n * Use with caution (actually, avoid using this). Do not use this to simply change your navigation model.\n */\n reset(): void {\n super.reset();\n this.maxInstructionCount = 10;\n if (!this._queue) {\n this._queue = [];\n } else {\n this._queue.length = 0;\n }\n }\n\n /**\n * Loads the specified URL.\n *\n * @param url The URL fragment to load.\n */\n loadUrl(url: string): Promise {\n return this\n ._createNavigationInstruction(url)\n .then(instruction => this._queueInstruction(instruction))\n .catch(error => {\n logger.error(error);\n restorePreviousLocation(this);\n });\n }\n\n /**\n * Registers a viewPort to be used as a rendering target for activated routes.\n *\n * @param viewPort The viewPort. This is typically a element in Aurelia default impl\n * @param name The name of the viewPort. 'default' if unspecified.\n */\n registerViewPort(viewPort: /*ViewPort*/ any, name?: string): Promise {\n // having strong typing without changing public API\n const $viewPort: ViewPort = viewPort;\n super.registerViewPort($viewPort, name);\n\n // beside adding viewport to the registry of this instance\n // AppRouter also configure routing/history to start routing functionality\n // There are situation where there are more than 1 element at root view\n // in that case, still only activate once via the following guard\n if (!this.isActive) {\n const viewModel = this._findViewModel($viewPort);\n if ('configureRouter' in viewModel) {\n // If there are more than one element at root view\n // use this flag to guard against configure method being invoked multiple times\n // this flag is set inside method configure\n if (!this.isConfigured) {\n // replace the real resolve with a noop to guarantee that any action in base class Router\n // won't resolve the configurePromise prematurely\n const resolveConfiguredPromise = this._resolveConfiguredPromise;\n this._resolveConfiguredPromise = () => {/**/};\n return this\n .configure(config =>\n Promise\n .resolve(viewModel.configureRouter(config, this))\n // an issue with configure interface. Should be fixed there\n // todo: fix this via configure interface in router\n .then(() => config) as any\n )\n .then(() => {\n this.activate();\n resolveConfiguredPromise();\n });\n }\n } else {\n this.activate();\n }\n }\n // when a viewport is added dynamically to a root view that is already activated\n // just process the navigation instruction\n else {\n this._dequeueInstruction();\n }\n\n return Promise.resolve();\n }\n\n /**\n * Activates the router. This instructs the router to begin listening for history changes and processing instructions.\n *\n * @params options The set of options to activate the router with.\n */\n activate(options?: NavigationOptions): void {\n if (this.isActive) {\n return;\n }\n\n this.isActive = true;\n // route handler property is responsible for handling url change\n // the interface of aurelia-history isn't clear on this perspective\n this.options = Object.assign({ routeHandler: this.loadUrl.bind(this) }, this.options, options);\n this.history.activate(this.options);\n this._dequeueInstruction();\n }\n\n /**\n * Deactivates the router.\n */\n deactivate(): void {\n this.isActive = false;\n this.history.deactivate();\n }\n\n /**@internal */\n _queueInstruction(instruction: NavigationInstruction): Promise {\n return new Promise((resolve) => {\n instruction.resolve = resolve;\n this._queue.unshift(instruction);\n this._dequeueInstruction();\n });\n }\n\n /**@internal */\n _dequeueInstruction(instructionCount: number = 0): Promise {\n return Promise.resolve().then(() => {\n if (this.isNavigating && !instructionCount) {\n // ts complains about inconsistent returns without void 0\n return void 0;\n }\n\n let instruction = this._queue.shift();\n this._queue.length = 0;\n\n if (!instruction) {\n // ts complains about inconsistent returns without void 0\n return void 0;\n }\n\n this.isNavigating = true;\n\n let navtracker: number = this.history.getState('NavigationTracker');\n let currentNavTracker = this.currentNavigationTracker;\n\n if (!navtracker && !currentNavTracker) {\n this.isNavigatingFirst = true;\n this.isNavigatingNew = true;\n } else if (!navtracker) {\n this.isNavigatingNew = true;\n } else if (!currentNavTracker) {\n this.isNavigatingRefresh = true;\n } else if (currentNavTracker < navtracker) {\n this.isNavigatingForward = true;\n } else if (currentNavTracker > navtracker) {\n this.isNavigatingBack = true;\n } if (!navtracker) {\n navtracker = Date.now();\n this.history.setState('NavigationTracker', navtracker);\n }\n this.currentNavigationTracker = navtracker;\n\n instruction.previousInstruction = this.currentInstruction;\n\n let maxInstructionCount = this.maxInstructionCount;\n\n if (!instructionCount) {\n this.events.publish(RouterEvent.Processing, { instruction });\n } else if (instructionCount === maxInstructionCount - 1) {\n logger.error(`${instructionCount + 1} navigation instructions have been attempted without success. Restoring last known good location.`);\n restorePreviousLocation(this);\n return this._dequeueInstruction(instructionCount + 1);\n } else if (instructionCount > maxInstructionCount) {\n throw new Error('Maximum navigation attempts exceeded. Giving up.');\n }\n\n let pipeline = this.pipelineProvider.createPipeline(!this.couldDeactivate);\n\n return pipeline\n .run(instruction)\n .then(result => processResult(instruction, result, instructionCount, this))\n .catch(error => {\n return { output: error instanceof Error ? error : new Error(error) } as PipelineResult;\n })\n .then(result => resolveInstruction(instruction, result, !!instructionCount, this));\n });\n }\n\n /**@internal */\n _findViewModel(viewPort: ViewPort): ConfiguresRouter | undefined {\n if (this.container.viewModel) {\n return this.container.viewModel;\n }\n\n if (viewPort.container) {\n let container = viewPort.container;\n\n while (container) {\n if (container.viewModel) {\n this.container.viewModel = container.viewModel;\n return container.viewModel;\n }\n\n container = container.parent;\n }\n }\n\n return undefined;\n }\n}\n\nconst processResult = (\n instruction: NavigationInstruction,\n result: PipelineResult,\n instructionCount: number,\n router: AppRouter\n): Promise => {\n if (!(result && 'completed' in result && 'output' in result)) {\n result = result || {} as PipelineResult;\n result.output = new Error(`Expected router pipeline to return a navigation result, but got [${JSON.stringify(result)}] instead.`);\n }\n\n let finalResult: PipelineResult = null;\n let navigationCommandResult = null;\n if (isNavigationCommand(result.output)) {\n navigationCommandResult = result.output.navigate(router);\n } else {\n finalResult = result;\n\n if (!result.completed) {\n if (result.output instanceof Error) {\n logger.error(result.output.toString());\n }\n\n restorePreviousLocation(router);\n }\n }\n\n return Promise.resolve(navigationCommandResult)\n .then(_ => router._dequeueInstruction(instructionCount + 1))\n .then(innerResult => finalResult || innerResult || result);\n};\n\nconst resolveInstruction = (\n instruction: NavigationInstruction,\n result: PipelineResult,\n isInnerInstruction: boolean,\n router: AppRouter\n): PipelineResult => {\n instruction.resolve(result);\n\n let eventAggregator = router.events;\n let eventArgs = { instruction, result };\n if (!isInnerInstruction) {\n router.isNavigating = false;\n router.isExplicitNavigation = false;\n router.isExplicitNavigationBack = false;\n router.isNavigatingFirst = false;\n router.isNavigatingNew = false;\n router.isNavigatingRefresh = false;\n router.isNavigatingForward = false;\n router.isNavigatingBack = false;\n router.couldDeactivate = false;\n\n let eventName: string;\n\n if (result.output instanceof Error) {\n eventName = RouterEvent.Error;\n } else if (!result.completed) {\n eventName = RouterEvent.Canceled;\n } else {\n let queryString = instruction.queryString ? ('?' + instruction.queryString) : '';\n router.history.previousLocation = instruction.fragment + queryString;\n eventName = RouterEvent.Success;\n }\n\n eventAggregator.publish(eventName, eventArgs);\n eventAggregator.publish(RouterEvent.Complete, eventArgs);\n } else {\n eventAggregator.publish(RouterEvent.ChildComplete, eventArgs);\n }\n\n return result;\n};\n\nconst restorePreviousLocation = (router: AppRouter): void => {\n let previousLocation = router.history.previousLocation;\n if (previousLocation) {\n router.navigate(previousLocation, { trigger: false, replace: true });\n } else if (router.fallbackRoute) {\n router.navigate(router.fallbackRoute, { trigger: true, replace: true });\n } else {\n logger.error('Router navigation failed, and no previous location or fallbackRoute could be restored.');\n }\n};\n","/**\n* The status of a Pipeline.\n*/\nexport const enum PipelineStatus {\n Completed = 'completed',\n Canceled = 'canceled',\n Rejected = 'rejected',\n Running = 'running'\n}\n","/**\n * A list of known router events used by the Aurelia router\n * to signal the pipeline has come to a certain state\n */\n// const enum is preserved in tsconfig\nexport const enum RouterEvent {\n Processing = 'router:navigation:processing',\n Error = 'router:navigation:error',\n Canceled = 'router:navigation:canceled',\n Complete = 'router:navigation:complete',\n Success = 'router:navigation:success',\n ChildComplete = 'router:navigation:child:complete'\n}\n","/**\n * Available pipeline slot names to insert interceptor into router pipeline\n */\n// const enum is preserved in tsconfig\nexport const enum PipelineSlotName {\n /**\n * Authorization slot. Invoked early in the pipeline,\n * before `canActivate` hook of incoming route\n */\n Authorize = 'authorize',\n /**\n * Pre-activation slot. Invoked early in the pipeline,\n * Invoked timing:\n * - after Authorization slot\n * - after canActivate hook on new view model\n * - before deactivate hook on old view model\n * - before activate hook on new view model\n */\n PreActivate = 'preActivate',\n /**\n * Pre-render slot. Invoked later in the pipeline\n * Invokcation timing:\n * - after activate hook on new view model\n * - before commit step on new navigation instruction\n */\n PreRender = 'preRender',\n /**\n * Post-render slot. Invoked last in the pipeline\n */\n PostRender = 'postRender'\n}\n","import { Container } from 'aurelia-dependency-injection';\nimport { createOverrideContext, OverrideContext } from 'aurelia-binding';\nimport {\n ViewSlot,\n ViewLocator,\n BehaviorInstruction,\n CompositionTransaction,\n CompositionEngine,\n ShadowDOM,\n SwapStrategies,\n ResourceDescription,\n HtmlBehaviorResource,\n CompositionTransactionNotifier,\n View,\n CompositionTransactionOwnershipToken,\n Controller,\n ViewFactory,\n CompositionContext,\n IStaticResourceConfig,\n IStaticViewConfig\n} from 'aurelia-templating';\nimport {\n Router\n} from 'aurelia-router';\nimport { Origin } from 'aurelia-metadata';\nimport { DOM } from 'aurelia-pal';\nimport { IRouterViewViewPortInstruction, Constructable } from './interfaces';\n\nclass EmptyLayoutViewModel {\n\n}\n\n/**\n * Implementation of Aurelia Router ViewPort. Responsible for loading route, composing and swapping routes views\n */\nexport class RouterView {\n\n /**@internal */\n static inject() {\n return [DOM.Element, Container, ViewSlot, Router, ViewLocator, CompositionTransaction, CompositionEngine];\n }\n\n /**\n * @internal Actively avoid using decorator to reduce the amount of code generated\n *\n * There is no view to compose by default in a router view\n * This custom element is responsible for composing its own view, based on current config\n */\n static $view: IStaticViewConfig = null;\n /**\n * @internal Actively avoid using decorator to reduce the amount of code generated\n */\n static $resource: IStaticResourceConfig = {\n name: 'router-view',\n bindables: ['swapOrder', 'layoutView', 'layoutViewModel', 'layoutModel', 'inherit-binding-context'] as any\n };\n\n /**\n * Swapping order when going to a new route. By default, supports 3 value: before, after, with\n * - before = new in -> old out\n * - after = old out -> new in\n * - with = new in + old out\n *\n * These values are defined by swapStrategies export in aurelia-templating/ aurelia-framework\n * Can be extended there and used here\n */\n swapOrder?: string;\n\n /**\n * Layout view used for this router-view layout, if no layout-viewmodel specified\n */\n layoutView?: any;\n\n /**\n * Layout view model used as binding context for this router-view layout\n * Actual type would be {string | Constructable | object}\n */\n layoutViewModel?: any;\n\n /**\n * Layout model used to activate layout view model, if specified with `layoutViewModel`\n */\n layoutModel?: any;\n\n /**\n * Element associated with this custom element\n */\n readonly element: Element;\n\n /**\n * Current router associated with this \n */\n readonly router: Router;\n\n /**\n * Container at this level\n */\n container: Container;\n\n /**\n * @internal\n * the view slot for adding / removing Routing related views created dynamically\n */\n viewSlot: ViewSlot;\n\n /**\n * @internal\n * Used to mimic partially functionalities of CompositionEngine\n */\n viewLocator: ViewLocator;\n\n /**\n * @internal\n * View composed by the CompositionEngine, depends on layout / viewports/ moduleId / viewModel of routeconfig\n */\n view: View;\n\n /**\n * @internal\n * The view where this `` is placed in\n */\n owningView: View;\n\n /**\n * @internal\n * Composition Transaction of initial composition transaction, when this is created\n */\n compositionTransaction: CompositionTransaction;\n\n /**\n * @internal\n * CompositionEngine instance, responsible for composing view/view model during process changes phase of this \n */\n compositionEngine: CompositionEngine;\n\n /**\n * Composition transaction notifier instance. Created when this router-view composing its instruction\n * for the first time.\n * Null on 2nd time and after.\n * @internal\n */\n compositionTransactionNotifier: CompositionTransactionNotifier;\n\n /**\n * @internal\n */\n compositionTransactionOwnershipToken: CompositionTransactionOwnershipToken;\n\n /**\n * @internal\n */\n overrideContext: OverrideContext;\n\n constructor(\n element: Element,\n container: Container,\n viewSlot: ViewSlot,\n router: Router,\n viewLocator: ViewLocator,\n compositionTransaction: CompositionTransaction,\n compositionEngine: CompositionEngine\n ) {\n this.element = element;\n this.container = container;\n this.viewSlot = viewSlot;\n this.router = router;\n this.viewLocator = viewLocator;\n this.compositionTransaction = compositionTransaction;\n this.compositionEngine = compositionEngine;\n // add this to router view ports lookup based on name attribute\n // when this router is the root router-view\n // also trigger AppRouter registerViewPort extra flow\n this.router.registerViewPort(this, this.element.getAttribute('name'));\n\n // Each process its instruction as a composition transaction\n // there are differences between intial composition and subsequent compositions\n // also there are differences between root composition and child composition\n // mark the first composition transaction with a property initialComposition to distinguish it\n // when the root gets new instruction for the first time\n if (!('initialComposition' in compositionTransaction)) {\n compositionTransaction.initialComposition = true;\n this.compositionTransactionNotifier = compositionTransaction.enlist();\n }\n }\n\n created(owningView: View): void {\n this.owningView = owningView;\n }\n\n bind(bindingContext: any, overrideContext: OverrideContext): void {\n // router needs to get access to view model of current route parent\n // doing it in generic way via viewModel property on container\n this.container.viewModel = bindingContext;\n this.overrideContext = overrideContext;\n }\n\n /**\n * Implementation of `aurelia-router` ViewPort interface, responsible for templating related part in routing Pipeline\n */\n process($viewPortInstruction: any, waitToSwap?: boolean): Promise {\n // have strong typings without exposing it in public typings, this is to ensure maximum backward compat\n const viewPortInstruction = $viewPortInstruction as IRouterViewViewPortInstruction;\n const component = viewPortInstruction.component;\n const childContainer = component.childContainer;\n const viewModel = component.viewModel;\n const viewModelResource = component.viewModelResource as unknown as ResourceDescription;\n const metadata = viewModelResource.metadata;\n const config = component.router.currentInstruction.config;\n const viewPortConfig = config.viewPorts ? (config.viewPorts[viewPortInstruction.name] || {}) : {};\n\n (childContainer.get(RouterViewLocator) as RouterViewLocator)._notify(this);\n\n // layoutInstruction is our layout viewModel\n const layoutInstruction = {\n viewModel: viewPortConfig.layoutViewModel || config.layoutViewModel || this.layoutViewModel,\n view: viewPortConfig.layoutView || config.layoutView || this.layoutView,\n model: viewPortConfig.layoutModel || config.layoutModel || this.layoutModel,\n router: viewPortInstruction.component.router,\n childContainer: childContainer,\n viewSlot: this.viewSlot\n };\n\n // viewport will be a thin wrapper around composition engine\n // to process instruction/configuration from users\n // preparing all information related to a composition process\n // first by getting view strategy of a ViewPortComponent View\n const viewStrategy = this.viewLocator.getViewStrategy(component.view || viewModel);\n if (viewStrategy && component.view) {\n viewStrategy.makeRelativeTo(Origin.get(component.router.container.viewModel.constructor).moduleId);\n }\n\n // using metadata of a custom element view model to load appropriate view-factory instance\n return metadata\n .load(childContainer, viewModelResource.value, null, viewStrategy, true)\n // for custom element, viewFactory typing is always ViewFactory\n // for custom attribute, it will be HtmlBehaviorResource\n .then((viewFactory: ViewFactory | HtmlBehaviorResource) => {\n // if this is not the first time that this is composing its instruction\n // try to capture ownership of the composition transaction\n // child will not be able to capture, since root typically captures\n // the ownership token\n if (!this.compositionTransactionNotifier) {\n this.compositionTransactionOwnershipToken = this.compositionTransaction.tryCapture();\n }\n\n if (layoutInstruction.viewModel || layoutInstruction.view) {\n viewPortInstruction.layoutInstruction = layoutInstruction;\n }\n\n const viewPortComponentBehaviorInstruction = BehaviorInstruction.dynamic(\n this.element,\n viewModel,\n viewFactory as ViewFactory\n );\n viewPortInstruction.controller = metadata.create(childContainer, viewPortComponentBehaviorInstruction);\n\n if (waitToSwap) {\n return null;\n }\n\n this.swap(viewPortInstruction);\n });\n }\n\n swap($viewPortInstruction: any): void | Promise {\n // have strong typings without exposing it in public typings, this is to ensure maximum backward compat\n const viewPortInstruction: IRouterViewViewPortInstruction = $viewPortInstruction;\n const viewPortController = viewPortInstruction.controller;\n const layoutInstruction = viewPortInstruction.layoutInstruction;\n const previousView = this.view;\n\n // Final step of swapping a ViewPortComponent\n const work = () => {\n const swapStrategy = SwapStrategies[this.swapOrder] || SwapStrategies.after;\n const viewSlot = this.viewSlot;\n\n swapStrategy(\n viewSlot,\n previousView,\n () => Promise.resolve(viewSlot.add(this.view))\n ).then(() => {\n this._notify();\n });\n };\n\n // Ensure all users setups have been completed\n const ready = (owningView_or_layoutView: View) => {\n viewPortController.automate(this.overrideContext, owningView_or_layoutView);\n const transactionOwnerShipToken = this.compositionTransactionOwnershipToken;\n // if this router-view is the root of a normal startup via aurelia.setRoot\n // attemp to take control of the transaction\n\n // if ownership can be taken\n // wait for transaction to complete before swapping\n if (transactionOwnerShipToken) {\n return transactionOwnerShipToken\n .waitForCompositionComplete()\n .then(() => {\n this.compositionTransactionOwnershipToken = null;\n return work();\n });\n }\n\n // otherwise, just swap\n return work();\n };\n\n // If there is layout instruction, new to compose layout before processing ViewPortComponent\n // layout controller/view/view-model is composed using composition engine APIs\n if (layoutInstruction) {\n if (!layoutInstruction.viewModel) {\n // createController chokes if there's no viewmodel, so create a dummy one\n // but avoid using a POJO as it creates unwanted metadata in Object constructor\n layoutInstruction.viewModel = new EmptyLayoutViewModel();\n }\n\n // using composition engine to create compose layout\n return this.compositionEngine\n // first create controller from layoutInstruction\n // and treat it as CompositionContext\n // then emulate slot projection with ViewPortComponent view\n .createController(layoutInstruction as CompositionContext)\n .then((layoutController: Controller) => {\n const layoutView = layoutController.view;\n ShadowDOM.distributeView(viewPortController.view, layoutController.slots || layoutView.slots);\n // when there is a layout\n // view hierarchy is: owner view -> layout view -> ViewPortComponent view\n layoutController.automate(createOverrideContext(layoutInstruction.viewModel), this.owningView);\n layoutView.children.push(viewPortController.view);\n return layoutView || layoutController;\n })\n .then((newView: View | Controller) => {\n this.view = newView as View;\n return ready(newView as View);\n });\n }\n\n // if there is no layout, then get ViewPortComponent view ready as view property\n // and process controller/swapping\n // when there is no layout\n // view hierarchy is: owner view -> ViewPortComponent view\n this.view = viewPortController.view;\n\n return ready(this.owningView);\n }\n\n /**\n * Notify composition transaction that this router has finished processing\n * Happens when this is the root router-view\n * @internal\n */\n _notify() {\n const notifier = this.compositionTransactionNotifier;\n if (notifier) {\n notifier.done();\n this.compositionTransactionNotifier = null;\n }\n }\n}\n\n/**\n* Locator which finds the nearest RouterView, relative to the current dependency injection container.\n*/\nexport class RouterViewLocator {\n\n /*@internal */\n promise: Promise;\n\n /*@internal */\n resolve: (val?: any) => void;\n\n /**\n * Creates an instance of the RouterViewLocator class.\n */\n constructor() {\n this.promise = new Promise((resolve) => this.resolve = resolve);\n }\n\n /**\n * Finds the nearest RouterView instance.\n * @returns A promise that will be resolved with the located RouterView instance.\n */\n findNearest(): Promise {\n return this.promise;\n }\n\n /**@internal */\n _notify(routerView: RouterView): void {\n this.resolve(routerView);\n }\n}\n","import { IStaticResourceConfig } from 'aurelia-templating';\nimport { Router } from 'aurelia-router';\nimport { DOM } from 'aurelia-pal';\nimport * as LogManager from 'aurelia-logging';\n\nconst logger = LogManager.getLogger('route-href');\n\n/**\n * Helper custom attribute to help associate an element with a route by name\n */\nexport class RouteHref {\n\n /*@internal */\n static inject() {\n return [Router, DOM.Element];\n }\n\n /**\n * @internal Actively avoid using decorator to reduce the amount of code generated\n */\n static $resource: IStaticResourceConfig = {\n type: 'attribute',\n name: 'route-href',\n bindables: [\n { name: 'route', changeHandler: 'processChange', primaryProperty: true },\n { name: 'params', changeHandler: 'processChange' },\n 'attribute'\n ] as any // type definition of Aurelia templating is wrong\n };\n\n /**\n * Current router of this attribute\n */\n readonly router: Router;\n\n /**\n * Element this attribute is associated with\n */\n readonly element: Element;\n\n /**@internal */\n isActive: boolean;\n\n /**\n * Name of the route this attribute refers to. This name should exist in the current router hierarchy\n */\n route: string;\n\n /**\n * Parameters of this attribute to generate URL.\n */\n params: Record;\n\n /**\n * Target property on a custom element if this attribute is put on a custom element\n * OR an attribute if this attribute is put on a normal element\n */\n attribute: string;\n\n constructor(\n router: Router,\n element: Element\n ) {\n this.router = router;\n this.element = element;\n this.attribute = 'href';\n }\n\n bind() {\n this.isActive = true;\n this.processChange();\n }\n\n unbind() {\n this.isActive = false;\n }\n\n attributeChanged(value: any, previous: any) {\n if (previous) {\n this.element.removeAttribute(previous);\n }\n\n return this.processChange();\n }\n\n processChange() {\n return this.router\n .ensureConfigured()\n .then((): null => {\n if (!this.isActive) {\n // returning null to avoid Bluebird warning\n return null;\n }\n const element = this.element as Element & { au: any };\n\n const href = this.router.generate(this.route, this.params);\n\n if (element.au.controller) {\n element.au.controller.viewModel[this.attribute] = href;\n } else {\n element.setAttribute(this.attribute, href);\n }\n\n // returning null to avoid Bluebird warning\n return null;\n })\n .catch((reason: any) => {\n logger.error(reason);\n });\n }\n}\n\n","import { Router, AppRouter, RouteLoader } from 'aurelia-router';\nimport { TemplatingRouteLoader } from './route-loader';\nimport { RouterView } from './router-view';\nimport { RouteHref } from './route-href';\nimport { IFrameworkConfiguration } from './interfaces';\n\nexport function configure(config: IFrameworkConfiguration) {\n config\n .singleton(RouteLoader, TemplatingRouteLoader)\n .singleton(Router, AppRouter)\n .globalResources(\n RouterView,\n RouteHref\n );\n\n config.container.registerAlias(Router, AppRouter);\n}\n\nexport {\n TemplatingRouteLoader,\n RouterView,\n RouteHref\n};\n"]}