hx-stream 0.0.2 → 0.0.4

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
@@ -1,13 +1,4 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  (function () {
12
3
  let binding;
13
4
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -32,32 +23,30 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
32
23
  }
33
24
  });
34
25
  const decoder = new TextDecoder("utf8");
35
- function Process(method, url, headers, formData, target) {
36
- return __awaiter(this, void 0, void 0, function* () {
37
- target.classList.add("htmx-request");
38
- const req = yield fetch(url, { method, headers, body: formData });
39
- if (!req.ok) {
40
- console.error(yield req.text());
41
- target.classList.remove("htmx-request");
42
- return;
43
- }
44
- if (!req.body) {
45
- console.error("hx-stream response is missing body");
46
- target.classList.remove("htmx-request");
47
- return;
48
- }
49
- const reader = req.body.getReader();
50
- // eslint-disable-next-line no-constant-condition
51
- while (true) {
52
- const { done, value: buffer } = yield reader.read();
53
- if (done)
54
- break;
55
- const html = decoder.decode(buffer).trim();
56
- if (html === "")
57
- continue; // ignore keepalive byte
58
- binding.swap(target, html, { swapStyle: "beforeend" });
59
- }
26
+ async function Process(method, url, headers, formData, target) {
27
+ target.classList.add("htmx-request");
28
+ const req = await fetch(url, { method, headers, body: formData });
29
+ if (!req.ok) {
30
+ console.error(await req.text());
60
31
  target.classList.remove("htmx-request");
61
- });
32
+ return;
33
+ }
34
+ if (!req.body) {
35
+ console.error("hx-stream response is missing body");
36
+ target.classList.remove("htmx-request");
37
+ return;
38
+ }
39
+ const reader = req.body.getReader();
40
+ // eslint-disable-next-line no-constant-condition
41
+ while (true) {
42
+ const { done, value } = await reader.read();
43
+ if (done)
44
+ break;
45
+ const html = decoder.decode(value).trim();
46
+ if (html === "")
47
+ continue; // ignore keepalive byte
48
+ binding.swap(target, html, { swapStyle: "beforeend" });
49
+ }
50
+ target.classList.remove("htmx-request");
62
51
  }
63
52
  })();
