This is the multi-page printable view of this section. Click here to print.

Return to the regular view of this page.

Documentation

Documentation for altseven, the client-side JavaScript framework. Current release: 9.1.4.

altseven is a reactive framework for building single-page applications with plain JavaScript and ES6 template literals — no JSX, no build step, no virtual DOM.

If you are new to altseven, start here:

  1. Overview — what altseven is and whether it fits your project
  2. Getting Started — install and run a minimal application
  3. Your First App — a complete working application
  4. Core Concepts — the Application object, views, events and routing
  5. The Data Layer — entities, services and data providers

1 - Configuring Your Application

Every option accepted by the Application constructor, with defaults.

The complete options reference for new Application( options ). All options have defaults; the only required option for a working app is remote: {} (or a populated remote config).

The options structure

import { Application } from "/lib/altseven/dist/a7.js";

export const myApp = new Application( {
	name: "myapp",
	auth: { sessionTimeout: 15 * 60 * 1000 },
	console: { enabled: false },
	events: {},
	logging: { logLevel: "ERROR,FATAL,INFO", toBrowserConsole: false },
	model: "altseven",
	remote: {
		loginURL: "",
		logoutURL: "",
		refreshURL: "",
		useTokens: true,
		tokenType: "X-Token",
		credentials: "same-origin",
		modules: {}
	},
	router: undefined,             // omit entirely to run without routing
	security: { enabled: true, userArgs: {} },
	services: [],
	ui: {
		enableMouseTracking: false,
		mouseTrackingDeBounceTime: 100,
		renderer: "templateLiterals",
		debounceTime: 18,
		timeout: 600000,
		cacheTemplates: true
	}
} );

Reference

name (string, default "a7")

The application’s name. Naming the exported instance (export const myApp) gives your code its namespace; name appears in logs.

auth.sessionTimeout (ms, default 900000 — 15 minutes)

How often the framework calls the refresh endpoint to keep the session alive.

console

The in-browser console that displays log messages in real time — including back-end logs relayed over WebSocket.

Key Type / default Meaning
enabled boolean, false Create the console at init
wsServer string, "" WebSocket URL to receive remote log messages
container object, FloatingPane if gadget-ui present Container component
top, left integer, 100 / 500 Position
width, height integer, 500 / 300 Size

events (object, {})

Topics to subscribe at init: { "topic.name": handlerFunction }. A null value declares the topic without a handler (a view can subscribe later).

logging

Key Type / default Meaning
logLevel string, "ERROR,FATAL,INFO" Enabled levels: TRACE,DEBUG,INFO,WARN,ERROR,FATAL
toBrowserConsole boolean, false Mirror log messages to console

Usage: myApp.log.info( "..." ), myApp.log.debug( "..." ), myApp.log.error( "msg", error ).

model (string or object, default "altseven")

"altseven" uses the built-in model (with undo/redo/rewind/fast-forward history); "gadgetui" uses the gadget-ui model; or pass a custom object with the same get/set/exists/bind methods.

remote

Required — pass at least remote: {}. Without the option, init() throws.

Key Type / default Meaning
modules object, {} Your remote modules (see Remote Modules)
loginURL string, "" Login endpoint (HTTP Basic auth)
logoutURL string, "" Logout endpoint
refreshURL string, "" Session refresh endpoint
useTokens boolean, true Send session tokens with secure calls
tokenType string, "X-Token" "X-Token" header, or "access_token" for Authorization: Bearer
credentials string, "same-origin" fetch credentials mode; "include" for SAML/cross-origin cookie SSO

router (object, optional)

Omit the option entirely to run without routing. Otherwise:

Key Type / default Meaning
routes array [ path, handler ] pairs (see Routing)
useEvents boolean, true Handlers are event topic names (vs. functions)

security

Key Type / default Meaning
enabled boolean, true Run the auth check at init and manage the session user
userArgs object, {} Default fields for the User object, e.g. { userID: "" }

With security enabled, init() awaits security.isAuthenticated() and sets myApp.authenticated and myApp.user before your startup code continues.

services (array, [])

Service instances to register automatically at init — equivalent to calling myApp.services.register( service ) for each.

ui

Key Type / default Meaning
renderer string, "templateLiterals" Also "Mustache" / "Handlebars" (auto-detected if those libraries are loaded)
debounceTime ms, 18 Debounce window for render events
timeout ms, 600000 Stale-view check interval for transient views (10 minutes)
cacheTemplates boolean, true App-wide master switch for template caching; per-view props.cacheTemplate is still opt-in (default false)
enableMouseTracking boolean, false Track the mouse position (myApp.ui.mousePosition), debounced by mouseTrackingDeBounceTime

Conventional properties

Set by the framework (not options): myApp.constants (your app-wide constants) and myApp.user (the session user when security is enabled).

2 - Overview

What altseven is, how it works, and whether it fits your project.

altseven is a reactive JavaScript framework for building single page applications — using core JavaScript language constructs, with no transpiling and no build step. Current release: 9.1.4 (see the release history).

Just what is altseven?

altseven is a reactive framework intended for building single page applications (SPA). It simplifies SPA development by relying on core JavaScript constructs — ES6 classes, ES modules, and template literals for templating — rather than extensions like JSX that require transpiling before deployment.

altseven has no runtime dependencies and no compile step: you write ES modules, the browser loads them, and templates are plain template literals that produce HTML strings. There is no virtual DOM; when a view’s state changes, its template is re-evaluated and its container element is repainted, with a render queue and configurable debouncing to keep repaints cheap.

Since version 8.0, the framework is organized as ES6 classes. You create an Application instance, which initializes the modules your app needs — logging, model, remote (AJAX/WebSocket), events, security, router and UI manager — and exposes them as properties of that instance. Your application object becomes the namespace for your code.

Why would I want it?

  • What it is good for:

    • A declarative View class with state, templates and child views
    • A data layer with Entity, Service and DataProvider classes providing schema validation, client-side caching, data binding and request deduplication
    • A built-in remote module for JSON APIs, with token-based authentication and an optional credentials mode for SAML/cookie-based SSO
    • Managed WebSocket sessions with exponential backoff, ping/pong zombie detection and online/visibility-aware reconnects (9.1.0)
    • A Trie-based client-side URL router with parameters and browser history
    • A publish/subscribe event system with isolated listeners
    • A model with undo/redo/rewind/fast-forward history
    • Logging with multiple levels and an optional in-browser console fed over WebSocket, so you can watch back-end logs in real time
    • Error capture
  • What it is not good for: projects that want a compiler, bundler, tree shaking or code obfuscation. altseven development ships source modules directly to the browser.

  • What it is not yet proven for: very large scale deployments. If you need a framework with a long track record at scale, look at React or Vue.

Design principles

  1. Core language constructs over tooling. Templates are template literals; components are ES6 classes; modules are ES modules. If you know modern JavaScript, you already know most of altseven.
  2. Reactivity without a virtual DOM. Views declare a template that reads their state. Calling setState() schedules a debounced repaint of exactly that view. Child views render when their parent paints.
  3. One cache, one source of truth. Services cache entities in the model and notify data providers when entities change, so views bound to the same data stay in sync without manual plumbing.

Where should I go next?

3 - Authentication Tutorial

A complete login flow: options, a login view, and the events that wire it together.

Build a login form and wire it to the framework’s built-in authentication, with a protected main view.

1. Configure the application

import { Application } from "/lib/altseven/dist/a7.js";

export const myApp = new Application( {
	name: "myapp",
	remote: {
		loginURL: "/api/auth/login",
		logoutURL: "/api/auth/logout",
		refreshURL: "/api/auth/refresh",
		useTokens: true,
		tokenType: "X-Token"
	},
	security: {
		enabled: true,
		userArgs: { userID: "" }
	}
} );

With security.enabled, await myApp.init() performs the auth check: it calls the refresh endpoint and sets myApp.authenticated and myApp.user. Your startup function can branch on the result.

2. Structure the app around the login state

export let loginForm;
export let main;

export async function application() {
	try {
		await myApp.init();

		loginForm = LoginForm( { id: "loginForm", selector: "#loginForm" } );
		main = Main( { id: "main", selector: "#main" } );

		if( myApp.authenticated ) {
			showApp();
		} else {
			showLogin();
		}
	} catch( e ) {
		console.error( "App init failed:", e );
	}
}

