Datapages offline

From romshark/datapages · View interactive version

Datapages offline is an AI agent skill from the GitHub repository romshark/datapages. The Datapages service worker: offline page snapshots and cached shims written by handlers through the pageCache parameter, the offline module and its Config, and the PageOffline fallback.

How to use this skill

Skill file

Offline and instant loads

Read datapages first for the build loop, hard rules and naming conventions.

modules/offline serves a service worker and adds registration to HTML responses. Handlers write its cache through the pageCache datapages.PageCacheWriter parameter:

The worker runs only in a secure context (HTTPS or localhost). Everywhere else the API does nothing.

Configure the module

Declaring PageOffline generates a WithOffline option with that page's route:

// PageOffline is /offline
type PageOffline struct{ App *App }

func (PageOffline) GET(r *http.Request) (body datapages.Component, err error) {
	return pageOffline(), nil
}
opts := []datapages.ServerOption{
	// Self-host Datastar: the CDN is unreachable offline.
	datapages.WithDatastarJS(assets.Path("datastar-1.0.5.js")),
	datapagesgen.WithOffline(app.OfflineConfig()),
}
// OfflineWorkerVersion identifies the installed worker and its cache. Increment
// it after a Datapages upgrade or a change to Assets, ExcludePaths,
// CrossOriginDestinations, OfflineClass, or PageOffline. Changes to Assets or
// PageOffline require a new installation because the worker fetches them only
// during installation.
const OfflineWorkerVersion = 1

func OfflineConfig() offline.Config {
	return offline.Config{
		WorkerVersion: OfflineWorkerVersion,
		// Precache the files required to render cached pages offline.
		Assets: []string{
			assets.Path("style.css"), assets.Path("datastar-1.0.5.js"),
		},
	}
}

For shims without PageOffline, install the module directly:

offline.WithServiceWorker("", offline.Config{WorkerVersion: 1})

| offline.Config field | default |

| ---------------------- | ------- |

| WorkerVersion | 1; increment after a Datapages upgrade or a change to Assets, ExcludePaths, CrossOriginDestinations, OfflineClass, or PageOffline |

| ScriptURL | /service-worker.js; the scope is the whole origin either way |

| Assets | none; files cached during installation |

| OfflineClass | is-offline, toggled on <html> while offline |

| CrossOriginDestinations | image, style, script, font; empty non-nil disables |

| ExcludePaths | none; same-origin prefixes never cached |

Style offline state in CSS, no Go code:

.is-offline [data-needs-network] { opacity: .5; pointer-events: none }

Datapages compresses after WithOffline, so compressed pages keep the worker registration. Put a custom compressing middleware before WithOffline. An already encoded response passes through WithOffline unchanged and gets no worker registration.

Offline support writes inline scripts: the connectivity script, the worker registration and queued cache writes. Each script uses the nonce from WithCSPNonce. WithOffline reads the nonce when each request arrives, independent of option order. Set offline.Config.CSPNonce to use a different nonce for the connectivity and registration scripts. The queued cache writes always use the nonce from WithCSPNonce.

When offline.Config.CSPNonce is nil, offline.WithServiceWorker uses the nonce from WithCSPNonce. Calling offline.Middleware through datapages.WithMiddleware does not copy the server nonce. A nonce-only policy blocks the middleware scripts.

A cached page is rendered once and replayed. It cannot contain a valid per-response nonce. Its shim hydration trigger and connectivity script are written without one. The service worker provides no policy header, and the browser does not require a nonce. A Content-Security-Policy in a meta element would block those scripts.

PageOffline

PageOffline is reserved like PageError404 and PageError500. The worker caches it during installation and returns it for an uncached URL while offline. It renders with a zero Session. Datapages supplies a minimal default.

The pageCache parameter

The parameter is optional on GET methods and on page or *App actions.

| method | effect |

| ------ | ------ |

| Version() | the version the client holds for this request's URL, 0 if none |

| Set(url, body, version) | cache body for url, served only while offline |

| SetShim(url, body, version) | cache body for url, served online too |

| Clear(url) | remove 1 entry |

| ClearAll() | remove every page cache entry |

url comes from the generated href package. Writes remain queued until the handler returns without error. The worker then applies them together, with ClearAll first.

Version() covers this URL only. Caching any other URL is therefore unconditional.

Snapshots

func (p PagePost) GET(
	r *http.Request,
	pageCache datapages.PageCacheWriter,
	path datapages.Path[struct {
		Slug string `path:"slug"`
	}],
) (body datapages.Component, err error) {
	post, ok := p.App.Post(path.Values.Slug)
	if !ok {
		return nil, datapages.ErrNotFound
	}
	if ver := postVersion(post); pageCache.Version() != ver {
		pageCache.Set(href.PagePost(post.Slug), postOffline(post), ver)
	}
	return postPage(post), nil
}

A snapshot need not match the live body. It is what the user sees with no network: leave out what cannot work there.

A GET can cache its own page when visited. An action can cache other URLs, such as ticket pages created by a purchase.

Shims

A shim renders the navigation and layout with placeholders for slow content. The worker returns the cached shim immediately and fetches the live page in parallel. Datapages adds the trigger that replaces the shim's head and body through Datastar and applies the attributes of the live <html> element. The shim contains no Datastar attributes.

A shim renders with no session and contains no CSRF script. Do not put actions in the placeholder content.

// shimVersion changes when the placeholder markup changes.
const shimVersion = 1

func (p PageIndex) GET(
	r *http.Request, pageCache datapages.PageCacheWriter,
) (body datapages.Component, err error) {
	rows, err := p.App.Rows(r.Context())
	if err != nil {
		return nil, err
	}
	if pageCache.Version() != shimVersion {
		pageCache.SetShim(href.PageIndex(), shim(len(rows)), shimVersion)
	}
	return indexPage(rows), nil
}

A shim is also shown online. It must not make an offline-only claim. If the live request fails, the shim remains visible.

Rules

```go

// The ownership button changes, so ownership is part of the version.

ver := snapshotVersion(session.UserID, owned) // For example, an FNV-1a hash.

if pageCache.Version() != ver {

pageCache.Set(href.PagePost(slug), postOffline(post), ver)

}

```

What may be cached

A snapshot is stored in the browser's cache for the origin. Any script on that origin can read it. It is not bound to a session and stays readable after the visitor signs out.

Delivery

The generated code picks how queued writes reach the worker from the handler signature, first row that matches. An action on *App follows the same rules as one on a page.

| handler | delivery |

| ------- | -------- |

| GET | embedded in the page HTML and applied on load |

| action taking sse | sent over that stream |

| action returning redirect | sent in its text/javascript response; navigation waits up to 500ms for the worker. This applies even when the action also returns a body |

| action returning only a body | embedded in the rendered document |

| action returning neither | sent over an SSE stream opened for that purpose |

An action that takes datapages.PageCacheWriter answers 406 to a request without Datastar-Request: true. Call it through a Datastar action, not a plain form: an HTTP redirect cannot carry the writes.

newSession and closeSession cannot be combined with sse. Sign-in and sign-out therefore take pageCache and return a redirect. Navigation waits up to 500ms for the worker to apply ClearAll before loading the destination.

<!-- written by datapages sha256:64821e2c6232acdf -->

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.