@@ -1 +1 @@
1
- "use strict";var __awaiter=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{c(n.next(e))}catch(e){i(e)}}function a(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};!function(){let e;globalThis.htmx.defineExtension("hx-stream",{init:t=>{e=t},onEvent:(r,n)=>{if("htmx:beforeRequest"!==r);else{const r=n.detail.elt;if("on"!==e.getAttributeValue(r,"hx-stream"))return;n.preventDefault();const o=n.detail.requestConfig.formData,i=n.detail.requestConfig.headers,s=n.detail.requestConfig.path;(function(r,n,o,i,s){return __awaiter(this,void 0,void 0,(function*(){s.classList.add("htmx-request");const a=yield fetch(n,{method:r,headers:o,body:i});if(!a.ok)return console.error(yield a.text()),void s.classList.remove("htmx-request");if(!a.body)return console.error("hx-stream response is missing body"),void s.classList.remove("htmx-request");const c=a.body.getReader();for(;;){const{done:r,value:n}=yield c.read();if(r)break;const o=t.decode(n).trim();""!==o&&e.swap(s,o,{swapStyle:"beforeend"})}s.classList.remove("htmx-request")}))})(n.detail.requestConfig.verb,s,i,o,n.detail.target).catch(console.error)}}});const t=new TextDecoder("utf8")}();
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")}();
package/dist/server.d.ts CHANGED
@@ -8,7 +8,7 @@ type RenderOptions = {
8
8
  type HasRender<O> = O extends {
9
9
  render: (jsx: JSX.Element) => string;
10
10
  } ? true : false;
11
- export declare class StreamResponse<O extends Options<boolean>, T extends boolean = HasRender<O>> {
11
+ export declare class StreamResponse<JsxEnabled extends boolean> {
12
12
  #private;
13
13
  readonly response: Response;
14
14
  readonly withCredentials: boolean;
@@ -17,11 +17,13 @@ export declare class StreamResponse<O extends Options<boolean>, T extends boolea
17
17
  static CONNECTING: number;
18
18
  static OPEN: number;
19
19
  static CLOSED: number;
20
- constructor(request: Request, options: O);
20
+ constructor(request: Request, options: Options<JsxEnabled>);
21
+ bind(controller: ReadableByteStreamController): void;
21
22
  private sendBytes;
22
23
  private sendText;
23
24
  private keepAlive;
24
- send(target: string, swap: string, html: T extends true ? (JSX.Element | string) : string): boolean;
25
+ send(target: string, swap: string, html: JsxEnabled extends true ? (JSX.Element | string) : string): boolean;
25
26
  close(): boolean;
26
27
  }
28
+ export declare function MakeStream<O extends (DefaultOptions | RenderOptions)>(request: Request, options: O): StreamResponse<HasRender<O>>;
27
29
  export {};
package/dist/server.js ADDED
@@ -0,0 +1,93 @@
1
+ const encoder = new TextEncoder();
2
+ const headers = {
3
+ // Chunked encoding with immediate forwarding by proxies (i.e. nginx)
4
+ "X-Accel-Buffering": "no",
5
+ "Transfer-Encoding": "chunked",
6
+ "Content-Type": "text/html",
7
+ // the maximum keep alive chrome shouldn't ignore
8
+ "Keep-Alive": "timeout=60",
9
+ "Connection": "keep-alive",
10
+ };
11
+ export class StreamResponse {
12
+ #controller;
13
+ #timer;
14
+ #state;
15
+ #render;
16
+ response;
17
+ // just to make it polyfill
18
+ withCredentials;
19
+ url;
20
+ get readyState() { return this.#state; }
21
+ static CONNECTING = 0;
22
+ static OPEN = 1;
23
+ static CLOSED = 2;
24
+ constructor(request, options) {
25
+ this.#controller = null;
26
+ this.#state = StreamResponse.CONNECTING;
27
+ this.withCredentials = request.mode === "cors";
28
+ this.url = request.url;
29
+ // immediate prepare for abortion
30
+ const cancel = () => { this.close(); };
31
+ request.signal.addEventListener('abort', cancel);
32
+ const start = (c) => { this.#controller = c; this.#state = StreamResponse.OPEN; };
33
+ const stream = new ReadableStream({ start, cancel }, { highWaterMark: 0 });
34
+ this.response = new Response(stream, { headers });
35
+ this.#timer = setInterval(() => this.keepAlive(), options.keepAlive || 30_000);
36
+ }
37
+ bind(controller) {
38
+ this.#controller = controller;
39
+ }
40
+ sendBytes(chunk) {
41
+ if (!this.#controller)
42
+ return false;
43
+ try {
44
+ this.#controller.enqueue(chunk);
45
+ return true;
46
+ }
47
+ catch (e) {
48
+ console.error(e);
49
+ this.close(); // unbind on failure
50
+ return false;
51
+ }
52
+ }
53
+ sendText(chunk) {
54
+ return this.sendBytes(encoder.encode(chunk));
55
+ }
56
+ keepAlive() { return this.sendText(" "); }
57
+ send(target, swap, html) {
58
+ if (this.#state === StreamResponse.CLOSED) {
59
+ const err = new Error(`Warn: Attempted to send data on closed stream for: ${this.url}`);
60
+ console.warn(err);
61
+ }
62
+ if (typeof html !== "string") {
63
+ if (!this.#render)
64
+ throw new Error(`Cannot render to JSX when no renderer provided during class initialization`);
65
+ html = this.#render(html);
66
+ }
67
+ return this.sendText(`<div hx-swap-oob="${swap}:${target}">${html}</div>`);
68
+ }
69
+ close() {
70
+ if (this.#state === StreamResponse.CLOSED) {
71
+ this.#controller = null;
72
+ return false;
73
+ }
74
+ if (this.#controller) {
75
+ try {
76
+ this.#controller.close();
77
+ }
78
+ catch (e) {
79
+ console.error(e);
80
+ }
81
+ this.#controller = null;
82
+ }
83
+ // Cleanup
84
+ if (this.#timer)
85
+ clearInterval(this.#timer);
86
+ // Mark closed
87
+ this.#state = StreamResponse.CLOSED;
88
+ return true;
89
+ }
90
+ }
91
+ export function MakeStream(request, options) {
92
+ return new StreamResponse(request, options);
93
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hx-stream",
3
- "version": "0.0.2",
3
+ "version": "0.0.4",
4
4
  "description": "keep htmx client state across page refreshes",
5
5
  "keywords": [ "htmx", "streaming" ],
6
6
  "homepage": "https://hx-stream.ajanibilby.com",
@@ -14,7 +14,7 @@
14
14
  "scripts": {
15
15
  "build": "npm run build:client & npm run build:server",
16
16
  "build:client": "tsc --project tsconfig.client.json",
17
- "build:server": "tsc --project tsconfig.server.json",
17
+ "build:server": "tsc --project tsconfig.json",
18
18
  "minify": "npm run minify:client",
19
19
  "minify:client": "terser dist/client.js --compress --mangle --output dist/client.min.js"
20
20
  },