@hamur/devtools 0.0.0-stage → 0.0.2

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.
Files changed (134) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +24 -2
  3. package/dist/src/client.js +780 -0
  4. package/dist/src/index.js +1711 -0
  5. package/dist/types/src/apps/locator.d.ts +3 -0
  6. package/dist/types/src/bridge.d.ts +8 -0
  7. package/dist/types/src/client.d.ts +3 -0
  8. package/dist/types/src/dev/analyze.d.ts +31 -0
  9. package/dist/types/src/dev/assets.d.ts +33 -0
  10. package/dist/types/src/dev/authz.d.ts +49 -0
  11. package/dist/types/src/dev/bundle.d.ts +22 -0
  12. package/dist/types/src/dev/config.d.ts +24 -0
  13. package/dist/types/src/dev/handler.d.ts +20 -0
  14. package/dist/types/src/dev/modules.d.ts +28 -0
  15. package/dist/types/src/dev/overview.d.ts +20 -0
  16. package/dist/types/src/dev/processes.d.ts +4 -0
  17. package/dist/types/src/dev/server-routes.d.ts +7 -0
  18. package/dist/types/src/dev/tasks.d.ts +26 -0
  19. package/dist/types/src/dev/timeline.d.ts +20 -0
  20. package/dist/types/src/dev/virtual.d.ts +9 -0
  21. package/dist/types/src/icons.d.ts +24 -0
  22. package/dist/types/src/index.d.ts +8 -0
  23. package/dist/types/src/locator.d.ts +17 -0
  24. package/dist/types/src/mask.d.ts +8 -0
  25. package/dist/types/src/module.d.ts +27 -0
  26. package/dist/types/src/open-in-editor.d.ts +4 -0
  27. package/dist/types/src/options.d.ts +14 -0
  28. package/dist/types/src/panel/document.d.ts +16 -0
  29. package/dist/types/src/panel/groups.d.ts +14 -0
  30. package/dist/types/src/panel/index.d.ts +1 -0
  31. package/dist/types/src/panel/settings.d.ts +69 -0
  32. package/dist/types/src/panel/style.d.ts +1 -0
  33. package/dist/types/src/panel/ui.d.ts +34 -0
  34. package/dist/types/src/server/authz.d.ts +30 -0
  35. package/dist/types/src/server/index.d.ts +3 -0
  36. package/dist/types/src/server/routes.d.ts +6 -0
  37. package/dist/types/src/server/storage.d.ts +56 -0
  38. package/dist/types/src/source-link.d.ts +2 -0
  39. package/dist/types/src/tabs/analyze-model.d.ts +31 -0
  40. package/dist/types/src/tabs/analyze.d.ts +2 -0
  41. package/dist/types/src/tabs/assets.d.ts +11 -0
  42. package/dist/types/src/tabs/audit-model.d.ts +42 -0
  43. package/dist/types/src/tabs/audit.d.ts +2 -0
  44. package/dist/types/src/tabs/authz-model.d.ts +11 -0
  45. package/dist/types/src/tabs/authz.d.ts +2 -0
  46. package/dist/types/src/tabs/config.d.ts +8 -0
  47. package/dist/types/src/tabs/inspect.d.ts +7 -0
  48. package/dist/types/src/tabs/modules.d.ts +4 -0
  49. package/dist/types/src/tabs/overview.d.ts +2 -0
  50. package/dist/types/src/tabs/pages.d.ts +2 -0
  51. package/dist/types/src/tabs/payload.d.ts +6 -0
  52. package/dist/types/src/tabs/plugins-model.d.ts +15 -0
  53. package/dist/types/src/tabs/plugins.d.ts +2 -0
  54. package/dist/types/src/tabs/seo-model.d.ts +36 -0
  55. package/dist/types/src/tabs/seo.d.ts +2 -0
  56. package/dist/types/src/tabs/server-routes.d.ts +2 -0
  57. package/dist/types/src/tabs/storage.d.ts +13 -0
  58. package/dist/types/src/tabs/tasks-model.d.ts +16 -0
  59. package/dist/types/src/tabs/tasks.d.ts +2 -0
  60. package/dist/types/src/tabs/terminals-model.d.ts +53 -0
  61. package/dist/types/src/tabs/terminals.d.ts +2 -0
  62. package/dist/types/src/tabs/timeline-model.d.ts +58 -0
  63. package/dist/types/src/tabs/timeline.d.ts +2 -0
  64. package/dist/types/src/tester.d.ts +43 -0
  65. package/dist/types/src/toolbar/element.d.ts +28 -0
  66. package/dist/types/src/toolbar/shortcut.d.ts +14 -0
  67. package/dist/types/src/toolbar/style.d.ts +3 -0
  68. package/dist/types/src/view-context.d.ts +13 -0
  69. package/package.json +34 -4
  70. package/src/apps/locator.ts +131 -0
  71. package/src/bridge.ts +172 -0
  72. package/src/client.ts +10 -0
  73. package/src/dev/analyze.ts +128 -0
  74. package/src/dev/assets.ts +208 -0
  75. package/src/dev/authz.ts +162 -0
  76. package/src/dev/bundle.ts +91 -0
  77. package/src/dev/config.ts +132 -0
  78. package/src/dev/handler.ts +161 -0
  79. package/src/dev/modules.ts +60 -0
  80. package/src/dev/overview.ts +57 -0
  81. package/src/dev/processes.ts +34 -0
  82. package/src/dev/server-routes.ts +14 -0
  83. package/src/dev/tasks.ts +93 -0
  84. package/src/dev/timeline.ts +43 -0
  85. package/src/dev/virtual.ts +40 -0
  86. package/src/env.d.ts +21 -0
  87. package/src/icons.ts +48 -0
  88. package/src/index.ts +12 -0
  89. package/src/locator.ts +31 -0
  90. package/src/mask.ts +16 -0
  91. package/src/module.ts +352 -0
  92. package/src/open-in-editor.ts +18 -0
  93. package/src/options.ts +36 -0
  94. package/src/panel/document.ts +60 -0
  95. package/src/panel/groups.ts +41 -0
  96. package/src/panel/index.ts +429 -0
  97. package/src/panel/settings.ts +224 -0
  98. package/src/panel/style.ts +321 -0
  99. package/src/panel/ui.ts +52 -0
  100. package/src/server/authz.ts +110 -0
  101. package/src/server/index.ts +25 -0
  102. package/src/server/routes.ts +51 -0
  103. package/src/server/storage.ts +251 -0
  104. package/src/source-link.ts +29 -0
  105. package/src/tabs/analyze-model.ts +97 -0
  106. package/src/tabs/analyze.ts +217 -0
  107. package/src/tabs/assets.ts +375 -0
  108. package/src/tabs/audit-model.ts +216 -0
  109. package/src/tabs/audit.ts +223 -0
  110. package/src/tabs/authz-model.ts +28 -0
  111. package/src/tabs/authz.ts +337 -0
  112. package/src/tabs/config.ts +250 -0
  113. package/src/tabs/inspect.ts +101 -0
  114. package/src/tabs/modules.ts +58 -0
  115. package/src/tabs/overview.ts +104 -0
  116. package/src/tabs/pages.ts +188 -0
  117. package/src/tabs/payload.ts +224 -0
  118. package/src/tabs/plugins-model.ts +44 -0
  119. package/src/tabs/plugins.ts +95 -0
  120. package/src/tabs/seo-model.ts +140 -0
  121. package/src/tabs/seo.ts +162 -0
  122. package/src/tabs/server-routes.ts +469 -0
  123. package/src/tabs/storage.ts +313 -0
  124. package/src/tabs/tasks-model.ts +59 -0
  125. package/src/tabs/tasks.ts +287 -0
  126. package/src/tabs/terminals-model.ts +127 -0
  127. package/src/tabs/terminals.ts +294 -0
  128. package/src/tabs/timeline-model.ts +200 -0
  129. package/src/tabs/timeline.ts +260 -0
  130. package/src/tester.ts +158 -0
  131. package/src/toolbar/element.ts +428 -0
  132. package/src/toolbar/shortcut.ts +56 -0
  133. package/src/toolbar/style.ts +94 -0
  134. package/src/view-context.ts +93 -0
