@sourceregistry/sveltekit-enhance 1.6.0 → 1.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -309,6 +309,40 @@ Locals set: `trace: { id: string; started_at: bigint }`.
309
309
 
310
310
  ---
311
311
 
312
+ ### `StartUp`
313
+
314
+ Gates request handling until app-startup work (DB connect, cache warm, etc.) resolves. Requests during startup get a `503` — JSON body for non-HTML requests, or `showPage`'s rendered HTML for HTML requests — both with `Retry-After: 4`. Once ready, `showPage` itself redirects to `readyRedirect` (so a plain Svelte page with no server guard can't be visited after startup completes) — disabled in dev so you can still preview the page. Any rejected startup item calls `onFailure` (defaults to logging + `process.exit(1)`).
315
+
316
+ ```ts
317
+ import { StartUp, Deferred } from '@sourceregistry/sveltekit-enhance';
318
+
319
+ const dbReady = Deferred.Derive(db.connect());
320
+
321
+ export const handle = enhance.handle(
322
+ myHandler,
323
+ StartUp.await([dbReady], {
324
+ showPage: '/startup', // HTML requests are redirected here while not ready
325
+ showJSON: { error: 'service_starting', message: 'Application is initializing' },
326
+ allowedPaths: ['/health'], // always allowed through, in addition to showPage
327
+ readyRedirect: '/', // where showPage redirects to once ready
328
+ }),
329
+ );
330
+ ```
331
+
332
+ #### `StartupConfiguration`
333
+
334
+ | Option | Type | Default | Description |
335
+ |--------|------|---------|-------------|
336
+ | `showPage` | `string` | `/startup` | Path HTML requests are redirected to while not ready; always allowed through |
337
+ | `showJSON` | `Record<string, any>` | `{ error: 'service_starting', message: 'Application is initializing' }` | Body returned for non-HTML requests |
338
+ | `allowedPaths` | `string[]` | `[]` | Extra paths allowed through before startup completes |
339
+ | `onFailure` | `(reason: unknown) => void` | logs to stderr + `process.exit(1)` | Called when a startup item rejects |
340
+ | `readyRedirect` | `string` | `/` | Where `showPage` 302-redirects to once ready |
341
+
342
+ `waitOn` accepts `Deferred` instances or plain `Promise`s (wrapped via `Deferred.Derive`).
343
+
344
+ ---
345
+
312
346
  ### `CacheControl`
313
347
 
314
348
  Sets `Cache-Control` response headers. Provides named directive helpers so policies are readable at a glance, and two enhancers — one for broad handle-level rules, one for per-route load-level overrides.
@@ -6,5 +6,8 @@ export * from './form.ts';
6
6
  export * from './request-correlation.js';
7
7
  export * from './request-monitor.js';
8
8
  export * from './request-rate-limit.js';
9
+ export * from './startup.js';
9
10
  export * from './CSRF.js';
10
11
  export * from './internal/logger.js';
12
+ export * from './internal/Deferred.js';
13
+ export * from './internal/client_ip.js';
@@ -6,5 +6,8 @@ export * from "./form.js";
6
6
  export * from './request-correlation.js';
7
7
  export * from './request-monitor.js';
8
8
  export * from './request-rate-limit.js';
9
+ export * from './startup.js';
9
10
  export * from './CSRF.js';
10
11
  export * from './internal/logger.js';
