All files / http / mod.ts

100.00% Branches 83/83
100.00% Lines 251/251
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
x10
x114
x10
x10
x17
x18
x18
x17
x17
 
 
x17
x25
x25
 
x25
x26
x26
 
x25
x26
x26
 
x25
x31
x25
x25
x115
x17
x10
 
 
x10
x10
x50
x80
x30
x30
x30
x30
x10
x10
 
 
x10
 
 
 
x10
x10
x10
x10
x10
x10
x114
x10
x10
x20
x21
x21
x20
x80
 
 
x20
x29
 
x44
x24
x24
x24
x24
x24
x24
 
x41
x21
x21
x21
x21
x21
x21
 
x42
x22
x22
x22
x22
x22
x22
 
x41
x21
x21
x21
x21
x126
x21
x21
x20
x174
x20
x10
 
 
x10
x10
x40
x30
x30
x30
x30
x30
x30
x30
x30
x10
x10
 
 
 
 
 
 
x10
 
 
x10
x10
x10
x10
x10
x10
x114
x10
x10
x66
x69
x69
x696
 
 
x66
x66
x528
x384
x391
x391
x384
 
 
x119
x161
x1157
x161
x197
x199
x199
x231
x231
x161
x162
x162
x1206
x161
x1336
x167
x201
x119
x66
x72
x72
x439
x126
x126
x618
x66
x10
 
 
x10
x10
x90
x30
x30
x30
x30
x30
x30
x10
x10
 
 
 
 
 
 
 
x10
 
 
 
x10
x10
x10
x10
x10
x10
x10
x10
x54
x55
x55
x97
x54
x57
x57
 
 
x54
x388
 
 
x97
x103
x109
x444
x111
x109
x111
x111
x444
x103
x103
x106
x106
x103
 
x137
x137
x137
 
x97
x104
 
x104
x111
x111
x109
x109
x327
x109
x109
x109
x109
x109
x104
x104
 
x137
 
x212
x115
x115
x115
 
x204
x107
x107
x109
x109
x107
x107
 
x196
x297
x99
x100
x100
x99
x99
 
x196
x99
x99
x99
 
x195
x98
x98
x98
x98
x97
 
x873
x97
x312
x104
x97
x54
x10
 
 
x60

























































































































































































































































































































// 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: Directive<{
  Cache: WeakMap<HTMLElement, Headers>
}> = {
  name: "%header",
  phase: Phase.HTTP_HEADER,
  multiple: true,
  init(this: typeof _header, renderer) {
    renderer.cache<Cache<typeof this>>(this.name, new WeakMap())
  },
  async execute(this: typeof _header, 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 } }
  },
}

/** `%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: Directive<{
  Cache: WeakMap<HTMLElement, BodyInit>
  Typings: typeof _body_typings
  Prefix: true
}> = {
  name: "%body",
  prefix: "%",
  phase: Phase.HTTP_BODY,
  typings: _body_typings,
  init(this: typeof _body, renderer) {
    renderer.cache<Cache<typeof this>>(this.name, new WeakMap())
  },
  async execute(this: typeof _body, 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 } }
  },
}

/** `%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: Directive<{
  Cache: WeakMap<Element, string>
  Prefix: true
}> = {
  name: "%http",
  prefix: "%",
  phase: Phase.HTTP_REQUEST,
  typings: _http_typings,
  init(this: typeof _http, renderer) {
    renderer.cache<Cache<typeof this>>(this.name, new WeakMap())
  },
  execute(this: typeof _http, 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 } }))
  },
}

/** `%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: Directive<{
  Typings: typeof _response_typings
  Default: true
  Prefix: true
}> = {
  name: "%response",
  prefix: "%",
  phase: Phase.HTTP_CONTENT,
  typings: _response_typings,
  multiple: true,
  default: "null",
  async execute(this: typeof _response, 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) {
        return { element: parent }
      }
    }
  },
}

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