function showLogin() {
	// toggle mount-point visibility (plain DOM, not view state — these are
	// static containers in index.html)
	document.querySelector( "#loginForm" ).style.display = "block";
	document.querySelector( "#main" ).style.display = "none";
}

function showApp() {
	document.querySelector( "#loginForm" ).style.display = "none";
	document.querySelector( "#main" ).style.display = "block";
	main.setState( { user: myApp.user } );
}

3. The login view

import { myApp } from "./app.js";
import { View } from "/lib/altseven/dist/a7.js";

export function LoginForm( props ) {

	const loginForm = new View( props );

	loginForm.state = { username: "", password: "", message: "" };

	loginForm.template = function() {
		const state = loginForm.getState();
		return `
		<form data-onsubmit="handleLogin">
			<h2>Sign in</h2>
			${ state.message ? `<p class="error">${ state.message }</p>` : "" }
			<input type="text" name="username" value="${ state.username }"
				placeholder="Username" autocomplete="username">
			<input type="password" name="password" value=""
				placeholder="Password" autocomplete="current-password">
			<button type="submit">Sign in</button>
		</form>`;
	};

	loginForm.eventHandlers = {
		handleLogin: function( event ) {
			event.preventDefault();
			const form = event.target;
			loginForm.setState( { message: "" } );

			myApp.events.publish( "auth.login", {
				username: form.elements.username.value,
				password: form.elements.password.value,
				success: function( json ) {
					showApp();
				},
				failure: function( json ) {
					loginForm.setState( {
						message: json.message || "Login failed",
						username: form.elements.username.value
					} );
				}
			} );
		}
	};

	myApp.ui.register( loginForm );
	return loginForm;
}

The auth.login publisher (built into the framework) POSTs to loginURL with HTTP Basic auth headers. On { success: true, user } it stores the token and the user, then invokes your success; on { success: false } it invokes your failure with the JSON body.

4. Success and failure as routes or events

Instead of functions, success/failure can name an event topic or a route:

myApp.events.publish( "auth.login", {
	username, password,
	success: "auth.loginSuccess",     // event topic...
	failure: "auth.loginFailure"
} );
myApp.events.subscribe( "auth.loginSuccess", function( json ) {
	showApp();
} );

…or, when the router is configured, a route path — the router opens it and the mapped event fires:

myApp.events.publish( "auth.login", {
	username, password,
	success: "/",      // router destination
	failure: "/login"
} );

5. The back end contract

A minimal Node/Express implementation of the three endpoints:

// POST /api/auth/login
//   Authorization: Basic base64(user:pass)   (set by the framework)
//   Body: { "rememberMe": false }
app.post( "/api/auth/login", ( req, res ) => {
	const [ user, pass ] = basicAuthCredentials( req );
	if( !checkCredentials( user, pass ) ) {
		return res.json( { success: false, message: "Invalid credentials" } );
	}
	res.set( "X-Token", issueToken( user ) );       // framework reads this header
	res.json( { success: true, user: { userID: 7, name: user } } );
} );

// GET /api/auth/refresh  (token attached by the framework)
app.get( "/api/auth/refresh", ( req, res ) => {
	const user = validateToken( req.header( "X-Token" ) );
	if( !user ) return res.status( 401 ).end();
	res.json( { authenticated: true, user } );       // 401 → authenticated: false
} );

// POST /api/auth/logout
app.post( "/api/auth/logout", ( req, res ) => {
	revokeToken( req.header( "X-Token" ) );
	res.json( { success: true } );
} );

6. Logout

myApp.events.publish( "auth.logout", {
	success: function( json ) {
		showLogin();
	}
} );

On success the framework invalidates the session (token cleared, user reset) before invoking your handler.

Common pitfalls

  • success/failure strings depend on the router. With a router configured, plain strings are treated as route destinations; without one, they are event topics. Pass functions when you want to be explicit.
  • The login view keeps re-rendering while typing. Don’t setState() on every keystroke from the password field; read input values from event.target.elements in the submit handler (as above).
  • A 401 from refresh at startup is normal for logged-out visitors — myApp.authenticated is simply false; it is not an error condition.

4 - Getting Started

Install altseven and run a minimal application.

Install the framework, serve it to the browser, and run your first application.

Prerequisites

altseven is a client-side JavaScript framework. It runs in the browser and is typically served by a web server such as NGINX, Apache or Express. You need:

  • Node.js (for npm install and for running a dev server)
  • A modern browser with ES module support

Installation

Install via npm:

$ npm install altseven

or clone the source from the Peopoli git server:

$ git clone https://git.peopoli.com/code/altseven

Either way, the browser-ready build lives in the dist/ folder:

File Purpose
dist/a7.js The framework, as a single ES module
dist/a7.min.js Minified build
dist/a7.css Base styles used by some framework features

Serve the framework to the browser

Your application imports the framework with an ES module import, so dist/a7.js must be reachable from the browser at a stable URL. Two common setups:

npm install — serve node_modules/altseven under an alias, e.g. with Express:

app.use( "/lib/altseven", express.static( "node_modules/altseven" ) );

git clone / vendored copy — copy (or symlink) the framework folder into your project so that /lib/altseven/dist/a7.js resolves.

A minimal application

An altseven application needs three things: an HTML page with a mount point, an Application instance, and a registered view.

Two rules apply from the very first line of code:

index.html

<!doctype html>
<html>
	<head>
		<title>altseven — hello</title>
		<script type="module">
			import { application } from "./app.js";
			application();
		</script>
	</head>
	<body>
		<div name="main"></div>
	</body>
</html>

app.js

import { Application, View } from "/lib/altseven/dist/a7.js";

export const myApp = new Application( {
	name: "hello",
	security: { enabled: false },
	remote: {}
} );

export async function application() {
	try {
		// creates the modules; nothing above this line may use myApp.ui etc.
		await myApp.init();

		const hello = new View( {
			id: "hello",
			selector: "div[name='main']"
		} );
		hello.state = { text: " World!" };
		hello.template = function() {
			return `<h3>Hello ${ hello.state.text }</h3>`;
		};
		myApp.ui.register( hello );

		myApp.log.info( "App initialized." );
	} catch( e ) {
		console.error( "App init failed:", e );
	}
}

Serve the directory (any static server works — just make sure /lib/altseven resolves) and open the page. You should see Hello World!

$ npx http-server . -p 8417

What just happened?

  1. new Application( options ) created the application shell and normalized the options. With security: { enabled: false }, no authentication check runs at startup. (See Configuring Your Application.)
  2. await myApp.init() initialized the modules: logging, model, remote, events, UI manager.
  3. new View( props ) created a view with an id, a selector pointing at the <div name="main"> mount point, a state object, and a template function returning an HTML string.
  4. myApp.ui.register( hello ) registered the view with the UI manager, which enqueued it for rendering into its selector.

Organizing larger applications

As an application grows, the convention is to move views into their own modules that import the application instance back from app.js:

// hello.js
import { myApp } from "./app.js";
import { View } from "/lib/altseven/dist/a7.js";

export function Hello( props ) {
	const hello = new View( props );
	// ... state, template, event handlers ...
	myApp.ui.register( hello );
	return hello;
}

This circular import is safe because the application instance is only used inside functions, never at module evaluation time — by the time Hello() runs, app.js has finished evaluating and init() has completed.

Continue with Your First App to build a complete application with events, routing and views.

4.1 - Your First App

Build a complete, runnable altseven application with views, events and routing.

This tutorial builds a small but complete note-taking app: multiple views, child views, template event handlers, pub/sub events and URL routing. It runs entirely in the browser with no back end — and every line of it has been verified against altseven 9.1.4.

Project layout

notes-app/
├── index.html
└── js/
    ├── app.js        # bootstrap: Application, subscriptions, views, routing
    ├── notes.js      # state + actions for the notes data
    └── views.js      # view components

Serve the folder with any static server, with the framework available at /lib/altseven/dist/a7.js (see Getting Started).

index.html

<!doctype html>
<html>
	<head>
		<title>altseven — notes</title>
		<script type="module">
			import { application } from "./js/app.js";
			application();
		</script>
	</head>
	<body>
		<div id="app"></div>
	</body>
</html>

