All files / http / mod.ts

100.00% Branches 75/75
100.00% Lines 234/234
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
 
x9
x9
 
 
 
x9
x9
x9
x9
x9
x109
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
x109
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
x58
x61
x61
x608
 
 
x58
x58
x464
x334
x341
x341
x334
 
 
x104
x139
x983
x139
x140
x140
x834
x139
x1160
x145
x139
x104
x58
x64
x64
x380
x111
x111
x522
x58
x9
 
 
x9
x9
x81
x27
x27
x27
x27
x27
x27
x9
x9
 
 
 
 
 
 
 
x9
x9
x9
x9
x9
x9
x9
x9
x46
x47
x47
x82
x46
x47
x47
 
 
x46
x336
 
 
x84
x90
x96
x392
x98
x96
x98
x98
x392
x90
x90
x93
x93
x90
 
x119
x119
 
x84
x88
 
x88
x90
x90
x90
x90
x270
x90
x90
x90
x90
x90
x88
x88
 
x119
 
x184
x100
x100
x100
 
x178
x94
x94
x96
x96
x94
x94
 
x170
x86
x86
x87
x87
x86
x86
 
x170
x86
x86
x86
 
x169
x85
x85
x85
x85
x84
 
x756
x119
x46
x9
 
 
x54































































































































































































































































































// 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 Directive<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("./import/xml/stringify.ts")
        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>

/** `%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,
  execute(renderer, element, { 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 (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 & { execute: NonNullable<Directive["execute"]> }

/** `%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>
      // 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 = await $response.text()
          if (!expression) {
            element.innerHTML = $content
          }
          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("./import/xml/parse.ts")
          $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"]> }

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