hx-stream 0.0.10 → 0.2.0

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
@@ -26,7 +26,7 @@
26
26
  const decoder = new TextDecoder("utf8");
27
27
  async function Process(method, url, headers, formData, source) {
28
28
  source.classList.add("htmx-request");
29
- const req = await fetch(url, { method, headers, body: formData });
29
+ const req = await fetch(url, { method, headers, body: formData, duplex: "half" });
30
30
  if (!req.ok) {
31
31
  console.error(await req.text());
32
32
  source.classList.remove("htmx-request");
@@ -1 +1 @@
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 d=c.headers.get("X-Chunk-Boundary");if(!d)return console.error("hx-stream response is chunk boundary header"),void a.classList.remove("htmx-request");const l=`<${d}>`,h=`</${d}>`,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(l,c);if(-1===r)return console.error("hx-stream received invalid chunk");r+=l.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(),d=f.slice(n+1,c);let u;switch(o){case"this":u=a;break;case"body":u=document.body;break;default:u=t.find(a,o)}u?e.swap(u,d,{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")}();
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,duplex:"half"});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);let u;switch(o){case"this":u=a;break;case"body":u=document.body;break;default: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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hx-stream",
3
- "version": "0.0.10",
3
+ "version": "0.2.0",
4
4
  "description": "keep htmx client state across page refreshes",
5
5
  "keywords": [ "htmx", "streaming" ],
6
6
  "homepage": "https://hx-stream.ajanibilby.com",
@@ -16,12 +16,12 @@
16
16
  "build:client": "tsc --project tsconfig.client.json",
17
17
  "build:server": "tsc --project tsconfig.json",
18
18
  "minify": "npm run minify:client",
19
- "minify:client": "terser dist/client.js --compress --mangle --output dist/client.min.js"
19
+ "minify:client": "terser client.js --compress --mangle --output client.min.js"
20
20
  },
21
21
  "license": "MIT",
22
22
  "author": "Ajani Bilby",
23
23
  "type": "module",
24
- "main": "dist/client.min.js",
24
+ "main": "client.min.js",
25
25
  "devDependencies": {
26
26
  "terser": "^5.39.0",
27
27
  "typescript": "^5.8.3"
package/dist/server.d.ts DELETED
@@ -1,30 +0,0 @@
1
- type Options<T extends boolean> = T extends true ? RenderOptions : DefaultOptions;
2
- type DefaultOptions = {
3
- keepAlive?: number;
4
- highWaterMark?: number;
5
- };
6
- type RenderOptions = {
7
- render: (jsx: JSX.Element) => string;
8
- } & DefaultOptions;
9
- type HasRender<O> = O extends {
10
- render: (jsx: JSX.Element) => string;
11
- } ? true : false;
12
- export declare class StreamResponse<JsxEnabled extends boolean> {
13
- #private;
14
- readonly response: Response;
15
- readonly withCredentials: boolean;
16
- readonly url: string;
17
- get readyState(): number;
18
- static CONNECTING: number;
19
- static OPEN: number;
20
- static CLOSED: number;
21
- constructor(request: Request, options: Options<JsxEnabled>);
22
- bind(controller: ReadableByteStreamController): void;
23
- private sendBytes;
24
- private sendText;
25
- private keepAlive;
26
- send(target: string, swap: string, html: JsxEnabled extends true ? (JSX.Element | string) : string): boolean;
27
- close(): boolean;
28
- }
29
- export declare function MakeStream<O extends (DefaultOptions | RenderOptions)>(request: Request, options: O): StreamResponse<HasRender<O>>;
30
- export {};
package/dist/server.js DELETED
@@ -1,106 +0,0 @@
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
- const SCALE = 36 ** 6;
12
- function MakeBoundary() {
13
- return "hx-" + Math.floor(Math.random() * SCALE).toString(36);
14
- }
15
- export class StreamResponse {
16
- #controller;
17
- #signal;
18
- #timer;
19
- #state;
20
- #boundary;
21
- #render;
22
- response;
23
- // just to make it polyfill
24
- withCredentials;
25
- url;
26
- get readyState() { return this.#state; }
27
- static CONNECTING = 0;
28
- static OPEN = 1;
29
- static CLOSED = 2;
30
- constructor(request, options) {
31
- this.#controller = null;
32
- this.#state = StreamResponse.CONNECTING;
33
- this.#render = options.render;
34
- this.#boundary = MakeBoundary();
35
- this.withCredentials = request.mode === "cors";
36
- this.url = request.url;
37
- // immediate prepare for abortion
38
- const cancel = () => { this.close(); };
39
- request.signal.addEventListener('abort', cancel);
40
- this.#signal = request.signal;
41
- const start = (c) => { this.#controller = c; this.#state = StreamResponse.OPEN; };
42
- const stream = new ReadableStream({ start, cancel }, { highWaterMark: options.highWaterMark || 0 });
43
- this.response = new Response(stream, { headers });
44
- this.response.headers.set("X-Chunk-Boundary", this.#boundary);
45
- this.#timer = setInterval(() => this.keepAlive(), options.keepAlive || 30_000);
46
- }
47
- bind(controller) {
48
- this.#controller = controller;
49
- }
50
- sendBytes(chunk) {
51
- if (this.#state === StreamResponse.CLOSED) {
52
- const err = new Error(`Warn: Attempted to send data on closed stream for: ${this.url}`);
53
- console.warn(err);
54
- }
55
- if (this.#signal.aborted) {
56
- this.close();
57
- return false;
58
- }
59
- if (!this.#controller)
60
- return false;
61
- try {
62
- this.#controller.enqueue(chunk);
63
- return true;
64
- }
65
- catch (e) {
66
- console.error(e);
67
- this.close(); // unbind on failure
68
- return false;
69
- }
70
- }
71
- sendText(chunk) {
72
- return this.sendBytes(encoder.encode(chunk));
73
- }
74
- keepAlive() { return this.sendText(" "); }
75
- send(target, swap, html) {
76
- if (typeof html !== "string") {
77
- if (!this.#render)
78
- throw new Error(`Cannot render to JSX when no renderer provided during class initialization`);
79
- html = this.#render(html);
80
- }
81
- return this.sendText(`<${this.#boundary}>${target}|${swap}|${html}</${this.#boundary}>\n`);
82
- }
83
- close() {
84
- if (this.#controller) {
85
- try {
86
- this.#controller.close();
87
- }
88
- catch (e) {
89
- console.error(e);
90
- }
91
- this.#controller = null;
92
- }
93
- // Cleanup
94
- if (this.#timer)
95
- clearInterval(this.#timer);
96
- // was already closed
97
- if (this.#state === EventSource.CLOSED)
98
- return false;
99
- // Mark closed
100
- this.#state = StreamResponse.CLOSED;
101
- return true;
102
- }
103
- }
104
- export function MakeStream(request, options) {
105
- return new StreamResponse(request, options);
106
- }