Every mount point needs a matching selector: the view’s props.selector must resolve to a node that exists in the page (or is created by a parent view’s template). If a top-level selector never resolves, the view is silently unregistered — this is the single most common altseven mistake.

app.js

The application module wires everything together. Note the shape:

  • Module scope creates the Application (which only stores options and logging — see the Getting Started warnings) and declares placeholders for the views.
  • Inside application(), after await myApp.init(), we subscribe to events, create the views, and route the current URL.
import { Application } from "/lib/altseven/dist/a7.js";
import { notes } from "./notes.js";
import { App, NotesList } from "./views.js";

export const myApp = new Application( {
	name: "notes",
	security: { enabled: false },
	remote: {},
	logging: { logLevel: "ERROR,FATAL,INFO", toBrowserConsole: true },
	router: {
		routes: [
			[ "/", "app.home" ],
			[ "/notes/:noteID", "app.note" ]
		]
	}
} );

// these exist only after init(); views are created inside application()
export let app;
export let notesList;

export async function application() {
	try {
		await myApp.init();

		// pub/sub wiring
		myApp.events.subscribe( "notes.changed", () => {
			notesList.setState( { items: notes.all() } );
		} );
		myApp.events.subscribe( "app.home", () => {
			notesList.setState( { items: notes.all() } );
		} );
		myApp.events.subscribe( "app.note", ( params ) => {
			notesList.setState( { items: notes.all(), selected: params.noteID } );
		} );

		// views: the parent renders into #app; the child renders into
		// the #notesList div that the parent's template creates
		app = App( { id: "app", selector: "#app" } );
		notesList = NotesList( {
			id: "notesList",
			parentID: "app",
			selector: "#notesList"
		} );

		// routes are NOT matched automatically on page load — do it here
		myApp.router.match( document.location.pathname + document.location.search );
	} catch( e ) {
		console.error( "App init failed:", e );
	}
}

Two things to notice:

  • Routes map paths to events. [ "/notes/:noteID", "app.note" ] declares a URL pattern with a parameter; when the URL matches, the app.note event is published with the extracted parameters (plus anything passed to router.open()) as its payload.
  • The router does not fire on load. window.onpopstate (back/forward) is handled for you, but the initial URL must be matched explicitly with myApp.router.match().

notes.js

Application state that is not view state lives in plain modules. This one is an in-memory store standing in for a server API:

let seed = 1;
const store = new Map();

export const notes = {
	add( text ) {
		const note = { noteID: `n${ seed++ }`, text, done: false };
		store.set( note.noteID, note );
		return note;
	},
	toggle( noteID ) {
		const note = store.get( noteID );
		if( note ) note.done = !note.done;
		return note;
	},
	remove( noteID ) {
		store.delete( noteID );
	},
	all() {
		return Array.from( store.values() );
	}
};

In a real application this module would call a Service, which caches entities and notifies your views automatically — but the shape of the code stays the same.

views.js

Views own their appearance and their DOM event handlers. The template is a function that returns an HTML string built from state; elements with data-on<event> attributes get event listeners bound to methods on view.eventHandlers after each render.

import { myApp } from "./app.js";
import { View } from "/lib/altseven/dist/a7.js";

export function App( props ) {

	const app = new View( props );

	app.template = function() {
		return `
		<nav class="app-nav">
			<h1>Notes</h1>
			<a href="/" data-onclick="goHome">All notes</a>
		</nav>
		<div id="notesList"></div>`;
	};

	app.eventHandlers = {
		goHome: function( event ) {
			event.preventDefault();
			myApp.router.open( "/" );
		}
	};

	myApp.ui.register( app );
	return app;
}

export function NotesList( props ) {

	const notesList = new View( props );

	notesList.state = { items: [], draft: "" };

	notesList.template = function() {
		const state = notesList.getState();
		const items = state.items.map( note => `
			<li>
				<label>
					<input type="checkbox" data-onchange="toggleNote"
						data-id="${ note.noteID }" ${ note.done ? "checked" : "" }>
					${ note.text }
				</label>
				<button data-onclick="removeNote" data-id="${ note.noteID }">✕</button>
			</li>` ).join( "" );

		return `
		<form data-onsubmit="addNote">
			<input type="text" name="draft" value="${ state.draft }"
				placeholder="Write a note…">
			<button type="submit">Add</button>
		</form>
		<ul>${ items }</ul>
		<p>${ state.items.length } note(s)</p>`;
	};

	notesList.eventHandlers = {

		addNote: function( event ) {
			event.preventDefault();
			const draft = event.target.elements.draft.value.trim();
			if( draft === "" ) return;
			notes.add( draft );
			event.target.elements.draft.value = "";
			// notify the app that notes data changed
			myApp.events.publish( "notes.changed", {} );
		},

		toggleNote: function( event ) {
			notes.toggle( event.target.dataset.id );
			myApp.events.publish( "notes.changed", {} );
		},

		removeNote: function( event ) {
			notes.remove( event.target.dataset.id );
			myApp.events.publish( "notes.changed", {} );
		}
	};

	myApp.ui.register( notesList );
	return notesList;
}

Note the pattern:

  1. A DOM event handler (data-onclick, data-onchange, data-onsubmit, …) mutates application data and publishes an event.
  2. The notes.changed subscriber calls setState() on the affected view.
  3. setState() schedules a debounced re-render of that view; the template re-evaluates and the container repaints.

You never touch innerHTML yourself, and you never re-render other views manually. The supported data-on<event> names cover the standard browser event groups (mouse, keyboard, focus, form — including submit — media, clipboard, and more); data-onclick="goHome" becomes a click listener, data-onsubmit="addNote" a submit listener.

Run it

$ npx http-server . -p 8417

Open http://localhost:8417, add a few notes, tick them, and watch the URL change as you navigate. The full flow — DOM event → data change → pub/sub event → setState() → debounced repaint — is the core loop of every altseven application.

Gotchas worth knowing

These are all behaviors verified against 9.1.4:

  • remote: {} is required. Omitting the remote option makes init() throw (Object.keys(undefined) in the remote manager) — even for apps with no back end at all.
  • Nothing that touches modules may run before await myApp.init(). Views created at module scope crash with “cannot read properties of undefined”; myApp.events.subscribe at module scope crashes the same way. Create views and subscriptions inside your startup function, after init.
  • Routes don’t fire on load. Call myApp.router.match(location.pathname + location.search) once your views exist, or a fresh visit to /notes/123 renders an empty shell.
  • A missing selector silently unregisters a top-level view. If nothing appears, the first thing to check is that every selector in your code matches an id in the HTML or a node created by a parent template.

Where to go next

  • Views — the view lifecycle, child views and rendering rules
  • Events — the publish/subscribe system in depth
  • Routing — route patterns, parameters and history
  • The Data Layer — replace the in-memory store with entities, services and data providers backed by a real API

5 - Core Concepts

How altseven applications are structured: the Application object, views, events and routing.

The architecture of an altseven application, and the concepts you need before building real features.

The Application object

Everything in altseven hangs off an Application instance. You create one at startup, pass it options, and export it so the rest of your code can use it:

import { Application } from "/lib/altseven/dist/a7.js";

export const myApp = new Application( {
	name: "myapp",
	security: { enabled: false }
} );

The instance name you choose (myApp here, a7 if you want the legacy name) becomes the namespace for your whole application. The Application constructor synchronously builds the module registry from your options; init() (called automatically when you construct the application) then initializes each module and, if security is enabled, awaits the authentication check before your code continues.

Property Module Purpose
myApp.log LogManager Leveled logging
myApp.model ModelManager Application-wide data store with undo/redo
myApp.remote RemoteManager AJAX fetch, remote modules, WebSockets
myApp.services ServiceManager Registry of your Service instances
myApp.dataproviders DataProviderManager Registry of DataProviders and their bindings
myApp.events EventManager Publish/subscribe topics
myApp.security SecurityManager Session/user state
myApp.router RouterManager URL routing (only if options.router is set)
myApp.ui UIManager View registry and render queue
myApp.error ErrorManager Global error capture
myApp.console Console Optional in-browser console
myApp.constants — Convention: your app-wide constants
myApp.user — Convention: the session user (when security is enabled)

ES modules

altseven is an ES modules project. The framework ships as a single ES module (dist/a7.js) that exports the classes you build with: Application, View, Entity, Service, DataProvider, and a few others. Your application code is also organized as ES modules — there is no bundler, so your server must serve each file and the browser resolves the import graph at load time.

