@namzu/browser 0.1.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.
Files changed (74) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/LICENSE.md +110 -0
  3. package/README.md +149 -0
  4. package/dist/classifier.d.ts +70 -0
  5. package/dist/classifier.d.ts.map +1 -0
  6. package/dist/classifier.js +147 -0
  7. package/dist/classifier.js.map +1 -0
  8. package/dist/detect.d.ts +126 -0
  9. package/dist/detect.d.ts.map +1 -0
  10. package/dist/detect.js +282 -0
  11. package/dist/detect.js.map +1 -0
  12. package/dist/errors.d.ts +64 -0
  13. package/dist/errors.d.ts.map +1 -0
  14. package/dist/errors.js +99 -0
  15. package/dist/errors.js.map +1 -0
  16. package/dist/host.d.ts +167 -0
  17. package/dist/host.d.ts.map +1 -0
  18. package/dist/host.js +1024 -0
  19. package/dist/host.js.map +1 -0
  20. package/dist/index.d.ts +17 -0
  21. package/dist/index.d.ts.map +1 -0
  22. package/dist/index.js +10 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/page-scripts.d.ts +51 -0
  25. package/dist/page-scripts.d.ts.map +1 -0
  26. package/dist/page-scripts.js +123 -0
  27. package/dist/page-scripts.js.map +1 -0
  28. package/dist/policy.d.ts +61 -0
  29. package/dist/policy.d.ts.map +1 -0
  30. package/dist/policy.js +150 -0
  31. package/dist/policy.js.map +1 -0
  32. package/dist/profiles.d.ts +107 -0
  33. package/dist/profiles.d.ts.map +1 -0
  34. package/dist/profiles.js +312 -0
  35. package/dist/profiles.js.map +1 -0
  36. package/dist/relay.d.ts +27 -0
  37. package/dist/relay.d.ts.map +1 -0
  38. package/dist/relay.js +69 -0
  39. package/dist/relay.js.map +1 -0
  40. package/dist/snapshot.d.ts +101 -0
  41. package/dist/snapshot.d.ts.map +1 -0
  42. package/dist/snapshot.js +265 -0
  43. package/dist/snapshot.js.map +1 -0
  44. package/dist/windows-bridge-script.d.ts +29 -0
  45. package/dist/windows-bridge-script.d.ts.map +1 -0
  46. package/dist/windows-bridge-script.js +161 -0
  47. package/dist/windows-bridge-script.js.map +1 -0
  48. package/dist/windows-bridge.d.ts +120 -0
  49. package/dist/windows-bridge.d.ts.map +1 -0
  50. package/dist/windows-bridge.js +267 -0
  51. package/dist/windows-bridge.js.map +1 -0
  52. package/dist/windows-engine.d.ts +55 -0
  53. package/dist/windows-engine.d.ts.map +1 -0
  54. package/dist/windows-engine.js +154 -0
  55. package/dist/windows-engine.js.map +1 -0
  56. package/dist/wsl.d.ts +52 -0
  57. package/dist/wsl.d.ts.map +1 -0
  58. package/dist/wsl.js +134 -0
  59. package/dist/wsl.js.map +1 -0
  60. package/package.json +74 -0
  61. package/src/classifier.ts +191 -0
  62. package/src/detect.ts +432 -0
  63. package/src/errors.ts +121 -0
  64. package/src/host.ts +1217 -0
  65. package/src/index.ts +79 -0
  66. package/src/page-scripts.ts +154 -0
  67. package/src/policy.ts +190 -0
  68. package/src/profiles.ts +373 -0
  69. package/src/relay.ts +101 -0
  70. package/src/snapshot.ts +317 -0
  71. package/src/windows-bridge-script.ts +160 -0
  72. package/src/windows-bridge.ts +358 -0
  73. package/src/windows-engine.ts +208 -0
  74. package/src/wsl.ts +155 -0
