svelte store with a websocket backend
npm install svelte-websocket-store










Svelte store with a websocket backend
``js
import websocketStore from "svelte-websocket-store";
const initialValue = { };
export const myStore = websocketStore("wss://mydomain.com/ws1", initialValue, ['option 1', 'option 2']);
// send JSON to websocket server
$myStore = { content: "to be saved", other_values: "all" };
// receive JSON from server (push)
let response = $myStore;
`
* active
* Parameters
* Key
* Properties
* BaseRouter
* Parameters
* Properties
* component
* value
* path
* path
* Parameters
* replace
* Parameters
* push
* Parameters
* finalizePush
* Parameters
* continue
* Parameters
* abort
* Parameters
* subscribe
* Parameters
* updateActive
* Parameters
* addRoute
* Parameters
* routeFor
* Parameters
* pathFor
* Parameters
* BaseTransition
* searchParams
* searchParams
* Parameters
* nest
* Parameters
* continue
* abort
* Parameters
* DetailRoute
* Properties
* master
* first
* last
* previous
* next
* Entitlement
* Parameters
* Guard
* enter
* Parameters
* leave
* Parameters
* redirectGuard
* Parameters
* sequenceGuard
* Parameters
* parallelGuard
* Parameters
* websocketStore
* Parameters
* login
* Parameters
* handleFailedResponse
* Parameters
* MasterRoute
* Parameters
* Properties
* nullGuard
* RootRoute
* hasParams
* path
* propertyMapping
* guard
* SkeletonRoute
* Parameters
* Properties
* enter
* Parameters
* leave
* Parameters
* isAcceptable
* Parameters
* propertiesFor
* Parameters
* commonAncestor
* Parameters
* valueFor
* Parameters
* value
* propertyMapping
* objectInstance
* ValueStoreRoute
* SessionData
* Properties
* msecsRequiredForRefresh
* supportedTokenTypes
* Session
* Parameters
* Properties
* update
* Parameters
* refresh
* authorizationHeader
* isValid
* invalidate
* hasEntitlement
* Parameters
* subscribe
* Parameters
* decode
* Parameters
* Transition
* Parameters
* Properties
* start
* end
* redirect
* Parameters
* abort
* Parameters
* findClosestAttribute
* Parameters
* dispatchNavigationEvent
* Parameters
* nameValueStore
* Parameters
* Properties
* WaitingGuard
* Parameters
* See: {Router.updateActive}
Keeps the node active state in sync.
* node Element router
* Router
Keys also act as svelte stores and can be subscribed.
`js`
export const article = derived(
[articles, router.keys.article],
([$articles, $id], set) => {
set($articles.find(a => a.id === $id));
return () => {};
}
);
Type: Object
* name string value
* any subscriptions
* Set
Extends BaseTransition
key subscriptions:
`js`
const aKey = router.keys.aKey;
$aKey // fired if value of aKey changes
* routes Array\base
* string url (optional, default new URL("../",import.meta.url).pathname)
* linkNodes Set<Node> nodes having their active state updatedroutes
* Array\keys
* Object collected keys of all routesparams
* Object value mapping from keys (from current route)route
* Route currentnested
* Transition ongoing nested transitionbase
* string url
Current component.
Either from a nested transition or from the current route
Returns SvelteComponent
Value if the current route
Returns any
Returns string url path with fragment & query
Replace current route.
#### Parameters
* path string
Replace current route without updating the state.
#### Parameters
* path string
Returns Object former state
Leave current route and enter route for given path.
The work is done by a Transition.
#### Parameters
* path string where to go
Returns Transition running transition
Called from a Transition to manifest the new destination.
If path is undefined the Transition has been aborderd.
#### Parameters
* path string
Continue a transition to its original destination.
Shortcut for this.transition.continue().
If there is no transition ongoing and a fallbackPath is
present, it will be entered.
Otherwise does nothing.
#### Parameters
* fallbackPath string
Abort a transition.
Shortcut for this.transition.abort()
If there is no transition ongoing and a fallbackPath is
present it will be entered.
Otherwise does nothing.
#### Parameters
* fallbackPath string
Router subscription.
Changes in the current route will trigger a update
#### Parameters
* subscription Function
Update the active state of a node.
A node is considered active if it shared the path prefix with the current route.
#### Parameters
* node Element
Add a new Route.
#### Parameters
* route Route
Find Route for a given value.
#### Parameters
* value any
Returns Route able to support given value
Find path for a given value.
#### Parameters
* value any suffix
* string to be appended
Returns string path + suffix
Deliver url search params form the current location.
Returns URLSearchParams as extracted from the path
Replaces the search part of the path with the given searchParams.
#### Parameters
* searchParams (URLSearchParams | Object)
Add another transition nesting level.
Starts a transition from the given factory.
#### Parameters
* path string factory
* Transition
Continue a nested route to its original destination.
Does nothing if the transition has not been nested.
Abort the transition.
#### Parameters
* error
Returns Promise<boolean> truen in case there was a nesten transition
Extends ValueStoreRoute
Route to represent a slice of the masters list of values.
* master Route route holding the master records
Route holding the list ov values
Returns Route our master
Returns Promise\
Returns any last entry
Returns any previous value
Returns Promise\
Enforces conditions of routes
Like the presents of values in the context
Called while entering a route (current outlet is not yet set)
#### Parameters
* transition Transition
Called before leaving a route
#### Parameters
* transition Transition
Redirects to a given path if condition is met.
* path string condition
* Function redirects when returning true
Execute guards in a sequence.
* children Iterable<Guard>
Execute guards in a parallel.
* children Iterable<Guard>
Create a writable store based on a web-socket.
Data is transferred as JSON.
Keeps socket open (reopens if closed) as long as there are subscriptions.
* url string the WebSocket urlinitialValue
* any store value used before 1st. response from server is presentsocketOptions
* Array<string> transparently passed to the WebSocket constructor
Returns Store
Bring session into the valid state by calling the authorization endpoint
and asking for a access\_token.
Executes a POST on the endpoint url expecting username, and password as json
* session Session to be openedendpoint
* string authorization urlusername
* string id of the userpassword
* string user credentialstokenmap
* Object token names in response to internal known values (optional, default defaultTokenMap)
Returns Promise<(string | undefined)> error message in case of failure or undefined on success
Extract error description from response.
* response Response
Extends SkeletonRoute
Route holding a ordered collection of values.
* path options
*
* value Array\
Default empty guard does nothing.
Route at the root of the tree.
This route has no parent.
All other routes are below of this one.
Are there parameters in the path.
Returns boolean true if route has parameters (:key)
Returns string empty as we are the root
Returns Object empty object
Returns Guard empty guard which does nothing
Extends RootRoute
Route
Subscriptions on Routes fire when the route value changes.
* path options
* (optional, default {})
* path string full path of the Route including all parentscomponent
* SvelteComponent target to showlinkComponent
* SvelteComponent content for ObjectLinkpropertyMapping
* Object Map properties to object attributespriority
Keys are the property names and values are the keys in the resulting object.
* number keys
* Array<string> as found in the pathregex
* RegEx value
* any
Enter the route from a former one.
All parent routes up to the common ancestor are entered first.
#### Parameters
* transition Transition untilRoute
* Route the common ancestor with the former route
Leave the route to a new one.
All parent routes up to the common ancestor are left.
#### Parameters
* transition Transition untilRoute
* Route the common ancestor with the future route
Check if value and properties are acceptable for the route.
#### Parameters
* value any to be placed into routeproperties
* Object as presented in the route
Returns boolean true if value can be accepted
Extract properties from a value.
All property values must be strings.
#### Parameters
* value any source of the properties
Returns (Object | undefined) properties extracted from given value
Find common ancestor with an other Route.
#### Parameters
* other Route
Returns (Route | undefined) common ancestor Route between receiver and other
Deliver value for a given set of properties of the transition.
Default implemantation asks the parent route.
#### Parameters
* transition Transition
Returns any for matching properties
Deliver route value.
Default implemantation asks the parent route.
Returns any
Deliver property mapping.
Default implemantation asks the parent route.
Returns Object for matching properties
Default implemantation asks the parent route.
Extends SkeletonRoute
Route holding a single value
Data as preserved in the backing store.
Type: Object
* username string user name (id)access_token
* string JWT tokenrefresh_token
* string JWT token
Time required to execute a refresh
Type: number
User session.
To create as session backed by browser local storage.
`js`
let session = new Session(localStorage);
or by browser session storage
`js`
let session = new Session(sessionStorage);
* store SessionData (optional, default localStorage)
* entitlements Set<string> subscriptions
* Set<Object> store subscriptionsexpirationDate
* Date when the access token expiresaccess_token
* string token itselfrefresh_token
* string refresh token
Consume auth response data and reflect internal state.
#### Parameters
* data Object
Refresh with refresh\_token.
Returns Promise<boolean> true if refresh was succcessfull false otherwise
Http header suitable for fetch.
Returns Object header The http header.
Returns string header.Authorization The Bearer access token.
As long as the expirationTimer is running we must be valid.
Returns boolean true if session is valid (not expired)
Remove all tokens from the session and the backing store.
Check presence of an entitlement.
#### Parameters
* name string of the entitlement
Returns boolean true if the named entitlement is present
Fired when the session changes.
#### Parameters
* subscription Function
Extract and decode the payload.
* token string
Returns Object payload object
Extends BaseTransition
Transition between routes.
* router Router path
* string new destination
* router Router path
* string new destination
Start the transition
* leave old route
* find matching target route @see matcher()
* enter new route
* set params
* set current route
* See: Router.finalizePush
Cleanup transition.
Update Nodes active state
Halt current transition and go to another route.
To proceed with the original route call continue())
The original transition will keept in place and can be continued afterwards.
#### Parameters
* path string new route to enter temporary
Bring back the router into the state before the transition has started.
All nested transitions also will be termniated.
#### Parameters
* e (Exception | undefined)
Walks up the dom tree parents unti a node with a given attribute is found or the root node is reached.
* element Element attributeName
* string
Dispatches a NAVIGATION\_EVENT with pathname and hash
* event Event
Create a named object which also acts as a store.
* name string value
* any initial value
* value any
Returns Store
Extends Guard
Shows a component during transition.
* component SvelteComponent to show up during th transitionrampUpTime
* number initial delay for the componnt to show up (optional, default 300)
With npm do:
`shell`
npm install svelte-websocket-store
With yarn do:
`shell`
yarn add svelte-websocket-store
`sh``
export BROWSER=safari|chrome|...
npm|yarn test
BSD-2-Clause