my-app/
├── index.html
├── assets/
│   └── js/
│       ├── app.js          # bootstrap: Application, options, routes, top views
│       ├── entity/         # Entity subclasses (data schemas)
│       ├── service/        # Service subclasses (CRUD + caching)
│       ├── dataprovider/   # DataProvider subclasses (view state + bindings)
│       └── view/           # View factories (components)

Configuration options

Everything is configured through the options structure passed to the Application constructor — logging, authentication, remote endpoints, routing, UI behavior. All options have defaults, so {} is valid, but most real apps set at least remote, router and logging. The full reference is in Configuring Your Application.

Templating

Views render HTML with template literals. Template literal expressions (${ ... }) are plain JavaScript, so you can compute, filter and join inside templates without learning a template language. Interactivity is declared with data-on<event> attributes in the template and implemented in a parallel eventHandlers object on the view. See Views.

In This Section

  • Views — state, templates, event handlers, lifecycle
  • Events — publish/subscribe topics and conventions
  • Routing — URL routes, parameters, browser history

5.1 - Views

The View class: state, templates, event handlers, children and the render lifecycle.

Views are the building blocks of an altseven UI. A view owns a mount point in the DOM, a state object, and a template that turns state into HTML.

Creating and registering a view

A view is created with new View( props ) and registered with the UI manager:

import { View } from "/lib/altseven/dist/a7.js";

const greeting = new View( {
	id: "greeting",              // unique id used to address the view
	selector: "#greeting",       // CSS selector of its mount point
	parentID: "main",            // omit for top-level views
	cacheTemplate: false,        // opt-in template caching (see below)
	isTransient: false           // transient views are garbage-collected
} );

greeting.state = { name: "world" };
greeting.template = function() {
	return `<h3>Hello ${ greeting.state.name }!</h3>`;
};

myApp.ui.register( greeting );

register() injects the application’s log, model, UI manager, renderer and debounce settings into the view, links it to its parent (if parentID is set), and fires the registered event — which enqueues top-level views for their first render. Child views render when their parent paints, not when they are registered.

Templates

A template is either a string or a function returning a string. Template literal expressions are plain JavaScript:

todoList.template = function() {
	const state = todoList.getState();
	const items = state.items
		.filter( t => !t.done )
		.map( t => `<li data-id="${ t.id }">${ t.title }</li>` )
		.join( "" );
	return `<ul>${ items }</ul>
		<p>${ state.items.length - state.items.filter( t => t.done ).length } remaining</p>`;
};

The rendered string is assigned to the mount point’s innerHTML, then the framework scans it for data-on<event> and data-bind attributes (below).

Event handlers: data-on attributes

Event listeners cannot be embedded in template literals, so altseven uses a declarative convention: an element attribute data-on<event> names a method on the view’s eventHandlers object, and the framework binds the listener after each render.

counter.template = function() {
	return `<button data-onclick="increment">${ counter.state.count }</button>`;
};

counter.eventHandlers = {
	increment: function( event ) {
		counter.setState( { count: counter.state.count + 1 } );
	}
};

The supported events are the standard browser event groups: mouse (click, dblclick, mousedown, …), keyboard (keydown, keyup, …), focus, form (submit, reset), clipboard, media, CSS animation/transition, printing, and more.

Because listeners are re-bound after every render, handlers always operate on the current DOM — you never have to manually re-attach anything.

State

setState() merges the keys you pass into the existing state and schedules a debounced repaint of that view:

// merge { count: 5 } into state; other keys are untouched
counter.setState( { count: 5 } );

const state = counter.getState();   // a copy of the current state

Since 8.0, setState() is a partial update: only the keys in the argument change. The view repaints via the UI manager’s render queue; the debounce interval defaults to 18ms and is configurable (ui.debounceTime).

If the view has a registered DataProvider, setState() and getState() delegate to it (see DataProviders).

Child views

Views form a tree via props.parentID. A child’s selector must match a node created by its parent’s template, not the static page HTML:

// parent
const main = new View( { id: "main", selector: "#main" } );
main.template = () => `
	<header id="header"></header>
	<section id="content"></section>`;
myApp.ui.register( main );

// children
const header = new View( {
	id: "header",
	parentID: "main",
	selector: "#header"
} );
const content = new View( {
	id: "content",
	parentID: "main",
	selector: "#content"
} );
myApp.ui.register( header );
myApp.ui.register( content );

After a parent renders, its onRendered() re-resolves and renders every registered child, so children repaint whenever the parent repaints.

The render lifecycle

You drive rendering through setState(); the framework handles the rest. The internal sequence for a repaint:

  1. setState() clears the view’s template cache and fires mustRender.
  2. mustRender is debounced by debounceTime; when it lands, the view is enqueued in the UI manager’s render queue.
  3. render() resolves the mount point, evaluates the template (or reuses the cached string — see below), paints, binds data-on listeners and data-bind model bindings.
  4. hasRendered is set, then the rendered event fires onRendered(), which renders the view’s children.
  5. Errors in rendered callbacks are caught and logged — they cannot leave the render pipeline stuck or block other views in the queue (8.2.1).

If the mount point of a top-level view (or of a child whose parent has already painted) no longer exists, the view is removed from its parent and unregistered — that is a genuine misconfiguration, not a timing issue.

Template caching (opt-in)

Since 9.0, template caching is per-view and off by default. A view that opts in with props.cacheTemplate: true (and the app-wide ui.cacheTemplates not disabled) reuses the last rendered string on mayRender repaints — useful when a view is repainted but its template output cannot have changed.

  • mustRender — template inputs may have changed; always re-evaluates the template. Fired by setState().
  • mayRender — repaint, allowed to use the cached template. Use when you know the output hasn’t changed (e.g. re-attach after a parent re-render).

You rarely fire these yourself — setState() covers the normal path.

Transient views

Set props.isTransient: true for views that should be garbage-collected if their mount point disappears (e.g. overlays, modals). The framework schedules a check after each render (interval: ui.timeout, default 10 minutes) and unregisters the view when its selector no longer resolves.

Model bindings: data-bind

Any element with a data-bind="<key>" attribute is bound to a key in the application model after each render: changes in the model update the element and edits to the element update the model.

profile.template = () => `
	<input type="text" data-bind="user.firstname">`;

See Configuring Your Application for the model options, and the API reference for the full View method list.

5.2 - Events

The publish/subscribe event system and the conventions for using it well.

altseven uses a lightweight publish/subscribe system (myApp.events) for communication between components, plus per-view instance events for the render lifecycle.

Application events: publish/subscribe

The EventManager manages named topics. Any code can publish to a topic; any code can subscribe:

// subscribe — returns a handle with .remove() to unsubscribe
const handle = myApp.events.subscribe( "user.profile", function( obj ) {
	// load and display the user profile
} );

// later: handle.remove();

// publish
myApp.events.publish( "user.profile", { userID: user.userID } );

Publishing to a topic with no listeners is a no-op. Each listener is isolated (since 9.1.2): a listener that throws is logged via myApp.log.error and the remaining listeners still run — one bad subscriber can no longer take out unrelated ones.

Declaring events at startup

The events option is a shorthand for subscribing a whole set of topics when the application initializes:

export const myApp = new Application( {
	events: {
		"settings.foo.show": function( info ) { /* ... */ },
		// a declared-but-unhandled topic: publishes won't warn, a view
		// can subscribe later
		"settings.foo.hide": null
	}
} );

options.events may look like the natural place to wire everything — but remember that subscriptions at module scope run before await myApp.init(), when myApp.events doesn’t exist yet. The events option is safe (the EventManager subscribes them during init); manual myApp.events.subscribe() calls belong inside your startup function after init.

Built-in authentication topics

When the security module is enabled, the framework pre-subscribes these topics to the matching remote auth methods:

Topic Action
auth.login Calls remote.invoke("auth.login", params) — the login flow
auth.logout Calls remote.invoke("auth.logout", params)
auth.refresh Calls remote.invoke("auth.refresh", params) — session refresh
auth.sessionTimeout Invalidates the session
auth.invalidateSession Invalidates the session

So a login form publishes auth.login with { username, password, success, failure } — see Authentication for the full flow.

