hx-stream 0.0.6 → 0.0.8

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/dist/client.js CHANGED
@@ -2,7 +2,8 @@
2
2
  (function () {
3
3
  let binding;
4
4
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
5
- globalThis.htmx.defineExtension("hx-stream", {
5
+ const htmx = globalThis.htmx;
6
+ htmx.defineExtension("hx-stream", {
6
7
  init: (config) => { binding = config; },
7
8
  onEvent: (name, event) => {
8
9
  switch (name) {
@@ -23,30 +24,61 @@
23
24
  }
24
25
  });
25
26
  const decoder = new TextDecoder("utf8");
26
- async function Process(method, url, headers, formData, target) {
27
- target.classList.add("htmx-request");
27
+ async function Process(method, url, headers, formData, source) {
28
+ source.classList.add("htmx-request");
28
29
  const req = await fetch(url, { method, headers, body: formData });
29
30
  if (!req.ok) {
30
31
  console.error(await req.text());
31
- target.classList.remove("htmx-request");
32
+ source.classList.remove("htmx-request");
32
33
  return;
33
34
  }
34
35
  if (!req.body) {
35
36
  console.error("hx-stream response is missing body");
36
- target.classList.remove("htmx-request");
37
+ source.classList.remove("htmx-request");
37
38
  return;
38
39
  }
40
+ const boundary = req.headers.get("X-Chunk-Boundary");
41
+ if (!boundary) {
42
+ console.error("hx-stream response is chunk boundary header");
43
+ source.classList.remove("htmx-request");
44
+ return;
45
+ }
46
+ const open = `<${boundary}>`;
47
+ const close = `</${boundary}>`;
39
48
  const reader = req.body.getReader();
49
+ let buffer = "";
40
50
  // eslint-disable-next-line no-constant-condition
41
51
  while (true) {
42
52
  const { done, value } = await reader.read();
43
53
  if (done)
44
54
  break;
45
- const html = decoder.decode(value).trim();
46
- if (html === "")
47
- continue; // ignore keepalive byte
48
- binding.swap(target, html, { swapStyle: "beforeend" });
55
+ const html = decoder.decode(value);
56
+ const search = Math.max(0, buffer.length - close.length);
57
+ buffer += html;
58
+ let idx = buffer.indexOf(close, search);
59
+ while (idx !== -1) {
60
+ let a = buffer.lastIndexOf(open, idx);
61
+ if (a === -1)
62
+ return console.error("hx-stream received invalid chunk");
63
+ a += open.length;
64
+ const b = buffer.indexOf("|", a);
65
+ if (b === -1)
66
+ return console.error("hx-stream received invalid chunk");
67
+ const c = buffer.indexOf("|", b + 1);
68
+ if (c === -1)
69
+ return console.error("hx-stream received invalid chunk");
70
+ const retarget = buffer.slice(a, b).trim();
71
+ const swap = buffer.slice(b + 1, c).trim();
72
+ const html = buffer.slice(c + 1, idx);
73
+ const target = htmx.find(source, retarget);
74
+ if (target)
75
+ binding.swap(target, html, { swapStyle: swap });
76
+ else
77
+ console.warn(`hx-stream unable to find target ${retarget}`);
78
+ buffer = buffer.slice(idx + close.length);
79
+ idx = buffer.indexOf(close);
80
+ }
49
81
  }
50
- target.classList.remove("htmx-request");
82
+ source.classList.remove("htmx-request");
51
83
  }
52
84
  })();
@@ -1 +1 @@
1
- "use strict";!function(){let e;globalThis.htmx.defineExtension("hx-stream",{init:t=>{e=t},onEvent:(s,r)=>{if("htmx:beforeRequest"!==s);else{const s=r.detail.elt;if("on"!==e.getAttributeValue(s,"hx-stream"))return;r.preventDefault();const o=r.detail.requestConfig.formData,a=r.detail.requestConfig.headers,i=r.detail.requestConfig.path;(async function(s,r,o,a,i){i.classList.add("htmx-request");const n=await fetch(r,{method:s,headers:o,body:a});if(!n.ok)return console.error(await n.text()),void i.classList.remove("htmx-request");if(!n.body)return console.error("hx-stream response is missing body"),void i.classList.remove("htmx-request");const d=n.body.getReader();for(;;){const{done:s,value:r}=await d.read();if(s)break;const o=t.decode(r).trim();""!==o&&e.swap(i,o,{swapStyle:"beforeend"})}i.classList.remove("htmx-request")})(r.detail.requestConfig.verb,i,a,o,r.detail.target).catch(console.error)}}});const t=new TextDecoder("utf8")}();
1
+ "use strict";!function(){let e;const t=globalThis.htmx;t.defineExtension("hx-stream",{init:t=>{e=t},onEvent:(s,n)=>{if("htmx:beforeRequest"!==s);else{const s=n.detail.elt;if("on"!==e.getAttributeValue(s,"hx-stream"))return;n.preventDefault();const o=n.detail.requestConfig.formData,i=n.detail.requestConfig.headers,a=n.detail.requestConfig.path;(async function(s,n,o,i,a){a.classList.add("htmx-request");const c=await fetch(n,{method:s,headers:o,body:i});if(!c.ok)return console.error(await c.text()),void a.classList.remove("htmx-request");if(!c.body)return console.error("hx-stream response is missing body"),void a.classList.remove("htmx-request");const l=c.headers.get("X-Chunk-Boundary");if(!l)return console.error("hx-stream response is chunk boundary header"),void a.classList.remove("htmx-request");const d=`<${l}>`,h=`</${l}>`,u=c.body.getReader();let f="";for(;;){const{done:s,value:n}=await u.read();if(s)break;const o=r.decode(n),i=Math.max(0,f.length-h.length);f+=o;let c=f.indexOf(h,i);for(;-1!==c;){let r=f.lastIndexOf(d,c);if(-1===r)return console.error("hx-stream received invalid chunk");r+=d.length;const s=f.indexOf("|",r);if(-1===s)return console.error("hx-stream received invalid chunk");const n=f.indexOf("|",s+1);if(-1===n)return console.error("hx-stream received invalid chunk");const o=f.slice(r,s).trim(),i=f.slice(s+1,n).trim(),l=f.slice(n+1,c),u=t.find(a,o);u?e.swap(u,l,{swapStyle:i}):console.warn(`hx-stream unable to find target ${o}`),f=f.slice(c+h.length),c=f.indexOf(h)}}a.classList.remove("htmx-request")})(n.detail.requestConfig.verb,a,i,o,n.detail.target).catch(console.error)}}});const r=new TextDecoder("utf8")}();
package/dist/server.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  type Options<T extends boolean> = T extends true ? RenderOptions : DefaultOptions;
2
2
  type DefaultOptions = {
3
3
  keepAlive?: number;
4
+ highWaterMark?: number;
4
5
  };
5
6
  type RenderOptions = {
6
7
  render: (jsx: JSX.Element) => string;
package/dist/server.js CHANGED
@@ -8,10 +8,15 @@ const headers = {
8
8
  "Keep-Alive": "timeout=60",
9
9
  "Connection": "keep-alive",
10
10
  };
11
+ const SCALE = 36 ** 6;
12
+ function MakeBoundary() {
13
+ return "hx-" + Math.floor(Math.random() * SCALE).toString(36);
14
+ }
11
15
  export class StreamResponse {
12
16
  #controller;
13
17
  #timer;
14
18
  #state;
19
+ #boundary;
15
20
  #render;
16
21
  response;
17
22
  // just to make it polyfill
@@ -25,14 +30,16 @@ export class StreamResponse {
25
30
  this.#controller = null;
26
31
  this.#state = StreamResponse.CONNECTING;
27
32
  this.#render = options.render;
33
+ this.#boundary = MakeBoundary();
28
34
  this.withCredentials = request.mode === "cors";
29
35
  this.url = request.url;
30
36
  // immediate prepare for abortion
31
37
  const cancel = () => { this.close(); };
32
38
  request.signal.addEventListener('abort', cancel);
33
39
  const start = (c) => { this.#controller = c; this.#state = StreamResponse.OPEN; };
34
- const stream = new ReadableStream({ start, cancel }, { highWaterMark: 0 });
40
+ const stream = new ReadableStream({ start, cancel }, { highWaterMark: options.highWaterMark || 0 });
35
41
  this.response = new Response(stream, { headers });
42
+ this.response.headers.set("X-Chunk-Boundary", this.#boundary);
36
43
  this.#timer = setInterval(() => this.keepAlive(), options.keepAlive || 30_000);
37
44
  }
38
45
  bind(controller) {
@@ -65,7 +72,7 @@ export class StreamResponse {
65
72
  throw new Error(`Cannot render to JSX when no renderer provided during class initialization`);
66
73
  html = this.#render(html);
67
74
  }
68
- return this.sendText(`<div hx-swap-oob="${swap}:${target}">${html}</div>`);
75
+ return this.sendText(`<${this.#boundary}>${target}|${swap}|${html}</${this.#boundary}>\n`);
69
76
  }
70
77
  close() {
71
78
  if (this.#state === StreamResponse.CLOSED) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hx-stream",
3
- "version": "0.0.6",
3
+ "version": "0.0.8",
4
4
  "description": "keep htmx client state across page refreshes",
5
5
  "keywords": [ "htmx", "streaming" ],
6
6
  "homepage": "https://hx-stream.ajanibilby.com",