1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299 |
x9
x9
x9
x9
x9
x9
x9
x111
x9
x9
x16
x17
x17
x16
x16
x16
x24
x24
x24
x25
x25
x24
x25
x25
x24
x30
x24
x24
x110
x16
x9
x9
x9
x45
x72
x27
x27
x27
x27
x9
x9
x9
x9
x9
x9
x9
x9
x111
x9
x9
x19
x20
x20
x19
x76
x19
x28
x42
x23
x23
x23
x23
x23
x23
x39
x20
x20
x20
x20
x20
x20
x40
x21
x21
x21
x21
x21
x21
x39
x20
x20
x20
x20
x120
x20
x20
x19
x168
x19
x9
x9
x9
x36
x27
x27
x27
x27
x27
x27
x27
x27
x9
x9
x9
x9
x9
x9
x9
x9
x111
x9
x9
x62
x65
x65
x656
x62
x62
x496
x362
x369
x369
x362
x112
x151
x1087
x151
x184
x186
x186
x215
x215
x151
x152
x152
x1128
x151
x1256
x157
x188
x112
x62
x68
x68
x412
x119
x119
x574
x62
x9
x9
x9
x81
x27
x27
x27
x27
x27
x27
x9
x9
x9
x9
x9
x9
x9
x9
x9
x9
x50
x51
x51
x90
x50
x53
x53
x50
x360
x90
x96
x102
x416
x104
x102
x104
x104
x416
x96
x96
x99
x99
x96
x127
x127
x90
x94
x94
x96
x96
x96
x96
x288
x96
x96
x96
x96
x96
x94
x94
x127
x198
x108
x108
x108
x190
x100
x100
x102
x102
x100
x100
x182
x276
x92
x93
x93
x92
x92
x182
x92
x92
x92
x181
x91
x91
x91
x91
x90
x810
x127
x50
x9
x54 |
|
import { type Arg, type Cache, type Directive, type Nullable, type Optional, Phase } from "@mizu/internal/engine"
import { escape } from "@std/html"
export type * from "@mizu/internal/engine"
export const _header = {
name: "%header",
phase: Phase.HTTP_HEADER,
multiple: true,
init(renderer) {
renderer.cache<Cache<typeof _header>>(this.name, new WeakMap())
},
async execute(renderer, element, { attributes, cache, ...options }) {
if (!renderer.isHtmlElement(element)) {
return
}
const headers = cache.get(element) ?? cache.set(element, new Headers()).get(element)!
const parsed = attributes.map((attribute) => renderer.parseAttribute(attribute))
for (const { tag: name, value: expression } of parsed) {
const value = await renderer.evaluate(element, expression, options)
switch (true) {
case (value === undefined) || (value === null):
headers.delete(name)
break
case Array.isArray(value):
value.forEach((v) => headers.append(name, v))
break
default:
headers.set(name, `${value}`)
}
}
return { state: { $headers: headers } }
},
} as Directive<WeakMap<HTMLElement, Headers>>
export const _body_typings = {
modifiers: {
header: { type: Boolean, default: true, enforce: true },
type: { type: String, allowed: ["text", "form", "json", "xml"] },
text: { type: Boolean },
form: { type: Boolean },
json: { type: Boolean },
xml: { type: Boolean },
},
} as const
export const _body = {
name: "%body",
prefix: "%",
phase: Phase.HTTP_BODY,
typings: _body_typings,
init(renderer) {
renderer.cache<Cache<typeof _body>>(this.name, new WeakMap())
},
async execute(renderer, element, { attributes: [attribute], ...options }) {
if (!renderer.isHtmlElement(element)) {
return
}
const headers = renderer.cache<Cache<typeof _header>>(_header.name)!.get(element) ?? renderer.cache<Cache<typeof _header>>(_header.name)!.set(element, new Headers()).get(element)!
const { modifiers, value: expression } = renderer.parseAttribute(attribute, this.typings, { prefix: this.prefix, modifiers: true })
let body = await renderer.evaluate(element, expression, options)
switch (true) {
case (modifiers.type === "text") || (modifiers.text): {
if (modifiers.header) {
headers.set("Content-Type", "text/plain")
}
body = `${body}`
break
}
case (modifiers.type === "form") || (modifiers.form): {
if (modifiers.header) {
headers.set("Content-Type", "application/x-www-form-urlencoded")
}
body = new URLSearchParams(body as Record<PropertyKey, string>)
break
}
case (modifiers.type === "json") || (modifiers.json): {
if (modifiers.header) {
headers.set("Content-Type", "application/json")
}
body = JSON.stringify(body)
break
}
case (modifiers.type === "xml") || (modifiers.xml): {
if (modifiers.header) {
headers.set("Content-Type", "application/xml")
}
const { stringify } = await import("@libs/xml/stringify")
body = stringify(body as Arg<typeof stringify>, { format: { indent: "", breakline: Infinity } })
break
}
}
return { state: { $headers: headers, $body: body } }
},
} as Directive<WeakMap<HTMLElement, BodyInit>, typeof _body_typings>
export const _http_typings = {
modifiers: {
follow: { type: Boolean, enforce: true },
history: { type: Boolean },
method: { type: String },
get: { type: Boolean },
head: { type: Boolean },
post: { type: Boolean },
put: { type: Boolean },
patch: { type: Boolean },
delete: { type: Boolean },
},
} as const
export const _http = {
name: "%http",
prefix: "%",
phase: Phase.HTTP_REQUEST,
typings: _http_typings,
init(renderer) {
renderer.cache<Cache<typeof _http>>(this.name, new WeakMap())
},
execute(renderer, element, { cache, attributes: [attribute], state, ...options }) {
if (!renderer.isHtmlElement(element)) {
return
}
const { modifiers } = renderer.parseAttribute(attribute, _http_typings, { prefix: this.prefix, modifiers: true })
const redirect = modifiers.follow ? "follow" : "manual"
let method = modifiers.method?.toLocaleUpperCase()
for (const key of ["get", "head", "post", "put", "patch", "delete"] as const) {
if (modifiers[key]) {
method = key.toUpperCase()
}
}
const callback = async function ($event: Nullable<Event>) {
const value = attribute.value
const url = new URL(URL.canParse(value) || /^\.?\//.test(value) ? value : `${await renderer.evaluate(element, value, { state: { ...state, $event }, ...options })}`, globalThis.location?.href)
if ($event === null) {
if (cache.get(element) === url.href) {
return
}
cache.set(element, url.href)
}
if (modifiers.history) {
renderer.window.history.pushState(null, "", url.href)
}
const $response = fetch(url, { redirect, method, headers: state.$headers as Headers, body: state.$body as BodyInit })
if ($event) {
await renderer.render(element, { ...options, state: { ...state, $event, $response: await $response } })
}
return $response
}
if (arguments[2]._return_callback) {
return callback as ReturnType<NonNullable<Directive["execute"]>>
}
if (!renderer.getAttributes(element, _response.name, { first: true })) {
return
}
return callback(null).then(($response) => ({ state: { $response } }))
},
} as Directive<WeakMap<Element, string>> & { execute: NonNullable<Directive["execute"]> }
export const _response_typings = {
modifiers: {
consume: { type: String, allowed: ["void", "text", "html", "json", "xml"] },
void: { type: Boolean },
text: { type: Boolean },
html: { type: Boolean },
json: { type: Boolean },
xml: { type: Boolean },
swap: { type: Boolean },
},
} as const
export const _response = {
name: "%response",
prefix: "%",
phase: Phase.HTTP_CONTENT,
typings: _response_typings,
multiple: true,
default: "null",
async execute(renderer, element, { attributes, state, ...options }) {
if (!renderer.isHtmlElement(element)) {
return
}
const $response = state.$response as Optional<Response>
if (!$response) {
return
}
for (const attribute of attributes) {
const { tag, modifiers, value: expression } = renderer.parseAttribute(attribute, this.typings, { prefix: this.prefix, modifiers: true })
if (tag) {
const match = tag.replace(/\s/g, "").split(",").map((code) => {
if (/^[2-5]xx$/i.test(code)) {
return [Number(code.at(0)) * 100, Number(code.at(0)) * 100 + 99]
}
if (/^\d+-\d+$/.test(code)) {
return code.split("-").map(Number)
}
return [Number(code), Number(code)]
}).some(([min, max]) => ($response.status >= min) && ($response.status <= max))
if (!match) {
continue
}
}
let $content = null
let consume = true as Nullable<boolean>
if (modifiers.swap) {
$content = await $response.text()
if ((modifiers.consume === "text") || (modifiers.text)) {
$content = escape($content)
element.outerHTML = $content
}
else {
const content = renderer.createElement("div", { innerHTML: $content })
new Set(Array.from(element.attributes))
.difference(new Set(renderer.directives.flatMap((directive) => renderer.getAttributes(element, directive.name))))
.forEach((attribute) => Array.from(content.children).forEach((child) => child.attributes.setNamedItem(attribute.cloneNode() as Attr)))
renderer.replaceElementWithChildNodes(element, content)
}
consume = null
}
switch (consume) {
case (modifiers.consume === "void") || (modifiers.void): {
await $response.body?.cancel()
break
}
case (modifiers.consume === "text") || (modifiers.text): {
$content = await $response.text()
if (!expression) {
element.textContent = $content
}
break
}
case (modifiers.consume === "html") || (modifiers.html): {
$content = renderer.createElement("body", { innerHTML: await $response.text() }) as HTMLBodyElement
if (!expression) {
element.innerHTML = $content.innerHTML
}
break
}
case (modifiers.consume === "json") || (modifiers.json): {
$content = await $response.json()
break
}
case (modifiers.consume === "xml") || (modifiers.xml): {
const { parse } = await import("@libs/xml/parse")
$content = parse(await $response.text())
break
}
}
await renderer.evaluate(element, arguments[2]._expression?.value ?? (expression || this.default), { state: { ...state, $response, $content }, ...options, args: arguments[2]._expression?.args })
}
},
} as Directive<null, typeof _response_typings> & { execute: NonNullable<Directive["execute"]> }
export default [_header, _body, _http, _response]
|