Naming conventions

Topics are plain strings; organize them hierarchically by area of the app:

"notes.changed"      // notes data changed anywhere
"user.profile"       // user profile actions
"auth.login"         // framework-reserved: authentication

A common pattern from the Your First App tutorial: DOM event handlers in views mutate data and publish a domain event (notes.changed); a single subscriber maps that event to setState() on the views that care. This keeps views decoupled from each other.

View instance events

Separately from pub/sub, every view has instance-level events used by the render lifecycle (fired and consumed mostly by the framework):

Event Meaning
mustRegister Fired by the View constructor
registered Fired after ui.register(); top-level views then fire mustRender
mustRender Template inputs may have changed — always re-evaluates the template
mayRender Repaint; may reuse the cached template if the view opted in
rendered The view painted; triggers onRendered() for children
mustUnregister The view should be removed from the UI manager
stateChanged State changed (fired by setState() or the DataProvider)

You can hook these on a view with view.on( eventName, handler ) — the same mechanism all framework components share — but you should rarely need to.

Component event bindings

All framework classes (views, services, data providers, the managers) extend a common base with on(), fireEvent(), and subscribe()-style bindings. Services use this to publish cacheChanged, entityChanged and entityDeleted — which is what makes data binding work.

5.3 - Routing

Client-side URL routing: route tables, parameters, and browser history.

altseven includes a Trie-based client-side URL router for bookmarking and browser history. Routes map URL patterns to events (or handler functions).

Declaring routes

Routes are declared in the router option as [ path, handler ] pairs:

export const myApp = new Application( {
	remote: {},
	router: {
		useEvents: true,    // default: handlers are event topics
		routes: [
			[ "/", "app.home" ],
			[ "/notes", "notes.list" ],
			[ "/notes/:noteID", "notes.detail" ],
			[ "/settings/profile", "settings.profile" ]
		]
	}
} );

With useEvents: true (the default), the handler string is a topic published on myApp.events when the route matches. With useEvents: false, handlers are called as functions: [ "/", ( params ) => { ... } ].

Paths support :param segments — /notes/:noteID matches /notes/n42 and extracts { noteID: "n42" }.

// simple navigation — publishes "app.home"
myApp.router.open( "/" );

// with parameters — merged with any route-pattern parameters
myApp.router.open( "/notes/n42", { highlight: true } );

open() pushes a history entry (parameters become the history state) and then dispatches, so the back button works. If no route matches, the router logs an error and does nothing.

Matching the current URL

match() behaves like open() but is intended for the initial navigation. Without it, a fresh visit or reload of /notes/n42 renders an empty shell.

Route handlers as event subscribers

Following the pub/sub conventions, subscribe to your route topics inside your startup function:

myApp.events.subscribe( "notes.detail", ( params ) => {
	// params = { noteID: "n42", ...anything passed to open() }
	detailView.setState( { noteID: params.noteID } );
} );

Routes exist to give the user a URL in the browser’s location bar; the actual logic lives in the event handlers, which keeps routes, views and events decoupled.

Nested paths

Since 8.3.0 the router handles nested paths (base-case matching), so /settings/profile and /settings can coexist without shadowing each other.

6 - The Data Layer

Entities, services and data providers: schemas, caching, and view binding.

The data layer gives you schema-validated entities, a caching service layer, and data providers that keep view state synchronized with the cache automatically.

The three classes

Class Role
Entity A typed, schema-validated data object with composite-key support
Service CRUD + custom operations against a remote API, with a client-side entity cache
DataProvider Per-view state manager that binds view state to service cache data

The flow is unidirectional:

View  ←(state)—  DataProvider  ←(entityChanged/cacheChanged)—  Service  →  remote API
     —(create/update/delete)—→ Service  —→ cache  —→ all bound DataProviders updated

Views never talk to the network. They render whatever their data provider (or plain state) gives them. Services cache every entity they see, so two views showing the same entity are always consistent — when one view saves a change, the other’s bound data updates automatically.

In This Section

6.1 - Entities

Defining typed, schema-validated data objects with the Entity class.

An Entity is a typed data object: you declare a static schema, and instances validate, coerce and serialize their data against it.

Defining an entity

Extend Entity and declare a static schema. Each field descriptor supports type, required, id, and entityClass (for nested entities):

import { Entity } from "/lib/altseven/dist/a7.js";

export class Todo extends Entity {
	static schema = {
		todoID:   { type: "string", id: true },
		title:    { type: "string", required: true },
		done:     { type: "boolean" },
		created:  { type: "date" },
		tags:     { type: "array" },
		priority: { type: "integer" }
	};
}

Supported types: string, integer, float, boolean, date, array, object (optionally with an entityClass for nested entities).

Creating instances

The constructor validates required fields, defines getters/setters for every schema field, and coerces values:

const todo = new Todo( {
	todoID: "t1",
	title: "Write the docs",
	created: "2026-11-16T09:00:00Z",  // string → Date
	done: 1                            // 1/0 → true/false
} );

todo.title;              // "Write the docs"
todo.created;            // Date object
todo.done;               // true
todo.id;                 // "t1" — .id returns the field marked id: true
todo.validate();         // true

Validation is strict: assigning a wrong type throws (Invalid type for property done. Expected boolean, but got string.), missing required fields throw at construction, and date fields accept either Date objects or parseable date strings.

Composite keys

Marking several fields with id: true defines a composite primary key. The service layer joins the values into a single string key ("user42|post7"), so entities with multi-field identities cache and bind correctly:

export class Enrollment extends Entity {
	static schema = {
		userID:  { type: "integer", id: true },
		courseID:{ type: "integer", id: true },
		grade:   { type: "string" }
	};
}

Nested entities

An object field with an entityClass is instantiated automatically:

export class Comment extends Entity {
	static schema = {
		commentID: { type: "string", id: true },
		author:    { type: "object", entityClass: User }  // another Entity class
	};
}

const c = new Comment( { commentID: "c1", author: { userID: 7, name: "Rob" } } );
c.author instanceof User;   // true — the plain object was coerced

Custom getters and setters

Subclasses can define their own getters/setters for schema fields; the Entity base detects them and wraps rather than replaces them — useful for computed values or side effects on assignment.

Serialization

Entities convert to and from plain objects at the API boundary:

todo.toFlatObject();
// { todoID: "t1", title: "Write the docs", done: true, created: Date, ... }

todo.fromFlatObject( { title: "Rewrite the docs" } );  // validates via setters

Service uses fromFlatObject() internally to load JSON responses into entity instances, so your endpoints just return plain JSON.

Where entities live

Entities are pure data — no network, no DOM. Instantiate them in services (the service layer does it for you), and pass them around as values. Views render entity data from their state; they don’t own entities.

6.2 - Services

CRUD operations against a REST API with client-side caching, filtering and sorting.

A Service wraps a remote API: it performs CRUD operations, caches every entity it loads or saves in the application model, deduplicates concurrent identical requests, and notifies data providers when cached data changes.

Remote modules first

Services call endpoints defined in remote modules — plain objects passed to the application in the remote.modules option. Each method is either an object { url, params } or a function:

// remote/todo.js
export var todo = {
	create: {
		url: "/api/todos"
	},                                    // POST /api/todos (create is POST by default)
	read: {
		url: "/api/todos/:todoID"          // GET, :todoID replaced from params
	},
	update: {
		url: "/api/todos/:todoID"          // PUT, body = params
	},
	destroy: {
		url: "/api/todos/:todoID"          // DELETE
	},
	readAll: {
		url: "/api/todos"                  // GET
	},
	readMany: {
		url: "/api/todos/byids",           // custom method: method from params, default GET
		params: { method: "POST" }
	},
	deleteByList: {                        // any custom name works
		url: "/api/todos/batch",
		params: { method: "DELETE" }
	}
};

The framework maps the standard action names to HTTP verbs: create → POST, read/readAll → GET, update → PUT, destroy → DELETE. :param segments in URLs are replaced from the params object ({ todoID: "t1" } → /api/todos/t1).

Function modules take the params object and do their own fetching:

export var stats = {
	mostActive: function( params ) {
		return myApp.remote.fetch( "/api/stats/mostActive", { method: "GET" }, true );
	}
};

Defining a service

Extend Service and pass four things: an id (also the cache key), a key (the fallback single-key field), the entityClass, and remoteMethods — a map of operation names to "module.action" strings:

