@davaux/user-agent 0.8.0

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.
package/CLAUDE.md ADDED
@@ -0,0 +1,95 @@
1
+ <!-- pka-generated -->
2
+ # @davaux/user-agent
3
+
4
+ > Generated by Project Knowledge Analyzer on 2026-06-06T21:53:10.521Z
5
+
6
+ ## Overview
7
+
8
+ User-Agent parsing middleware for Davaux
9
+
10
+ **Version**: 0.8.0
11
+ **Author**: David L Dyess II
12
+ **License**: MIT
13
+ **Repository**: https://codeberg.org/davaux/davaux#readme
14
+
15
+ ## Tech Stack
16
+
17
+ - **Language**: TypeScript
18
+ - **Module System**: ESM (`type: module`)
19
+
20
+ ## Commands
21
+
22
+ - `npm run build` — tsc
23
+ - `npm run typecheck` — tsc --noEmit
24
+
25
+ ## Project Structure
26
+
27
+ ```
28
+ ├── CLAUDE.md
29
+ ├── README.md
30
+ ├── package.json
31
+ ├── tsconfig.json
32
+ └── src/
33
+ └── index.ts
34
+
35
+ ```
36
+
37
+ ## Entry Points
38
+
39
+ - `src/index.ts`
40
+
41
+ ## Files by Type
42
+
43
+ ### Documentation (2)
44
+ - `CLAUDE.md`
45
+ - `README.md`
46
+
47
+ ### Config (2)
48
+ - `package.json`
49
+ - `tsconfig.json`
50
+
51
+ ### Module (1)
52
+ - `src/index.ts`
53
+
54
+
55
+ ## Git
56
+ - **Branch**: main
57
+ - **Last Commit**: chore: Add alpha status note to README
58
+ - **Author**: David Dyess II
59
+ - **Date**: 2026-06-06 15:52:27 -0600
60
+ - **Remote**: https://codeberg.org/davaux/davaux.git
61
+
62
+ ### Recent Commits
63
+ ```
64
+ f527031 chore: Add alpha status note to README
65
+ 90c819e chore: Add repo info to package.json files
66
+ b200d9d feat(davaux)!: Add OmlCacheConfig - opt-in with includes option or opt-out with excludes option; Fix OML implementation to follow OML spec - use output instead of return
67
+ 3bce0c2 chore: Update and add READMEs to packages; update ROADMAP
68
+ fc27c20 fix(davaux): Remove old dist folder on new builds; fix server port per DavauxConfig
69
+ c760659 feat(davaux): Add minify CSS in production builds
70
+ c899ab8 fix(davaux): Added method JS and JSX extenstion to scanner
71
+ 7d99f04 feat(davaux): Add support for declarative partial updates
72
+ 3b47f37 chore: Bump package versions to 0.8.0
73
+ aa0460f chore: Add CHANGELOG.md
74
+ ```
75
+
76
+ ## Dependencies
77
+
78
+
79
+ ### Development
80
+ @types/node, davaux, typescript
81
+
82
+
83
+
84
+
85
+
86
+
87
+
88
+
89
+
90
+ ## Exported Symbols
91
+
92
+ **`src/index.ts`**
93
+ `userAgent`, `UserAgent`
94
+
95
+
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 David L Dyess II
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,48 @@
1
+ # @davaux/user-agent
2
+
3
+ User-Agent parsing middleware for Davaux. Exposes structured device, browser, and OS information as `ctx.state.userAgent`.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @davaux/user-agent
9
+ ```
10
+
11
+ ## Setup
12
+
13
+ ```ts
14
+ // src/routes/_global.ts (or _middleware.ts for a subtree)
15
+ import { userAgent } from '@davaux/user-agent'
16
+ export default userAgent()
17
+ ```
18
+
19
+ ## Usage
20
+
21
+ ```ts
22
+ export default definePage((ctx) => {
23
+ const { isMobile, browserName, osName, isBot } = ctx.state.userAgent
24
+ return <p>Hello from {browserName} on {osName}</p>
25
+ })
26
+ ```
27
+
28
+ ## `UserAgent` fields
29
+
30
+ | Field | Type | Description |
31
+ |---|---|---|
32
+ | `raw` | `string` | Raw `User-Agent` header value |
33
+ | `isMobile` | `boolean` | Mobile device (excludes tablets) |
34
+ | `isTablet` | `boolean` | Tablet (iPad, or Android without Mobile token) |
35
+ | `isDesktop` | `boolean` | Desktop/laptop (not bot, mobile, or tablet) |
36
+ | `isBot` | `boolean` | Known bot, crawler, or non-browser client |
37
+ | `botName` | `string?` | Bot name when `isBot` is true, e.g. `'Googlebot'`, `'curl'` |
38
+ | `deviceType` | `'mobile' \| 'tablet' \| 'desktop' \| 'bot' \| 'unknown'` | Normalized device category |
39
+ | `browserName` | `string?` | e.g. `'Chrome'`, `'Firefox'`, `'Safari'`, `'Edge'` |
40
+ | `browserVersion` | `string?` | e.g. `'120.0.6099.130'` |
41
+ | `osName` | `string?` | e.g. `'Windows'`, `'macOS'`, `'Android'`, `'iOS'` |
42
+ | `osVersion` | `string?` | e.g. `'10'`, `'15.7'` |
43
+ | `engine` | `string?` | e.g. `'Blink'`, `'Gecko'`, `'WebKit'` |
44
+ | `partial` | `boolean` | `true` when signals are conflicting or insufficient to trust fully |
45
+
46
+ ## Documentation
47
+
48
+ [davaux.codeberg.page/docs/user-agent](https://davaux.codeberg.page/docs/user-agent)
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "@davaux/user-agent",
3
+ "version": "0.8.0",
4
+ "description": "User-Agent parsing middleware for Davaux",
5
+ "type": "module",
6
+ "author": "David L Dyess II",
7
+ "license": "MIT",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://codeberg.org/davaux/davaux"
11
+ },
12
+ "bugs": {
13
+ "url": "https://codeberg.org/davaux/davaux/issues"
14
+ },
15
+ "homepage": "https://codeberg.org/davaux/davaux#readme",
16
+ "exports": {
17
+ ".": {
18
+ "import": "./dist/index.js",
19
+ "types": "./dist/index.d.ts"
20
+ }
21
+ },
22
+ "scripts": {
23
+ "build": "tsc",
24
+ "typecheck": "tsc --noEmit"
25
+ },
26
+ "peerDependencies": {
27
+ "davaux": ">=0.8.0"
28
+ },
29
+ "devDependencies": {
30
+ "@types/node": "^25.0.0",
31
+ "davaux": "*",
32
+ "typescript": "^6.0.3"
33
+ }
34
+ }
package/src/index.ts ADDED
@@ -0,0 +1,306 @@
1
+ import type { MiddlewareFn } from 'davaux'
2
+
3
+ // ─── Types ────────────────────────────────────────────────────────────────────
4
+
5
+ export interface UserAgent {
6
+ /** Raw `User-Agent` header value. Empty string when the header is absent. */
7
+ raw: string
8
+ /** `true` when the UA contains mobile device indicators (excludes tablets). */
9
+ isMobile: boolean
10
+ /** `true` when the UA matches a tablet (iPad, Android without Mobile token). */
11
+ isTablet: boolean
12
+ /** `true` when the client is a desktop/laptop (not bot, not mobile, not tablet). */
13
+ isDesktop: boolean
14
+ /** `true` when the UA matches a known bot, crawler, or non-browser client. */
15
+ isBot: boolean
16
+ /** Bot name when `isBot` is true, e.g. `'Googlebot'`, `'curl'`. */
17
+ botName?: string
18
+ /** Normalized device category. */
19
+ deviceType: 'mobile' | 'tablet' | 'desktop' | 'bot' | 'unknown'
20
+ /** Browser family, e.g. `'Chrome'`, `'Firefox'`, `'Safari'`, `'Edge'`. */
21
+ browserName?: string
22
+ /** Browser version string, e.g. `'120.0.6099.130'`. */
23
+ browserVersion?: string
24
+ /** OS family, e.g. `'Windows'`, `'macOS'`, `'Android'`, `'iOS'`, `'Linux'`. */
25
+ osName?: string
26
+ /** OS version string, e.g. `'10'`, `'15.7'`, `'13'`. */
27
+ osVersion?: string
28
+ /** Rendering engine, e.g. `'Blink'`, `'Gecko'`, `'WebKit'`, `'Trident'`. */
29
+ engine?: string
30
+ /**
31
+ * `true` when signals are conflicting or insufficient to fully trust the result.
32
+ * Examples: a non-browser runtime running on a mobile/tablet OS (e.g. Dalvik on
33
+ * Android), or a Mozilla-prefixed UA with no detectable browser or OS (e.g. a
34
+ * gaming console with an unrecognised browser engine).
35
+ */
36
+ partial: boolean
37
+ }
38
+
39
+ declare module 'davaux' {
40
+ interface State {
41
+ userAgent: UserAgent
42
+ }
43
+ }
44
+
45
+ // ─── Bot detection ────────────────────────────────────────────────────────────
46
+
47
+ // Named patterns match in any UA format, including browser-disguised bots.
48
+ const BOT_PATTERNS: Array<[RegExp, string]> = [
49
+ [/Googlebot/i, 'Googlebot'],
50
+ [/Bingbot/i, 'Bingbot'],
51
+ [/DuckDuckBot/i, 'DuckDuckBot'],
52
+ [/Yahoo! Slurp/i, 'Yahoo Slurp'],
53
+ [/Baiduspider/i, 'Baiduspider'],
54
+ [/YandexBot/i, 'YandexBot'],
55
+ [/Sogou/i, 'Sogou'],
56
+ [/facebookexternalhit/i, 'FacebookBot'],
57
+ [/Twitterbot/i, 'Twitterbot'],
58
+ [/Applebot/i, 'Applebot'],
59
+ [/AdsBot-Google/i, 'AdsBot-Google'],
60
+ [/SemrushBot/i, 'SemrushBot'],
61
+ [/AhrefsBot/i, 'AhrefsBot'],
62
+ [/MJ12bot/i, 'MJ12bot'],
63
+ [/DotBot/i, 'DotBot'],
64
+ [/Screaming Frog/i, 'Screaming Frog'],
65
+ [/Scrapy/i, 'Scrapy'],
66
+ [/curl\//i, 'curl'],
67
+ [/wget\//i, 'wget'],
68
+ [/python-requests/i, 'python-requests'],
69
+ [/Python-urllib/i, 'Python-urllib'],
70
+ [/Go-http-client/i, 'Go HTTP'],
71
+ [/Java\/\d/i, 'Java'],
72
+ [/libwww-perl/i, 'libwww-perl'],
73
+ ]
74
+
75
+ function detectBot(ua: string): { isBot: boolean; botName?: string } {
76
+ // Named patterns first — work regardless of Mozilla prefix.
77
+ for (const [pattern, name] of BOT_PATTERNS) {
78
+ if (pattern.test(ua)) return { isBot: true, botName: name }
79
+ }
80
+
81
+ // Non-browser clients never start with Mozilla/.
82
+ if (ua && !/^Mozilla\//i.test(ua)) {
83
+ // Try Name/Version token (covers most HTTP libs, CMSes, app runtimes).
84
+ // Allow commas so tokens like "AppleTV14,1" are captured whole.
85
+ const m = /^([\w][\w.,+-]*)\//.exec(ua)
86
+ if (m) return { isBot: true, botName: m[1] }
87
+ // No version token — extract service name before a generic bot keyword.
88
+ // e.g. "Traackr.com Bot" → "Traackr.com"
89
+ const k = /^(.*?)\s+(?:bot|crawler|spider)\b/i.exec(ua)
90
+ if (k) return { isBot: true, botName: k[1].trim() || 'Unknown' }
91
+ return { isBot: true, botName: 'Unknown' }
92
+ }
93
+
94
+ // Mozilla-prefixed bots: URL reference gives a better name than generic keywords.
95
+ // Real browsers never embed a URL in their UA string.
96
+ if (/https?:\/\//i.test(ua)) {
97
+ const m = /\(compatible;\s*([\w][\w. +-]*)\//.exec(ua)
98
+ return { isBot: true, botName: m ? m[1].trim() : 'Unknown' }
99
+ }
100
+
101
+ // Last resort: generic keyword match for Mozilla-prefixed unknown bots.
102
+ if (/\b(?:bot|crawler|spider)\b/i.test(ua)) return { isBot: true, botName: 'Unknown' }
103
+
104
+ return { isBot: false }
105
+ }
106
+
107
+ // ─── Device detection ─────────────────────────────────────────────────────────
108
+
109
+ function detectTablet(ua: string): boolean {
110
+ if (/iPad/i.test(ua)) return true
111
+ // Android tablets omit "Mobile" from their UA string.
112
+ if (/Android/i.test(ua) && !/Mobile/i.test(ua)) return true
113
+ return false
114
+ }
115
+
116
+ function detectMobile(ua: string): boolean {
117
+ return /Mobi|Android|iPhone|iPod|Windows Phone|BlackBerry|IEMobile/i.test(ua)
118
+ }
119
+
120
+ // ─── Browser detection ────────────────────────────────────────────────────────
121
+
122
+ function extractVersion(ua: string, token: string): string | undefined {
123
+ const m = new RegExp(`${token}/([\\d._]+)`, 'i').exec(ua)
124
+ return m ? m[1].replace(/_/g, '.') : undefined
125
+ }
126
+
127
+ interface BrowserResult {
128
+ browserName?: string
129
+ browserVersion?: string
130
+ engine?: string
131
+ }
132
+
133
+ function detectBrowser(ua: string): BrowserResult {
134
+ // Samsung Browser embeds Chrome in its UA — check first.
135
+ if (/SamsungBrowser\//i.test(ua)) {
136
+ return {
137
+ browserName: 'Samsung Browser',
138
+ browserVersion: extractVersion(ua, 'SamsungBrowser'),
139
+ engine: 'Blink',
140
+ }
141
+ }
142
+ // Chromium-based Edge ("Edg/") ships alongside Chrome token — check before Chrome.
143
+ if (/Edg\/\d/i.test(ua)) {
144
+ return { browserName: 'Edge', browserVersion: extractVersion(ua, 'Edg'), engine: 'Blink' }
145
+ }
146
+ // Legacy EdgeHTML-based Edge.
147
+ if (/Edge\/\d/i.test(ua)) {
148
+ return { browserName: 'Edge', browserVersion: extractVersion(ua, 'Edge'), engine: 'EdgeHTML' }
149
+ }
150
+ // Opera (Chromium-based, "OPR/").
151
+ if (/OPR\/\d/i.test(ua)) {
152
+ return { browserName: 'Opera', browserVersion: extractVersion(ua, 'OPR'), engine: 'Blink' }
153
+ }
154
+ // Chromium (open-source build, distinct from Google Chrome).
155
+ if (/Chromium\/\d/i.test(ua)) {
156
+ return {
157
+ browserName: 'Chromium',
158
+ browserVersion: extractVersion(ua, 'Chromium'),
159
+ engine: 'Blink',
160
+ }
161
+ }
162
+ // Google Chrome.
163
+ if (/Chrome\/\d/i.test(ua)) {
164
+ return { browserName: 'Chrome', browserVersion: extractVersion(ua, 'Chrome'), engine: 'Blink' }
165
+ }
166
+ // Firefox.
167
+ if (/Firefox\/\d/i.test(ua)) {
168
+ return {
169
+ browserName: 'Firefox',
170
+ browserVersion: extractVersion(ua, 'Firefox'),
171
+ engine: 'Gecko',
172
+ }
173
+ }
174
+ // Safari — must come after Chrome/Chromium since their UAs also contain "Safari".
175
+ if (/Safari\/\d/i.test(ua)) {
176
+ return {
177
+ browserName: 'Safari',
178
+ // "Version/x.x" carries the human-readable Safari version; fall back to Safari token.
179
+ browserVersion: extractVersion(ua, 'Version') ?? extractVersion(ua, 'Safari'),
180
+ engine: 'WebKit',
181
+ }
182
+ }
183
+ // Internet Explorer 11 (Trident/7 with rv: version).
184
+ if (/Trident\/\d/i.test(ua)) {
185
+ const m = /rv:([\d.]+)/.exec(ua)
186
+ return { browserName: 'Internet Explorer', browserVersion: m?.[1], engine: 'Trident' }
187
+ }
188
+ // Internet Explorer ≤ 10.
189
+ const ieMatch = /MSIE\s([\d.]+)/i.exec(ua)
190
+ if (ieMatch) {
191
+ return { browserName: 'Internet Explorer', browserVersion: ieMatch[1], engine: 'Trident' }
192
+ }
193
+ return {}
194
+ }
195
+
196
+ // ─── OS detection ─────────────────────────────────────────────────────────────
197
+
198
+ const WINDOWS_NT_VERSIONS: Record<string, string> = {
199
+ '10.0': '10',
200
+ '6.3': '8.1',
201
+ '6.2': '8',
202
+ '6.1': '7',
203
+ '6.0': 'Vista',
204
+ '5.2': 'XP',
205
+ '5.1': 'XP',
206
+ '5.0': '2000',
207
+ }
208
+
209
+ interface OSResult {
210
+ osName?: string
211
+ osVersion?: string
212
+ }
213
+
214
+ function detectOS(ua: string): OSResult {
215
+ // Windows Phone must be checked before Windows NT.
216
+ let m = /Windows Phone(?:\s+OS)?\s+([\d.]+)/i.exec(ua)
217
+ if (m) return { osName: 'Windows Phone', osVersion: m[1] }
218
+
219
+ // Android (appears on both mobile and tablet UAs).
220
+ m = /Android\s+([\d.]+)/i.exec(ua)
221
+ if (m) return { osName: 'Android', osVersion: m[1] }
222
+
223
+ // iOS — covers iPhone, iPad (iPadOS ≥ 13 drops "iPhone" token), and iPod.
224
+ m = /(?:iPhone|iPad|iPod)[^)]*OS\s+([\d_]+)/i.exec(ua)
225
+ if (m) return { osName: 'iOS', osVersion: m[1].replace(/_/g, '.') }
226
+
227
+ // macOS / OS X.
228
+ m = /Mac OS X\s+([\d_.]+)/i.exec(ua)
229
+ if (m) return { osName: 'macOS', osVersion: m[1].replace(/_/g, '.') }
230
+
231
+ // Windows NT.
232
+ m = /Windows NT\s+([\d.]+)/i.exec(ua)
233
+ if (m) return { osName: 'Windows', osVersion: WINDOWS_NT_VERSIONS[m[1]] ?? m[1] }
234
+
235
+ if (/CrOS/i.test(ua)) return { osName: 'Chrome OS' }
236
+ if (/Linux/i.test(ua)) return { osName: 'Linux' }
237
+
238
+ return {}
239
+ }
240
+
241
+ // ─── Parser ───────────────────────────────────────────────────────────────────
242
+
243
+ function parse(raw: string): UserAgent {
244
+ const { isBot, botName } = detectBot(raw)
245
+ // Suppress device-type signals when isBot — they become noise, not signal.
246
+ const isTablet = !isBot && detectTablet(raw)
247
+ const isMobile = !isBot && !isTablet && detectMobile(raw)
248
+ const isDesktop = !isBot && !isTablet && !isMobile
249
+
250
+ let deviceType: UserAgent['deviceType']
251
+ if (isBot) deviceType = 'bot'
252
+ else if (isTablet) deviceType = 'tablet'
253
+ else if (isMobile) deviceType = 'mobile'
254
+ else if (raw) deviceType = 'desktop'
255
+ else deviceType = 'unknown'
256
+
257
+ const { browserName, browserVersion, engine } = detectBrowser(raw)
258
+ const { osName, osVersion } = detectOS(raw)
259
+
260
+ // Partial: non-browser runtime on a device we can identify (conflicting signals),
261
+ // or a browser UA with no detectable browser or OS (unrecognised device).
262
+ const partial =
263
+ (isBot && /Android|iPhone|iPad|iPod/i.test(raw)) ||
264
+ (!isBot && !browserName && !osName && raw.length > 0)
265
+
266
+ return {
267
+ raw,
268
+ isMobile,
269
+ isTablet,
270
+ isDesktop,
271
+ isBot,
272
+ botName,
273
+ deviceType,
274
+ browserName,
275
+ browserVersion,
276
+ engine,
277
+ osName,
278
+ osVersion,
279
+ partial,
280
+ }
281
+ }
282
+
283
+ // ─── Middleware ───────────────────────────────────────────────────────────────
284
+
285
+ /**
286
+ * Parses the `User-Agent` request header and exposes structured data as
287
+ * `ctx.state.userAgent`. When the header is absent, `raw` is an empty string
288
+ * and all other fields are `undefined` / `false`.
289
+ *
290
+ * ```ts
291
+ * import { userAgent } from '@davaux/user-agent'
292
+ *
293
+ * // _global.ts or _middleware.ts
294
+ * export default userAgent()
295
+ *
296
+ * // A route handler:
297
+ * const { isMobile, isBot, browserName, osName } = ctx.state.userAgent
298
+ * ```
299
+ */
300
+ export function userAgent(): MiddlewareFn {
301
+ return async (ctx, next) => {
302
+ const raw = (ctx.req.headers['user-agent'] as string | undefined) ?? ''
303
+ ctx.state.userAgent = parse(raw)
304
+ await next()
305
+ }
306
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,17 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ESNext",
4
+ "module": "NodeNext",
5
+ "moduleResolution": "NodeNext",
6
+ "strict": true,
7
+ "declaration": true,
8
+ "declarationMap": true,
9
+ "sourceMap": true,
10
+ "outDir": "./dist",
11
+ "rootDir": "./src",
12
+ "skipLibCheck": true,
13
+ "lib": ["ESNext"],
14
+ "types": ["node"]
15
+ },
16
+ "include": ["src/**/*"]
17
+ }