12
+ export * from './internal/Deferred.js';
13
+ export * from './internal/client_ip.js';
@@ -0,0 +1,31 @@
1
+ /**
2
+ * A deferred promise implementation that allows external resolution/rejection
3
+ */
4
+ export declare class Deferred<T = void> {
5
+ readonly promise: Promise<T>;
6
+ resolve: (value: T | PromiseLike<T>) => void;
7
+ reject: (reason?: any) => void;
8
+ private _isResolved;
9
+ private _isRejected;
10
+ private _rejectReason?;
11
+ constructor();
12
+ /**
13
+ * Returns true if the promise has been resolved
14
+ */
15
+ get isResolved(): boolean;
16
+ /**
17
+ * Returns true if the promise has been rejected
18
+ */
19
+ get isRejected(): boolean;
20
+ get rejectReason(): unknown;
21
+ /**
22
+ * Returns true if the promise is still pending
23
+ */
24
+ get isPending(): boolean;
25
+ /**
26
+ * Returns true if the promise has been settled (resolved or rejected)
27
+ */
28
+ get isSettled(): boolean;
29
+ step<TResult2 = never>(): [onfulfilled?: ((value: T) => T | PromiseLike<T>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null];
30
+ static Derive<T>(promise: Promise<T>): Deferred<T>;
31
+ }
@@ -0,0 +1,72 @@
1
+ /**
2
+ * A deferred promise implementation that allows external resolution/rejection
3
+ */
4
+ export class Deferred {
5
+ promise;
6
+ resolve;
7
+ reject;
8
+ _isResolved = false;
9
+ _isRejected = false;
10
+ _rejectReason = undefined;
11
+ constructor() {
12
+ this.promise = new Promise((resolve, reject) => {
13
+ this.resolve = (value) => {
14
+ if (!this._isResolved && !this._isRejected) {
15
+ this._isResolved = true;
16
+ resolve(value);
17
+ }
18
+ };
19
+ this.reject = (reason) => {
20
+ if (!this._isResolved && !this._isRejected) {
21
+ this._isRejected = true;
22
+ reject(reason);
23
+ }
24
+ };
25
+ });
26
+ }
27
+ /**
28
+ * Returns true if the promise has been resolved
29
+ */
30
+ get isResolved() {
31
+ return this._isResolved;
32
+ }
33
+ /**
34
+ * Returns true if the promise has been rejected
35
+ */
36
+ get isRejected() {
37
+ return this._isRejected;
38
+ }
39
+ get rejectReason() {
40
+ return this._rejectReason;
41
+ }
42
+ /**
43
+ * Returns true if the promise is still pending
44
+ */
45
+ get isPending() {
46
+ return !this._isResolved && !this._isRejected;
47
+ }
48
+ /**
49
+ * Returns true if the promise has been settled (resolved or rejected)
50
+ */
51
+ get isSettled() {
52
+ return this._isResolved || this._isRejected;
53
+ }
54
+ step() {
55
+ return [
56
+ (r) => {
57
+ this.resolve(r);
58
+ return r;
59
+ },
60
+ (reason) => {
61
+ this._rejectReason = reason;
62
+ this.reject(reason);
63
+ return reason;
64
+ }
65
+ ];
66
+ }
67
+ static Derive(promise) {
68
+ const deferred = new Deferred();
69
+ promise.then((res) => deferred.resolve(res), (res) => deferred.reject(res));
70
+ return deferred;
71
+ }
72
+ }
@@ -0,0 +1,12 @@
1
+ import type { EnhanceInput } from "../index.js";
2
+ import { Deferred } from "./internal/Deferred.js";
3
+ export type StartupConfiguration = {
4
+ showPage: string;
5
+ showJSON: Record<string, any>;
6
+ allowedPaths: string[];
7
+ onFailure: (reason: unknown) => void;
8
+ readyRedirect: string;
9
+ };
10
+ export declare const StartUp: {
11
+ await: (waitOn: (Deferred<any> | Promise<any>)[], config?: Partial<StartupConfiguration>) => (input: EnhanceInput<"handle">) => Promise<void>;
12
+ };
@@ -0,0 +1,50 @@
1
+ import { Deferred } from "./internal/Deferred.js";
2
+ import { dev } from '$app/environment';
3
+ export const StartUp = {
4
+ await: (waitOn, config = {}) => {
5
+ const { showPage = "/startup", showJSON = { error: 'service_starting', message: 'Application is initializing' }, allowedPaths = [], onFailure = (reason) => {
6
+ process.stderr.write(`Unable to startup application because of unresolved startup item reason: ${reason}`);
7
+ process.exit(1);
8
+ }, readyRedirect = "/" } = config;
9
+ const deferredPromises = waitOn.map((r) => {
10
+ if (r instanceof Deferred)
11
+ return r;
12
+ else
13
+ return Deferred.Derive(r);
14
+ });
15
+ const isReady = () => {
16
+ for (let waitOnElement of deferredPromises) {
17
+ if (waitOnElement.isRejected) {
18
+ onFailure(waitOnElement.rejectReason);
19
+ }
20
+ if (!waitOnElement.isResolved)
21
+ return false;
22
+ }
23
+ return true;
24
+ };
25
+ const isAllowed = (event) => {
26
+ return allowedPaths.includes(event.url.pathname) || event.url.pathname === showPage;
27
+ };
28
+ return async (input) => {
29
+ const ready = isReady();
30
+ if (ready && !dev && input.url.pathname === showPage) {
31
+ throw new Response(null, { status: 302, headers: { Location: readyRedirect } });
32
+ }
33
+ if (!ready && !isAllowed(input)) {
34
+ const acceptsHtml = input.request.headers.get('accept')?.includes('text/html') ?? false;
35
+ if (acceptsHtml) {
36
+ const response = await input.fetch(showPage);
37
+ const headers = new Headers(response.headers);
38
+ headers.set('Retry-After', '4');
39
+ throw new Response(response.body, { status: 503, headers });
40
+ }
41
+ else {
42
+ throw new Response(JSON.stringify(showJSON), {
43
+ status: 503,
44
+ headers: { 'Content-Type': 'application/json', 'Retry-After': '4' }
45
+ });
46
+ }
47
+ }
48
+ };
49
+ }
50
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourceregistry/sveltekit-enhance",
3
- "version": "1.6.0",
3
+ "version": "1.7.1",
4
4
  "description": "Composable enhance and form utilities for SvelteKit actions, loads, methods, and hooks.",
5
5
  "author": "A.P.A. Slaa (a.p.a.slaa@projectsource.nl)",
6
6
  "scripts": {