import { Service } from "/lib/altseven/dist/a7.js";
import { Todo } from "../entity/todo.js";

export class TodoService extends Service {
	constructor() {
		super( {
			id: "todos",                  // service id and model cache key
			key: "todoID",                // fallback key field
			entityClass: Todo,
			remoteMethods: {
				create:  "todo.create",
				read:    "todo.read",
				update:  "todo.update",
				delete:  "todo.destroy",      // Service.delete → remote action "destroy"
				readAll: "todo.readAll",
				readMany:"todo.readMany"
			}
		} );
	}
}

Register the service — either declaratively in options:

import { TodoService } from "./service/todo.js";

export const myApp = new Application( {
	remote: { modules: { todo, stats } },
	services: [ new TodoService() ]       // registered automatically at init
	// ...
} );

or manually after init: myApp.services.register( new TodoService() ).

CRUD operations

All service methods are async and return entity instances:

const todoService = myApp.services.getService( "todos" );

// create — POSTs, caches the saved entity (with its server-assigned id)
const todo = await todoService.create( { title: "Write the docs" } );

// read one — cache first; only a cache miss hits the network
const t1 = await todoService.read( { todoID: "t1" } );

// read many — fetches ONLY the ids missing from the cache
const list = await todoService.readMany( [ "t1", "t2", "t3" ] );  // → array

// read all — one request if the cache is empty
const all = await todoService.readAll();   // → Map keyed by entity id

// update — PUTs, re-caches, fires entityChanged
todo.done = true;
await todoService.update( todo );

// delete — DELETEs, evicts from cache, fires entityDeleted
await todoService.delete( todo );

Every create/update/delete updates the cache and fires entityChanged / entityDeleted events, which is what keeps bound views in sync.

Request deduplication

Concurrent identical read, readMany, readAll and invoke calls share one network request: the second caller receives the first caller’s promise. This matters when several views mount at once and all ask for the same data.

Custom methods

invoke() calls any remote module method not in the standard CRUD set, with optional caching and filtering:

// remoteMethods: { byUser: "todo.readMany" }
const todos = await todoService.invoke( "byUser", { userID: 7 } );

// options (all optional):
const result = await todoService.invoke( "byUser", { userID: 7 }, {
	checkCache: true,      // return cached data without a network call when possible
	merge: true,           // merge the response into the cache
	filter: { done: [ "=", false ] },
	returnType: "Array"    // or "Map"
} );

Cache access

The cache is a Map stored in the model under the service id:

todoService.get();        // whole cache Map
todoService.get( "t1" );  // one entity, or undefined if absent

// since 9.1.3: get() with NO argument returns everything; a *present but
// falsy* key (null, 0, "") is a lookup that MISSES and returns undefined —
// never the whole map. Rely on that; guard for undefined.

Filtering and sorting

filter() and sort() work on arrays or Maps of entities, client-side:

const open = todoService.filter( cached, {
	done: [ "=", false ],
	priority: [ ">=", 2 ],
	title: [ "=", "^write", true ],       // regex: [operator, pattern, useRegex]
	tags: [ "in", [ "docs", "api" ] ]     // also "not in", "=", "!=", ">", "<", ">=", "<="
} );

const sorted = todoService.sort( open, { priority: "desc", title: "asc" } );

// a bare value means equality:
const mine = todoService.filter( cached, { userID: 7 } );

A word on caching strategy

The cache never expires on its own — it is a session cache, not a database. readAll() will not re-fetch once the cache has data, so for data that changes server-side outside your app, either call invoke() with explicit options, or re-fetch into the cache with merge() when you know data changed (e.g. after a WebSocket notification).

6.3 - DataProviders

Binding view state to service cache data — automatic synchronization without plumbing.

A DataProvider owns a view’s state and keeps it synchronized with service cache data through declarative bindings.

Why a DataProvider

Without one, you wire data into views by hand: call a service, setState(), repeat on every change. A DataProvider replaces that with a declaration: “this view’s todos state key is the Todo entities matching this filter, kept up to date automatically.”

Defining one

A DataProvider takes the view it serves, an initial state, an optional schema, and a binding map — one rule per state key:

import { DataProvider } from "/lib/altseven/dist/a7.js";
import { Todo } from "../entity/todo.js";

export class TodoListDP extends DataProvider {
	constructor( props ) {
		props.binding = {
			todos: {
				entityClass: Todo,
				func: todoService.refreshActiveTodos,  // how to (re)load the data
				renderOn: [ "create", "delete" ]       // which cache actions re-render
			},
			selected: {
				entityClass: Todo,
				id: null        // bound to a single entity; id fixed at runtime
			}
		};

		props.schema = {
			todos:    { type: "map", entityClass: Todo },
			selected: { type: "object", entityClass: Todo },
			filterText: { type: "string" }
		};

		super( props );
	}
}

Binding rule properties:

Property Meaning
entityClass The entity type this key holds — used to find the matching service
func A refresh function (usually on the service) that returns the entities to bind
id Bind to a single entity by id instead of a collection
filter Client-side filter applied to bound data, e.g. { done: [ "=", false ] }
sort Sort applied to bound data, e.g. { created: "desc" }
renderOn Only re-render on these cache actions: create, update, delete
dependencies Re-run the binding when these state keys change (see below)

Registration — two steps

A DataProvider must be registered with both the application and the view:

const dp = new TodoListDP( { view: todosView } );

myApp.dataproviders.register( dp );        // wires bindings to services
todosView.registerDataProvider( dp );      // view state now flows through the DP

Once registered, todosView.setState() / getState() delegate to the DataProvider, and cache changes push new data into view state automatically — the view repaints through the normal stateChanged → mustRender path.

Collection binding

With a func (or the service cache as a whole), the DataProvider listens to the service’s cacheChanged event, re-resolves the bound data, applies filter/sort, and writes the result into view state. renderOn limits which actions trigger this — e.g. a list that doesn’t need to repaint when an existing item is merely updated can declare renderOn: [ "create", "delete" ].

Entity-specific binding

With an id, the binding tracks a single entity: when that entity changes, the view’s state key is set to the new entity; when it is deleted, the key is set to null. This is the normal shape for a detail view.

For an entity whose id is not known until runtime, declare the binding with id: null. The first matching entityChanged event sets the state (since 9.1.3 an id-less object binding correctly receives the event’s entity rather than the whole cache map).

Dependencies

dependencies re-runs a binding when related state changes — either in the same view ("filterText") or another view ("toolbar.selectedUserID"):

props.binding = {
	todos: {
		entityClass: Todo,
		func: todoService.refreshByFilter,
		dependencies: [ "filterText", "toolbar.selectedUserID" ]
	}
};

When filterText changes in this view (or selectedUserID changes in the toolbar view), the todos binding re-resolves — the func receives the current DP state and can use those values as its query parameters.

EntityMap relations

For master/detail loads (a page of items plus their parents), declare a relation in the schema and load it explicitly:

props.schema = {
	todos: {
		type: "entityMap",
		service: "todos",             // service id
		fetchMethod: "todo.byUser",   // returns an array of ids (or { ids: [...] })
		defaultCriteria: { userID: 7, limit: 20 }
	}
};
// fetch the id list, then readMany() the entities (cache-aware)
await dp.loadRelation( "todos", { userID: 7 } );

// paginate: merges with the stored criteria by default
await dp.refresh( "todos", { limit: 40 } );
await dp.refresh( "todos", { limit: 20 }, { reload: true } );  // replace criteria

dp.getRelationCriteria( "todos" );  // the currently stored criteria
dp.clearRelation( "todos" );        // empty the Map and forget the criteria

loadRelation fires relationLoaded, refresh fires relationRefreshed, clearRelation fires relationCleared.

When to use what

  • Plain view state — UI-only values (drafts, tab selection). No DataProvider needed.
  • DataProvider with bindings — view state that mirrors cached entities.
  • Model bindings (data-bind) — simple two-way field binding for form inputs backed by the application model.

7 - Core Tasks

How to accomplish specific tasks with altseven.

Task-oriented pages: communicating with a back end, WebSockets, and authentication.

In This Section:

7.1 - Remote Modules

Defining API endpoints as remote modules and calling them with fetch/invoke.

