All files / http / mod.ts

100.00% Branches 129/129
100.00% Functions 8/8
100.00% Lines 247/247
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
 
x10
x10
 
 
 
x10
x10
x10
x10
x10
x104
x10
x10
x7
x1
x1
x7
x7
 
 
x7
x8
x8
 
x8
x1
x1
 
x8
x1
x1
 
x8
x6
x8
x8
x6
x7
x10
 
 
 
 
x10
x10
x10
x10
x10
x10
x10
x10
x10
x10
 
 
x10
x10
x10
x10
x10
x10
x104
x10
x10
x10
x1
x1
x10
x10
 
 
x10
x9
 
x10
x4
x4
x4
x4
x4
x4
 
x10
x1
x1
x1
x1
x1
x1
 
x10
x2
x2
x2
x2
x2
x2
 
x10
x1
x1
x1
x1
x1
x1
x1
x10
x9
x10
x10
 
 
 
 
 
 
x10
x10
x10
x10
x10
x10
x10
x10
x10
x10
x10
x10
x10
 
 
 
 
 
 
x10
x10
x10
x10
x10
x10
x104
x10
x10
x56
x3
x3
x53
 
 
x56
x56
x56
x318
x7
x7
x318
 
 
x53
x42
x42
x42
x36
x2
x2
x34
x34
x42
x1
x1
x40
x42
x6
x6
x40
x53
x56
x6
x6
x49
x11
x11
x36
x56
x10
 
 
 
 
 
x10
x10
x10
x10
x10
x10
x10
x10
x10
x10
x10
 
 
 
 
 
 
 
x10
x10
x10
x10
x10
x10
x10
x10
x44
x1
x1
x43
x44
x3
x3
 
 
x44
x43
 
 
x43
x6
x6
x2
x2
x6
x2
x2
x2
x6
x6
x3
x3
x6
 
x40
x40
x40
 
x43
x7
 
x7
x2
x2
x5
x5
x5
x5
x5
x5
x5
x5
x7
x7
 
x40
 
x43
x18
x18
x18
 
x43
x10
x10
x2
x2
x10
x10
 
x43
x2
x2
x1
x1
x2
x2
 
x43
x2
x2
x2
 
x43
x1
x1
x1
x1
x43
 
x43
x43
x7
x7
x43
x44
x10
 
 
 
 
 
 
x10

























































































































































































































































































































// Imports
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"

/** `%header` directive. */
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))

    // Set headers
    for (const { tag: name, value: expression } of parsed) {
      const value = await renderer.evaluate(element, expression, options)
      switch (true) {
        // Unset header
        case (value === undefined) || (value === null):
          headers.delete(name)
          break
        // Multiple values header
        case Array.isArray(value):
          value.forEach((v) => headers.append(name, v))
          break
        // Single value header
        default:
          headers.set(name, `${value}`)
      }
    }
    return { state: { $headers: headers } }
  },
} as const satisfies Directive<{
  Cache: WeakMap<HTMLElement, Headers>
}>

/** `%body` typings. */
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

/** `%body` directive. */
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 })

    // Set body
    let body = await renderer.evaluate(element, expression, options)
    switch (true) {
      // Text body
      case (modifiers.type === "text") || (modifiers.text): {
        if (modifiers.header) {
          headers.set("Content-Type", "text/plain")
        }
        body = `${body}`
        break
      }
      // Form body
      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
      }
      // JSON body
      case (modifiers.type === "json") || (modifiers.json): {
        if (modifiers.header) {
          headers.set("Content-Type", "application/json")
        }
        body = JSON.stringify(body)
        break
      }
      // XML body
      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 const satisfies Directive<{
  Cache: WeakMap<HTMLElement, BodyInit>
  Typings: typeof _body_typings
  Prefix: true
}>

/** `%http` 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

/**
 * `%http` directive.
 *
 * @internal `_return_callback` Force the directive to return the request callback instead of executing it.
 */
export const _http = {
  name: "%http",
  prefix: "%",
  phase: Phase.HTTP_REQUEST,
  typings: _http_typings,
  init(renderer) {
    renderer.cache<Cache<typeof this>>(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 })

    // Configure request
    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()
      }
    }

    // Create request callback
    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 const satisfies Directive<{
  Cache: WeakMap<Element, string>
  Prefix: true
}>

/** `%response` typings. */
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

/**
 * `%response` directive.
 *
 * @internal `_expression.value` Force the directive to use specified value rather than the attribute value.
 * @internal `_expression.args` Force the directive to pass specified arguments during evaluation.
 */
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
    }

    // Process response callbacks
    for (const attribute of attributes) {
      const { tag, modifiers, value: expression } = renderer.parseAttribute(attribute, this.typings, { prefix: this.prefix, modifiers: true })

      // Verify status code if applicable
      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>
      const parent = element.parentElement
      // Apply swap modifier
      if (modifiers.swap) {
        $content = await $response.text()
        // Swap text content
        if ((modifiers.consume === "text") || (modifiers.text)) {
          $content = escape($content)
          element.outerHTML = $content
        } // Swap HTML content while preserving non-directive attributes
        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
      }
      // Parse response
      switch (consume) {
        // Void response
        case (modifiers.consume === "void") || (modifiers.void): {
          await $response.body?.cancel()
          break
        }
        // Text response
        case (modifiers.consume === "text") || (modifiers.text): {
          $content = await $response.text()
          if (!expression) {
            element.textContent = $content
          }
          break
        }
        // HTML response
        case (modifiers.consume === "html") || (modifiers.html): {
          $content = renderer.createElement("body", { innerHTML: await $response.text() }) as HTMLBodyElement
          if (!expression) {
            element.innerHTML = $content.innerHTML
          }
          break
        }
        // JSON response
        case (modifiers.consume === "json") || (modifiers.json): {
          $content = await $response.json()
          break
        }
        // XML response
        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 })
      if ((modifiers.swap) && parent) {
        return { element: parent }
      }
    }
  },
} as const satisfies Directive<{
  Typings: typeof _response_typings
  Default: true
  Prefix: true
}>

/** Default exports. */
export default [_header, _body, _http, _response]