@hyperspan/framework 1.0.20 → 1.0.22
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/package.json +2 -2
- package/src/actions.test.ts +1 -1
- package/src/actions.ts +15 -7
- package/src/client/_hs/hyperspan-actions.client.ts +97 -8
- package/src/middleware.ts +2 -2
- package/src/types.ts +26 -15
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hyperspan/framework",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.22",
|
|
4
4
|
"description": "Hyperspan Web Framework",
|
|
5
5
|
"main": "src/server.ts",
|
|
6
6
|
"types": "src/server.ts",
|
|
@@ -84,6 +84,6 @@
|
|
|
84
84
|
"@hyperspan/html": "^1.0.1",
|
|
85
85
|
"debug": "^4.4.3",
|
|
86
86
|
"isbot": "^5.1.32",
|
|
87
|
-
"zod": "^4.
|
|
87
|
+
"zod": "^4.4.3"
|
|
88
88
|
}
|
|
89
89
|
}
|
package/src/actions.test.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { test, expect, describe } from 'bun:test';
|
|
|
2
2
|
import { createAction } from './actions';
|
|
3
3
|
import { html, render, type HSHtml } from '@hyperspan/html';
|
|
4
4
|
import { createContext } from './server';
|
|
5
|
-
import * as z from 'zod
|
|
5
|
+
import * as z from 'zod';
|
|
6
6
|
|
|
7
7
|
describe('createAction', () => {
|
|
8
8
|
test('creates an action with a simple form and no schema', async () => {
|
package/src/actions.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { html } from '@hyperspan/html';
|
|
2
2
|
import { createRoute, HTTPResponseException, returnHTMLResponse } from './server';
|
|
3
|
-
import * as z from 'zod
|
|
3
|
+
import * as z from 'zod';
|
|
4
4
|
import type { Hyperspan as HS } from './types';
|
|
5
5
|
import { assetHash, formDataToJSON } from './utils';
|
|
6
6
|
import { buildClientJS } from './client/js';
|
|
@@ -23,12 +23,20 @@ const actionsClientJS = await buildClientJS(import.meta.resolve('./client/_hs/hy
|
|
|
23
23
|
* 5. Replaces form content in place with HTML response content from server via the Idiomorph library
|
|
24
24
|
* 6. Handles any Exception thrown on server as error displayed back to user on the page
|
|
25
25
|
*/
|
|
26
|
-
export function createAction<
|
|
26
|
+
export function createAction<S extends z.ZodType>(
|
|
27
|
+
params: { name: string; schema: S }
|
|
28
|
+
): HS.Action<S>;
|
|
29
|
+
export function createAction(
|
|
30
|
+
params: { name: string; schema?: undefined }
|
|
31
|
+
): HS.Action<undefined>;
|
|
32
|
+
export function createAction<S extends z.ZodType>(
|
|
33
|
+
params: { name: string; schema?: S }
|
|
34
|
+
): HS.Action<S | undefined> {
|
|
27
35
|
const { name, schema } = params;
|
|
28
36
|
const path = `/__actions/${assetHash(name)}`;
|
|
29
37
|
|
|
30
|
-
let _handler: Parameters<HS.Action<
|
|
31
|
-
let _errorHandler: Parameters<HS.Action<
|
|
38
|
+
let _handler: Parameters<HS.Action<S | undefined>['post']>[0] | null = null;
|
|
39
|
+
let _errorHandler: Parameters<HS.Action<S | undefined>['errorHandler']>[0] | null = null;
|
|
32
40
|
|
|
33
41
|
const route = createRoute({ path, name })
|
|
34
42
|
.get((c: HS.Context) => api.render(c))
|
|
@@ -37,7 +45,7 @@ export function createAction<T extends z.ZodObject<any, any>>(params: { name: st
|
|
|
37
45
|
throw new Error('Action POST handler not set! Every action must have a POST handler.');
|
|
38
46
|
}
|
|
39
47
|
|
|
40
|
-
const data = c.vars.body as
|
|
48
|
+
const data = c.vars.body as HS.InferActionData<S> || formDataToJSON(await c.req.formData()) || {};
|
|
41
49
|
log('POST handler', { data });
|
|
42
50
|
const response = await _handler(c, { data });
|
|
43
51
|
log('POST handler response', { response });
|
|
@@ -57,7 +65,7 @@ export function createAction<T extends z.ZodObject<any, any>>(params: { name: st
|
|
|
57
65
|
* Custom error handler for the action since validateBody() throws a HTTPResponseException
|
|
58
66
|
*/
|
|
59
67
|
.errorHandler(async (c: HS.Context, err: HTTPResponseException) => {
|
|
60
|
-
const data = c.vars.body as
|
|
68
|
+
const data = c.vars.body as HS.InferActionData<S> || formDataToJSON(await c.req.formData()) || {};
|
|
61
69
|
const error = err._error as ZodValidationError || err;
|
|
62
70
|
|
|
63
71
|
// Set the status to 400 if it's a ZodValidationError, otherwise 500 (Error thrown by user POST handler)
|
|
@@ -73,7 +81,7 @@ export function createAction<T extends z.ZodObject<any, any>>(params: { name: st
|
|
|
73
81
|
// Set the name of the action for the route
|
|
74
82
|
route._config.name = name;
|
|
75
83
|
|
|
76
|
-
const api: HS.Action<
|
|
84
|
+
const api: HS.Action<S | undefined> = {
|
|
77
85
|
_kind: 'hsAction',
|
|
78
86
|
_config: route._config,
|
|
79
87
|
_path() {
|
|
@@ -99,7 +99,7 @@ function formSubmitToRoute(e: Event, form: HTMLFormElement, opts: TFormSubmitOpt
|
|
|
99
99
|
}
|
|
100
100
|
|
|
101
101
|
fetch(formUrl, { body: formData, method, headers })
|
|
102
|
-
.then((res: Response) => {
|
|
102
|
+
.then(async (res: Response) => {
|
|
103
103
|
// Look for special header that indicates a redirect.
|
|
104
104
|
// fetch() automatically follows 3xx redirects, so we need to handle this manually to redirect the user to the full page
|
|
105
105
|
if (res.headers.has('X-Redirect-Location')) {
|
|
@@ -109,21 +109,20 @@ function formSubmitToRoute(e: Event, form: HTMLFormElement, opts: TFormSubmitOpt
|
|
|
109
109
|
|
|
110
110
|
// If the new URL is the same as the current URL, we can just fetch the new HTML and apply it
|
|
111
111
|
if (resolved.pathname === window.location.pathname) {
|
|
112
|
-
|
|
112
|
+
const pageRes = await fetch(resolved.href, {
|
|
113
113
|
headers: { Accept: 'text/html' },
|
|
114
|
-
})
|
|
115
|
-
|
|
114
|
+
});
|
|
115
|
+
await consumeStreamingHtmlResponse(pageRes, applyResponseHtml);
|
|
116
|
+
return;
|
|
116
117
|
}
|
|
117
118
|
|
|
118
119
|
// If the new URL is different, we need to redirect the user to the new URL
|
|
119
120
|
window.location.assign(newUrl);
|
|
120
121
|
}
|
|
121
|
-
return
|
|
122
|
+
return;
|
|
122
123
|
}
|
|
123
124
|
|
|
124
|
-
|
|
125
|
-
})
|
|
126
|
-
.then((content: string) => {
|
|
125
|
+
const content = await res.text();
|
|
127
126
|
// No content = DO NOTHING (redirect or something else happened)
|
|
128
127
|
if (!content) {
|
|
129
128
|
return;
|
|
@@ -134,4 +133,94 @@ function formSubmitToRoute(e: Event, form: HTMLFormElement, opts: TFormSubmitOpt
|
|
|
134
133
|
.catch((error) => {
|
|
135
134
|
console.error('[Hyperspan] Error submitting form action:', error);
|
|
136
135
|
});
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** Streaming async chunks use template ids ending in `_content`. */
|
|
139
|
+
const STREAM_CHUNK_MARKER = /<template id="[^"]+_content">/;
|
|
140
|
+
|
|
141
|
+
function splitInitialStreamHtml(html: string): { initial: string; streamTail: string | null } {
|
|
142
|
+
const match = STREAM_CHUNK_MARKER.exec(html);
|
|
143
|
+
if (!match || match.index === 0) {
|
|
144
|
+
return { initial: html, streamTail: null };
|
|
145
|
+
}
|
|
146
|
+
return {
|
|
147
|
+
initial: html.slice(0, match.index),
|
|
148
|
+
streamTail: html.slice(match.index),
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** Append streamed HTML to body and run any inline scripts (e.g. window._hsc.push). */
|
|
153
|
+
function appendHtmlToBody(html: string) {
|
|
154
|
+
if (!html) {
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const template = document.createElement('template');
|
|
159
|
+
template.innerHTML = html;
|
|
160
|
+
const scripts: HTMLScriptElement[] = [];
|
|
161
|
+
template.content.querySelectorAll('script').forEach((script) => {
|
|
162
|
+
scripts.push(script);
|
|
163
|
+
script.remove();
|
|
164
|
+
});
|
|
165
|
+
document.body.appendChild(template.content);
|
|
166
|
+
for (const script of scripts) {
|
|
167
|
+
const executable = document.createElement('script');
|
|
168
|
+
if (script.src) {
|
|
169
|
+
executable.src = script.src;
|
|
170
|
+
} else {
|
|
171
|
+
executable.textContent = script.textContent;
|
|
172
|
+
}
|
|
173
|
+
document.body.appendChild(executable);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Read a (possibly streaming) HTML response: Idiomorph the initial page HTML, then append
|
|
179
|
+
* later stream chunks to document.body so streaming scripts run and placeholders resolve.
|
|
180
|
+
*/
|
|
181
|
+
async function consumeStreamingHtmlResponse(
|
|
182
|
+
res: Response,
|
|
183
|
+
applyInitialHtml: (html: string) => void
|
|
184
|
+
) {
|
|
185
|
+
const body = res.body;
|
|
186
|
+
if (!body) {
|
|
187
|
+
const text = await res.text();
|
|
188
|
+
if (text) {
|
|
189
|
+
applyInitialHtml(text);
|
|
190
|
+
}
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
const reader = body.getReader();
|
|
195
|
+
const decoder = new TextDecoder();
|
|
196
|
+
let isFirstChunk = true;
|
|
197
|
+
|
|
198
|
+
function processChunk(html: string) {
|
|
199
|
+
if (!html) {
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
if (isFirstChunk) {
|
|
204
|
+
isFirstChunk = false;
|
|
205
|
+
const { initial, streamTail } = splitInitialStreamHtml(html);
|
|
206
|
+
if (initial) {
|
|
207
|
+
applyInitialHtml(initial);
|
|
208
|
+
}
|
|
209
|
+
if (streamTail) {
|
|
210
|
+
appendHtmlToBody(streamTail);
|
|
211
|
+
}
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
appendHtmlToBody(html);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
while (true) {
|
|
219
|
+
const { done, value } = await reader.read();
|
|
220
|
+
if (done) {
|
|
221
|
+
processChunk(decoder.decode());
|
|
222
|
+
break;
|
|
223
|
+
}
|
|
224
|
+
processChunk(decoder.decode(value, { stream: true }));
|
|
225
|
+
}
|
|
137
226
|
}
|
package/src/middleware.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { formDataToJSON } from './utils';
|
|
2
|
-
import { z, flattenError, prettifyError } from 'zod
|
|
2
|
+
import { z, flattenError, prettifyError } from 'zod';
|
|
3
3
|
import { HTTPResponseException } from './server';
|
|
4
4
|
|
|
5
|
-
import type { ZodAny, ZodObject, ZodError } from 'zod
|
|
5
|
+
import type { ZodAny, ZodObject, ZodError } from 'zod';
|
|
6
6
|
import type { Hyperspan as HS } from './types';
|
|
7
7
|
|
|
8
8
|
export type TValidationType = 'json' | 'form' | 'urlencoded';
|
package/src/types.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { HSHtml } from '@hyperspan/html';
|
|
2
|
-
import * as z from 'zod
|
|
2
|
+
import * as z from 'zod';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Hyperspan Types
|
|
@@ -175,30 +175,41 @@ export namespace Hyperspan {
|
|
|
175
175
|
/**
|
|
176
176
|
* Action = Form + route handler
|
|
177
177
|
*/
|
|
178
|
+
/** Raw form field values when an action has no schema */
|
|
179
|
+
export type ActionFormValues = Record<string, string | string[]>;
|
|
180
|
+
/** Infer validated action data from an optional schema */
|
|
181
|
+
export type InferActionData<S extends z.ZodType | undefined> =
|
|
182
|
+
S extends z.ZodType ? z.output<S> : ActionFormValues;
|
|
178
183
|
// Form renderer
|
|
179
184
|
export type ActionFormResponse = HSHtml | void | null | Promise<HSHtml | void | null>;
|
|
180
|
-
export type ActionFormProps<
|
|
181
|
-
|
|
182
|
-
|
|
185
|
+
export type ActionFormProps<S extends z.ZodType | undefined = undefined> = {
|
|
186
|
+
data?: Partial<InferActionData<S>>;
|
|
187
|
+
error?: ZodValidationError;
|
|
188
|
+
};
|
|
189
|
+
export type ActionForm<S extends z.ZodType | undefined = undefined> = (
|
|
190
|
+
c: Context, props: ActionFormProps<S>
|
|
183
191
|
) => ActionFormResponse;
|
|
184
192
|
// Form handler
|
|
185
193
|
export type ActionFormHandlerResponse = ActionFormResponse | Response | Promise<Response>;
|
|
186
|
-
export type ActionFormHandlerProps<
|
|
187
|
-
|
|
188
|
-
|
|
194
|
+
export type ActionFormHandlerProps<S extends z.ZodType | undefined = undefined> = {
|
|
195
|
+
data: InferActionData<S>;
|
|
196
|
+
error?: ZodValidationError | Error;
|
|
197
|
+
};
|
|
198
|
+
export type ActionFormHandler<S extends z.ZodType | undefined = undefined> = (
|
|
199
|
+
c: Context, props: ActionFormHandlerProps<S>
|
|
189
200
|
) => ActionFormHandlerResponse;
|
|
190
201
|
// Action API
|
|
191
|
-
export interface Action<
|
|
202
|
+
export interface Action<S extends z.ZodType | undefined = undefined> {
|
|
192
203
|
_kind: 'hsAction';
|
|
193
204
|
_config: Partial<Hyperspan.RouteConfig>;
|
|
194
205
|
_path(): string;
|
|
195
|
-
_form: null | ActionForm<
|
|
196
|
-
form(form: ActionForm<
|
|
197
|
-
render: (c: Context, props?: ActionFormProps<
|
|
198
|
-
post: (handler: ActionFormHandler<
|
|
199
|
-
errorHandler: (handler: ActionFormHandler<
|
|
200
|
-
use: (middleware: Hyperspan.MiddlewareFunction, opts?: Hyperspan.MiddlewareMethodOptions) => Action<
|
|
201
|
-
middleware: (middleware: Array<Hyperspan.MiddlewareFunction>, opts?: Hyperspan.MiddlewareMethodOptions) => Action<
|
|
206
|
+
_form: null | ActionForm<S>;
|
|
207
|
+
form(form: ActionForm<S>): Action<S>;
|
|
208
|
+
render: (c: Context, props?: ActionFormProps<S>) => ActionFormResponse;
|
|
209
|
+
post: (handler: ActionFormHandler<S>) => Action<S>;
|
|
210
|
+
errorHandler: (handler: ActionFormHandler<S>) => Action<S>;
|
|
211
|
+
use: (middleware: Hyperspan.MiddlewareFunction, opts?: Hyperspan.MiddlewareMethodOptions) => Action<S>;
|
|
212
|
+
middleware: (middleware: Array<Hyperspan.MiddlewareFunction>, opts?: Hyperspan.MiddlewareMethodOptions) => Action<S>;
|
|
202
213
|
fetch: (request: Request) => Promise<Response>;
|
|
203
214
|
}
|
|
204
215
|
|