Remote modules describe your back-end API in one place; the remote manager turns them into fetch calls with token handling included.

Defining modules

Pass modules in the remote option. Every app needs at least remote: {} — without the option at all, init() throws.

export const myApp = new Application( {
	remote: {
		modules: {
			user: {
				read:     { url: "/api/users/:userID" },
				readAll:  { url: "/api/users" },
				create:   { url: "/api/users" },
				update:   { url: "/api/users/:userID" },
				destroy:  { url: "/api/users/:userID" },
				search:   { url: "/api/users/search", params: { method: "POST" } }
			}
		},
		useTokens: true,                 // default: send the session token with secure calls
		tokenType: "X-Token",            // or "access_token" (Authorization: Bearer)
		credentials: "same-origin"       // "include" for SAML / cross-origin cookie SSO
	}
} );

Method shapes:

  • Object form { url, params } — the framework performs the fetch. Standard action names map to HTTP verbs: create → POST, read/readAll → GET, update → PUT, destroy → DELETE. :param segments in the URL are replaced from the params object. Custom names use params.method (default GET) and params.headers.
  • Function form — receives the params object and returns a fetch Response; use it when you need full control.

Calling methods

// invoke takes "module.action" strings
const response = await myApp.remote.invoke( "user.read", { userID: 7 } );
const user = await response.json();

const created = await myApp.remote.invoke( "user.create", { name: "Rob" } );

// custom methods work the same way
const found = await myApp.remote.invoke( "user.search", { q: "rob" } );

When called through a Service, entity conversion, caching and deduplication happen automatically — prefer services for anything entity-shaped.

Raw fetch

myApp.remote.fetch( uri, params, secure ) is the escape hatch:

const response = await myApp.remote.fetch(
	"/api/widgets/42",
	{ method: "GET" },
	true          // secure = attach the session token
);

With useTokens: true, secure calls send the token — as the X-Token header (default) or as Authorization: Bearer <token> when tokenType is "access_token". The token is set at login from the corresponding response header and kept in sessionStorage, so it survives page reloads.

Authentication endpoints

The loginURL, logoutURL and refreshURL settings define the three built-in auth endpoints; see Authentication.

Set credentials: "include" so every fetch sends cookies cross-origin (and the server must answer the CORS preflight with the right Access-Control-Allow-Credentials). This is how altseven apps integrate with a SAML identity provider: the session lives in cookies, not in the token header.

7.2 - WebSockets

Raw WebSocket connections and managed sessions with automatic reconnection.

The remote manager provides webSocket() for a raw connection and webSocketSession() (9.1.0) for a managed session with exponential backoff, ping/pong zombie detection, and reconnect on network recovery.

Raw WebSocket

const ws = myApp.remote.webSocket(
	"/ws/notifications",       // ws:// / wss:// URL, or a path (scheme chosen by isSecure)
	function( data ) {
		// data is the parsed JSON message
		console.log( "notification:", data );
	},
	true                        // isSecure → wss://
);

The URL is validated up front: an empty or non-string URL throws a TypeError at the call site instead of producing ws://undefined/.... With useTokens: true, the session token is appended as a ?token= query parameter.

A raw socket is exactly that — if it drops, it stays dropped. For anything that should survive network hiccups, use a session.

Managed sessions

webSocketSession( options ) returns a WebSocketSession:

const session = myApp.remote.webSocketSession( {
	url: "/ws/notifications",
	isSecure: true,                       // default: wss://
	handleMessage: function( data ) {
		// required — called with each parsed message
		notificationBell.setState( { items: data.items } );
	},
	onOpen: function( socket ) {
		// optional — called after each successful open; subscribe here
		socket.send( JSON.stringify( { type: "subscribe", topic: "tasks" } ) );
	},
	ping: {                                // optional — zombie detection
		interval: 30000,                   // ping every 30s
		timeout: 5000,                     // force-close if no pong in 5s
		send: ( socket ) => socket.send( JSON.stringify( { type: "ping" } ) ),
		isPong: ( data ) => data.type === "pong"
	},
	beforeReconnect: async function() {
		// optional — return false to give up permanently (e.g. logged out);
		// throw to treat the failure as transient (backoff continues)
		return myApp.authenticated;
	},
	backoff: { initial: 1000, max: 30000, jitter: true },
	maxAttempts: Infinity
} );

What the session does for you:

  • Exponential backoff with jitter between reconnect attempts (default 1s → 30s cap), so a flapping server isn’t met by a thundering herd.
  • Ping/pong zombie detection — a half-open TCP connection that silently stopped delivering messages is force-closed so the reconnect logic can take over.
  • Network awareness — online and visibilitychange events trigger an immediate reconnect attempt instead of waiting out the backoff timer.
  • State machine — session.state is one of idle, connecting, open, reconnecting, closed.

Sending and closing

session.send( JSON.stringify( { type: "chat", text: "hello" } ) );
// → true if sent, false if the socket is not currently open

session.close();   // explicit shutdown — no more reconnects after this

Pattern: socket events into the event system

A common integration maps socket messages to pub/sub topics, so views can subscribe like they do to everything else:

const session = myApp.remote.webSocketSession( {
	url: "/ws/events",
	handleMessage: ( data ) => {
		// data: { topic: "task.updated", payload: {...} }
		myApp.events.publish( data.topic, data.payload );
	},
	onOpen: ( socket ) => socket.send( JSON.stringify( { type: "subscribe-all" } ) )
} );

7.3 - Authentication

How the built-in authentication system works: tokens, refresh, sessions.

altseven ships an authentication mechanism built on HTTP Basic auth for login and a session token for subsequent requests, with an automatic refresh cycle.

See the authentication tutorial for a step-by-step login form example; this page describes the machinery.

Configuration

export const myApp = new Application( {
	remote: {
		loginURL: "/api/auth/login",
		logoutURL: "/api/auth/logout",
		refreshURL: "/api/auth/refresh",
		useTokens: true,           // default
		tokenType: "X-Token"       // or "access_token"
	},
	security: {
		enabled: true,             // default
		userArgs: { userID: "" }   // default fields for the session user
	},
	auth: {
		sessionTimeout: 15 * 60 * 1000   // default: 15 minutes
	}
} );

With security enabled, Application.init() awaits an authentication check before your startup code proceeds: it calls the auth.refresh remote method and resolves myApp.authenticated and myApp.user.

The three endpoints

login — POST loginURL. The framework sends HTTP Basic auth (Authorization: Basic base64(username:password)) and a JSON body { rememberMe: boolean }. Your server responds with:

  • the session token in the X-Token response header (or Access_token if tokenType: "access_token"), which the framework stores in sessionStorage
  • a JSON body { success: true, user: { ... } } (or { success: false, ... })

refresh — GET refreshURL with the token attached. Your server responds { authenticated: boolean, user: { ... } }. A 401 is treated as { authenticated: false }. This endpoint is called:

  • once at application startup (the isAuthenticated check)
  • periodically, on the auth.sessionTimeout timer, to keep the session alive

logout — POST logoutURL. On { success: true } the framework invalidates the session (clears the token, resets the user).

The flow from your code

You never call these endpoints directly — publish the built-in events:

myApp.events.publish( "auth.login", {
	username, password, rememberMe,
	success: function( json ) { /* navigate into the app */ },
	failure: function( json ) { /* show the error */ }
} );

myApp.events.publish( "auth.logout", { success: ( json ) => ... } );

success/failure may be functions, event topic names, or router paths (when the router is configured). See the tutorial for the full pattern.

Session state

  • The current user is held in myApp.user, mirrored into sessionStorage and (when a model is in use) myApp.model.get( "user" ).
  • myApp.security.isAuthenticated() returns a promise of { authenticated: boolean, user }; concurrent calls share one refresh request.
  • myApp.security.invalidateSession() clears the token and resets the user — the auth.sessionTimeout and auth.invalidateSession topics do this too.
  • When a refresh call fails unexpectedly, the framework publishes auth.logout itself.

SAML / SSO variants

Set remote.credentials: "include" to rely on cookie sessions instead of tokens (the login/refresh/logout calls then send cookies cross-origin). The rest of the flow — the three endpoints and the events — is unchanged.

8 - Reference

Low-level reference documentation for the altseven framework.

The full class and option reference for altseven 9.1.4, plus the release history.

