htmx-router 1.0.12 → 1.0.14

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/event-source.d.ts CHANGED
@@ -3,13 +3,17 @@
3
3
  * Includes a keep alive empty packet sent every 30sec (because Chrome implodes at 120sec, and can be unreliable at 60sec)
4
4
  */
5
5
  export declare class EventSource {
6
- private controller;
7
- private timer;
8
- private state;
6
+ #private;
9
7
  readonly response: Response;
8
+ readonly createdAt: number;
9
+ get updatedAt(): number;
10
+ readonly withCredentials: boolean;
10
11
  readonly url: string;
11
- constructor(request: Request, keepAlive?: number);
12
12
  get readyState(): number;
13
+ static CONNECTING: number;
14
+ static OPEN: number;
15
+ static CLOSED: number;
16
+ constructor(request: Request, keepAlive?: number);
13
17
  private sendBytes;
14
18
  private sendText;
15
19
  private keepAlive;
package/event-source.js CHANGED
@@ -2,45 +2,60 @@ import { ServerOnlyWarning } from "./internal/util.js";
2
2
  ServerOnlyWarning("event-source");
3
3
  // global for easy reuse
4
4
  const encoder = new TextEncoder();
5
- const headers = new Headers();
6
- // Chunked encoding with immediate forwarding by proxies (i.e. nginx)
7
- headers.set("X-Accel-Buffering", "no");
8
- headers.set("Transfer-Encoding", "chunked");
9
- headers.set("Content-Type", "text/event-stream");
10
- // the maximum keep alive chrome shouldn't ignore
11
- headers.set("Keep-Alive", "timeout=120");
12
- headers.set("Connection", "keep-alive");
5
+ const headers = {
6
+ // Chunked encoding with immediate forwarding by proxies (i.e. nginx)
7
+ "X-Accel-Buffering": "no",
8
+ "Transfer-Encoding": "chunked",
9
+ "Content-Type": "text/event-stream",
10
+ // the maximum keep alive chrome shouldn't ignore
11
+ "Keep-Alive": "timeout=60",
12
+ "Connection": "keep-alive",
13
+ };
13
14
  /**
14
15
  * Helper for Server-Sent-Events, with auto close on SIGTERM and SIGHUP messages
15
16
  * Includes a keep alive empty packet sent every 30sec (because Chrome implodes at 120sec, and can be unreliable at 60sec)
16
17
  */
17
18
  export class EventSource {
18
- controller;
19
- timer;
20
- state;
19
+ #controller;
20
+ #timer;
21
+ #state;
21
22
  response;
22
- url; // just to make it polyfill
23
+ // activity timestamps, in unix time for minimal storage
24
+ // since most use cases won't need the Date object anyway
25
+ // no point waiting space and cycles creating it
26
+ createdAt;
27
+ get updatedAt() { return this.#updatedAt; }
28
+ #updatedAt;
29
+ // just to make it polyfill
30
+ withCredentials;
31
+ url;
32
+ get readyState() { return this.#state; }
33
+ static CONNECTING = 0;
34
+ static OPEN = 1;
35
+ static CLOSED = 2;
23
36
  constructor(request, keepAlive = 30_000) {
24
- this.controller = null;
25
- this.state = 0;
37
+ this.#controller = null;
38
+ this.#state = EventSource.CONNECTING;
39
+ this.withCredentials = request.mode === "cors";
26
40
  this.url = request.url;
27
- const stream = new ReadableStream({
28
- start: (c) => { this.controller = c; this.state = 1; },
29
- cancel: () => { this.close(); }
30
- });
31
- request.signal.addEventListener('abort', () => this.close());
41
+ this.createdAt = Date.now();
42
+ this.#updatedAt = 0;
43
+ // immediate prepare for abortion
44
+ const cancel = () => { this.close(); };
45
+ request.signal.addEventListener('abort', cancel);
46
+ const start = (c) => { this.#controller = c; this.#state = EventSource.OPEN; };
47
+ const stream = new ReadableStream({ start, cancel }, { highWaterMark: 0 });
32
48
  this.response = new Response(stream, { headers });
33
- this.timer = setInterval(() => this.keepAlive(), keepAlive);
49
+ this.#timer = setInterval(() => this.keepAlive(), keepAlive);
34
50
  register.add(this);
35
51
  }
36
- get readyState() {
37
- return this.state;
38
- }
39
- sendBytes(chunk) {
40
- if (!this.controller)
52
+ sendBytes(chunk, active) {
53
+ if (!this.#controller)
41
54
  return false;
42
55
  try {
43
- this.controller.enqueue(chunk);
56
+ this.#controller.enqueue(chunk);
57
+ if (active)
58
+ this.#updatedAt = Date.now();
44
59
  return true;
45
60
  }
46
61
  catch (e) {
@@ -49,33 +64,40 @@ export class EventSource {
49
64
  return false;
50
65
  }
51
66
  }
52
- sendText(chunk) {
53
- return this.sendBytes(encoder.encode(chunk));
67
+ sendText(chunk, simulated) {
68
+ return this.sendBytes(encoder.encode(chunk), simulated);
54
69
  }
55
70
  keepAlive() {
56
- return this.sendText("\n\n");
71
+ return this.sendText("\n\n", false);
57
72
  }
58
73
  dispatch(type, data) {
59
- return this.sendText(`event: ${type}\ndata: ${data}\n\n`);
74
+ if (this.#state === EventSource.CLOSED) {
75
+ const err = new Error(`Warn: Attempted to dispatch event "${type}" to a closed connection for: ${this.url}`, {});
76
+ console.warn(err);
77
+ }
78
+ return this.sendText(`event: ${type}\ndata: ${data}\n\n`, true);
60
79
  }
61
80
  close(unlink = true) {
62
- if (this.state === 2)
81
+ if (this.#state === EventSource.CLOSED) {
82
+ this.#controller = null;
63
83
  return false;
64
- if (unlink)
65
- register.delete(this);
66
- try {
67
- this.controller?.close();
68
84
  }
69
- catch (e) {
70
- console.error(e);
71
- this.controller = null;
72
- return false;
85
+ if (this.#controller) {
86
+ try {
87
+ this.#controller.close();
88
+ }
89
+ catch (e) {
90
+ console.error(e);
91
+ }
92
+ this.#controller = null;
73
93
  }
74
94
  // Cleanup
75
- if (this.timer)
76
- clearInterval(this.timer);
77
- this.controller = null;
78
- this.state = 2;
95
+ if (this.#timer)
96
+ clearInterval(this.#timer);
97
+ if (unlink)
98
+ register.delete(this);
99
+ // Mark closed
100
+ this.#state = EventSource.CLOSED;
79
101
  return true;
80
102
  }
81
103
  }
@@ -12,12 +12,18 @@ export async function Resolve(request, tree, config) {
12
12
  const ctx = new GenericContext(request, new URL(request.url), config.render);
13
13
  let response;
14
14
  try {
15
- const x = ctx.url.pathname.endsWith("/") ? ctx.url.pathname.slice(0, -1) : ctx.url.pathname;
16
- const fragments = x.split("/").slice(1);
17
- const res = await tree.resolve(fragments, ctx);
18
- response = res === null
19
- ? new Response("No Route Found", MakeStatus("Not Found", ctx.headers))
20
- : res;
15
+ const x = ctx.url.pathname.slice(1);
16
+ if (x.endsWith("/")) {
17
+ ctx.headers.set("location", ctx.url.pathname.slice(0, -1) + ctx.url.search + ctx.url.hash);
18
+ response = new Response("", MakeStatus("Permanent Redirect", { headers: ctx.headers }));
19
+ }
20
+ else {
21
+ const fragments = x === "" ? [] : x.split("/");
22
+ const res = await tree.resolve(fragments, ctx);
23
+ response = res === null
24
+ ? new Response("No Route Found", MakeStatus("Not Found", ctx.headers))
25
+ : res;
26
+ }
21
27
  // Override with context headers
22
28
  if (response.headers !== ctx.headers) {
23
29
  for (const [key, value] of ctx.headers) {
package/navigate.d.ts CHANGED
@@ -1,3 +1,10 @@
1
- export declare function navigate(href: string, pushHistory?: boolean): Promise<void>;
2
- export declare function revalidate(): Promise<void>;
1
+ export declare function htmxNavigate(href?: string, pushHistory?: boolean): void;
2
+ /**
3
+ * @deprecated - use htmxNavigate() instead
4
+ */
5
+ export declare const navigate: void;
6
+ /**
7
+ * @deprecated - use navigate() instead
8
+ */
9
+ export declare function revalidate(): void;
3
10
  export declare function htmxAppend(href: string, verb?: string): Promise<void>;
package/navigate.js CHANGED
@@ -5,7 +5,7 @@ function htmx() {
5
5
  return htmx;
6
6
  }
7
7
  const driver = (typeof document === "object" ? document.createElement("a") : null);
8
- export async function navigate(href, pushHistory = true) {
8
+ export function htmxNavigate(href = "", pushHistory = true) {
9
9
  if (typeof window !== "object")
10
10
  return;
11
11
  if (!driver)
@@ -29,8 +29,15 @@ export async function navigate(href, pushHistory = true) {
29
29
  htmx().process(driver);
30
30
  driver.click();
31
31
  }
32
+ /**
33
+ * @deprecated - use htmxNavigate() instead
34
+ */
35
+ export const navigate = htmxNavigate();
36
+ /**
37
+ * @deprecated - use navigate() instead
38
+ */
32
39
  export function revalidate() {
33
- return navigate("", false);
40
+ return htmxNavigate("", false);
34
41
  }
35
42
  export async function htmxAppend(href, verb = "GET") {
36
43
  await htmx().ajax(verb, href, {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "htmx-router",
3
- "version": "1.0.12",
3
+ "version": "1.0.14",
4
4
  "description": "A lightweight SSR framework with server+client islands",
5
5
  "keywords": [
6
6
  "htmx",
@@ -28,8 +28,8 @@
28
28
  },
29
29
  "homepage": "https://htmx-router.ajanibilby.com/",
30
30
  "dependencies": {
31
- "es-module-lexer": "^1.5.4",
32
- "vite": "^6.2.3"
31
+ "es-module-lexer": "^1.7.0",
32
+ "vite": "^6.3.5"
33
33
  },
34
34
  "devDependencies": {
35
35
  "@types/node": "^20.4.5",
package/status.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- declare const definitions: {
1
+ declare const dictionary: {
2
2
  100: "Continue";
3
3
  101: "Switching Protocols";
4
4
  102: "Processing";
@@ -63,6 +63,12 @@ declare const definitions: {
63
63
  510: "Not Extended";
64
64
  511: "Network Authentication Required";
65
65
  };
66
- export type StatusText = typeof definitions[keyof typeof definitions];
67
- export declare function MakeStatus(lookup: number | StatusText, init?: ResponseInit | Headers): ResponseInit;
66
+ type Definitions = typeof dictionary;
67
+ export type StatusCode = keyof Definitions;
68
+ export type StatusText = Definitions[StatusCode];
69
+ export declare function MakeStatus(lookup: StatusCode | StatusText, init?: ResponseInit | Headers): ResponseInit;
70
+ /**
71
+ * @deprecated
72
+ */
73
+ export type Status = StatusCode;
68
74
  export {};
package/status.js CHANGED
@@ -1,4 +1,4 @@
1
- const definitions = {
1
+ const dictionary = {
2
2
  100: "Continue",
3
3
  101: "Switching Protocols",
4
4
  102: "Processing",
@@ -63,15 +63,15 @@ const definitions = {
63
63
  510: "Not Extended",
64
64
  511: "Network Authentication Required",
65
65
  };
66
- const lookup = new Array(500);
67
- for (let i = 100; i < 600; i++) {
68
- lookup[i - 100] = definitions[i]
69
- || definitions[i % 100];
70
- }
71
- const index = new Map();
72
- for (const key in definitions) {
73
- const code = Number(key);
74
- index.set(definitions[code].toLowerCase(), code);
66
+ const index = {
67
+ code: new Map(),
68
+ text: new Map()
69
+ };
70
+ for (const k in dictionary) {
71
+ const code = Number(k);
72
+ const text = dictionary[code];
73
+ index.code.set(text.toLowerCase(), code);
74
+ index.text.set(code, text);
75
75
  }
76
76
  export function MakeStatus(lookup, init) {
77
77
  if (init instanceof Headers)
@@ -80,25 +80,20 @@ export function MakeStatus(lookup, init) {
80
80
  return lookupCode(lookup, init);
81
81
  return lookupStatus(lookup, init);
82
82
  }
83
- function lookupCode(status, init) {
84
- if (status < 100)
85
- throw new TypeError(`Status ${status}<100`);
86
- if (status > 599)
87
- throw new TypeError(`Status ${status}>599`);
88
- const statusText = lookup[status];
89
- return Status(status, statusText, init);
83
+ function lookupCode(code, init) {
84
+ const text = index.text.get(code);
85
+ if (text === undefined)
86
+ throw new TypeError(`Status ${code} is not a known status code`);
87
+ return SetStatus(init, code, text);
90
88
  }
91
- function lookupStatus(statusText, init) {
92
- const status = index.get(statusText.toLowerCase());
93
- if (!status)
94
- throw new TypeError(`statusText ${statusText} is not of type StatusText`);
95
- return Status(status, statusText, init);
89
+ function lookupStatus(text, init) {
90
+ const code = index.code.get(text.toLowerCase());
91
+ if (code === undefined)
92
+ throw new TypeError(`Status "${text}" is not a known status text`);
93
+ return SetStatus(init, code, text);
96
94
  }
97
- function Status(status, statusText, init) {
98
- if (init) {
99
- init.statusText = statusText;
100
- init.status = status;
101
- return init;
102
- }
103
- return { status, statusText };
95
+ function SetStatus(into = {}, status, statusText) {
96
+ into.statusText = statusText;
97
+ into.status = status;
98
+ return into;
104
99
  }