package/dist/wsl.js ADDED
@@ -0,0 +1,134 @@
1
+ import { readdirSync, statSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ const NETWORKING_MODES = ['nat', 'mirrored', 'virtioproxy', 'none'];
4
+ /** The default mount root for Windows drives. */
5
+ export const DEFAULT_WSL_MOUNT_ROOT = '/mnt/';
6
+ /**
7
+ * The Linux path of a Windows drive path under `mountRoot` (`/mnt/` unless
8
+ * `/etc/wsl.conf` moved it): `C:\Users\A` → `/mnt/c/Users/A`. `undefined`
9
+ * for anything that is not `<letter>:\…` (a UNC path, a relative path).
10
+ */
11
+ export function windowsPathToWsl(windowsPath, mountRoot = DEFAULT_WSL_MOUNT_ROOT) {
12
+ const match = /^([A-Za-z]):(?:[\\/](.*))?$/.exec(windowsPath);
13
+ if (!match)
14
+ return undefined;
15
+ const drive = (match[1] ?? '').toLowerCase();
16
+ const rest = (match[2] ?? '').replace(/[\\/]+/g, '/').replace(/\/$/, '');
17
+ const root = mountRoot.endsWith('/') ? mountRoot : `${mountRoot}/`;
18
+ return rest.length > 0 ? `${root}${drive}/${rest}` : `${root}${drive}`;
19
+ }
20
+ /**
21
+ * The Windows path of a Linux path on a mounted Windows drive:
22
+ * `/mnt/c/Program Files/x.exe` → `C:\Program Files\x.exe`. `undefined` for a
23
+ * path outside the drive mounts.
24
+ */
25
+ export function wslPathToWindows(linuxPath, mountRoot = DEFAULT_WSL_MOUNT_ROOT) {
26
+ const root = mountRoot.endsWith('/') ? mountRoot : `${mountRoot}/`;
27
+ if (!linuxPath.startsWith(root))
28
+ return undefined;
29
+ const match = /^([a-zA-Z])(?:\/(.*))?$/.exec(linuxPath.slice(root.length));
30
+ if (!match)
31
+ return undefined;
32
+ const drive = (match[1] ?? '').toUpperCase();
33
+ const rest = (match[2] ?? '').replace(/\/+/g, '\\').replace(/\\$/, '');
34
+ return `${drive}:\\${rest}`;
35
+ }
36
+ /** Sections of an INI file (`wsl.conf`, `.wslconfig`), keys lowercased. */
37
+ function parseIni(text) {
38
+ const sections = new Map();
39
+ let current;
40
+ for (const raw of text.replace(/^\uFEFF/, '').split(/\r?\n/)) {
41
+ const line = raw.trim();
42
+ if (line.length === 0 || line.startsWith('#') || line.startsWith(';'))
43
+ continue;
44
+ const section = /^\[([^\]]+)\]$/.exec(line);
45
+ if (section) {
46
+ const name = (section[1] ?? '').trim().toLowerCase();
47
+ current = sections.get(name) ?? new Map();
48
+ sections.set(name, current);
49
+ continue;
50
+ }
51
+ const eq = line.indexOf('=');
52
+ if (eq <= 0 || !current)
53
+ continue;
54
+ const key = line.slice(0, eq).trim().toLowerCase();
55
+ let value = line
56
+ .slice(eq + 1)
57
+ .replace(/\s[#;].*$/, '')
58
+ .trim();
59
+ if (/^(["']).*\1$/.test(value))
60
+ value = value.slice(1, -1);
61
+ current.set(key, value);
62
+ }
63
+ return sections;
64
+ }
65
+ /** The `[automount] root` of `/etc/wsl.conf`, with a trailing slash; `/mnt/` by default. */
66
+ export function parseWslMountRoot(wslConf) {
67
+ if (!wslConf)
68
+ return DEFAULT_WSL_MOUNT_ROOT;
69
+ const root = parseIni(wslConf).get('automount')?.get('root');
70
+ if (!root || !root.startsWith('/'))
71
+ return DEFAULT_WSL_MOUNT_ROOT;
72
+ return root.endsWith('/') ? root : `${root}/`;
73
+ }
74
+ /** `wslinfo --networking-mode`'s output as a mode; `unknown` for anything else. */
75
+ export function parseNetworkingModeOutput(output) {
76
+ const word = (output ?? '').trim().toLowerCase();
77
+ return NETWORKING_MODES.includes(word)
78
+ ? word
79
+ : 'unknown';
80
+ }
81
+ /**
82
+ * The networking mode a `.wslconfig` asks for: `[wsl2] networkingMode`, or
83
+ * the older `[experimental] networkingMode`. No setting is NAT, WSL's
84
+ * default; a file that cannot be read is `unknown`.
85
+ */
86
+ export function parseWslConfigNetworkingMode(text) {
87
+ if (text === undefined)
88
+ return 'unknown';
89
+ const ini = parseIni(text);
90
+ const value = ini.get('wsl2')?.get('networkingmode') ?? ini.get('experimental')?.get('networkingmode');
91
+ if (value === undefined)
92
+ return 'nat';
93
+ return parseNetworkingModeOutput(value);
94
+ }
95
+ export const WSL_RUN_DIR = '/run/WSL';
96
+ /**
97
+ * The interop socket a process without `WSL_INTEROP` can use: a systemd
98
+ * service's, which WSL starts outside any session. `1_interop` is the one WSL
99
+ * links for systemd to the distro's own init, so it lives as long as the
100
+ * distro; failing that, the newest session's. The CLI's desktop
101
+ * notifications choose the same way.
102
+ */
103
+ export function findWslInteropSocket(sockets) {
104
+ const stable = sockets.find((socket) => socket.path === `${WSL_RUN_DIR}/1_interop`);
105
+ if (stable)
106
+ return stable.path;
107
+ return [...sockets].sort((a, b) => b.mtimeMs - a.mtimeMs)[0]?.path;
108
+ }
109
+ /** The interop sockets under `/run/WSL` on this machine. Reads the file system. */
110
+ export function listWslInteropSockets(dir = WSL_RUN_DIR) {
111
+ const sockets = [];
112
+ let names;
113
+ try {
114
+ names = readdirSync(dir);
115
+ }
116
+ catch {
117
+ return sockets;
118
+ }
119
+ for (const name of names) {
120
+ if (!/^\d+_interop$/.test(name))
121
+ continue;
122
+ const path = join(dir, name);
123
+ try {
124
+ const stat = statSync(path);
125
+ if (stat.isSocket())
126
+ sockets.push({ path, mtimeMs: stat.mtimeMs });
127
+ }
128
+ catch {
129
+ // Gone between the listing and the stat: a session that just ended.
130
+ }
131
+ }
132
+ return sockets;
133
+ }
134
+ //# sourceMappingURL=wsl.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wsl.js","sourceRoot":"","sources":["../src/wsl.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAA;AAC/C,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAehC,MAAM,gBAAgB,GAAiC,CAAC,KAAK,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,CAAC,CAAA;AAEjG,iDAAiD;AACjD,MAAM,CAAC,MAAM,sBAAsB,GAAG,OAAO,CAAA;AAE7C;;;;GAIG;AACH,MAAM,UAAU,gBAAgB,CAC/B,WAAmB,EACnB,YAAoB,sBAAsB;IAE1C,MAAM,KAAK,GAAG,6BAA6B,CAAC,IAAI,CAAC,WAAW,CAAC,CAAA;IAC7D,IAAI,CAAC,KAAK;QAAE,OAAO,SAAS,CAAA;IAC5B,MAAM,KAAK,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,WAAW,EAAE,CAAA;IAC5C,MAAM,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,OAAO,CAAC,SAAS,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAA;IACxE,MAAM,IAAI,GAAG,SAAS,CAAC,Q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"0.1.0",
4
+ "description": "Playwright-based browser host for @namzu/sdk: accessibility snapshots with element refs, a host-side site policy checked after every navigation, sign-in and CAPTCHA detection that hands the page to a person, and persistent profiles.",
5
+ "license": "FSL-1.1-MIT",
6
+ "engines": {
7
+ "node": ">=20.0.0"
8
+ },
9
+ "type": "module",
10
+ "homepage": "https://github.com/cogitave/namzu#readme",
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/cogitave/namzu.git",
14
+ "directory": "packages/browser"
15
+ },
16
+ "bugs": {
17
+ "url": "https://github.com/cogitave/namzu/issues"
18
+ },
19
+ "main": "./dist/index.js",
20
+ "types": "./dist/index.d.ts",
21
+ "exports": {
22
+ ".": {
23
+ "types": "./dist/index.d.ts",
24
+ "import": "./dist/index.js"
25
+ }
26
+ },
27
+ "files": [
28
+ "dist",
29
+ "!dist/**/*.test.*",
30
+ "!dist/**/*.proc-test.*",
31
+ "!dist/**/__tests__",
32
+ "!dist/**/__fixtures__",
33
+ "!dist/**/test-setup.*",
34
+ "src",
35
+ "!src/**/*.test.*",
36
+ "!src/**/*.proc-test.*",
37
+ "!src/**/__tests__",
38
+ "!src/**/__fixtures__",
39
+ "!src/**/test-setup.*",
40
+ "LICENSE.md",
41
+ "README.md",
42
+ "CHANGELOG.md"
43
+ ],
44
+ "publishConfig": {
45
+ "access": "public",
46
+ "provenance": true
47
+ },
48
+ "dependencies": {
49
+ "playwright-core": "1.63.0",
50
+ "ws": "^8.21.3"
51
+ },
52
+ "peerDependencies": {
53
+ "@namzu/sdk": ">=44.4.0"
54
+ },
55
+ "devDependencies": {
56
+ "@biomejs/biome": "^1.9.4",
57
+ "@types/node": "^22.19.17",
58
+ "@types/ws": "^8.18.1",
59
+ "typescript": "^5.5.0",
60
+ "vitest": "^4.1.11",
61
+ "@namzu/sdk": "^45.1.0"
62
+ },
63
+ "scripts": {
64
+ "build": "tsc --build",
65
+ "dev": "tsc --build --watch",
66
+ "lint": "biome check src/",
67
+ "lint:fix": "biome check --write src/",
68
+ "format": "biome format --write src/",
69
+ "test": "vitest run --passWithNoTests",
70
+ "test:e2e": "NAMZU_BROWSER_E2E=1 vitest run src/__tests__/e2e/host.test.ts",
71
+ "test:e2e:wsl": "NAMZU_BROWSER_WSL_E2E=1 vitest run src/__tests__/e2e/windows.test.ts",
72
+ "typecheck": "tsc --noEmit"
73
+ }
74
+ }
@@ -0,0 +1,191 @@
1
+ import type { BrowserHumanRequiredReason } from '@namzu/sdk'
2
+
3
+ /**
4
+ * What the host read off a page to decide whether it needs a person. Every
5
+ * field is gathered by the host from the browser, never from the model.
6
+ */
7
+ export interface BrowserPageSignals {
8
+ /** The main frame's address. */
9
+ readonly url: string
10
+ /** The document title. */
11
+ readonly title: string
12
+ /** HTTP status of the main document's last response, when known. */
13
+ readonly status?: number
14
+ /** Visible password fields (`type=password`, `autocomplete=current-password`). */
15
+ readonly passwordFields: number
16
+ /** Visible one-time-code fields (`autocomplete=one-time-code`, or named like one). */
17
+ readonly oneTimeCodeFields: number
18
+ /** Addresses of visible child frames, the only place a CAPTCHA widget is drawn. */
19
+ readonly frameUrls: readonly string[]
20
+ }
21
+
22
+ export interface BrowserHumanClassifierOptions {
23
+ /**
24
+ * More sign-in addresses, as `host` (`sso.example.com`) or `host/path`
25
+ * prefix (`example.com/account/login`). Added to {@link SIGN_IN_ADDRESSES}.
26
+ */
27
+ readonly signInAddresses?: readonly string[]
28
+ }
29
+
30
+ /**
31
+ * Hosts and host/path prefixes that are a sign-in wherever they appear. The
32
+ * path forms below catch the rest (`/login`, `/signin`, `/sso`, …).
33
+ */
34
+ export const SIGN_IN_ADDRESSES: readonly string[] = [
35
+ 'accounts.google.com',
36
+ 'login.microsoftonline.com',
37
+ 'login.live.com',
38
+ 'appleid.apple.com',
39
+ 'github.com/login',
40
+ 'github.com/session',
41
+ 'gitlab.com/users/sign_in',
42
+ ]
43
+
44
+ /** Second-factor addresses: a sign-in that is already half done. */
45
+ const TWO_FACTOR_ADDRESSES: readonly string[] = ['github.com/sessions/two-factor']
46
+
47
+ /** A path segment that is a sign-in page. `/author` is not `/auth`. */
48
+ const SIGN_IN_PATH =
49
+ /(?:^|\/)(?:login|log-in|signin|sign-in|sign_in|auth|sso|oauth2?\/authorize|authorize)(?:\/|\.[a-z]+$|$)/i
50
+
51
+ const TWO_FACTOR_PATH = /(?:^|\/)(?:two-factor|2fa|mfa|otp|totp)(?:\/|\.[a-z]+$|$)/i
52
+
53
+ /**
54
+ * Hosts that draw CAPTCHA and bot-check widgets in a frame. A frame served
55
+ * from one of these (or a subdomain) is a challenge.
56
+ */
57
+ export const CAPTCHA_FRAME_HOSTS: readonly string[] = [
58
+ 'challenges.cloudflare.com',
59
+ 'hcaptcha.com',
60
+ 'newassets.hcaptcha.com',
61
+ 'arkoselabs.com',
62
+ 'funcaptcha.com',
63
+ 'recaptcha.net',
64
+ ]
65
+
66
+ /** reCAPTCHA is served from google.com under this path. */
67
+ const RECAPTCHA_PATH = /^\/recaptcha\//
68
+
69
+ /**
70
+ * Titles of interstitial bot checks and blocks. Anchored and short on
71
+ * purpose: a page ABOUT access control must not match.
72
+ */
73
+ const BOT_BLOCK_TITLES: readonly RegExp[] = [
74
+ /^just a moment\.{0,3}$/i,
75
+ /^attention required!?(?: \| cloudflare)?$/i,
76
+ /^access denied$/i,
77
+ /^are you a robot\??$/i,
78
+ /^verify(?:ing)? (?:you are|that you are) (?:a )?human\.{0,3}$/i,
79
+ /^(?:security|human) (?:check|verification)$/i,
80
+ /^checking (?:your browser|if the site connection is secure)[\s\S]{0,40}$/i,
81
+ /^pardon our interruption\.{0,3}$/i,
82
+ /^please verify you are a human$/i,
83
+ /^one more step$/i,
84
+ /^robot check$/i,
85
+ /^ddos-guard$/i,
86
+ ]
87
+
88
+ function hostMatches(host: string, entry: string): boolean {
89
+ return host === entry || host.endsWith(`.${entry}`)
90
+ }
91
+
92
+ function addressMatches(url: URL, entry: string): boolean {
93
+ const slash = entry.indexOf('/')
94
+ const host = (slash === -1 ? entry : entry.slice(0, slash)).toLowerCase()
95
+ const path = slash === -1 ? '' : entry.slice(slash)
96
+ if (url.hostname !== host) return false
97
+ if (path === '') return true
98
+ return url.pathname === path || url.pathname.startsWith(path.endsWith('/') ? path : `${path}/`)
99
+ }
100
+
101
+ function parse(raw: string): URL | undefined {
102
+ try {
103
+ return new URL(raw)
104
+ } catch {
105
+ return undefined
106
+ }
107
+ }
108
+
109
+ /** Is `frameUrl` a CAPTCHA or bot-check widget? Invisible-badge frames are not. */
110
+ export function isCaptchaFrame(frameUrl: string): boolean {
111
+ const url = parse(frameUrl)
112
+ if (!url || (url.protocol !== 'https:' && url.protocol !== 'http:')) return false
113
+ if (url.searchParams.get('size') === 'invisible') return false
114
+ const host = url.hostname
115
+ if (CAPTCHA_FRAME_HOSTS.some((entry) => hostMatches(host, entry))) return true
116
+ return (host === 'www.google.com' || host === 'google.com') && RECAPTCHA_PATH.test(url.pathname)
117
+ }
118
+
119
+ /** Is `title` the title of a bot check or block page? */
120
+ export function isBotBlockTitle(title: string): boolean {
121
+ const flat = title.replace(/\s+/g, ' ').trim()
122
+ return BOT_BLOCK_TITLES.some((pattern) => pattern.test(flat))
123
+ }
124
+
125
+ /** Is `rawUrl` a sign-in address, by host list or by path? */
126
+ export function isSignInAddress(
127
+ rawUrl: string,
128
+ options: BrowserHumanClassifierOptions = {},
129
+ ): boolean {
130
+ const url = parse(rawUrl)
131
+ if (!url || (url.protocol !== 'https:' && url.protocol !== 'http:')) return false
132
+ const entries = [...SIGN_IN_ADDRESSES, ...(options.signInAddresses ?? [])]
133
+ if (entries.some((entry) => addressMatches(url, entry))) return true
134
+ return SIGN_IN_PATH.test(url.pathname)
135
+ }
136
+
137
+ function isTwoFactorAddress(rawUrl: string): boolean {
138
+ const url = parse(rawUrl)
139
+ if (!url) return false
140
+ if (TWO_FACTOR_ADDRESSES.some((entry) => addressMatches(url, entry))) return true
141
+ return TWO_FACTOR_PATH.test(url.pathname)
142
+ }
143
+
144
+ /**
145
+ * Does the page need a person, and why? `undefined` when it does not.
146
+ *
147
+ * Order matters only for the reason reported: an HTTP credential prompt,
148
+ * then a CAPTCHA, a bot wall, a second factor, and last a sign-in. All of it
149
+ * is read by the host; nothing the model says reaches this function.
150
+ *
151
+ * It errs toward stopping. A page with a visible password box is treated as
152
+ * a sign-in even when it is a settings page, because the cost of a false stop
153
+ * is a question to the operator and the cost of a false pass is an agent
154
+ * typing near a credential.
155
+ */
156
+ export function classifyHumanRequired(
157
+ signals: BrowserPageSignals,
158
+ options: BrowserHumanClassifierOptions = {},
159
+ ): BrowserHumanRequiredReason | undefined {
160
+ if (signals.status === 401 || signals.status === 407) return 'http-auth'
161
+ if (signals.frameUrls.some(isCaptchaFrame)) return 'captcha'
162
+ if (isBotBlockTitle(signals.title)) return 'bot-block'
163
+ if (signals.oneTimeCodeFields > 0 || isTwoFactorAddress(signals.url)) return 'two-factor'
164
+ if (signals.passwordFields > 0 || isSignInAddress(signals.url, options)) return 'sign-in'
165
+ return undefined
166
+ }
167
+
168
+ /** What the host read about one field before typing into it. */
169
+ export interface BrowserFieldFacts {
170
+ readonly tag: string
171
+ readonly type: string
172
+ readonly autocomplete: string
173
+ readonly name: string
174
+ readonly id: string
175
+ readonly label: string
176
+ }
177
+
178
+ const ONE_TIME_CODE_NAME =
179
+ /(?:^|[^a-z])(?:otp|totp|2fa|mfa|one[-_ ]?time[-_ ]?(?:code|password)|verification[-_ ]?code|passcode|security[-_ ]?code|auth(?:entication)?[-_ ]?code)(?:[^a-z]|$)/i
180
+
181
+ /**
182
+ * Is this field a password or a one-time code? Typing into one is always
183
+ * refused, whatever the gate allowed: the agent never handles a credential.
184
+ */
185
+ export function isCredentialField(field: BrowserFieldFacts): boolean {
186
+ if (field.tag !== 'input' && field.tag !== 'textarea') return false
187
+ if (field.type.toLowerCase() === 'password') return true
188
+ const autocomplete = field.autocomplete.toLowerCase()
189
+ if (/\b(?:current-password|new-password|one-time-code)\b/.test(autocomplete)) return true
190
+ return [field.name, field.id, field.label].some((value) => ONE_TIME_CODE_NAME.test(value))
191
+ }