In This Section:

  • API Reference — every class and method exported by dist/a7.js
  • Release notes are published on the blog and maintained in the repository at release_notes.md.

8.1 - API Reference

Classes and methods exported by the altseven framework (v9.1.4).

Everything exported by dist/a7.js. This reference reflects the source at version 9.1.4.

Exports

import {
	Application, View, Entity, Service, DataProvider, User, Model
} from "/lib/altseven/dist/a7.js";

Application

The application object; created once at startup and exported from app.js.

Member Kind Notes
constructor( options ) — Normalizes options; only options, name, util, log, constants exist until init()
async init() method Creates all modules; awaits the auth check when security is enabled; returns the application
.options property The normalized options (see Configuring)
.log module LogManager — available immediately
.util module Utilities incl. debounce( fn, ms ) and base64 encode/decode
.constants property Convention: your app-wide constants
.model module ModelManager (after init)
.remote module RemoteManager (after init)
.services module ServiceManager (after init)
.dataproviders module DataProviderManager (after init)
.events module EventManager (after init)
.ui module UIManager (after init)
.security module SecurityManager (when security enabled)
.router module RouterManager (only when options.router is set)
.error module ErrorManager (when security enabled)
.console module Console (when console.enabled)
.user / .authenticated property Session user / auth flag (when security enabled)

View

Constructor props

Prop Type Meaning
id string Unique view id (used to address the view everywhere)
selector string CSS selector of the mount point
parentID string id of the parent view; child renders into the parent’s template
cacheTemplate boolean, false Opt in to template caching for mayRender repaints
isTransient boolean, false Garbage-collect when the mount point disappears

Methods and properties

Member Notes
state / setState( args ) Partial merge of args into state; clears the template cache; fires mustRender (or delegates to the DataProvider)
getState() Copy of the current state
template String or () => string producing the view’s HTML
eventHandlers Map of data-on<event> attribute names to handlers
render() Resolve mount point, paint, bind data-on / data-bind, fire rendered
onRendered() Renders registered children (called by the framework)
addChild( view ) / removeChild( view ) / clearChildren() / getParent() Child-view tree management
registerDataProvider( dp ) / unregisterDataProvider() Route state through a DataProvider
hasRendered boolean — has this view ever painted (drives the 9.1.4 child-render fix)
on( event, handler ) Instance event subscription (mustRender, rendered, stateChanged, …)
fireEvent( event, args ) Instance event publish

Entity

Member Notes
static schema Field descriptors: { type, required, id, entityClass }; types: string, integer, float, boolean, date, array, object
constructor( props ) Validates required fields; coerces (string→Date, 1/0→boolean, plain object→entityClass)
.id Value of the field marked id: true
validate() Re-validates all fields; returns true or throws
toFlatObject() Plain object (nested entities flattened recursively)
fromFlatObject( obj ) Set values via setters (validated); returns the entity

Service

Member Notes
constructor( props ) { id, key, entityClass, remoteMethods }; remoteMethods maps operations to "module.action" strings
async create( obj ) POST; caches and returns the saved entity (with server-assigned id)
async read( obj ) GET one; cache first; deduplicates concurrent identical calls
async readMany( IDs ) Fetches only ids missing from cache; returns an array
async readAll( obj ) GET all (one request if cache empty); returns a Map
async update( obj ) PUT; re-caches; fires entityChanged
async delete( obj ) DELETE (remote action destroy); evicts; fires entityDeleted
async invoke( name, params, options ) Custom method; options { merge, checkCache, filter, returnType }
get() / get( ID ) Whole cache Map / one entity. A present-but-falsy ID (null, 0, “”) is a miss returning undefined (9.1.3) — never the whole map
merge( items ) Merge raw entities into the cache; fires cacheChanged + per-entity events
cacheSet( entity, action ) / cacheDelete( id ) Manual cache mutation with events
filter( items, criteria ) Operators: =, !=, >, <, >=, <=, in, not in; [op, value, true] uses regex; bare value = equality
sort( items, sortFields ) e.g. { priority: "desc", title: "asc" }
bind( key, filter ) (Called by the DataProviderManager)
on( "cacheChanged" / "entityChanged" / "entityDeleted", … ) Cache events consumed by data providers

DataProvider

Member Notes
constructor( props ) { view, state, schema, binding }
setState( args ) / setStateOnly( args ) Merge state (+ fire stateChanged) / merge without firing
getState() Copy of current state
async loadRelation( name, criteria, options ) Fetch an entityMap relation: id list → service.readMany; options { merge, returnData }
async refresh( name, criteria, options ) Re-fetch a loaded relation; options { merge, reload, returnData }
clearRelation( name ) Empty the relation and forget its criteria
getRelationCriteria( name ) Currently stored criteria (or null)
on( "relationLoaded" / "relationRefreshed" / "relationCleared" / "stateChanged", … ) Relation lifecycle events

Binding rule properties: entityClass, func, id, filter, sort, renderOn, dependencies — see DataProviders.

Model (myApp.model)

Method Notes
get( name [, key] ) Whole value, or one entity from a Map. A present-but-falsy key is a miss (9.1.3)
set( name, value ) Store a value (deep-copied; Maps preserved as Maps)
exists( name ) Whether the key is present
bind( key, element ) Two-way HTML binding for data-bind elements
undo( name ) / redo( name ) Step back / forward in the value’s history
rewind( name ) / fastForward( name ) Jump to the oldest / newest history entry

EventManager (myApp.events)

Method Notes
subscribe( topic, listener ) Returns { remove() }; non-function listeners are ignored but still declare the topic
publish( topic, info ) Fires all listeners with info || {}; each listener is isolated — a throwing listener is logged, the rest still run (9.1.2)

Built-in topics: auth.login, auth.logout, auth.refresh, auth.sessionTimeout, auth.invalidateSession.

RemoteManager (myApp.remote)

Method Notes
async invoke( "module.action", params ) Dispatches to the module method; object methods map to CRUD verbs; function methods are called directly
async fetch( uri, params, secure ) Raw fetch; secure attaches the session token
webSocket( url, handleMessage, isSecure ) Raw socket; JSON-parses messages (async handlers supported); returns the WebSocket
webSocketSession( options ) Managed session — see WebSockets
setToken( t ) / getToken() / invalidateToken() Session token management (sessionStorage-backed)

RouterManager (myApp.router)

Method Notes
open( path, params ) Navigate: push history, publish the mapped event with merged params
match( path, params ) Same as open — use for the initial page load (no auto-match at startup)
find( path ) Look up a route: { handler, params } or undefined
add( path, handler ) Register a route programmatically

UIManager (myApp.ui)

Method Notes
register( view ) Inject app modules into the view, add to registry, link to parent, fire registered
unregister( id ) Remove a stale view
getView( id ) Look up a registered view
setSelector( name, selector ) / getSelector( name ) / getNode( name ) Named selector/node registry used by layout helpers
enqueueForRender( id ) Add a view to the render queue
mousePosition { x, y } when ui.enableMouseTracking is on

SecurityManager (myApp.security)

Method Notes
async isAuthenticated() Promise of { authenticated, user }; concurrent calls share one refresh request
setUser( user ) / getUser() Session user in sessionStorage + model
invalidateSession() Clear token and reset the user

LogManager (myApp.log)

trace, debug, info, warn, error, fatal — enabled levels configured via logging.logLevel. error/fatal accept ( message, error ).

9 - Examples

Complete, runnable altseven applications.

Complete applications and runnable examples built with altseven.

In the documentation

  • Your First App — a complete note-taking app with views, child views, events and routing. Every line verified against 9.1.4; copy the folder, serve it, and it runs.

The framework’s test apps

The altseven repository at git.peopoli.com/code/altseven ships working test applications under test/8.x/ — the ES6 template-literals app (app.es6.html), data-binding, Mustache and Handlebars variants. They are plain static pages: serve the repo root and open them.

LacesIDE

LacesIDE is an open source JavaScript editor and sandbox environment that you can install and run locally or on your own server. It was built with altseven and demonstrates the framework’s features at application scale — the whole thing is under five thousand lines, small enough to review in its entirety, but big enough to show how a real altseven application is organized.

Peopoli

The Peopoli social platform’s client applications are built on altseven, exercising the data layer (entities, services, data providers), WebSocket sessions and SAML-backed authentication in production.