@@ -0,0 +1,162 @@
1
+ import { defineDevtoolsApp } from "hamur/app"
2
+ import { element, pill, UI } from "../panel/ui.ts"
3
+ import {
4
+ NETWORK_TITLES,
5
+ NETWORKS,
6
+ seoReport,
7
+ type Network,
8
+ type SeoCard,
9
+ type SeoCheck,
10
+ type SeoReport,
11
+ } from "./seo-model.ts"
12
+
13
+ const POLL_MS = 500
14
+
15
+ function checkRow(check: SeoCheck): HTMLElement {
16
+ const missing = check.required && check.value === undefined
17
+ const dot = element("span", {
18
+ className: `flex-none size-2 rounded-full ${missing ? "bg-amber" : check.value === undefined ? "bg-fg-3" : "bg-green"}`,
19
+ })
20
+ const value = check.value ?? (missing ? "missing" : "not set")
21
+ const row = element(
22
+ "div",
23
+ { className: "flex items-center gap-3 h-8 mx-1.5 px-2.5 rounded-md" },
24
+ dot,
25
+ element("span", { className: "flex-none w-28 truncate font-mono text-sm font-medium text-fg" }, check.name),
26
+ element(
27
+ "span",
28
+ {
29
+ className: `flex-1 min-w-0 truncate font-mono text-xs ${missing ? "text-amber" : check.value === undefined ? "text-fg-4" : "text-fg-2"}`,
30
+ },
31
+ value,
32
+ ),
33
+ )
34
+ row.dataset.check = check.name
35
+ row.dataset.state = missing ? "missing" : check.value === undefined ? "unset" : "ok"
36
+ return row
37
+ }
38
+
39
+ function cardElement(card: SeoCard): HTMLElement {
40
+ const image = element("div", {
41
+ className: `${card.layout === "large" ? "h-32" : "h-20"} flex items-center justify-center bg-field border-b border-line text-xs overflow-hidden`,
42
+ })
43
+ image.dataset.image = card.image ?? ""
44
+ if (card.image) {
45
+ const picture = element("img", { src: card.image, alt: "", className: "w-full max-h-full object-contain" })
46
+ picture.addEventListener("error", () => {
47
+ image.className += " text-amber"
48
+ image.replaceChildren("og:image could not be loaded")
49
+ })
50
+ image.append(picture)
51
+ } else {
52
+ image.className += " text-amber"
53
+ image.append("og:image missing")
54
+ }
55
+ const lines = [
56
+ card.network === "slack"
57
+ ? element("span", { className: "text-xs font-medium text-fg-2" }, card.siteName ?? card.domain)
58
+ : element("span", { className: "text-xs text-fg-3" }, card.domain),
59
+ element("span", { className: "text-sm font-medium" }, card.title ?? "No title"),
60
+ ]
61
+ if (card.description) lines.push(element("span", { className: "text-xs text-fg-3" }, card.description))
62
+ const box = element(
63
+ "div",
64
+ { className: "flex flex-col rounded-lg overflow-hidden ring-1 ring-inset ring-line" },
65
+ image,
66
+ element("div", { className: "flex flex-col gap-0.5 px-3 py-2.5" }, ...lines),
67
+ )
68
+ box.dataset.card = card.network
69
+ return box
70
+ }
71
+
72
+ export default defineDevtoolsApp({
73
+ init(canvas, ctx) {
74
+ const page = ctx.page
75
+ if (!page) {
76
+ const config = JSON.parse(document.getElementById("hamur-devtools-config")!.textContent!) as {
77
+ shortcut: string | false
78
+ }
79
+ canvas.append(
80
+ element(
81
+ "p",
82
+ { className: UI.notice },
83
+ `Open this tab from the app page${config.shortcut === false ? "" : ` (${config.shortcut})`}`,
84
+ ),
85
+ )
86
+ return
87
+ }
88
+ canvas.className = "flex flex-col flex-1 min-h-0"
89
+ const parent = window.parent
90
+ let network: Network = "x"
91
+ let report: SeoReport | undefined
92
+ let last = ""
93
+ const path = element("span", { className: "font-mono text-xs text-fg-3" })
94
+ const checks = element("div", { className: "w-96 flex-none overflow-auto py-1.5" })
95
+ const pills = element("div", { className: "flex items-center gap-0.5" })
96
+ const preview = element("div")
97
+ canvas.append(
98
+ element(
99
+ "div",
100
+ { className: UI.strip },
101
+ path,
102
+ element("span", { className: "flex-1" }),
103
+ element("span", { className: "text-xs text-fg-4" }, "from the current head"),
104
+ ),
105
+ element(
106
+ "div",
107
+ { className: "flex-1 min-h-0 flex" },
108
+ checks,
109
+ element(
110
+ "div",
111
+ { className: "flex-1 min-w-0 flex flex-col gap-2.5 p-4 border-l border-line overflow-auto" },
112
+ pills,
113
+ preview,
114
+ ),
115
+ ),
116
+ )
117
+
118
+ const paint = () => {
119
+ if (!report) return
120
+ const missing = report.missing.length
121
+ checks.replaceChildren(
122
+ element(
123
+ "div",
124
+ { className: UI.groupHead },
125
+ element("span", { className: "font-medium text-fg-2" }, "Checks"),
126
+ element(
127
+ "span",
128
+ { className: missing ? "text-amber" : "text-fg-4" },
129
+ missing ? `${missing} missing` : "none missing",
130
+ ),
131
+ ),
132
+ ...report.checks.map(checkRow),
133
+ )
134
+ pills.replaceChildren(
135
+ ...NETWORKS.map((name) => {
136
+ const button = element(
137
+ "button",
138
+ { type: "button", className: pill(name === network), onclick: () => ((network = name), paint()) },
139
+ NETWORK_TITLES[name],
140
+ )
141
+ button.dataset.network = name
142
+ return button
143
+ }),
144
+ )
145
+ preview.replaceChildren(cardElement(report.cards[network]))
146
+ }
147
+
148
+ const read = () => {
149
+ const next = seoReport(page.head(), parent.document.documentElement.lang, parent.location.href)
150
+ const snapshot = JSON.stringify(next)
151
+ path.textContent = page.router.current().path
152
+ if (snapshot === last) return
153
+ last = snapshot
154
+ report = next
155
+ ctx.setBadge(next.missing.length ? String(next.missing.length) : undefined)
156
+ paint()
157
+ }
158
+ read()
159
+ const timer = setInterval(read, POLL_MS)
160
+ return () => clearInterval(timer)
161
+ },
162
+ })
@@ -0,0 +1,469 @@
1
+ import { defineDevtoolsApp } from "hamur/app"
2
+ import { PANEL_CONFIG_ID, type PanelConfig } from "../panel/document.ts"
3
+ import { element, FOCUS, tab, UI } from "../panel/ui.ts"
4
+ import type { ServerRouteRow } from "../dev/server-routes.ts"
5
+ import { sourceLink } from "../source-link.ts"
6
+ import {
7
+ addSaved,
8
+ buildRequest,
9
+ cookieWrites,
10
+ fillPattern,
11
+ paramNames,
12
+ prefillBody,
13
+ readSaved,
14
+ routeKey,
15
+ withQuery,
16
+ writeSaved,
17
+ type BodyKind,
18
+ type Pairs,
19
+ type SavedRequests,
20
+ type TesterState,
21
+ } from "../tester.ts"
22
+
23
+ const METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]
24
+ const PANES = ["Params", "Query", "Headers", "Body", "Cookies"] as const
25
+ const NONE = "–"
26
+
27
+ const METHOD_COLORS: Record<string, string> = {
28
+ GET: "text-green",
29
+ POST: "text-blue",
30
+ PUT: "text-amber",
31
+ PATCH: "text-amber",
32
+ DELETE: "text-red",
33
+ }
34
+
35
+ const baseURL = (): string => {
36
+ const config = JSON.parse(document.getElementById(PANEL_CONFIG_ID)?.textContent ?? "{}") as Partial<PanelConfig>
37
+ return (config.baseURL ?? "/").replace(/\/+$/, "")
38
+ }
39
+
40
+ const storage = (): Storage | undefined => {
41
+ try {
42
+ return localStorage
43
+ } catch {
44
+ return undefined
45
+ }
46
+ }
47
+
48
+ function pairsEditor(
49
+ label: string,
50
+ onChange: () => void,
51
+ ): { node: HTMLElement; get(): Pairs; set(pairs: Pairs): void } {
52
+ const rows = element("div", { className: "flex flex-col" })
53
+ const add = (name = "", value = "") => {
54
+ const nameInput = element("input", {
55
+ type: "text",
56
+ placeholder: "name",
57
+ value: name,
58
+ className: `${UI.field} flex-1 font-mono`,
59
+ })
60
+ nameInput.setAttribute("aria-label", `${label} name`)
61
+ const valueInput = element("input", {
62
+ type: "text",
63
+ placeholder: "value",
64
+ value: value,
65
+ className: `${UI.field} flex-1 font-mono`,
66
+ })
67
+ valueInput.setAttribute("aria-label", `${label} value`)
68
+ const remove = element("button", { type: "button", title: "Remove", className: UI.iconButton }, "×")
69
+ const row = element("div", { className: "flex items-center gap-1.5 my-1" }, nameInput, valueInput, remove)
70
+ row.dataset.pair = ""
71
+ remove.addEventListener("click", () => (row.remove(), onChange()))
72
+ for (const input of [nameInput, valueInput]) input.addEventListener("input", onChange)
73
+ rows.append(row)
74
+ }
75
+ const plus = element("button", { type: "button", className: `${UI.button} self-start` }, `Add ${label.toLowerCase()}`)
76
+ plus.addEventListener("click", () => add())
77
+ const get = (): Pairs =>
78
+ [...rows.querySelectorAll<HTMLElement>("[data-pair]")].map((row) => {
79
+ const [name, value] = row.querySelectorAll("input")
80
+ return [name!.value, value!.value]
81
+ })
82
+ return {
83
+ node: element("div", { className: "flex flex-col gap-1" }, rows, plus),
84
+ get,
85
+ set(pairs) {
86
+ rows.replaceChildren()
87
+ for (const [name, value] of pairs) add(name, value)
88
+ },
89
+ }
90
+ }
91
+
92
+ function jsonTree(value: unknown): HTMLElement {
93
+ const leaf = (item: unknown) => element("code", { className: "text-fg-2" }, JSON.stringify(item) ?? String(item))
94
+ const branch = (item: object, key: string): HTMLElement => {
95
+ const entries = Object.entries(item)
96
+ const list = element("ul", { className: "m-0 pl-4 list-none" })
97
+ for (const [name, child] of entries) {
98
+ const li = element("li")
99
+ li.append(
100
+ typeof child === "object" && child !== null
101
+ ? branch(child, name)
102
+ : element("span", {}, element("span", { className: "text-fg-3" }, name), ": ", leaf(child)),
103
+ )
104
+ list.append(li)
105
+ }
106
+ const summary = `${key}${Array.isArray(item) ? ` [${entries.length}]` : ` {${entries.length}}`}`
107
+ const details = element("details", {}, element("summary", { className: "cursor-pointer text-fg-2" }, summary), list)
108
+ details.open = true
109
+ return details
110
+ }
111
+ const frame = "m-0 px-3.5 py-2.5 list-none rounded-lg bg-field ring-1 ring-inset ring-line font-mono text-xs"
112
+ if (typeof value !== "object" || value === null) return element("p", { className: frame }, leaf(value))
113
+ return element(
114
+ "ul",
115
+ { className: frame },
116
+ element("li", {}, branch(value, Array.isArray(value) ? "array" : "object")),
117
+ )
118
+ }
119
+
120
+ const sizeText = (bytes: number): string => (bytes < 1024 ? `${bytes} B` : `${(bytes / 1024).toFixed(1)} kB`)
121
+
122
+ function defaultState(route: ServerRouteRow): TesterState {
123
+ const method = route.method === "*" ? "GET" : route.method
124
+ const body = route.bodySchema ? JSON.stringify(prefillBody(route.bodySchema), null, 2) : ""
125
+ const params = Object.fromEntries(paramNames(route.path).map((name) => [name, ""]))
126
+ return {
127
+ method,
128
+ url: `${baseURL()}${route.path}`,
129
+ params,
130
+ query: [],
131
+ headers: [],
132
+ bodyKind: route.bodySchema ? "json" : "none",
133
+ json: body,
134
+ form: [],
135
+ cookies: [],
136
+ }
137
+ }
138
+
139
+ function tester(route: ServerRouteRow, saved: { all: SavedRequests }): HTMLElement {
140
+ const key = routeKey(route.method, route.path)
141
+ const initial = defaultState(route)
142
+ const methodSelect = element(
143
+ "select",
144
+ { name: "method", className: `${UI.field} w-28 font-mono` },
145
+ ...[...new Set([initial.method, ...METHODS])].map((method) => element("option", { value: method }, method)),
146
+ )
147
+ methodSelect.value = initial.method
148
+ methodSelect.setAttribute("aria-label", "Method")
149
+ const urlInput = element("input", {
150
+ type: "text",
151
+ name: "url",
152
+ value: initial.url,
153
+ className: `${UI.field} flex-1 h-8 font-mono`,
154
+ })
155
+ urlInput.setAttribute("aria-label", "URL")
156
+ const send = element("button", { type: "submit", className: UI.primary }, "Send")
157
+ const save = element("button", { type: "button", className: UI.button }, "Save")
158
+ const savedSelect = element("select", { name: "saved", className: `${UI.field} w-48` })
159
+ savedSelect.setAttribute("aria-label", "Saved requests")
160
+
161
+ const params = new Map<string, HTMLInputElement>()
162
+ const paramsPane = element("div", { className: "flex flex-col gap-1" })
163
+ for (const name of paramNames(route.path)) {
164
+ const input = element("input", { type: "text", placeholder: "value", className: `${UI.field} flex-1 font-mono` })
165
+ input.setAttribute("aria-label", `Param ${name}`)
166
+ params.set(name, input)
167
+ paramsPane.append(
168
+ element(
169
+ "div",
170
+ { className: "flex items-center gap-1.5 my-1" },
171
+ element("code", { className: "flex-none w-24 truncate font-mono text-xs text-fg-2" }, name),
172
+ input,
173
+ ),
174
+ )
175
+ }
176
+ if (!params.size) paramsPane.append(element("p", { className: UI.hint }, "This route has no params"))
177
+ const query = pairsEditor("Query", () => syncURL())
178
+ const headers = pairsEditor("Header", () => {})
179
+ const cookies = pairsEditor("Cookie", () => {})
180
+ const form = pairsEditor("Field", () => {})
181
+ const json = element("textarea", {
182
+ name: "json",
183
+ rows: 8,
184
+ value: initial.json,
185
+ spellcheck: false,
186
+ className: UI.textarea,
187
+ })
188
+ json.setAttribute("aria-label", "JSON body")
189
+ const kind = element(
190
+ "select",
191
+ { name: "bodyKind", className: `${UI.field} w-28 self-start` },
192
+ element("option", { value: "none" }, "None"),
193
+ element("option", { value: "json" }, "JSON"),
194
+ element("option", { value: "form" }, "Form"),
195
+ )
196
+ kind.value = initial.bodyKind
197
+ kind.setAttribute("aria-label", "Body type")
198
+ const bodyPane = element("div", { className: "flex flex-col gap-2" }, kind, json, form.node)
199
+ const syncBody = () => {
200
+ json.hidden = kind.value !== "json"
201
+ form.node.hidden = kind.value !== "form"
202
+ }
203
+ kind.addEventListener("change", syncBody)
204
+ syncBody()
205
+
206
+ const paneNodes: Record<(typeof PANES)[number], HTMLElement> = {
207
+ Params: paramsPane,
208
+ Query: query.node,
209
+ Headers: headers.node,
210
+ Body: bodyPane,
211
+ Cookies: cookies.node,
212
+ }
213
+ const tabs = element("div", { className: "flex border-b border-line", role: "tablist" })
214
+ const show = (name: (typeof PANES)[number]) => {
215
+ for (const pane of PANES) {
216
+ paneNodes[pane].hidden = pane !== name
217
+ const button = tabs.querySelector<HTMLElement>(`[data-pane="${pane}"]`)!
218
+ button.setAttribute("aria-selected", String(pane === name))
219
+ button.className = tab(pane === name)
220
+ }
221
+ }
222
+ for (const pane of PANES) {
223
+ const button = element("button", { type: "button", role: "tab" }, pane)
224
+ button.dataset.pane = pane
225
+ button.addEventListener("click", () => show(pane))
226
+ tabs.append(button)
227
+ }
228
+ show(params.size ? "Params" : route.bodySchema ? "Body" : "Query")
229
+
230
+ const paramValues = () => Object.fromEntries([...params].map(([name, input]) => [name, input.value]))
231
+ const syncURL = () => {
232
+ urlInput.value = withQuery(fillPattern(`${baseURL()}${route.path}`, paramValues()), query.get())
233
+ }
234
+ for (const input of params.values()) input.addEventListener("input", syncURL)
235
+
236
+ const read = (): TesterState => ({
237
+ method: methodSelect.value,
238
+ url: urlInput.value,
239
+ params: paramValues(),
240
+ query: query.get(),
241
+ headers: headers.get(),
242
+ bodyKind: kind.value as BodyKind,
243
+ json: json.value,
244
+ form: form.get(),
245
+ cookies: cookies.get(),
246
+ })
247
+ const write = (state: TesterState) => {
248
+ methodSelect.value = state.method
249
+ urlInput.value = state.url
250
+ for (const [name, input] of params) input.value = state.params[name] ?? ""
251
+ query.set(state.query)
252
+ headers.set(state.headers)
253
+ cookies.set(state.cookies)
254
+ form.set(state.form)
255
+ kind.value = state.bodyKind
256
+ json.value = state.json
257
+ syncBody()
258
+ }
259
+
260
+ const fillSaved = () => {
261
+ const list = saved.all[key] ?? []
262
+ savedSelect.replaceChildren(
263
+ element("option", { value: "" }, list.length ? "Saved…" : "No saved requests"),
264
+ ...list.map((item, index) =>
265
+ element(
266
+ "option",
267
+ { value: String(index) },
268
+ `${item.state.method} ${item.state.url} · ${item.savedAt.slice(11, 19)}`,
269
+ ),
270
+ ),
271
+ )
272
+ }
273
+ fillSaved()
274
+ savedSelect.addEventListener("change", () => {
275
+ const item = saved.all[key]?.[Number(savedSelect.value)]
276
+ if (item) write(item.state)
277
+ })
278
+ save.addEventListener("click", () => {
279
+ saved.all = addSaved(saved.all, key, { savedAt: new Date().toISOString(), state: read() })
280
+ writeSaved(storage(), saved.all)
281
+ fillSaved()
282
+ })
283
+
284
+ const bar = element("div", { className: "flex flex-col gap-2 pt-3 border-t border-line" })
285
+ bar.dataset.response = ""
286
+ const request = element(
287
+ "form",
288
+ { className: "flex items-center gap-2" },
289
+ methodSelect,
290
+ urlInput,
291
+ send,
292
+ save,
293
+ savedSelect,
294
+ )
295
+
296
+ const run = async () => {
297
+ bar.replaceChildren(element("p", { className: UI.hint }, "Sending…"))
298
+ send.disabled = true
299
+ const state = read()
300
+ const previous = new Map(
301
+ document.cookie
302
+ .split("; ")
303
+ .filter(Boolean)
304
+ .map((part) => [part.slice(0, part.indexOf("=")), part] as const),
305
+ )
306
+ const writes = cookieWrites(state.cookies)
307
+ try {
308
+ const { url, init } = buildRequest(state, location.origin)
309
+ for (const text of writes) document.cookie = text
310
+ const started = performance.now()
311
+ const response = await fetch(url, init)
312
+ const text = await response.text()
313
+ const elapsed = Math.round(performance.now() - started)
314
+ let body: HTMLElement
315
+ try {
316
+ body = jsonTree(JSON.parse(text))
317
+ body.dataset.kind = "json"
318
+ } catch {
319
+ body = element(
320
+ "pre",
321
+ {
322
+ className:
323
+ "m-0 px-3.5 py-2.5 rounded-lg bg-field ring-1 ring-inset ring-line font-mono text-xs text-fg-2 whitespace-pre-wrap break-all",
324
+ },
325
+ text,
326
+ )
327
+ body.dataset.kind = "text"
328
+ }
329
+ const status =
330
+ response.type === "opaqueredirect"
331
+ ? "Redirect (not followed)"
332
+ : `${response.status} ${response.statusText}`.trim()
333
+ const summary = element(
334
+ "p",
335
+ { className: "m-0 flex items-center gap-1.5 text-sm text-fg-3" },
336
+ element("strong", { className: response.ok ? "text-green" : "text-red" }, status),
337
+ ` · ${elapsed} ms · ${sizeText(new TextEncoder().encode(text).length)}`,
338
+ )
339
+ summary.dataset.status = String(response.status)
340
+ const headerList = element(
341
+ "table",
342
+ { className: "w-full border-collapse font-mono text-xs" },
343
+ element(
344
+ "tbody",
345
+ {},
346
+ ...[...response.headers].map(([name, value]) =>
347
+ element(
348
+ "tr",
349
+ {},
350
+ element("td", { className: "py-0.5 pr-3 align-top text-fg-3" }, name),
351
+ element("td", { className: "py-0.5 break-all text-fg-2" }, value),
352
+ ),
353
+ ),
354
+ ),
355
+ )
356
+ bar.replaceChildren(
357
+ summary,
358
+ element(
359
+ "details",
360
+ {},
361
+ element(
362
+ "summary",
363
+ { className: "cursor-pointer text-xs text-fg-3" },
364
+ `Headers (${[...response.headers].length})`,
365
+ ),
366
+ headerList,
367
+ ),
368
+ body,
369
+ )
370
+ } catch (error) {
371
+ const failure = element("p", { className: UI.fail }, error instanceof Error ? error.message : String(error))
372
+ failure.dataset.error = ""
373
+ bar.replaceChildren(failure)
374
+ } finally {
375
+ for (const [name] of state.cookies
376
+ .map(([cookie]) => [encodeURIComponent(cookie.trim())] as const)
377
+ .filter(([name]) => name)) {
378
+ document.cookie = previous.has(name) ? previous.get(name)! : `${name}=; path=/; max-age=0`
379
+ }
380
+ send.disabled = false
381
+ }
382
+ }
383
+ request.addEventListener("submit", (event) => {
384
+ event.preventDefault()
385
+ void run()
386
+ })
387
+
388
+ const box = element(
389
+ "section",
390
+ { className: "flex flex-col gap-3.5" },
391
+ request,
392
+ tabs,
393
+ paramsPane,
394
+ query.node,
395
+ headers.node,
396
+ bodyPane,
397
+ cookies.node,
398
+ bar,
399
+ )
400
+ box.dataset.tester = ""
401
+ box.dataset.route = key
402
+ return box
403
+ }
404
+
405
+ export default defineDevtoolsApp({
406
+ async init(canvas, ctx) {
407
+ let routes: ServerRouteRow[]
408
+ try {
409
+ routes = await ctx.rpc<ServerRouteRow[]>("devtools:server-routes", {})
410
+ } catch (error) {
411
+ canvas.append(element("p", { className: UI.error }, error instanceof Error ? error.message : String(error)))
412
+ return
413
+ }
414
+ canvas.className = "flex flex-1 min-h-0"
415
+ const saved = { all: readSaved(storage()) }
416
+ const list = element("ul", { className: "m-0 p-0 list-none" })
417
+ const testerHost = element(
418
+ "div",
419
+ { className: "flex-1 min-w-0 overflow-auto p-4" },
420
+ element("p", { className: UI.hint }, routes.length ? "Pick a route" : "This app has no server routes"),
421
+ )
422
+ const buttons = new Map<string, HTMLButtonElement>()
423
+ for (const route of routes) {
424
+ const key = routeKey(route.method, route.path)
425
+ const chip = element(
426
+ "span",
427
+ { className: `flex-none w-12 font-mono text-2xs font-medium ${METHOD_COLORS[route.method] ?? "text-fg-3"}` },
428
+ route.method,
429
+ )
430
+ chip.dataset.method = route.method
431
+ const meta = element(
432
+ "span",
433
+ { className: "text-xs text-fg-4 break-words" },
434
+ `middleware: ${route.middleware.length ? route.middleware.join(", ") : NONE} · rules: ${Object.keys(route.rules).length ? JSON.stringify(route.rules) : NONE}`,
435
+ )
436
+ const button = element(
437
+ "button",
438
+ {
439
+ type: "button",
440
+ className: `flex items-center gap-3 w-full p-0 border-0 bg-transparent text-left text-fg cursor-pointer ${FOCUS}`,
441
+ },
442
+ chip,
443
+ element("code", { className: "flex-1 min-w-0 truncate font-mono text-sm font-medium" }, route.path),
444
+ )
445
+ button.dataset.key = key
446
+ button.addEventListener("click", () => {
447
+ for (const [other, node] of buttons) {
448
+ node.setAttribute("aria-current", String(other === key))
449
+ node.closest("li")!.classList.toggle("bg-active", other === key)
450
+ }
451
+ testerHost.replaceChildren(tester(route, saved))
452
+ })
453
+ buttons.set(key, button)
454
+ list.append(
455
+ element(
456
+ "li",
457
+ { className: "flex flex-col gap-0.5 mx-1.5 px-2.5 py-1.5 rounded-md hover:bg-hover" },
458
+ button,
459
+ element("span", { className: "font-mono text-xs text-fg-3 break-all" }, sourceLink(route.file)),
460
+ meta,
461
+ ),
462
+ )
463
+ }
464
+ canvas.append(
465
+ element("aside", { className: "w-72 flex-none py-1.5 border-r border-line overflow-auto" }, list),
466
+ testerHost,
467
+ )
468
+ },
469
+ })