Skip to content

Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥

Update AI SDK to Latest Version (#2369)

Abimael Martell90188cb4b812
diff --git a/apps/api/package.json b/apps/api/package.json
index f98bb74f2..a3c9a58ff 100644
--- a/apps/api/package.json
+++ b/apps/api/package.json
@@ -68,13 +68,13 @@
"typescript": "^5.8.3"
},
"dependencies": {
- "@ai-sdk/anthropic": "^1.2.4",
- "@ai-sdk/deepinfra": "^0.2.4",
- "@ai-sdk/fireworks": "^0.2.4",
- "@ai-sdk/google": "^1.2.3",
- "@ai-sdk/google-vertex": "^2.2.15",
- "@ai-sdk/groq": "^1.2.1",
- "@ai-sdk/openai": "^1.3.12",
+ "@ai-sdk/anthropic": "^2.0.41",
+ "@ai-sdk/deepinfra": "^1.0.27",
+ "@ai-sdk/fireworks": "^1.0.27",
+ "@ai-sdk/google": "^2.0.28",
+ "@ai-sdk/google-vertex": "^3.0.58",
+ "@ai-sdk/groq": "^2.0.28",
+ "@ai-sdk/openai": "2.0.64",
"@apidevtools/json-schema-ref-parser": "^15.1.2",
"@bull-board/api": "^6.14.0",
"@bull-board/express": "^6.14.0",
@@ -93,7 +93,7 @@
"@sentry/profiling-node": "^10.27.0",
"@supabase/supabase-js": "^2.52.0",
"@types/ws": "^8.5.12",
- "ai": "^4.3.4",
+ "ai": "5.0.89",
"ajv": "^8.16.0",
"amqplib": "^0.10.9",
"async-mutex": "^0.5.0",
@@ -143,7 +143,7 @@
"ws": "^8.18.0",
"x402-express": "^0.6.5",
"xml2js": "^0.6.2",
- "zod": "^3.24.2"
+ "zod": "4.1.12"
},
"nodemonConfig": {
"ignore": [
diff --git a/apps/api/pnpm-lock.yaml b/apps/api/pnpm-lock.yaml
index 61de3f96c..c4024d1a1 100644
--- a/apps/api/pnpm-lock.yaml
+++ b/apps/api/pnpm-lock.yaml
@@ -15,26 +15,26 @@ importers:
.:
dependencies:
'@ai-sdk/anthropic':
- specifier: ^1.2.4
- version: 1.2.4([email protected])
+ specifier: ^2.0.41
+ version: 2.0.50([email protected])
'@ai-sdk/deepinfra':
- specifier: ^0.2.4
- version: 0.2.4([email protected])
+ specifier: ^1.0.27
+ version: 1.0.29([email protected])
'@ai-sdk/fireworks':
- specifier: ^0.2.4
- version: 0.2.4([email protected])
+ specifier: ^1.0.27
+ version: 1.0.29([email protected])
'@ai-sdk/google':
- specifier: ^1.2.3
- version: 1.2.3([email protected])
+ specifier: ^2.0.28
+ version: 2.0.44([email protected])
'@ai-sdk/google-vertex':
- specifier: ^2.2.15
+ specifier: ^3.0.58
+ version: 3.0.82([email protected])
'@ai-sdk/groq':
- specifier: ^1.2.1
- version: 1.2.1([email protected])
+ specifier: ^2.0.28
+ version: 2.0.32([email protected])
'@ai-sdk/openai':
- specifier: ^1.3.12
- version: 1.3.12([email protected])
+ specifier: 2.0.64
+ version: 2.0.64([email protected])
'@apidevtools/json-schema-ref-parser':
specifier: ^15.1.2
version: 15.1.2(@types/[email protected])
@@ -58,7 +58,7 @@ importers:
version: link:native
'@openrouter/ai-sdk-provider':
specifier: ^0.4.5
- version: 0.4.5([email protected])
+ version: 0.4.5([email protected])
'@opentelemetry/api':
specifier: ^1.9.0
version: 1.9.0
@@ -90,8 +90,8 @@ importers:
specifier: ^8.5.12
version: 8.5.12
ai:
- specifier: ^4.3.4
+ specifier: 5.0.89
+ version: 5.0.89([email protected])
ajv:
specifier: ^8.16.0
version: 8.16.0
@@ -169,10 +169,10 @@ importers:
version: 14.1.2
ollama-ai-provider:
specifier: ^1.2.0
- version: 1.2.0([email protected])
+ version: 1.2.0([email protected])
openai:
specifier: ^5.20.2
parse-diff:
specifier: ^0.11.1
version: 0.11.1
@@ -240,8 +240,8 @@ importers:
specifier: ^0.6.2
version: 0.6.2
zod:
- specifier: ^3.24.2
- version: 3.24.2
+ specifier: 4.1.12
+ version: 4.1.12
devDependencies:
'@jest/globals':
specifier: ^30.2.0
@@ -351,65 +351,59 @@ packages:
'@adraffy/[email protected]':
resolution: {integrity: sha512-nhCBV3quEgesuf7c7KYfperqSS14T8bYuvJ8PcLJp6znkZpFc0AuW4qBtr8eKVyPPe/8RSr7sglCWPU5eaxwKQ==}
- '@ai-sdk/[email protected]':
- resolution: {integrity: sha512-PyE7EC2fPjs9DnzRAHDrPQmcnI2m2Eojr8pfhckOejOlDEh2w7NnSJr1W3qe5hUWzKr+6d7NG1ZKR9fhmpDdEQ==}
+ '@ai-sdk/[email protected]':
+ resolution: {integrity: sha512-21PaHfoLmouOXXNINTsZJsMw+wE5oLR2He/1kq/sKokTVKyq7ObGT1LDk6ahwxaz/GoaNaGankMh+EgVcdv2Cw==}
engines: {node: '>=18'}
peerDependencies:
- zod: ^3.0.0
-
- '@ai-sdk/[email protected]':
- resolution: {integrity: sha512-dAN6MXvLffeFVAr2gz3RGvOTgX1KL/Yn5q1l4/Dt0TUeDjQgCt4AbbYxZZB2qIAYzQvoyAFPhlw0sB3nNizG/g==}
- engines: {node: '>=18'}
- peerDependencies:
- zod: ^3.0.0
+ zod: ^3.25.76 || ^4.1.8
- '@ai-sdk/[email protected]':
- resolution: {integrity: sha512-JBF3tUOLYgQDCwkvN9I5ZbSqsAxTJWOKmIpyJXJl5RpLXOEviJUqpKSZufs11J9S4Z0U9vZX9jfhO1+DBjS56w==}
+ '@ai-sdk/[email protected]':
+ resolution: {integrity: sha512-8p8P5joI2yylD1QtJKssmu6Rw3hWeEDbUBSk76DrvXKTdGspU0bm+F9mGlKXOJV+Bd8d+2mFSrCEX1ryeHEzLw==}
engines: {node: '>=18'}
peerDependencies:
- zod: ^3.0.0
+ zod: ^3.25.76 || ^4.1.8
- '@ai-sdk/[email protected]':
- resolution: {integrity: sha512-tNXJfEyyXHBD4hMoYjZW/IrsZNcTlmZkQFx3hFRwhiz35rT9TC9QG/RuKCz+UtziQU765g7NP4G/t7f0cJ154Q==}
+ '@ai-sdk/[email protected]':
+ resolution: {integrity: sha512-tHPwOiJ9WIJQ4JQwAL33LwjC2MID5FfC5CAGep2a4/CNS9A/IyUy0SRs1wikeAejJyQmSsHzzdA+y+KobNftuQ==}
engines: {node: '>=18'}
peerDependencies:
- zod: ^3.0.0
+ zod: ^3.25.76 || ^4.1.8
- '@ai-sdk/[email protected]':
- resolution: {integrity: sha512-XTl0dQ1rvLjhrkifSy/483qw3O7vCI6H2b4aAJnzQMfy0vzczMXmvQFS5RA8KmnO+YvsKTuZwBM2xRCNvKw1oQ==}
+ '@ai-sdk/[email protected]':
+ resolution: {integrity: sha512-/AI5AKi4vOK9SEb8Z1dfXkhsJ5NAfWsoJQc96B/mzn2KIrjw5occOjIwD06scuhV9xWlghCoXJT1sQD9QH/tyg==}
engines: {node: '>=18'}
peerDependencies:
- zod: ^3.0.0
+ zod: ^3.25.76 || ^4.1.8
- '@ai-sdk/[email protected]':
- resolution: {integrity: sha512-gjGcxKcRri/Jbkujs9nVwP4qOW5GI4rYQ6vQ17uLAvGMo3qnwr26Q2KUqUWuVHQYtboXVSrxC/Kb6sm3hE5WUQ==}
+ '@ai-sdk/[email protected]':
+ resolution: {integrity: sha512-G5drurtbYLdauF5ChNe5EnMnThrlM5qJoaW6RaBuuZbq1qR/kgaDZJ4A9ojx8RclHQ/t5hD6e9A+j447udskhw==}
engines: {node: '>=18'}
peerDependencies:
- zod: ^3.0.0
+ zod: ^3.25.76 || ^4.1.8
- '@ai-sdk/[email protected]':
- resolution: {integrity: sha512-zsgwko7T+MFIdEfhg4fIXv6O2dnzTLFr6BOpAA21eo/moOBA5szVzOto1jTwIwoBYsF2ixPGNZBoc+k/fQ2AWw==}
+ '@ai-sdk/[email protected]':
+ resolution: {integrity: sha512-c5dck36FjqiVoeeMJQLTEmUheoURcGTU/nBT6iJu8/nZiKFT/y8pD85KMDRB7RerRYaaQOtslR2d6/5PditiRw==}
engines: {node: '>=18'}
peerDependencies:
- zod: ^3.0.0
+ zod: ^3.25.76 || ^4.1.8
- '@ai-sdk/[email protected]':
- resolution: {integrity: sha512-e9Vn6sE6u+pm97YSK9+xiTgQ2ScRdipE5gAwXj/9HdgMnUyp3mDpWjFsmDM6bzyeb2iKOGv6f3eiRsLxOAPv4A==}
+ '@ai-sdk/[email protected]':
+ resolution: {integrity: sha512-5kadf9Mjd4Ep6jVhrIy56UL7DV5HDisW8UakwB11IN7lSLi8Qwb1fB9uO34GT7JxYqE4w7qZXVuelOmTH9m2Mg==}
engines: {node: '>=18'}
peerDependencies:
- zod: ^3.0.0
+ zod: ^3.25.76 || ^4.1.8
- '@ai-sdk/[email protected]':
- resolution: {integrity: sha512-hLQnBn5e69rUXvXW+9SOkiL+S4yQX62hjtlX3zKXBI/3VnfOTcGKMamK51GoQB7uQCN1h7l9orvWqWpuQXxzRg==}
+ '@ai-sdk/[email protected]':
+ resolution: {integrity: sha512-yKubDxLYtXyGUzkr9lNStf/lE/I+Okc8tmotvyABhsQHHieLKk6oV5fJeRJxhr67Ejhg+FRnwUOxAmjRoFM4dA==}
engines: {node: '>=18'}
peerDependencies:
- zod: ^3.0.0
+ zod: ^3.25.76 || ^4.1.8
- '@ai-sdk/[email protected]':
- resolution: {integrity: sha512-ueAP69p8a/ZR2ns+pmlr9h/nyV2/DAwzfnPUGZiLpXbxWnLXd2g3a7l38CuEhBydH/nOfDb/byMgpS8+bnJHTg==}
+ '@ai-sdk/[email protected]':
+ resolution: {integrity: sha512-+1mqxn42uB32DPZ6kurSyGAmL3MgCaDpkYU7zNDWI4NLy3Zg97RxTsI1jBCGIqkEVvRZKJlIMYtb89OvMnq3AQ==}
engines: {node: '>=18'}
peerDependencies:
- zod: ^3.0.0
+ zod: ^3.25.76 || ^4.1.8
'@ai-sdk/[email protected]':
resolution: {integrity: sha512-4GZ8GHjOFxePFzkl3q42AU0DQOtTQ5w09vmaWUf/pKFXJPizlnzKSUkF0f+VkapIUfDugyMqPMT1ge8XQzVI7Q==}
@@ -429,29 +423,17 @@ packages:
zod:
optional: true
- '@ai-sdk/[email protected]':
- resolution: {integrity: sha512-BuExLp+NcpwsAVj1F4bgJuQkSqO/+roV9wM7RdIO+NVrcT8RBUTdXzf5arHt5T58VpK7bZyB2V9qigjaPHE+Dg==}
- engines: {node: '>=18'}
- peerDependencies:
- zod: ^3.23.8
-
- '@ai-sdk/[email protected]':
- resolution: {integrity: sha512-o3fWTzkxzI5Af7U7y794MZkYNEsxbjLam2nxyoUZSScqkacb7vZ3EYHLh21+xCcSSzEC161C7pZAGHtC0hTUMw==}
- engines: {node: '>=18'}
- peerDependencies:
- zod: ^3.23.8
-
- '@ai-sdk/[email protected]':
- resolution: {integrity: sha512-sUlZ7Gnq84DCGWMQRIK8XVbkzIBnvPR1diV4v6JwPgpn5armnLI/j+rqn62MpLrU5ZCQZlDKl/Lw6ed3ulYqaA==}
+ '@ai-sdk/[email protected]':
+ resolution: {integrity: sha512-lsWQY9aDXHitw7C1QRYIbVGmgwyT98TF3MfM8alNIXKpdJdi+W782Rzd9f1RyOfgRmZ08gJ2EYNDhWNK7RqpEA==}
engines: {node: '>=18'}
peerDependencies:
- zod: ^3.23.8
+ zod: ^3.25.76 || ^4.1.8
- '@ai-sdk/[email protected]':
- resolution: {integrity: sha512-kM0xS3GWg3aMChh9zfeM+80vEZfXzR3JEUBdycZLtbRZ2TRT8xOj3WodGHPb06sUK5yD7pAXC/P7ctsi2fvUGQ==}
+ '@ai-sdk/[email protected]':
+ resolution: {integrity: sha512-ypv1xXMsgGcNKUP+hglKqtdDuMg68nWHucPPAhIENrbFAI+xCHiqPVN8Zllxyv1TNZwGWUghPxJXU+Mqps0YRQ==}
engines: {node: '>=18'}
peerDependencies:
- zod: ^3.23.8
+ zod: ^3.25.76 || ^4.1.8
'@ai-sdk/[email protected]':
resolution: {integrity: sha512-f9jSYwKMdXvm44Dmab1vUBnfCDSFfI5rOtvV1W9oKB7WYHR5dGvCC6x68Mk3NUfrdmNoMVHGoh6JT9HCVMlMow==}
@@ -461,34 +443,10 @@ packages:
resolution: {integrity: sha512-jie6ZJT2ZR0uVOVCDc9R2xCX5I/Dum/wEK28lx21PJx6ZnFAN9EzD2WsPhcDWfCgGx3OAZZ0GyM3CEobXpa9LA==}
engines: {node: '>=18'}
- '@ai-sdk/[email protected]':
- resolution: {integrity: sha512-0M+qjp+clUD0R1E5eWQFhxEvWLNaOtGQRUaBn8CUABnSKredagq92hUS9VjOzGsTm37xLfpaxl97AVtbeOsHew==}
+ '@ai-sdk/[email protected]':
+ resolution: {integrity: sha512-6o7Y2SeO9vFKB8lArHXehNuusnpddKPk7xqL7T2/b+OvXMRIXUO1rR4wcv1hAFUAT9avGZshty3Wlua/XA7TvA==}
engines: {node: '>=18'}
- '@ai-sdk/[email protected]':
- resolution: {integrity: sha512-ITdgNilJZwLKR7X5TnUr1BsQW6UTX5yFp0h66Nfx8XjBYkWD9W3yugr50GOz3CnE9m/U/Cd5OyEbTMI0rgi6ZQ==}
- engines: {node: '>=18'}
-
- '@ai-sdk/[email protected]':
- resolution: {integrity: sha512-qZMxYJ0qqX/RfnuIaab+zp8UAeJn/ygXXAffR5I4N0n1IrvA6qBsjc8hXLmBiMV2zoXlifkacF7sEFnYnjBcqg==}
- engines: {node: '>=18'}
-
- '@ai-sdk/[email protected]':
- resolution: {integrity: sha512-S2FzCSi4uTF0JuSN6zYMXyiAWVAzi/Hho8ISYgHpGZiICYLNCP2si4DuXQOsnWef3IXzQPLVoE11C63lILZIkw==}
- engines: {node: '>=18'}
- peerDependencies:
- react: ^18 || ^19 || ^19.0.0-rc
- zod: ^3.23.8
- peerDependenciesMeta:
- zod:
- optional: true
-
- '@ai-sdk/[email protected]':
- resolution: {integrity: sha512-OVRxa4SDj0wVsMZ8tGr/whT89oqNtNoXBKmqWC2BRv5ZG6azL2LYZ5ZK35u3lb4l1IE7cWGsLlmq0py0ttsL7A==}
- engines: {node: '>=18'}
- peerDependencies:
- zod: ^3.23.8
-
'@apidevtools/[email protected]':
resolution: {integrity: sha512-54vnqDyGsDAVM0LOIdGMnfVyCN1NlqoGnHEGpMfaDBLMvClfT4j2XbJgvfuF0Ca0kxT6Gb7xUgS5W1I14QqjiQ==}
engines: {node: '>=20'}
@@ -3109,6 +3067,9 @@ packages:
'@solana/[email protected]':
resolution: {integrity: sha512-vv9lfnvjUsRiq//+j5pBdXig0IQdtzA0BRZ3bXEP4KaIyF1CcaydWqgyzQgfZMNIsWNWmG+AUHwPy4AHOD6gpw==}
+ '@standard-schema/[email protected]':
+ resolution: {integrity: sha512-m2bOd0f2RT9k8QJx1JN85cZYyH1RqFBdlwtkSlf4tBDYLCiiZnv1fIIwacK6cqwXavOydf0NPToMQgpKq+dVlA==}
+
'@supabase/[email protected]':
resolution: {integrity: sha512-mMIQHBRc+SKpZFRB2qtupuzulaUhFYupNyxqDj5Jp/LyPvcWvjaJzZzObv6URtL/O6lPxkanASnotGtNpS3H2Q==}
@@ -3210,9 +3171,6 @@ packages:
resolution: {integrity: sha512-vIChWdVG3LG1SMxEvI/AK+FWJthlrqlTu7fbrlywTkkaONwk/UAGaULXRlf8vkzFBLVm0zkMdCquhL5aOjhXPQ==}
- '@types/[email protected]':
- resolution: {integrity: sha512-xFdR6tkm0MWvBfO8xXCSsinYxHcqkQUlcHeSpMC2ukzOb6lwQAfDmW+Qt0AvlGd8HpsS28qKsB+oPeJn9I39jg==}
-
resolution: {integrity: sha512-qZ72SFTgUAZ5a7Tj6kf2SHLetiH5S6f8G5frB2SPQ3EyF02kxdyBFf4Tz4banE3xCgGnKgWLt//a6VuYHKYJTg==}
@@ -3451,6 +3409,10 @@ packages:
cpu: [x64]
os: [win32]
+ '@vercel/[email protected]':
+ resolution: {integrity: sha512-yNEQvPcVrK9sIe637+I0jD6leluPxzwJKx/Haw6F4H77CdDsszUn5V3o96LPziXkSNE2B83+Z3mjqGKBK/R6Gg==}
+ engines: {node: '>= 20'}
+
resolution: {integrity: sha512-OkiElOI8xXGPDZE5UdG6NgDT3laSkEh9llX1DDapUnfnKecK3Tr/HUf5YzgwDhEoox8mdxp+8ZCjtnTKz56SdA==}
peerDependencies:
@@ -3642,15 +3604,11 @@ packages:
resolution: {integrity: sha512-5GG/5IbQQpC9FpkRGsSvZI5QYeSCzlJHdpBQntCsuTOxhKD8lqKhrleg2Yi7yvMIf82Ycmmqln9U8V9qwEiJew==}
engines: {node: '>= 8.0.0'}
- resolution: {integrity: sha512-hxJ+6YCdGOK1MVPGITmz1if+LXR/aW72w8TI8kiV+3R7lpK1hfpApR8EjqN2ag6cWa0R7OEI3gb/srWkQ3hT2Q==}
+ resolution: {integrity: sha512-8Nq+ZojGacQrupoJEQLrTDzT5VtR3gyp5AaqFSV3tzsAXlYQ9Igb7QE3yeoEdzOk5IRfDwWL7mDCUD+oBg1hDA==}
engines: {node: '>=18'}
peerDependencies:
- react: ^18 || ^19 || ^19.0.0-rc
- zod: ^3.23.8
- peerDependenciesMeta:
- react:
- optional: true
+ zod: ^3.25.76 || ^4.1.8
resolution: {integrity: sha512-F0twR8U1ZU67JIEtekUcLkXkoO5mMMmgGD8sK/xUFzJ805jxHQl92hImFAqqXMyMYjSPOyUPAwHYhB72g5sTXw==}
@@ -4132,6 +4090,10 @@ packages:
resolution: {integrity: sha512-1+BhOB8ahCn4O0cep0Sh2l9KCOfOdY+BXJnKMHFFzDEouSr/el18QwXEMRlOj9UY5nCeA8UN3a/82rUWRBeyBw==}
engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}
+ resolution: {integrity: sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==}
+ engines: {node: '>= 12'}
+
resolution: {integrity: sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg==}
engines: {node: '>=18'}
@@ -4198,10 +4160,6 @@ packages:
resolution: {integrity: sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==}
engines: {node: '>= 0.8'}
- resolution: {integrity: sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==}
- engines: {node: '>=6'}
-
resolution: {integrity: sha512-OCg2UsLbXK7GmmpzMXhYkdO64vhJ1ROUUGaTFyHjVwEdMEcTTRj7W1TxLbSBxdY8QLBPCcp66MTyaSy0RpO17A==}
peerDependencies:
@@ -4228,9 +4186,6 @@ packages:
resolution: {integrity: sha512-rXSP0bf+5n0Qonsb+SVVfNfIsimO4HEtmnIpPHY8Q1UCzKlQrDMfdobr8nJOOsRgWCyMRqeSBQzmWUMq7zvVig==}
- resolution: {integrity: sha512-IayShXAgj/QMXgB0IWmKx+rOPuGMhqm5w6jvFxmVenXKIzRqTAAsbBPT3kWQeGANj3jGgvcvv4yK6SxqYmikgw==}
-
resolution: {integrity: sha512-A46qtFgd+g7pDZinpnwiRJtxbC1hpgf0uzP3iG89scHk0AUC7A1TGxf5OiiOUv/JMZR8GOt8hL900hV0bOy5xA==}
engines: {node: '>=0.3.1'}
@@ -4453,6 +4408,10 @@ packages:
resolution: {integrity: sha512-T1C0XCUimhxVQzW4zFipdx0SficT651NnkR0ZSH3yQwh+mFMdLfgjABVi4YtMTtaL4s168593DaoaRLMqryavA==}
engines: {node: '>=18.0.0'}
+ resolution: {integrity: sha512-Vo1ab+QXPzZ4tCa8SwIHJFaSzy4R6SHf7BY79rFBDf0idraZWAkYrDjDj8uWaSm3S2TK+hJ7/t1CEmZ7jXw+pg==}
+ engines: {node: '>=18.0.0'}
+
resolution: {integrity: sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==}
engines: {node: '>=10'}
@@ -4534,6 +4493,10 @@ packages:
resolution: {integrity: sha512-OP2IUU6HeYKJi3i0z4A19kHMQoLVs4Hc+DPqqxI2h/DPZHTm/vjsfC6P0b4jCMy14XizLBqvndQ+UilD7707Jw==}
+ resolution: {integrity: sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==}
+ engines: {node: ^12.20 || >= 14.13}
+
resolution: {integrity: sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==}
@@ -4589,6 +4552,10 @@ packages:
engines: {node: '>=18.3.0'}
hasBin: true
+ resolution: {integrity: sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==}
+ engines: {node: '>=12.20.0'}
+
resolution: {integrity: sha512-Oz5Hwvwak/DCaXVVUtPn4oLMLLy1CdclLKO1LFgU7XzDpVMUU5UjlSLpGMocyQNNk8F6IJW9M/YdooSn2MRI+Q==}
@@ -4621,10 +4588,18 @@ packages:
resolution: {integrity: sha512-LDODD4TMYx7XXdpwxAVRAIAuB0bzv0s+ywFonY46k126qzQHT9ygyoa9tncmOiQmmDrik65UYsEkv3lbfqQ3yQ==}
engines: {node: '>=14'}
+ resolution: {integrity: sha512-YGGyuEdVIjqxkxVH1pUTMY/XtmmsApXrCVv5EU25iX6inEPbV+VakJfLealkBtJN69AQmh1eGOdCl9Sm1UP6XQ==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-a4tiq7E0/5fTjxPAaH4jpjkSv/uCaU2p5KC6HVGrvl0cDjA8iBZv4vv1gyzlmK0ZUKqwpOyQMKzZQe3lTit77A==}
engines: {node: '>=14'}
+ resolution: {integrity: sha512-zV/5HKTfCeKWnxG0Dmrw51hEWFGfcF2xiXqcA3+J90WDuP0SvoiSO5ORvcBsifmx/FoIjgQN3oNOGaQ5PhLFkg==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==}
engines: {node: '>=6.9.0'}
@@ -4681,6 +4656,10 @@ packages:
resolution: {integrity: sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==}
deprecated: Glob versions prior to v9 are no longer supported
+ resolution: {integrity: sha512-7ABviyMOlX5hIVD60YOfHw4/CxOfBhyduaYB+wbFWCWoni4N7SLcV46hrVRktuBbZjFC9ONyqamZITN7q3n32w==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-Jb6Z0+nvECVz+2lzSMt9u98UsoakXxA2HGHMCxh+so3n90XgYWkq5dur19JAJV7ONiJY22yBTyJB1TSkvPq9Ng==}
engines: {node: '>=14'}
@@ -4689,6 +4668,10 @@ packages:
resolution: {integrity: sha512-NEgUnEcBiP5HrPzufUkBzJOD/Sxsco3rLNo1F1TNf7ieU8ryUzBhqba8r756CjLX7rn3fHl6iLEwPYuqpoKgQQ==}
engines: {node: '>=14'}
+ resolution: {integrity: sha512-eAmLkjDjAFCVXg7A1unxHsLf961m6y17QFqXqAXGj/gVkKFrEICfStRfwUlGNfeCEjNRa32JEWOUTlYXPyyKvA==}
+ engines: {node: '>=14'}
+
resolution: {integrity: sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==}
@@ -4703,6 +4686,10 @@ packages:
resolution: {integrity: sha512-pCcEwRi+TKpMlxAQObHDQ56KawURgyAf6jtIY046fJ5tIv3zDe/LEIubckAO8fj6JnAxLdmWkUfNyulQ2iKdEw==}
engines: {node: '>=14.0.0'}
+ resolution: {integrity: sha512-+CqsMbHPiSTdtSO14O51eMNlrp9N79gmeqmXeouJOhfucAedHw9noVe/n5uJk3tbKE6a+6ZCQg3RPhVhHByAIw==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-z5cFQWDffyOe4vQ9xIqNfCZdV4p//vy6fBnr8Q1AWnVZ0teurKMG66rLj++TKwKPUP3u7iMUvrvKaEUiQw2QWQ==}
@@ -5213,11 +5200,6 @@ packages:
engines: {node: '>=6'}
hasBin: true
- resolution: {integrity: sha512-3QItJOXp2AP1uv7waBkao5nCvhEv+QmJAd38Ybq7wNI74Q+BBmnLn4EDKz6yI9xGAIQoUF87qHt+kc1IVxB4zQ==}
- engines: {node: ^18.0.0 || >=20.0.0}
- hasBin: true
-
resolution: {integrity: sha512-jrZ2Qx916EA+fq9cEAeCROWPTfCwi1IVHqT2tapuqLEVVDKFDENFw1oL+MwrTvH6msKxsd1YTDVw6uKEcsrLEA==}
@@ -5527,6 +5509,11 @@ packages:
resolution: {integrity: sha512-qN8v/s2PAJwGUtr1/hYTpNKlD6Y9rc4p8KSmJXyGdYGZsDGKXrGThikLFP9OCHFeLeEpQzPwiAtdIvBLqm//Hw==}
+ resolution: {integrity: sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==}
+ engines: {node: '>=10.5.0'}
+ deprecated: Use your platform's native DOMException instead
+
resolution: {integrity: sha512-DRI60hzo2oKN1ma0ckc6nQWlHU69RH6xN0sjQTjMpChPfTYvKZdcQFfdYK2RWbJcKyUizSIy/l8OTGxMAM1QDw==}
@@ -5542,6 +5529,10 @@ packages:
encoding:
optional: true
+ resolution: {integrity: sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==}
+ engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}
+
resolution: {integrity: sha512-s+w+rBWnpTMwSFbaE0UXsRlg7hU4FjekKU4eyAih5T8nJuNZT1nNsskXpxmeqSK9UzkBl6UgRlnKc8hz8IEqOw==}
hasBin: true
@@ -6141,6 +6132,10 @@ packages:
resolution: {integrity: sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==}
+ resolution: {integrity: sha512-l0OE8wL34P4nJH/H2ffoaniAokM2qSmrtXHmlpvYr5AVVX8msAyW0l8NVJFDxlSK4u3Uh/f41cQheDVdnYijwQ==}
+ hasBin: true
+
resolution: {integrity: sha512-s+pyvQeIKIZ0dx5iJiQk1tPLJAWln39+MI5jtM8wnyws+G5azk+dMnMX0qfbqNetKKNgcWWOdi0sfm+FbQbgdQ==}
engines: {node: '>=10.0.0'}
@@ -6453,11 +6448,6 @@ packages:
resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==}
engines: {node: '>= 0.4'}
- resolution: {integrity: sha512-dshNvs3ExOqtZ6kJBaAsabhPdHyeY4P2cKwRCniDVifBMoG/SVI7tfLWqPXriVspf2Rg4tPzXJTnwaihIeFw2A==}
- peerDependencies:
- react: ^16.11.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
-
resolution: {integrity: sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==}
@@ -6491,10 +6481,6 @@ packages:
resolution: {integrity: sha512-UkEhKIg2pD+fjkHQKyJO3yoIvAP3N6RlNFt2dUhcS1FGvCD1cQa1M/PGknCLFIyZdtJOWQjejp7bdNqmN7zwdA==}
- resolution: {integrity: sha512-nt6AMGKW1p/70DF/hGBdJB57B8Tspmbp5gfJ8ilhLnt7kkr2ye7hzD6NVG8GGErk2HWF34igrL2CXmNIkzKqKw==}
- engines: {node: '>=18'}
-
resolution: {integrity: sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg==}
@@ -6756,11 +6742,6 @@ packages:
peerDependencies:
react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
- resolution: {integrity: sha512-Rb46I4cGGVBmjamjphe8L/UnvJD+uPPtTkNvX5mZgqdbavhI4EbgIWJiIHXJ8bc/i9EQGPRh4DwEURJ552Do0A==}
- peerDependencies:
- react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
-
resolution: {integrity: sha512-Z6czzLq4u8fPOyx7TU6X3dvUZVvoJmxSQ+IcrlmagKhilxlhZgxPK6C5Jqbkw1IDUmFTM+cz9QDnnLTwDz/2gQ==}
engines: {node: '>=6.14.2'}
@@ -6848,6 +6829,10 @@ packages:
resolution: {integrity: sha512-ts/8E8l5b7kY0vlWLewOkDXMmPdLcVV4GmOQLyxuSswIJsweeFZtAsMF7k1Nszz+TYBQrlYRmzOnr398y1JemQ==}
+ resolution: {integrity: sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==}
+ engines: {node: '>= 8'}
+
resolution: {integrity: sha512-c5s35LgVa5tFaHhrZDnr3FpQpjj1BB+RXhLTYUxGqBVN460HkbM8TBtEqdXWbpTKfzwCcjAZVF7zXCYSKtcp9g==}
@@ -7062,22 +7047,14 @@ packages:
resolution: {integrity: sha512-U/PBtDf35ff0D8X8D0jfdzHYEPFxAI7jJlxZXwCSez5M3190m+QobIfh+sWDWSHMCWWJN2AWamkegn6vr6YBTw==}
engines: {node: '>=18'}
- resolution: {integrity: sha512-/AuWwMP+YqiPbsJx5D6TfgRTc4kTLjsh5SOcd4bLsfUg2RcEXrFMJl1DGgdHy2aCfsIA/cr/1JM0xcB2GZji8g==}
- peerDependencies:
- zod: ^3.24.1
-
resolution: {integrity: sha512-iC+8Io04lddc+mVqQ9AZ7OQ2MrUKGN+oIQyq1vemgt46jwCwLfhq7/pwnBnNXXXZb8VTVLKwp9EDkx+ryxIWmg==}
- resolution: {integrity: sha512-lY7CDW43ECgW9u1TcT3IoXHflywfVqDYze4waEz812jR/bZ8FHDsl7pFQoSZTz5N+2NqRXs8GBwnAwo3ZNxqhQ==}
-
resolution: {integrity: sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==}
- resolution: {integrity: sha512-WPsqwxITS2tzx1bzhIKsEs19ABD5vmCVa4xBo2tq/SrV4RNZtfws1EnCWQXM6yh8bD08a1idvkB5MZSBiZsjwg==}
+ resolution: {integrity: sha512-JInaHOamG8pt5+Ey8kGmdcAcg3OL9reK8ltczgHTAwNhMys/6ThXHityHxVV2p3fkw/c+MAvBHFVYHFZDmjMCQ==}
resolution: {integrity: sha512-LE+VcmbartOPM+auOjCCLQOsQ05zUTp8RkgwRzefUk+2jISdMMFnxvyTjA4YNWr5ZGXYbVsEMZosttuxUBkojQ==}
@@ -7137,119 +7114,99 @@ snapshots:
'@adraffy/[email protected]': {}
dependencies:
- '@ai-sdk/provider': 1.1.3
- '@ai-sdk/provider-utils': 2.2.7([email protected])
- zod: 3.24.2
+ '@ai-sdk/provider': 2.0.0
+ '@ai-sdk/provider-utils': 3.0.18([email protected])
+ zod: 4.1.12
dependencies:
- '@ai-sdk/provider': 1.1.0
- '@ai-sdk/provider-utils': 2.2.3([email protected])
- zod: 3.24.2
+ '@ai-sdk/openai-compatible': 1.0.28([email protected])
+ '@ai-sdk/provider': 2.0.0
+ '@ai-sdk/provider-utils': 3.0.18([email protected])
+ zod: 4.1.12
dependencies:
- '@ai-sdk/openai-compatible': 0.2.4([email protected])
- '@ai-sdk/provider': 1.1.0
- '@ai-sdk/provider-utils': 2.2.3([email protected])
- zod: 3.24.2
+ '@ai-sdk/openai-compatible': 1.0.28([email protected])
+ '@ai-sdk/provider': 2.0.0
+ '@ai-sdk/provider-utils': 3.0.18([email protected])
+ zod: 4.1.12
dependencies:
- '@ai-sdk/openai-compatible': 0.2.4([email protected])
- '@ai-sdk/provider': 1.1.0
- '@ai-sdk/provider-utils': 2.2.3([email protected])
- zod: 3.24.2
+ '@ai-sdk/provider': 2.0.0
+ '@ai-sdk/provider-utils': 3.0.16([email protected])
+ '@vercel/oidc': 3.0.3
+ zod: 4.1.12
dependencies:
- '@ai-sdk/anthropic': 1.2.10([email protected])
- '@ai-sdk/google': 1.2.11([email protected])
- '@ai-sdk/provider': 1.1.3
- '@ai-sdk/provider-utils': 2.2.7([email protected])
- google-auth-library: 9.15.1([email protected])
- zod: 3.24.2
+ '@ai-sdk/anthropic': 2.0.50([email protected])
+ '@ai-sdk/google': 2.0.44([email protected])
+ '@ai-sdk/provider': 2.0.0
+ '@ai-sdk/provider-utils': 3.0.18([email protected])
+ google-auth-library: 10.5.0
+ zod: 4.1.12
transitivePeerDependencies:
- - encoding
- supports-color
- dependencies:
- '@ai-sdk/provider': 1.1.3
- '@ai-sdk/provider-utils': 2.2.7([email protected])
- zod: 3.24.2
-
dependencies:
- '@ai-sdk/provider': 1.1.0
- '@ai-sdk/provider-utils': 2.2.1([email protected])
- zod: 3.24.2
+ '@ai-sdk/provider': 2.0.0
+ '@ai-sdk/provider-utils': 3.0.18([email protected])
+ zod: 4.1.12
dependencies:
- '@ai-sdk/provider': 1.1.0
- '@ai-sdk/provider-utils': 2.2.1([email protected])
- zod: 3.24.2
+ '@ai-sdk/provider': 2.0.0
+ '@ai-sdk/provider-utils': 3.0.18([email protected])
+ zod: 4.1.12
dependencies:
- '@ai-sdk/provider': 1.1.0
- '@ai-sdk/provider-utils': 2.2.3([email protected])
- zod: 3.24.2
+ '@ai-sdk/provider': 2.0.0
+ '@ai-sdk/provider-utils': 3.0.18([email protected])
+ zod: 4.1.12
dependencies:
- '@ai-sdk/provider': 1.1.3
- '@ai-sdk/provider-utils': 2.2.7([email protected])
- zod: 3.24.2
+ '@ai-sdk/provider': 2.0.0
+ '@ai-sdk/provider-utils': 3.0.16([email protected])
+ zod: 4.1.12
dependencies:
'@ai-sdk/provider': 1.0.9
eventsource-parser: 3.0.0
nanoid: 3.3.8
secure-json-parse: 2.7.0
optionalDependencies:
- zod: 3.24.2
+ zod: 4.1.12
dependencies:
'@ai-sdk/provider': 1.0.8
eventsource-parser: 3.0.0
nanoid: 3.3.8
secure-json-parse: 2.7.0
optionalDependencies:
- zod: 3.24.2
+ zod: 4.1.12
dependencies:
- '@ai-sdk/provider': 1.1.0
- nanoid: 3.3.8
- secure-json-parse: 2.7.0
- zod: 3.24.2
+ '@ai-sdk/provider': 2.0.0
+ '@standard-schema/spec': 1.0.0
+ eventsource-parser: 3.0.6
+ zod: 4.1.12
dependencies:
- '@ai-sdk/provider': 1.1.0
- nanoid: 3.3.8
- secure-json-parse: 2.7.0
- zod: 3.24.2
-
- dependencies:
- '@ai-sdk/provider': 1.1.2
- nanoid: 3.3.8
- secure-json-parse: 2.7.0
- zod: 3.24.2
-
- dependencies:
- '@ai-sdk/provider': 1.1.3
- nanoid: 3.3.8
- secure-json-parse: 2.7.0
- zod: 3.24.2
+ '@ai-sdk/provider': 2.0.0
+ '@standard-schema/spec': 1.0.0
+ eventsource-parser: 3.0.6
+ zod: 4.1.12
'@ai-sdk/[email protected]':
dependencies:
@@ -7259,35 +7216,10 @@ snapshots:
dependencies:
json-schema: 0.4.0
- '@ai-sdk/[email protected]':
- dependencies:
- json-schema: 0.4.0
-
- '@ai-sdk/[email protected]':
- dependencies:
- json-schema: 0.4.0
-
- '@ai-sdk/[email protected]':
+ '@ai-sdk/[email protected]':
dependencies:
json-schema: 0.4.0
- dependencies:
- '@ai-sdk/provider-utils': 2.2.6([email protected])
- '@ai-sdk/ui-utils': 1.2.7([email protected])
- react: 18.3.1
- swr: 2.3.3([email protected])
- throttleit: 2.1.0
- optionalDependencies:
- zod: 3.24.2
-
- dependencies:
- '@ai-sdk/provider': 1.1.2
- '@ai-sdk/provider-utils': 2.2.6([email protected])
- zod: 3.24.2
- zod-to-json-schema: 3.24.5([email protected])
-
'@apidevtools/[email protected](@types/[email protected])':
dependencies:
'@types/json-schema': 7.0.15
@@ -7510,7 +7442,7 @@ snapshots:
idb-keyval: 6.2.1
preact: 10.24.2
transitivePeerDependencies:
- '@types/react'
@@ -7584,7 +7516,7 @@ snapshots:
idb-keyval: 6.2.1
preact: 10.24.2
transitivePeerDependencies:
- '@types/react'
@@ -7791,7 +7723,7 @@ snapshots:
dependencies:
'@metamask/rpc-errors': 7.0.2
eventemitter3: 5.0.1
transitivePeerDependencies:
- supports-color
@@ -8763,11 +8695,11 @@ snapshots:
'@one-ini/[email protected]': {}
dependencies:
'@ai-sdk/provider': 1.0.9
- '@ai-sdk/provider-utils': 2.1.10([email protected])
- zod: 3.24.2
+ '@ai-sdk/provider-utils': 2.1.10([email protected])
+ zod: 4.1.12
'@opentelemetry/[email protected]':
dependencies:
@@ -9814,7 +9746,7 @@ snapshots:
dependencies:
big.js: 6.2.2
dayjs: 1.11.13
transitivePeerDependencies:
- bufferutil
- typescript
@@ -9827,7 +9759,7 @@ snapshots:
'@reown/appkit-wallet': 1.7.8([email protected])([email protected])([email protected])
valtio: 1.13.2([email protected])
transitivePeerDependencies:
- '@azure/app-configuration'
- '@azure/cosmos'
@@ -9973,7 +9905,7 @@ snapshots:
'@walletconnect/logger': 2.1.2
valtio: 1.13.2([email protected])
transitivePeerDependencies:
- '@azure/app-configuration'
- '@azure/cosmos'
@@ -10026,7 +9958,7 @@ snapshots:
bs58: 6.0.0
valtio: 1.13.2([email protected])
transitivePeerDependencies:
- '@azure/app-configuration'
- '@azure/cosmos'
@@ -10067,7 +9999,7 @@ snapshots:
dependencies:
'@safe-global/safe-gateway-typescript-sdk': 3.23.1
transitivePeerDependencies:
- bufferutil
- typescript
@@ -10743,6 +10675,8 @@ snapshots:
- typescript
- utf-8-validate
+ '@standard-schema/[email protected]': {}
+
'@supabase/[email protected]':
dependencies:
'@supabase/node-fetch': 2.6.15
@@ -10873,8 +10807,6 @@ snapshots:
dependencies:
'@types/ms': 2.1.0
- '@types/[email protected]': {}
-
'@types/[email protected]': {}
@@ -11095,6 +11027,8 @@ snapshots:
optional: true
+ '@vercel/[email protected]': {}
+
dependencies:
@@ -11107,7 +11041,7 @@ snapshots:
cbw-sdk: '@coinbase/[email protected]'
optionalDependencies:
typescript: 5.8.3
transitivePeerDependencies:
@@ -11145,7 +11079,7 @@ snapshots:
dependencies:
eventemitter3: 5.0.1
mipd: 0.0.7([email protected])
optionalDependencies:
'@tanstack/query-core': 5.83.1
@@ -11693,35 +11627,30 @@ snapshots:
typescript: 5.8.3
zod: 3.22.4
- optionalDependencies:
- typescript: 5.8.3
- zod: 3.24.2
-
optionalDependencies:
typescript: 5.8.3
zod: 3.25.76
optionalDependencies:
typescript: 5.8.3
- zod: 3.22.4
+ zod: 4.1.12
optionalDependencies:
typescript: 5.8.3
- zod: 3.24.2
+ zod: 3.22.4
optionalDependencies:
typescript: 5.8.3
zod: 3.25.76
optionalDependencies:
typescript: 5.8.3
- zod: 4.1.11
+ zod: 4.1.12
dependencies:
@@ -11754,17 +11683,13 @@ snapshots:
dependencies:
humanize-ms: 1.2.1
dependencies:
- '@ai-sdk/provider': 1.1.2
- '@ai-sdk/provider-utils': 2.2.6([email protected])
- '@ai-sdk/react': 1.2.8([email protected])([email protected])
- '@ai-sdk/ui-utils': 1.2.7([email protected])
+ '@ai-sdk/gateway': 2.0.7([email protected])
+ '@ai-sdk/provider': 2.0.0
+ '@ai-sdk/provider-utils': 3.0.16([email protected])
'@opentelemetry/api': 1.9.0
- jsondiffpatch: 0.6.0
- zod: 3.24.2
- optionalDependencies:
- react: 18.3.1
+ zod: 4.1.12
dependencies:
@@ -12288,6 +12213,8 @@ snapshots:
+
dependencies:
whatwg-mimetype: 4.0.0
@@ -12329,8 +12256,6 @@ snapshots:
-
dependencies:
valtio: 1.13.2([email protected])
@@ -12350,8 +12275,6 @@ snapshots:
asap: 2.0.6
wrappy: 1.0.2
-
@@ -12594,6 +12517,8 @@ snapshots:
+
dependencies:
cross-spawn: 7.0.6
@@ -12716,6 +12641,11 @@ snapshots:
+ dependencies:
+ node-domexception: 1.0.0
+ web-streams-polyfill: 3.3.3
+
@@ -12779,6 +12709,10 @@ snapshots:
dependencies:
fd-package-json: 2.0.0
+ dependencies:
+ fetch-blob: 3.2.0
+
dependencies:
'@paralleldrive/cuid2': 2.2.2
@@ -12812,6 +12746,15 @@ snapshots:
- encoding
- supports-color
+ dependencies:
+ extend: 3.0.2
+ https-proxy-agent: 7.0.6
+ node-fetch: 3.3.2
+ rimraf: 5.0.10
+ transitivePeerDependencies:
+ - supports-color
+
dependencies:
gaxios: 6.7.1([email protected])
@@ -12821,6 +12764,14 @@ snapshots:
- encoding
- supports-color
+ dependencies:
+ gaxios: 7.1.3
+ google-logging-utils: 1.1.3
+ json-bigint: 1.0.0
+ transitivePeerDependencies:
+ - supports-color
+
@@ -12898,6 +12849,18 @@ snapshots:
once: 1.4.0
path-is-absolute: 1.0.1
+ dependencies:
+ base64-js: 1.5.1
+ ecdsa-sig-formatter: 1.0.11
+ gaxios: 7.1.3
+ gcp-metadata: 8.1.2
+ google-logging-utils: 1.1.3
+ gtoken: 8.0.0
+ jws: 4.0.0
+ transitivePeerDependencies:
+ - supports-color
+
dependencies:
base64-js: 1.5.1
@@ -12912,6 +12875,8 @@ snapshots:
+
dependencies:
get-intrinsic: 1.3.0
@@ -12928,6 +12893,13 @@ snapshots:
- encoding
- supports-color
+ dependencies:
+ gaxios: 7.1.3
+ jws: 4.0.0
+ transitivePeerDependencies:
+ - supports-color
+
dependencies:
cookie-es: 1.2.2
@@ -13703,12 +13675,6 @@ snapshots:
- dependencies:
- '@types/diff-match-patch': 1.0.36
- chalk: 5.6.0
- diff-match-patch: 1.0.5
-
dependencies:
buffer-equal-constant-time: 1.0.1
@@ -13743,7 +13709,7 @@ snapshots:
smol-toml: 1.5.2
strip-json-comments: 5.0.3
typescript: 5.8.3
- zod: 4.1.11
+ zod: 4.1.12
@@ -14001,6 +13967,8 @@ snapshots:
+
@@ -14011,6 +13979,12 @@ snapshots:
optionalDependencies:
encoding: 0.1.13
+ dependencies:
+ data-uri-to-buffer: 4.0.1
+ fetch-blob: 3.2.0
+ formdata-polyfill: 4.0.10
+
dependencies:
detect-libc: 2.1.2
@@ -14071,13 +14045,13 @@ snapshots:
node-fetch-native: 1.6.7
ufo: 1.6.1
dependencies:
'@ai-sdk/provider': 1.0.8
- '@ai-sdk/provider-utils': 2.1.9([email protected])
+ '@ai-sdk/provider-utils': 2.1.9([email protected])
partial-json: 0.1.7
optionalDependencies:
- zod: 3.24.2
+ zod: 4.1.12
@@ -14103,10 +14077,10 @@ snapshots:
dependencies:
mimic-function: 5.0.1
optionalDependencies:
- zod: 3.24.2
+ zod: 4.1.12
dependencies:
@@ -14157,7 +14131,7 @@ snapshots:
transitivePeerDependencies:
- zod
dependencies:
'@adraffy/ens-normalize': 1.11.1
'@noble/ciphers': 1.3.0
@@ -14165,14 +14139,14 @@ snapshots:
'@noble/hashes': 1.8.0
'@scure/bip32': 1.7.0
'@scure/bip39': 1.6.0
eventemitter3: 5.0.1
optionalDependencies:
typescript: 5.8.3
transitivePeerDependencies:
- zod
dependencies:
'@adraffy/ens-normalize': 1.11.1
'@noble/ciphers': 1.3.0
@@ -14180,14 +14154,14 @@ snapshots:
'@noble/hashes': 1.8.0
'@scure/bip32': 1.7.0
'@scure/bip39': 1.6.0
eventemitter3: 5.0.1
optionalDependencies:
typescript: 5.8.3
transitivePeerDependencies:
- zod
dependencies:
'@adraffy/ens-normalize': 1.11.1
'@noble/ciphers': 1.3.0
@@ -14195,7 +14169,7 @@ snapshots:
'@noble/hashes': 1.8.0
'@scure/bip32': 1.7.0
'@scure/bip39': 1.6.0
eventemitter3: 5.0.1
optionalDependencies:
typescript: 5.8.3
@@ -14403,15 +14377,15 @@ snapshots:
hono: 4.9.10
idb-keyval: 6.2.2
mipd: 0.0.7([email protected])
- zod: 4.1.11
+ zod: 4.1.12
optionalDependencies:
'@tanstack/react-query': 5.84.1([email protected])
react: 18.3.1
typescript: 5.8.3
transitivePeerDependencies:
- '@types/react'
- immer
@@ -14678,6 +14652,10 @@ snapshots:
+ dependencies:
+ glob: 10.4.2
+
@@ -15021,12 +14999,6 @@ snapshots:
- dependencies:
- dequal: 2.0.3
- react: 18.3.1
- use-sync-external-store: 1.5.0([email protected])
-
@@ -15064,8 +15036,6 @@ snapshots:
dependencies:
real-require: 0.1.0
-
@@ -15277,10 +15247,6 @@ snapshots:
dependencies:
react: 18.3.1
- dependencies:
- react: 18.3.1
-
dependencies:
node-gyp-build: 4.8.4
@@ -15355,15 +15321,15 @@ snapshots:
- utf-8-validate
- zod
dependencies:
'@noble/curves': 1.9.2
'@noble/hashes': 1.8.0
'@scure/bip32': 1.7.0
'@scure/bip39': 1.6.0
optionalDependencies:
typescript: 5.8.3
@@ -15372,15 +15338,15 @@ snapshots:
- utf-8-validate
- zod
dependencies:
'@noble/curves': 1.9.2
'@noble/hashes': 1.8.0
'@scure/bip32': 1.7.0
'@scure/bip39': 1.6.0
optionalDependencies:
typescript: 5.8.3
@@ -15393,14 +15359,14 @@ snapshots:
dependencies:
xml-name-validator: 5.0.0
dependencies:
'@tanstack/react-query': 5.84.1([email protected])
react: 18.3.1
use-sync-external-store: 1.4.0([email protected])
optionalDependencies:
typescript: 5.8.3
transitivePeerDependencies:
@@ -15437,6 +15403,8 @@ snapshots:
dependencies:
makeerror: 1.0.12
+
@@ -15607,8 +15575,8 @@ snapshots:
zod: 3.25.76
transitivePeerDependencies:
- '@azure/app-configuration'
@@ -15710,17 +15678,11 @@ snapshots:
- dependencies:
- zod: 3.24.2
-
-
optionalDependencies:
diff --git a/apps/api/src/__tests__/snips/v1/types-validation.test.ts b/apps/api/src/__tests__/snips/v1/types-validation.test.ts
new file mode 100644
index 000000000..11c62c39b
--- /dev/null
+++ b/apps/api/src/__tests__/snips/v1/types-validation.test.ts
@@ -0,0 +1,923 @@
+import { z } from "zod";
+import {
+ scrapeRequestSchema,
+ scrapeOptions,
+ extractRequestSchema,
+ crawlRequestSchema,
+ mapRequestSchema,
+ batchScrapeRequestSchema,
+ ScrapeRequest,
+ ScrapeRequestInput,
+ ExtractRequest,
+ ExtractRequestInput,
+ CrawlRequest,
+ CrawlRequestInput,
+ MapRequest,
+ MapRequestInput,
+ BatchScrapeRequest,
+ BatchScrapeRequestInput,
+} from "../../../controllers/v1/types";
+
+describe("V1 Types Validation", () => {
+ describe("scrapeRequestSchema", () => {
+ it("should accept valid minimal scrape request", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ expect(result.url).toBe("https://example.com");
+ expect(result.origin).toBe("api");
+ expect(result.timeout).toBe(30000);
+ expect(result.formats).toEqual(["markdown"]);
+ });
+
+ it("should accept valid scrape request with all optional fields", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ formats: ["markdown", "html"],
+ onlyMainContent: false,
+ waitFor: 1000,
+ mobile: true,
+ parsePDF: false,
+ skipTlsVerification: true,
+ removeBase64Images: false,
+ fastMode: true,
+ blockAds: false,
+ proxy: "stealth",
+ maxAge: 3600000,
+ storeInCache: false,
+ origin: "custom",
+ timeout: 60000,
+ zeroDataRetention: true,
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ expect(result.url).toBe("https://example.com");
+ expect(result.formats).toEqual(["markdown", "html"]);
+ expect(result.origin).toBe("custom");
+ expect(result.timeout).toBe(60000);
+ });
+
+ it("should reject invalid URL", () => {
+ const input = {
+ url: "not-a-url",
+ };
+
+ expect(() => scrapeRequestSchema.parse(input)).toThrow();
+ });
+
+ it("should reject missing URL", () => {
+ const input = {};
+
+ expect(() => scrapeRequestSchema.parse(input)).toThrow();
+ });
+
+ it("should reject invalid format combination (screenshot and screenshot@fullPage)", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ formats: ["screenshot", "screenshot@fullPage"],
+ };
+
+ expect(() => scrapeRequestSchema.parse(input)).toThrow(
+ "You may only specify either screenshot or screenshot@fullPage",
+ );
+ });
+
+ it("should reject changeTracking without markdown", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ formats: ["changeTracking"],
+ };
+
+ expect(() => scrapeRequestSchema.parse(input)).toThrow(
+ "The changeTracking format requires the markdown format to be specified as well",
+ );
+ });
+
+ it("should accept changeTracking with markdown", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ formats: ["markdown", "changeTracking"],
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ expect(result.formats).toContain("markdown");
+ expect(result.formats).toContain("changeTracking");
+ });
+
+ it("should reject extract format without extract options", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ formats: ["extract"],
+ };
+
+ expect(() => scrapeRequestSchema.parse(input)).toThrow(
+ "When 'extract' or 'json' format is specified, corresponding options must be provided",
+ );
+ });
+
+ it("should accept extract format with extract options", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ formats: ["extract"],
+ extract: {
+ schema: {
+ type: "object",
+ properties: {
+ title: { type: "string" },
+ },
+ },
+ },
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ expect(result.formats).toContain("extract");
+ expect(result.extract).toBeDefined();
+ expect(result.timeout).toBe(60000); // Should be transformed from 30000
+ });
+
+ it("should reject json format without jsonOptions", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ formats: ["json"],
+ };
+
+ expect(() => scrapeRequestSchema.parse(input)).toThrow(
+ "When 'extract' or 'json' format is specified, corresponding options must be provided",
+ );
+ });
+
+ it("should accept json format with jsonOptions", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ formats: ["json"],
+ jsonOptions: {
+ schema: {
+ type: "object",
+ properties: {
+ title: { type: "string" },
+ },
+ },
+ },
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ expect(result.formats).toContain("json");
+ expect(result.formats).toContain("extract"); // Should be added by transform
+ expect(result.jsonOptions).toBeDefined();
+ expect(result.timeout).toBe(60000); // Should be transformed from 30000
+ });
+
+ it("should reject extract options without extract format", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ extract: {
+ schema: {
+ type: "object",
+ properties: {
+ title: { type: "string" },
+ },
+ },
+ },
+ };
+
+ expect(() => scrapeRequestSchema.parse(input)).toThrow(
+ "When 'extract' or 'json' format is specified, corresponding options must be provided",
+ );
+ });
+
+ it("should reject waitFor exceeding timeout/2", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ timeout: 1000,
+ waitFor: 600,
+ };
+
+ expect(() => scrapeRequestSchema.parse(input)).toThrow(
+ "waitFor must not exceed half of timeout",
+ );
+ });
+
+ it("should accept waitFor within timeout/2", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ timeout: 1000,
+ waitFor: 400,
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ expect(result.waitFor).toBe(400);
+ expect(result.timeout).toBe(1000);
+ });
+
+ it("should reject both agent and jsonOptions with fire-1 model", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ formats: ["json"],
+ agent: {
+ model: "fire-1",
+ prompt: "test",
+ },
+ jsonOptions: {
+ agent: {
+ model: "fire-1",
+ prompt: "test",
+ },
+ schema: {
+ type: "object",
+ properties: {
+ title: { type: "string" },
+ },
+ },
+ },
+ };
+
+ expect(() => scrapeRequestSchema.parse(input)).toThrow(
+ "You may only specify the FIRE-1 model in agent or jsonOptions.agent, but not both",
+ );
+ });
+
+ it("should transform jsonOptions to extract when json format is used", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ formats: ["json"],
+ jsonOptions: {
+ schema: {
+ type: "object",
+ properties: {
+ title: { type: "string" },
+ },
+ },
+ },
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ expect(result.extract).toBeDefined();
+ expect(result.jsonOptions).toBeDefined();
+ });
+
+ it("should apply default values correctly", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ expect(result.origin).toBe("api");
+ expect(result.timeout).toBe(30000);
+ expect(result.formats).toEqual(["markdown"]);
+ expect(result.onlyMainContent).toBe(true);
+ expect(result.waitFor).toBe(0);
+ expect(result.mobile).toBe(false);
+ expect(result.parsePDF).toBe(true);
+ expect(result.removeBase64Images).toBe(true);
+ expect(result.fastMode).toBe(false);
+ expect(result.blockAds).toBe(true);
+ expect(result.proxy).toBe("basic");
+ expect(result.storeInCache).toBe(true);
+ });
+
+ it("should accept valid integration value", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ integration: "dify",
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ expect(result.integration).toBe("dify");
+ });
+
+ it("should accept integration value starting with underscore", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ integration: "_custom",
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ expect(result.integration).toBe("_custom");
+ });
+
+ it("should reject invalid integration value", () => {
+ const input = {
+ url: "https://example.com",
+ integration: "invalid-integration",
+ };
+
+ expect(() => scrapeRequestSchema.parse(input)).toThrow(
+ "Invalid enum value",
+ );
+ });
+
+ it("should handle iframe selector transformation", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ includeTags: ["iframe", "div"],
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ expect(result.includeTags).toContain('div[data-original-tag="iframe"]');
+ });
+ });
+
+ describe("extractRequestSchema", () => {
+ it("should accept valid extract request with urls", () => {
+ const input: ExtractRequestInput = {
+ urls: ["https://example.com"],
+ schema: {
+ type: "object",
+ properties: {
+ title: { type: "string" },
+ },
+ },
+ };
+
+ const result = extractRequestSchema.parse(input);
+ expect(result.urls).toEqual(["https://example.com"]);
+ expect(result.origin).toBe("api");
+ expect(result.timeout).toBe(60000);
+ });
+
+ it("should accept valid extract request with prompt", () => {
+ const input: ExtractRequestInput = {
+ prompt: "Extract the title",
+ schema: {
+ type: "object",
+ properties: {
+ title: { type: "string" },
+ },
+ },
+ };
+
+ const result = extractRequestSchema.parse(input);
+ expect(result.prompt).toBe("Extract the title");
+ });
+
+ it("should reject extract request without urls or prompt", () => {
+ const input = {
+ schema: {
+ type: "object",
+ properties: {
+ title: { type: "string" },
+ },
+ },
+ };
+
+ expect(() => extractRequestSchema.parse(input)).toThrow(
+ "Either 'urls' or 'prompt' must be provided",
+ );
+ });
+
+ it("should reject more than 10 URLs", () => {
+ const input: ExtractRequestInput = {
+ urls: Array.from({ length: 11 }, (_, i) => `https://example${i}.com`),
+ schema: {
+ type: "object",
+ properties: {
+ title: { type: "string" },
+ },
+ },
+ };
+
+ expect(() => extractRequestSchema.parse(input)).toThrow(
+ "Maximum of 10 URLs allowed per request while in beta",
+ );
+ });
+
+ it("should accept up to 10 URLs", () => {
+ const input: ExtractRequestInput = {
+ urls: Array.from({ length: 10 }, (_, i) => `https://example${i}.com`),
+ schema: {
+ type: "object",
+ properties: {
+ title: { type: "string" },
+ },
+ },
+ };
+
+ const result = extractRequestSchema.parse(input);
+ expect(result.urls).toHaveLength(10);
+ });
+
+ it("should reject invalid JSON schema", () => {
+ const input: ExtractRequestInput = {
+ urls: ["https://example.com"],
+ schema: {
+ type: "invalid-type",
+ properties: "not-an-object",
+ },
+ };
+
+ expect(() => extractRequestSchema.parse(input)).toThrow(
+ "Invalid JSON schema",
+ );
+ });
+
+ it("should transform allowExternalLinks when enableWebSearch is true", () => {
+ const input: ExtractRequestInput = {
+ urls: ["https://example.com"],
+ enableWebSearch: true,
+ schema: {
+ type: "object",
+ properties: {
+ title: { type: "string" },
+ },
+ },
+ };
+
+ const result = extractRequestSchema.parse(input);
+ expect(result.allowExternalLinks).toBe(true);
+ });
+ });
+
+ describe("crawlRequestSchema", () => {
+ it("should accept valid minimal crawl request", () => {
+ const input: CrawlRequestInput = {
+ url: "https://example.com",
+ };
+
+ const result = crawlRequestSchema.parse(input);
+ expect(result.url).toBe("https://example.com");
+ expect(result.origin).toBe("api");
+ expect(result.limit).toBe(10000);
+ expect(result.maxDepth).toBe(10);
+ expect(result.scrapeOptions).toBeDefined();
+ });
+
+ it("should accept valid crawl request with all crawler options", () => {
+ const input: CrawlRequestInput = {
+ url: "https://example.com",
+ includePaths: ["/blog"],
+ excludePaths: ["/admin"],
+ maxDepth: 5,
+ maxDiscoveryDepth: 10,
+ limit: 5000,
+ crawlEntireDomain: true,
+ allowExternalLinks: true,
+ allowSubdomains: true,
+ ignoreRobotsTxt: true,
+ ignoreSitemap: true,
+ deduplicateSimilarURLs: false,
+ ignoreQueryParameters: true,
+ regexOnFullURL: true,
+ delay: 1000,
+ scrapeOptions: {
+ formats: ["markdown"],
+ },
+ };
+
+ const result = crawlRequestSchema.parse(input);
+ expect(result.url).toBe("https://example.com");
+ expect(result.maxDepth).toBe(5);
+ expect(result.crawlEntireDomain).toBe(true);
+ expect(result.allowBackwardLinks).toBe(true); // Should be transformed
+ });
+
+ it("should reject URL depth exceeding maxDepth", () => {
+ const input: CrawlRequestInput = {
+ url: "https://example.com/level1/level2/level3/level4/level5/level6/level7/level8/level9/level10/level11",
+ maxDepth: 5,
+ };
+
+ expect(() => crawlRequestSchema.parse(input)).toThrow(
+ "URL depth exceeds the specified maxDepth",
+ );
+ });
+
+ it("should transform crawlEntireDomain to allowBackwardLinks", () => {
+ const input: CrawlRequestInput = {
+ url: "https://example.com",
+ crawlEntireDomain: true,
+ };
+
+ const result = crawlRequestSchema.parse(input);
+ expect(result.allowBackwardLinks).toBe(true);
+ });
+
+ it("should apply default scrapeOptions when not provided", () => {
+ const input: CrawlRequestInput = {
+ url: "https://example.com",
+ };
+
+ const result = crawlRequestSchema.parse(input);
+ expect(result.scrapeOptions).toBeDefined();
+ expect(result.scrapeOptions.formats).toEqual(["markdown"]);
+ });
+ });
+
+ describe("mapRequestSchema", () => {
+ it("should accept valid minimal map request", () => {
+ const input: MapRequestInput = {
+ url: "https://example.com",
+ };
+
+ const result = mapRequestSchema.parse(input);
+ expect(result.url).toBe("https://example.com");
+ expect(result.origin).toBe("api");
+ expect(result.limit).toBe(5000);
+ expect(result.includeSubdomains).toBe(true);
+ expect(result.ignoreQueryParameters).toBe(true);
+ expect(result.filterByPath).toBe(true);
+ expect(result.useIndex).toBe(true);
+ });
+
+ it("should reject limit exceeding MAX_MAP_LIMIT", () => {
+ const input: MapRequestInput = {
+ url: "https://example.com",
+ limit: 200000,
+ };
+
+ expect(() => mapRequestSchema.parse(input)).toThrow();
+ });
+
+ it("should reject limit below 1", () => {
+ const input: MapRequestInput = {
+ url: "https://example.com",
+ limit: 0,
+ };
+
+ expect(() => mapRequestSchema.parse(input)).toThrow();
+ });
+
+ it("should accept limit within valid range", () => {
+ const input: MapRequestInput = {
+ url: "https://example.com",
+ limit: 10000,
+ };
+
+ const result = mapRequestSchema.parse(input);
+ expect(result.limit).toBe(10000);
+ });
+ });
+
+ describe("batchScrapeRequestSchema", () => {
+ it("should accept valid batch scrape request", () => {
+ const input: BatchScrapeRequestInput = {
+ urls: ["https://example.com", "https://example.org"],
+ };
+
+ const result = batchScrapeRequestSchema.parse(input);
+ expect(result.urls).toHaveLength(2);
+ expect(result.origin).toBe("api");
+ expect(result.ignoreInvalidURLs).toBe(false);
+ });
+
+ it("should reject empty urls array", () => {
+ const input = {
+ urls: [],
+ };
+
+ expect(() => batchScrapeRequestSchema.parse(input)).toThrow();
+ });
+
+ it("should accept valid UUID for appendToId", () => {
+ const input: BatchScrapeRequestInput = {
+ urls: ["https://example.com"],
+ appendToId: "123e4567-e89b-12d3-a456-426614174000",
+ };
+
+ const result = batchScrapeRequestSchema.parse(input);
+ expect(result.appendToId).toBe("123e4567-e89b-12d3-a456-426614174000");
+ });
+
+ it("should reject invalid UUID for appendToId", () => {
+ const input = {
+ urls: ["https://example.com"],
+ appendToId: "not-a-uuid",
+ };
+
+ expect(() => batchScrapeRequestSchema.parse(input)).toThrow();
+ });
+ });
+
+ describe("Type inference", () => {
+ it("should correctly infer ScrapeRequest type", () => {
+ const result: ScrapeRequest = scrapeRequestSchema.parse({
+ url: "https://example.com",
+ });
+
+ // TypeScript should enforce these types
+ expect(typeof result.url).toBe("string");
+ expect(typeof result.origin).toBe("string");
+ expect(typeof result.timeout).toBe("number");
+ expect(Array.isArray(result.formats)).toBe(true);
+ });
+
+ it("should correctly infer ExtractRequest type", () => {
+ const result: ExtractRequest = extractRequestSchema.parse({
+ urls: ["https://example.com"],
+ schema: {
+ type: "object",
+ properties: {
+ title: { type: "string" },
+ },
+ },
+ });
+
+ expect(Array.isArray(result.urls)).toBe(true);
+ expect(typeof result.timeout).toBe("number");
+ });
+
+ it("should correctly infer CrawlRequest type", () => {
+ const result: CrawlRequest = crawlRequestSchema.parse({
+ url: "https://example.com",
+ });
+
+ expect(typeof result.url).toBe("string");
+ expect(typeof result.maxDepth).toBe("number");
+ expect(result.scrapeOptions).toBeDefined();
+ });
+
+ it("should correctly infer MapRequest type", () => {
+ const result: MapRequest = mapRequestSchema.parse({
+ url: "https://example.com",
+ });
+
+ expect(typeof result.url).toBe("string");
+ expect(typeof result.limit).toBe("number");
+ });
+
+ it("should correctly infer BatchScrapeRequest type", () => {
+ const result: BatchScrapeRequest = batchScrapeRequestSchema.parse({
+ urls: ["https://example.com"],
+ });
+
+ expect(Array.isArray(result.urls)).toBe(true);
+ expect(result.urls.length).toBeGreaterThan(0);
+ });
+ });
+
+ describe("scrapeOptions schema", () => {
+ it("should accept valid scrape options", () => {
+ const input = {
+ formats: ["markdown", "html"],
+ onlyMainContent: false,
+ waitFor: 1000,
+ };
+
+ const result = scrapeOptions.parse(input);
+ expect(result.formats).toEqual(["markdown", "html"]);
+ expect(result.onlyMainContent).toBe(false);
+ expect(result.waitFor).toBe(1000);
+ });
+
+ it("should reject invalid actions wait time", () => {
+ const input = {
+ formats: ["markdown"],
+ waitFor: 0,
+ actions: Array.from({ length: 100 }, () => ({
+ type: "wait" as const,
+ milliseconds: 1000,
+ })),
+ };
+
+ expect(() => scrapeOptions.parse(input)).toThrow(
+ "Total wait time (waitFor + wait actions) cannot exceed",
+ );
+ });
+ });
+
+ describe("Edge cases", () => {
+ it("should handle URL without protocol (should add http://)", () => {
+ const input = {
+ url: "example.com",
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ expect(result.url).toMatch(/^https?:\/\//);
+ });
+
+ it("should handle undefined integration (optional field)", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ // Integration transform converts undefined/falsy to null
+ expect(result.integration).toBeNull();
+ });
+
+ it("should handle changeTracking format timeout transformation", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ formats: ["markdown", "changeTracking"],
+ timeout: 30000,
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ expect(result.timeout).toBe(60000); // Should be transformed
+ expect(result.waitFor).toBeGreaterThanOrEqual(5000); // Should be at least 5000
+ });
+
+ it("should handle agent timeout transformation", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ agent: {
+ model: "fire-1",
+ prompt: "test",
+ },
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ expect(result.timeout).toBe(300000); // Should be transformed
+ });
+
+ it("should handle stealth proxy timeout transformation", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ proxy: "stealth",
+ timeout: 30000,
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ expect(result.timeout).toBe(120000); // Should be transformed
+ });
+
+ it("should handle auto proxy timeout transformation", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ proxy: "auto",
+ timeout: 30000,
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ expect(result.timeout).toBe(120000); // Should be transformed
+ });
+
+ it("should handle location schema with valid country code", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ location: {
+ country: "US",
+ languages: ["en"],
+ },
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ expect(result.location?.country).toBe("us"); // Should be transformed to lowercase
+ expect(result.location?.languages).toEqual(["en"]);
+ });
+
+ it("should handle location schema with special country codes", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ location: {
+ country: "us-generic",
+ },
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ expect(result.location?.country).toBe("us-generic");
+ });
+
+ it("should reject location schema with invalid country code", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ location: {
+ country: "INVALID",
+ },
+ };
+
+ expect(() => scrapeRequestSchema.parse(input)).toThrow(
+ "Invalid country code",
+ );
+ });
+
+ it("should handle geolocation schema (deprecated) with valid country", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ geolocation: {
+ country: "us",
+ languages: ["en"],
+ },
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ expect(result.geolocation?.country).toBe("US"); // Should be transformed to uppercase
+ expect(result.geolocation?.languages).toEqual(["en"]);
+ });
+
+ it("should reject geolocation schema with invalid country", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ geolocation: {
+ country: "INVALID",
+ },
+ };
+
+ expect(() => scrapeRequestSchema.parse(input)).toThrow(
+ "Invalid country code",
+ );
+ });
+
+ it("should handle valid actions", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ actions: [
+ { type: "click", selector: "button" },
+ { type: "wait", milliseconds: 1000 },
+ { type: "scroll", direction: "down" },
+ ],
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ expect(result.actions).toHaveLength(3);
+ expect(result.actions?.[0].type).toBe("click");
+ expect(result.actions?.[1].type).toBe("wait");
+ });
+
+ it("should reject wait action with both milliseconds and selector", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ actions: [
+ {
+ type: "wait",
+ milliseconds: 1000,
+ selector: "button",
+ },
+ ],
+ };
+
+ expect(() => scrapeRequestSchema.parse(input)).toThrow(
+ "Either 'milliseconds' or 'selector' must be provided, but not both",
+ );
+ });
+
+ it("should reject wait action without milliseconds or selector", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ actions: [
+ {
+ type: "wait",
+ },
+ ],
+ };
+
+ expect(() => scrapeRequestSchema.parse(input)).toThrow();
+ });
+
+ it("should reject more than 50 actions", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ actions: Array.from({ length: 51 }, () => ({
+ type: "click" as const,
+ selector: "button",
+ })),
+ };
+
+ expect(() => scrapeRequestSchema.parse(input)).toThrow(
+ "Number of actions cannot exceed 50",
+ );
+ });
+
+ it("should handle changeTrackingOptions with valid schema", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ formats: ["markdown", "changeTracking"],
+ changeTrackingOptions: {
+ schema: {
+ type: "object",
+ properties: {
+ changes: { type: "array" },
+ },
+ },
+ modes: ["json"],
+ tag: "test-tag",
+ },
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ expect(result.changeTrackingOptions).toBeDefined();
+ expect(result.changeTrackingOptions?.modes).toEqual(["json"]);
+ expect(result.changeTrackingOptions?.tag).toBe("test-tag");
+ });
+
+ it("should handle changeTrackingOptions with null tag", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ formats: ["markdown", "changeTracking"],
+ changeTrackingOptions: {
+ tag: null,
+ },
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ expect(result.changeTrackingOptions?.tag).toBeNull();
+ });
+
+ it("should reject invalid changeTrackingOptions schema", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ formats: ["markdown", "changeTracking"],
+ changeTrackingOptions: {
+ schema: {
+ type: "invalid",
+ },
+ },
+ };
+
+ expect(() => scrapeRequestSchema.parse(input)).toThrow(
+ "Invalid JSON schema",
+ );
+ });
+ });
+});
diff --git a/apps/api/src/__tests__/snips/v2/scrape.test.ts b/apps/api/src/__tests__/snips/v2/scrape.test.ts
index 8641c8a24..676b7f735 100644
--- a/apps/api/src/__tests__/snips/v2/scrape.test.ts
+++ b/apps/api/src/__tests__/snips/v2/scrape.test.ts
@@ -1510,12 +1510,9 @@ describe("Scrape tests", () => {
type: "json",
prompt: "Extract company info as JSON",
schema: {
- prompt: "Extract company info as JSON",
- schema: {
- type: "object",
- properties: {
- name: { type: "string" },
- },
+ type: "object",
+ properties: {
+ name: { type: "string" },
},
},
},
diff --git a/apps/api/src/__tests__/snips/v2/types-validation.test.ts b/apps/api/src/__tests__/snips/v2/types-validation.test.ts
new file mode 100644
index 000000000..cb1e98b8e
--- /dev/null
+++ b/apps/api/src/__tests__/snips/v2/types-validation.test.ts
@@ -0,0 +1,1066 @@
+import { z } from "zod";
+import {
+ scrapeRequestSchema,
+ scrapeOptions,
+ extractRequestSchema,
+ crawlRequestSchema,
+ mapRequestSchema,
+ batchScrapeRequestSchema,
+ searchRequestSchema,
+ ScrapeRequest,
+ ScrapeRequestInput,
+ ExtractRequest,
+ ExtractRequestInput,
+ CrawlRequest,
+ CrawlRequestInput,
+ MapRequest,
+ MapRequestInput,
+ BatchScrapeRequest,
+ BatchScrapeRequestInput,
+ SearchRequest,
+ SearchRequestInput,
+} from "../../../controllers/v2/types";
+
+describe("V2 Types Validation", () => {
+ describe("scrapeRequestSchema", () => {
+ it("should accept valid minimal scrape request", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ expect(result.url).toBe("https://example.com");
+ expect(result.origin).toBe("api");
+ expect(result.formats).toEqual([{ type: "markdown" }]);
+ });
+
+ it("should accept valid scrape request with format objects", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ formats: [{ type: "markdown" }, { type: "html" }],
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ expect(result.formats).toEqual([{ type: "markdown" }, { type: "html" }]);
+ });
+
+ it("should accept valid scrape request with string formats (preprocessed)", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ formats: ["markdown", "html"],
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ expect(result.formats).toEqual([{ type: "markdown" }, { type: "html" }]);
+ });
+
+ it("should accept valid scrape request with json format options", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ formats: [
+ {
+ type: "json",
+ schema: {
+ type: "object",
+ properties: {
+ title: { type: "string" },
+ },
+ },
+ },
+ ],
+ timeout: 30000,
+ proxy: "basic", // Use basic proxy to avoid auto/stealth timeout transformation
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ expect(result.formats).toHaveLength(1);
+ expect(result.formats[0].type).toBe("json");
+ expect(result.timeout).toBe(60000); // Should be transformed from 30000
+ });
+
+ it("should accept valid scrape request with changeTracking format", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ formats: [
+ { type: "markdown" },
+ {
+ type: "changeTracking",
+ schema: {
+ type: "object",
+ properties: {
+ changes: { type: "array" },
+ },
+ },
+ modes: ["json"],
+ tag: "test-tag",
+ },
+ ],
+ timeout: 30000,
+ proxy: "basic", // Use basic proxy to avoid auto/stealth timeout transformation
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ expect(result.formats).toHaveLength(2);
+ expect(result.timeout).toBe(60000); // Should be transformed
+ expect(result.waitFor).toBeGreaterThanOrEqual(5000); // Should be at least 5000
+ });
+
+ it("should reject changeTracking without markdown", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ formats: [
+ {
+ type: "changeTracking",
+ },
+ ],
+ };
+
+ expect(() => scrapeRequestSchema.parse(input)).toThrow(
+ "The changeTracking format requires the markdown format to be specified as well",
+ );
+ });
+
+ it("should reject multiple screenshot formats", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ formats: [
+ { type: "screenshot", fullPage: false },
+ { type: "screenshot", fullPage: true },
+ ],
+ };
+
+ expect(() => scrapeRequestSchema.parse(input)).toThrow(
+ "You may only specify one screenshot format",
+ );
+ });
+
+ it("should accept screenshot format with options", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ formats: [
+ {
+ type: "screenshot",
+ fullPage: true,
+ quality: 90,
+ viewport: {
+ width: 1920,
+ height: 1080,
+ },
+ },
+ ],
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ expect(result.formats[0].type).toBe("screenshot");
+ expect((result.formats[0] as any).fullPage).toBe(true);
+ expect((result.formats[0] as any).quality).toBe(90);
+ });
+
+ it("should accept attributes format with selectors", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ formats: [
+ {
+ type: "attributes",
+ selectors: [
+ {
+ selector: ".product",
+ attribute: "data-product-id",
+ },
+ ],
+ },
+ ],
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ expect(result.formats[0].type).toBe("attributes");
+ expect((result.formats[0] as any).selectors).toHaveLength(1);
+ });
+
+ it("should reject invalid URL", () => {
+ const input = {
+ url: "not-a-url",
+ };
+
+ expect(() => scrapeRequestSchema.parse(input)).toThrow();
+ });
+
+ it("should reject missing URL", () => {
+ const input = {};
+
+ expect(() => scrapeRequestSchema.parse(input)).toThrow();
+ });
+
+ it("should reject waitFor exceeding timeout/2", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ timeout: 1000,
+ waitFor: 600,
+ };
+
+ expect(() => scrapeRequestSchema.parse(input)).toThrow(
+ "waitFor must not exceed half of timeout",
+ );
+ });
+
+ it("should accept waitFor within timeout/2", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ timeout: 1000,
+ waitFor: 400,
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ expect(result.waitFor).toBe(400);
+ expect(result.timeout).toBe(1000);
+ });
+
+ it("should apply default values correctly", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ expect(result.origin).toBe("api");
+ expect(result.formats).toEqual([{ type: "markdown" }]);
+ expect(result.onlyMainContent).toBe(true);
+ expect(result.waitFor).toBe(0);
+ expect(result.mobile).toBe(false);
+ expect(result.removeBase64Images).toBe(true);
+ expect(result.fastMode).toBe(false);
+ expect(result.blockAds).toBe(true);
+ expect(result.proxy).toBe("auto"); // v2 default is "auto"
+ expect(result.storeInCache).toBe(true);
+ });
+
+ it("should accept valid integration value", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ integration: "dify",
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ expect(result.integration).toBe("dify");
+ });
+
+ it("should accept integration value starting with underscore", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ integration: "_custom",
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ expect(result.integration).toBe("_custom");
+ });
+
+ it("should reject invalid integration value", () => {
+ const input = {
+ url: "https://example.com",
+ integration: "invalid-integration",
+ };
+
+ expect(() => scrapeRequestSchema.parse(input)).toThrow(
+ "Invalid enum value",
+ );
+ });
+
+ it("should handle iframe selector transformation", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ includeTags: ["iframe", "div"],
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ expect(result.includeTags).toContain('div[data-original-tag="iframe"]');
+ });
+
+ it("should handle parsers with PDF options", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ parsers: [
+ {
+ type: "pdf",
+ maxPages: 100,
+ },
+ ],
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ expect(result.parsers).toBeDefined();
+ expect((result.parsers as any)[0].type).toBe("pdf");
+ expect((result.parsers as any)[0].maxPages).toBe(100);
+ });
+
+ it("should reject PDF parser with maxPages exceeding limit", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ parsers: [
+ {
+ type: "pdf",
+ maxPages: 20000,
+ },
+ ],
+ };
+
+ expect(() => scrapeRequestSchema.parse(input)).toThrow();
+ });
+
+ it("should handle stealth proxy timeout transformation", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ proxy: "stealth",
+ timeout: 30000,
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ expect(result.timeout).toBe(120000); // Should be transformed
+ });
+
+ it("should handle auto proxy timeout transformation", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ proxy: "auto",
+ timeout: 30000,
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ expect(result.timeout).toBe(120000); // Should be transformed
+ });
+
+ it("should handle location schema with valid country code", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ location: {
+ country: "US",
+ languages: ["en"],
+ },
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ expect(result.location?.country).toBe("us"); // Should be transformed to lowercase
+ expect(result.location?.languages).toEqual(["en"]);
+ });
+
+ it("should reject location schema with invalid country code", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ location: {
+ country: "INVALID",
+ },
+ };
+
+ expect(() => scrapeRequestSchema.parse(input)).toThrow(
+ "Invalid country code",
+ );
+ });
+
+ it("should handle valid actions", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ actions: [
+ { type: "click", selector: "button" },
+ { type: "wait", milliseconds: 1000 },
+ { type: "scroll", direction: "down" },
+ ],
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ expect(result.actions).toHaveLength(3);
+ expect(result.actions?.[0].type).toBe("click");
+ expect(result.actions?.[1].type).toBe("wait");
+ });
+
+ it("should reject wait action with both milliseconds and selector", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ actions: [
+ {
+ type: "wait",
+ milliseconds: 1000,
+ selector: "button",
+ },
+ ],
+ };
+
+ expect(() => scrapeRequestSchema.parse(input)).toThrow(
+ "Either 'milliseconds' or 'selector' must be provided, but not both",
+ );
+ });
+
+ it("should reject more than 50 actions", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ actions: Array.from({ length: 51 }, () => ({
+ type: "click" as const,
+ selector: "button",
+ })),
+ };
+
+ expect(() => scrapeRequestSchema.parse(input)).toThrow(
+ "Number of actions cannot exceed 50",
+ );
+ });
+
+ it("should handle screenshot action with viewport", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ actions: [
+ {
+ type: "screenshot",
+ fullPage: false,
+ quality: 90,
+ viewport: {
+ width: 1920,
+ height: 1080,
+ },
+ },
+ ],
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ expect(result.actions?.[0].type).toBe("screenshot");
+ });
+
+ it("should reject screenshot action with invalid viewport dimensions", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ actions: [
+ {
+ type: "screenshot",
+ viewport: {
+ width: 10000, // Exceeds max
+ height: 1080,
+ },
+ },
+ ],
+ };
+
+ expect(() => scrapeRequestSchema.parse(input)).toThrow();
+ });
+ });
+
+ describe("extractRequestSchema", () => {
+ it("should accept valid extract request with urls", () => {
+ const input: ExtractRequestInput = {
+ urls: ["https://example.com"],
+ schema: {
+ type: "object",
+ properties: {
+ title: { type: "string" },
+ },
+ },
+ };
+
+ const result = extractRequestSchema.parse(input);
+ expect(result.urls).toEqual(["https://example.com"]);
+ expect(result.origin).toBe("api");
+ expect(result.ignoreInvalidURLs).toBe(true); // v2 default is true
+ });
+
+ it("should accept valid extract request with prompt", () => {
+ const input: ExtractRequestInput = {
+ prompt: "Extract the title",
+ schema: {
+ type: "object",
+ properties: {
+ title: { type: "string" },
+ },
+ },
+ };
+
+ const result = extractRequestSchema.parse(input);
+ expect(result.prompt).toBe("Extract the title");
+ });
+
+ it("should reject extract request without urls or prompt", () => {
+ const input = {
+ schema: {
+ type: "object",
+ properties: {
+ title: { type: "string" },
+ },
+ },
+ };
+
+ expect(() => extractRequestSchema.parse(input)).toThrow(
+ "Either 'urls' or 'prompt' must be provided",
+ );
+ });
+
+ it("should reject more than 10 URLs", () => {
+ const input: ExtractRequestInput = {
+ urls: Array.from({ length: 11 }, (_, i) => `https://example${i}.com`),
+ schema: {
+ type: "object",
+ properties: {
+ title: { type: "string" },
+ },
+ },
+ };
+
+ expect(() => extractRequestSchema.parse(input)).toThrow(
+ "Maximum of 10 URLs allowed per request while in beta",
+ );
+ });
+
+ it("should accept up to 10 URLs", () => {
+ const input: ExtractRequestInput = {
+ urls: Array.from({ length: 10 }, (_, i) => `https://example${i}.com`),
+ schema: {
+ type: "object",
+ properties: {
+ title: { type: "string" },
+ },
+ },
+ };
+
+ const result = extractRequestSchema.parse(input);
+ expect(result.urls).toHaveLength(10);
+ });
+
+ it("should reject invalid JSON schema", () => {
+ const input: ExtractRequestInput = {
+ urls: ["https://example.com"],
+ schema: {
+ type: "invalid-type",
+ properties: "not-an-object",
+ },
+ };
+
+ expect(() => extractRequestSchema.parse(input)).toThrow(
+ "Invalid JSON schema",
+ );
+ });
+
+ it("should transform allowExternalLinks when enableWebSearch is true", () => {
+ const input: ExtractRequestInput = {
+ urls: ["https://example.com"],
+ enableWebSearch: true,
+ schema: {
+ type: "object",
+ properties: {
+ title: { type: "string" },
+ },
+ },
+ };
+
+ const result = extractRequestSchema.parse(input);
+ expect(result.allowExternalLinks).toBe(true);
+ });
+ });
+
+ describe("crawlRequestSchema", () => {
+ it("should accept valid minimal crawl request", () => {
+ const input: CrawlRequestInput = {
+ url: "https://example.com",
+ };
+
+ const result = crawlRequestSchema.parse(input);
+ expect(result.url).toBe("https://example.com");
+ expect(result.origin).toBe("api");
+ expect(result.limit).toBe(10000);
+ expect(result.scrapeOptions).toBeDefined();
+ expect(result.sitemap).toBe("include");
+ });
+
+ it("should accept valid crawl request with all crawler options", () => {
+ const input: CrawlRequestInput = {
+ url: "https://example.com",
+ includePaths: ["/blog"],
+ excludePaths: ["/admin"],
+ maxDiscoveryDepth: 10,
+ limit: 5000,
+ crawlEntireDomain: true,
+ allowExternalLinks: true,
+ allowSubdomains: true,
+ ignoreRobotsTxt: true,
+ sitemap: "skip",
+ deduplicateSimilarURLs: false,
+ ignoreQueryParameters: true,
+ regexOnFullURL: true,
+ delay: 1000,
+ prompt: "Extract blog posts",
+ scrapeOptions: {
+ formats: [{ type: "markdown" }],
+ },
+ };
+
+ const result = crawlRequestSchema.parse(input);
+ expect(result.url).toBe("https://example.com");
+ expect(result.maxDiscoveryDepth).toBe(10);
+ expect(result.crawlEntireDomain).toBe(true);
+ expect(result.sitemap).toBe("skip");
+ expect(result.prompt).toBe("Extract blog posts");
+ });
+
+ it("should apply default scrapeOptions when not provided", () => {
+ const input: CrawlRequestInput = {
+ url: "https://example.com",
+ };
+
+ const result = crawlRequestSchema.parse(input);
+ expect(result.scrapeOptions).toBeDefined();
+ expect(result.scrapeOptions.formats).toEqual([{ type: "markdown" }]);
+ });
+
+ it("should handle sitemap enum values", () => {
+ const input: CrawlRequestInput = {
+ url: "https://example.com",
+ sitemap: "include",
+ };
+
+ const result = crawlRequestSchema.parse(input);
+ expect(result.sitemap).toBe("include");
+ });
+
+ it("should reject invalid sitemap value", () => {
+ const input = {
+ url: "https://example.com",
+ sitemap: "invalid",
+ };
+
+ expect(() => crawlRequestSchema.parse(input)).toThrow();
+ });
+ });
+
+ describe("mapRequestSchema", () => {
+ it("should accept valid minimal map request", () => {
+ const input: MapRequestInput = {
+ url: "https://example.com",
+ };
+
+ const result = mapRequestSchema.parse(input);
+ expect(result.url).toBe("https://example.com");
+ expect(result.origin).toBe("api");
+ expect(result.limit).toBe(5000);
+ expect(result.includeSubdomains).toBe(true);
+ expect(result.ignoreQueryParameters).toBe(true);
+ expect(result.sitemap).toBe("include");
+ expect(result.filterByPath).toBe(true);
+ expect(result.useIndex).toBe(true);
+ });
+
+ it("should reject limit exceeding MAX_MAP_LIMIT", () => {
+ const input: MapRequestInput = {
+ url: "https://example.com",
+ limit: 200000,
+ };
+
+ expect(() => mapRequestSchema.parse(input)).toThrow();
+ });
+
+ it("should reject limit below 1", () => {
+ const input: MapRequestInput = {
+ url: "https://example.com",
+ limit: 0,
+ };
+
+ expect(() => mapRequestSchema.parse(input)).toThrow();
+ });
+
+ it("should accept limit within valid range", () => {
+ const input: MapRequestInput = {
+ url: "https://example.com",
+ limit: 10000,
+ };
+
+ const result = mapRequestSchema.parse(input);
+ expect(result.limit).toBe(10000);
+ });
+
+ it("should handle sitemap enum values", () => {
+ const input: MapRequestInput = {
+ url: "https://example.com",
+ sitemap: "only",
+ };
+
+ const result = mapRequestSchema.parse(input);
+ expect(result.sitemap).toBe("only");
+ });
+ });
+
+ describe("batchScrapeRequestSchema", () => {
+ it("should accept valid batch scrape request", () => {
+ const input: BatchScrapeRequestInput = {
+ urls: ["https://example.com", "https://example.org"],
+ };
+
+ const result = batchScrapeRequestSchema.parse(input);
+ expect(result.urls).toHaveLength(2);
+ expect(result.origin).toBe("api");
+ expect(result.ignoreInvalidURLs).toBe(true); // v2 default is true
+ });
+
+ it("should reject empty urls array", () => {
+ const input = {
+ urls: [],
+ };
+
+ expect(() => batchScrapeRequestSchema.parse(input)).toThrow();
+ });
+
+ it("should accept valid UUID for appendToId", () => {
+ const input: BatchScrapeRequestInput = {
+ urls: ["https://example.com"],
+ appendToId: "123e4567-e89b-12d3-a456-426614174000",
+ };
+
+ const result = batchScrapeRequestSchema.parse(input);
+ expect(result.appendToId).toBe("123e4567-e89b-12d3-a456-426614174000");
+ });
+
+ it("should reject invalid UUID for appendToId", () => {
+ const input = {
+ urls: ["https://example.com"],
+ appendToId: "not-a-uuid",
+ };
+
+ expect(() => batchScrapeRequestSchema.parse(input)).toThrow();
+ });
+ });
+
+ describe("searchRequestSchema", () => {
+ it("should accept valid minimal search request", () => {
+ const input: SearchRequestInput = {
+ query: "test query",
+ };
+
+ const result = searchRequestSchema.parse(input);
+ expect(result.query).toBe("test query");
+ expect(result.limit).toBe(10); // v2 default is 10
+ expect(result.lang).toBe("en");
+ expect(result.origin).toBe("api");
+ // Sources are transformed from string array to object array
+ expect(result.sources).toEqual([
+ {
+ type: "web",
+ tbs: undefined,
+ filter: undefined,
+ lang: "en",
+ country: "us",
+ location: undefined,
+ },
+ ]);
+ });
+
+ it("should accept search request with simple sources array", () => {
+ const input: SearchRequestInput = {
+ query: "test",
+ sources: ["web", "images"],
+ };
+
+ const result = searchRequestSchema.parse(input);
+ // Sources are transformed from string array to object array
+ // lang defaults to "en" and is applied to web source
+ expect(result.sources).toEqual([
+ {
+ type: "web",
+ tbs: undefined,
+ filter: undefined,
+ lang: "en", // Default lang is applied
+ country: "us",
+ location: undefined,
+ },
+ {
+ type: "images",
+ },
+ ]);
+ });
+
+ it("should accept search request with advanced sources format", () => {
+ const input: SearchRequestInput = {
+ query: "test",
+ sources: [
+ {
+ type: "web",
+ tbs: "qdr:d",
+ filter: "active",
+ lang: "en",
+ country: "us",
+ location: "New York",
+ },
+ {
+ type: "images",
+ },
+ ],
+ };
+
+ const result = searchRequestSchema.parse(input);
+ expect(result.sources).toBeDefined();
+ expect(Array.isArray(result.sources)).toBe(true);
+ });
+
+ it("should accept search request with simple categories array", () => {
+ const input: SearchRequestInput = {
+ query: "test",
+ categories: ["github", "research"],
+ };
+
+ const result = searchRequestSchema.parse(input);
+ // Categories are transformed from string array to object array
+ expect(result.categories).toEqual([
+ { type: "github" },
+ { type: "research" },
+ ]);
+ });
+
+ it("should accept search request with advanced categories format", () => {
+ const input: SearchRequestInput = {
+ query: "test",
+ categories: [
+ {
+ type: "github",
+ },
+ {
+ type: "research",
+ },
+ {
+ type: "pdf",
+ },
+ ],
+ };
+
+ const result = searchRequestSchema.parse(input);
+ expect(result.categories).toBeDefined();
+ expect(Array.isArray(result.categories)).toBe(true);
+ });
+
+ it("should reject limit exceeding 100", () => {
+ const input: SearchRequestInput = {
+ query: "test",
+ limit: 150,
+ };
+
+ expect(() => searchRequestSchema.parse(input)).toThrow();
+ });
+
+ it("should accept limit within valid range", () => {
+ const input: SearchRequestInput = {
+ query: "test",
+ limit: 50,
+ };
+
+ const result = searchRequestSchema.parse(input);
+ expect(result.limit).toBe(50);
+ });
+
+ it("should handle enterprise array", () => {
+ const input: SearchRequestInput = {
+ query: "test",
+ enterprise: ["default", "zdr"],
+ };
+
+ const result = searchRequestSchema.parse(input);
+ expect(result.enterprise).toEqual(["default", "zdr"]);
+ });
+ });
+
+ describe("Type inference", () => {
+ it("should correctly infer ScrapeRequest type", () => {
+ const result: ScrapeRequest = scrapeRequestSchema.parse({
+ url: "https://example.com",
+ });
+
+ expect(typeof result.url).toBe("string");
+ expect(typeof result.origin).toBe("string");
+ expect(Array.isArray(result.formats)).toBe(true);
+ });
+
+ it("should correctly infer ExtractRequest type", () => {
+ const result: ExtractRequest = extractRequestSchema.parse({
+ urls: ["https://example.com"],
+ schema: {
+ type: "object",
+ properties: {
+ title: { type: "string" },
+ },
+ },
+ });
+
+ expect(Array.isArray(result.urls)).toBe(true);
+ });
+
+ it("should correctly infer CrawlRequest type", () => {
+ const result: CrawlRequest = crawlRequestSchema.parse({
+ url: "https://example.com",
+ });
+
+ expect(typeof result.url).toBe("string");
+ expect(typeof result.limit).toBe("number");
+ expect(result.scrapeOptions).toBeDefined();
+ });
+
+ it("should correctly infer MapRequest type", () => {
+ const result: MapRequest = mapRequestSchema.parse({
+ url: "https://example.com",
+ });
+
+ expect(typeof result.url).toBe("string");
+ expect(typeof result.limit).toBe("number");
+ });
+
+ it("should correctly infer BatchScrapeRequest type", () => {
+ const result: BatchScrapeRequest = batchScrapeRequestSchema.parse({
+ urls: ["https://example.com"],
+ });
+
+ expect(Array.isArray(result.urls)).toBe(true);
+ expect(result.urls.length).toBeGreaterThan(0);
+ });
+
+ it("should correctly infer SearchRequest type", () => {
+ const result: SearchRequest = searchRequestSchema.parse({
+ query: "test",
+ });
+
+ expect(typeof result.query).toBe("string");
+ expect(typeof result.limit).toBe("number");
+ });
+ });
+
+ describe("scrapeOptions schema", () => {
+ it("should accept valid scrape options", () => {
+ const input = {
+ formats: [{ type: "markdown" }, { type: "html" }],
+ onlyMainContent: false,
+ waitFor: 1000,
+ };
+
+ const result = scrapeOptions.parse(input);
+ expect(result.formats).toHaveLength(2);
+ expect(result.onlyMainContent).toBe(false);
+ expect(result.waitFor).toBe(1000);
+ });
+
+ it("should reject invalid actions wait time", () => {
+ const input = {
+ formats: [{ type: "markdown" }],
+ waitFor: 0,
+ actions: Array.from({ length: 100 }, () => ({
+ type: "wait" as const,
+ milliseconds: 1000,
+ })),
+ };
+
+ expect(() => scrapeOptions.parse(input)).toThrow(
+ "Total wait time (waitFor + wait actions) cannot exceed",
+ );
+ });
+ });
+
+ describe("Edge cases", () => {
+ it("should handle URL without protocol (should add http://)", () => {
+ const input = {
+ url: "example.com",
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ expect(result.url).toMatch(/^https?:\/\//);
+ });
+
+ it("should handle undefined integration (optional field)", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ // Integration transform converts undefined/falsy to null
+ expect(result.integration).toBeNull();
+ });
+
+ it("should handle changeTracking format timeout transformation", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ formats: [
+ { type: "markdown" },
+ {
+ type: "changeTracking",
+ schema: {
+ type: "object",
+ properties: {
+ changes: { type: "array" },
+ },
+ },
+ },
+ ],
+ timeout: 30000,
+ proxy: "basic", // Use basic proxy to avoid auto/stealth timeout transformation
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ expect(result.timeout).toBe(60000); // Should be transformed
+ expect(result.waitFor).toBeGreaterThanOrEqual(5000); // Should be at least 5000
+ });
+
+ it("should handle json format timeout transformation", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ formats: [
+ {
+ type: "json",
+ schema: {
+ type: "object",
+ properties: {
+ title: { type: "string" },
+ },
+ },
+ },
+ ],
+ timeout: 30000,
+ proxy: "basic", // Use basic proxy to avoid auto/stealth timeout transformation
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ expect(result.timeout).toBe(60000); // Should be transformed
+ });
+
+ it("should handle changeTrackingOptions with null tag", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ formats: [
+ { type: "markdown" },
+ {
+ type: "changeTracking",
+ tag: null,
+ },
+ ],
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ const changeTracking = result.formats.find(
+ f => typeof f === "object" && f.type === "changeTracking",
+ );
+ expect((changeTracking as any).tag).toBeNull();
+ });
+
+ it("should handle minAge and maxAge", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ minAge: 1000,
+ maxAge: 5000,
+ };
+
+ const result = scrapeRequestSchema.parse(input);
+ expect(result.minAge).toBe(1000);
+ expect(result.maxAge).toBe(5000);
+ });
+
+ it("should reject negative minAge", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ minAge: -1,
+ };
+
+ expect(() => scrapeRequestSchema.parse(input)).toThrow();
+ });
+
+ it("should reject negative maxAge", () => {
+ const input: ScrapeRequestInput = {
+ url: "https://example.com",
+ maxAge: -1,
+ };
+
+ expect(() => scrapeRequestSchema.parse(input)).toThrow();
+ });
+ });
+});
diff --git a/apps/api/src/controllers/v0/crawl-status.ts b/apps/api/src/controllers/v0/crawl-status.ts
index 048a56a8d..aea5775d3 100644
--- a/apps/api/src/controllers/v0/crawl-status.ts
+++ b/apps/api/src/controllers/v0/crawl-status.ts
@@ -11,6 +11,7 @@ import { toLegacyDocument } from "../v1/types";
import type { DBScrape, PseudoJob } from "../v1/crawl-status";
import { getJobFromGCS } from "../../lib/gcs-jobs";
import { scrapeQueue, NuQJob } from "../../services/worker/nuq";
+import { includesFormat } from "../../lib/format-utils";
configDotenv();
async function getJobs(
@@ -170,7 +171,7 @@ export async function crawlStatusController(req: Request, res: Response) {
jobs[0].data &&
jobs[0].data.scrapeOptions &&
jobs[0].data.scrapeOptions.formats &&
- !jobs[0].data.scrapeOptions.formats.includes("rawHtml")
+ !includesFormat(jobs[0].data.scrapeOptions.formats, "rawHtml")
) {
data.forEach(item => {
if (item) {
diff --git a/apps/api/src/controllers/v1/crawl.ts b/apps/api/src/controllers/v1/crawl.ts
index 39df4b6cd..b67415cd3 100644
--- a/apps/api/src/controllers/v1/crawl.ts
+++ b/apps/api/src/controllers/v1/crawl.ts
@@ -75,9 +75,12 @@ export async function crawlController(
url: undefined,
scrapeOptions: undefined,
};
+
+ const bodyScrapeOptions =
+ req.body.scrapeOptions ?? ({} as typeof req.body.scrapeOptions);
const { scrapeOptions, internalOptions } = fromV1ScrapeOptions(
- req.body.scrapeOptions,
- req.body.scrapeOptions.timeout,
+ bodyScrapeOptions,
+ bodyScrapeOptions.timeout,
req.auth.team_id,
);
diff --git a/apps/api/src/controllers/v1/extract.ts b/apps/api/src/controllers/v1/extract.ts
index 798ac4b89..cd3eb1218 100644
--- a/apps/api/src/controllers/v1/extract.ts
+++ b/apps/api/src/controllers/v1/extract.ts
@@ -17,7 +17,10 @@ import { performExtraction_F0 } from "../../lib/extract/fire-0/extraction-servic
import { BLOCKLISTED_URL_MESSAGE } from "../../lib/strings";
import { isUrlBlocked } from "../../scraper/WebScraper/utils/blocklist";
import { logger as _logger } from "../../lib/logger";
-import { fromV1ScrapeOptions } from "../v2/types";
+import {
+ fromV1ScrapeOptions,
+ ExtractRequest as V2ExtractRequest,
+} from "../v2/types";
import { createWebhookSender, WebhookEvent } from "../../services/webhook";
import { logRequest } from "../../services/logging/log_job";
@@ -39,18 +42,33 @@ async function oldExtract(
sender?.send(WebhookEvent.EXTRACT_STARTED, { success: true });
try {
+ // Convert v1 scrapeOptions to v2 format
+ const scrapeOptions = req.body.scrapeOptions
+ ? fromV1ScrapeOptions(
+ req.body.scrapeOptions,
+ req.body.scrapeOptions.timeout,
+ req.auth.team_id,
+ ).scrapeOptions
+ : undefined;
+
+ // Create request with converted scrapeOptions (v2 format)
+ const request: V2ExtractRequest = {
+ ...req.body,
+ scrapeOptions,
+ } as V2ExtractRequest;
+
let result: ExtractResult;
const model = req.body.agent?.model;
if (req.body.agent && model && model.toLowerCase().includes("fire-1")) {
result = await performExtraction(extractId, {
- request: req.body,
+ request,
teamId: req.auth.team_id,
subId: req.acuc?.sub_id ?? undefined,
apiKeyId: req.acuc?.api_key_id ?? null,
});
} else {
result = await performExtraction_F0(extractId, {
- request: req.body,
+ request,
teamId: req.auth.team_id,
subId: req.acuc?.sub_id ?? undefined,
apiKeyId: req.acuc?.api_key_id ?? null,
diff --git a/apps/api/src/controllers/v1/scrape.ts b/apps/api/src/controllers/v1/scrape.ts
index 050166915..d78c4af80 100644
--- a/apps/api/src/controllers/v1/scrape.ts
+++ b/apps/api/src/controllers/v1/scrape.ts
@@ -13,6 +13,7 @@ import { fromV1ScrapeOptions } from "../v2/types";
import { TransportableError } from "../../lib/error";
import { NuQJob } from "../../services/worker/nuq";
import { checkPermissions } from "../../lib/permissions";
+import { includesFormat } from "../../lib/format-utils";
import { teamConcurrencySemaphore } from "../../services/worker/team-semaphore";
import { processJobInternal } from "../../services/worker/scrape-worker";
import { ScrapeJobData } from "../../types";
@@ -205,7 +206,7 @@ export async function scrapeController(
logger.info("Removed job from queue");
- if (!req.body.formats.includes("rawHtml")) {
+ if (!includesFormat(req.body.formats, "rawHtml")) {
if (doc && doc.rawHtml) {
delete doc.rawHtml;
}
@@ -215,14 +216,14 @@ export async function scrapeController(
const controllerTime = new Date().getTime() - controllerStartTime;
let usedLlm =
- req.body.formats?.includes("json") ||
- req.body.formats?.includes("summary") ||
- req.body.formats?.includes("branding") ||
- req.body.formats?.includes("extract");
+ includesFormat(req.body.formats, "json") ||
+ includesFormat(req.body.formats, "summary") ||
+ includesFormat(req.body.formats, "branding") ||
+ includesFormat(req.body.formats, "extract");
if (
!usedLlm &&
- req.body.formats?.includes("changeTracking") &&
+ includesFormat(req.body.formats, "changeTracking") &&
req.body.changeTrackingOptions?.modes?.includes("json")
) {
usedLlm = true;
diff --git a/apps/api/src/controllers/v1/types.ts b/apps/api/src/controllers/v1/types.ts
index ce06468f5..c5f70f5e2 100644
--- a/apps/api/src/controllers/v1/types.ts
+++ b/apps/api/src/controllers/v1/types.ts
@@ -13,6 +13,7 @@ import { getURLDepth } from "../../scraper/WebScraper/utils/maxDepthUtils";
import Ajv from "ajv";
import { ErrorCodes } from "../../lib/error";
import { integrationSchema } from "../../utils/integration";
+import { includesFormat } from "../../lib/format-utils";
import { webhookSchema } from "../../services/webhook/schema";
import { BrandingProfile } from "../../types/branding";
@@ -48,7 +49,6 @@ export const url = z.preprocess(
return x;
},
z
- .string()
.url()
.regex(/^https?:\/\//i, "URL uses unsupported protocol")
.refine(x => {
@@ -79,9 +79,6 @@ export const url = z.preprocess(
// .refine((x) => !isUrlBlocked(x as string), BLOCKLISTED_URL_MESSAGE),
);
-const strictMessage =
- "Unrecognized key in body -- please review the v1 API documentation for request body changes";
-
const agentExtractModelValue = "fire-1";
export const isAgentExtractModelValid = (x: string | undefined) =>
x?.toLowerCase() === agentExtractModelValue;
@@ -180,15 +177,13 @@ function validateSchemaForOpenAI(schema: any): boolean {
const OPENAI_SCHEMA_ERROR_MESSAGE =
"Schema contains invalid structure for OpenAI: object type with no 'properties' defined but 'additionalProperties: true' (schema-less dictionary not supported by OpenAI). Please define specific properties for your object.";
-export const agentOptionsExtract = z
- .object({
- model: z.string().default(agentExtractModelValue),
- })
- .strict(strictMessage);
+export const agentOptionsExtract = z.strictObject({
+ model: z.string().prefault(agentExtractModelValue),
+});
export const extractOptions = z
- .object({
- mode: z.enum(["llm"]).default("llm"),
+ .strictObject({
+ mode: z.enum(["llm"]).prefault("llm"),
schema: z
.any()
.optional()
@@ -203,18 +198,17 @@ export const extractOptions = z
}
},
{
- message: "Invalid JSON schema.",
+ error: "Invalid JSON schema.",
},
)
.transform(val => normalizeSchemaForOpenAI(val))
.refine(val => validateSchemaForOpenAI(val), {
message: OPENAI_SCHEMA_ERROR_MESSAGE,
}),
- systemPrompt: z.string().max(10000).default(""),
+ systemPrompt: z.string().max(10000).prefault(""),
prompt: z.string().max(10000).optional(),
temperature: z.number().optional(),
})
- .strict(strictMessage)
.transform(data => ({
...data,
systemPrompt:
@@ -222,8 +216,8 @@ export const extractOptions = z
}));
const extractOptionsWithAgent = z
- .object({
- mode: z.enum(["llm"]).default("llm"),
+ .strictObject({
+ mode: z.enum(["llm"]).prefault("llm"),
schema: z
.any()
.optional()
@@ -238,24 +232,23 @@ const extractOptionsWithAgent = z
}
},
{
- message: "Invalid JSON schema.",
+ error: "Invalid JSON schema.",
},
)
.transform(val => normalizeSchemaForOpenAI(val))
.refine(val => validateSchemaForOpenAI(val), {
message: OPENAI_SCHEMA_ERROR_MESSAGE,
}),
- systemPrompt: z.string().max(10000).default(""),
+ systemPrompt: z.string().max(10000).prefault(""),
prompt: z.string().max(10000).optional(),
temperature: z.number().optional(),
agent: z
- .object({
- model: z.string().default(agentExtractModelValue),
+ .strictObject({
+ model: z.string().prefault(agentExtractModelValue),
prompt: z.string().optional(),
})
.optional(),
})
- .strict(strictMessage)
.transform(data => ({
...data,
systemPrompt: isAgentExtractModelValid(data.agent?.model)
@@ -277,6 +270,13 @@ Key Instructions:
}));
export type ExtractOptions = z.infer<typeof extractOptions>;
+// Explicitly define input type to make schema optional in input
+export type ExtractOptionsInput = Omit<
+ z.input<typeof extractOptions>,
+ "schema"
+> & {
+ schema?: z.input<typeof extractOptions>["schema"];
+};
const ACTIONS_MAX_WAIT_TIME = 60;
const MAX_ACTIONS = 50;
@@ -304,7 +304,7 @@ const actionSchema = z.union([
z
.object({
type: z.literal("wait"),
- milliseconds: z.number().int().positive().finite().optional(),
+ milliseconds: z.int().positive().finite().optional(),
selector: z.string().optional(),
})
.refine(
@@ -312,18 +312,18 @@ const actionSchema = z.union([
(data.milliseconds !== undefined || data.selector !== undefined) &&
!(data.milliseconds !== undefined && data.selector !== undefined),
{
- message:
+ error:
"Either 'milliseconds' or 'selector' must be provided, but not both.",
},
),
z.object({
type: z.literal("click"),
selector: z.string(),
- all: z.boolean().default(false),
+ all: z.boolean().prefault(false),
}),
z.object({
type: z.literal("screenshot"),
- fullPage: z.boolean().default(false),
+ fullPage: z.boolean().prefault(false),
quality: z.number().min(1).max(100).optional(),
}),
z.object({
@@ -336,7 +336,7 @@ const actionSchema = z.union([
}),
z.object({
type: z.literal("scroll"),
- direction: z.enum(["up", "down"]).optional().default("down"),
+ direction: z.enum(["up", "down"]).optional().prefault("down"),
selector: z.string().optional(),
}),
z.object({
@@ -348,8 +348,8 @@ const actionSchema = z.union([
}),
z.object({
type: z.literal("pdf"),
- landscape: z.boolean().default(false),
- scale: z.number().default(1),
+ landscape: z.boolean().prefault(false),
+ scale: z.number().prefault(1),
format: z
.enum([
"A0",
@@ -364,7 +364,7 @@ const actionSchema = z.union([
"Tabloid",
"Ledger",
])
- .default("Letter"),
+ .prefault("Letter"),
}),
]);
@@ -411,177 +411,144 @@ function transformIframeSelector(selector: string): string {
});
}
-const baseScrapeOptions = z
- .object({
- formats: z
- .enum([
- "markdown",
- "html",
- "rawHtml",
- "links",
- "screenshot",
- "screenshot@fullPage",
- "extract",
- "json",
- "summary",
- "changeTracking",
- "branding",
- ])
- .array()
- .optional()
- .default(["markdown"])
- .refine(
- x => !(x.includes("screenshot") && x.includes("screenshot@fullPage")),
- "You may only specify either screenshot or screenshot@fullPage",
- )
- .refine(
- x => !x.includes("changeTracking") || x.includes("markdown"),
- "The changeTracking format requires the markdown format to be specified as well",
- ),
- headers: z.record(z.string(), z.string()).optional(),
- includeTags: z
- .string()
- .array()
- .transform(tags => tags.map(transformIframeSelector))
- .optional(),
- excludeTags: z
- .string()
- .array()
- .transform(tags => tags.map(transformIframeSelector))
- .optional(),
- onlyMainContent: z.boolean().default(true),
- timeout: z.number().int().positive().finite().safe().optional(),
- waitFor: z
- .number()
- .int()
- .nonnegative()
- .finite()
- .safe()
- .max(60000)
- .default(0),
- // Deprecate this to jsonOptions
- extract: extractOptions.optional(),
- // New
- jsonOptions: extractOptions.optional(),
- changeTrackingOptions: z
- .object({
- prompt: z.string().optional(),
- schema: z
- .any()
- .optional()
- .refine(
- val => {
- if (!val) return true; // Allow undefined schema
- try {
- const validate = ajv.compile(val);
- return typeof validate === "function";
- } catch (e) {
- return false;
- }
- },
- {
- message: "Invalid JSON schema.",
- },
- )
- .transform(val => normalizeSchemaForOpenAI(val))
- .refine(val => validateSchemaForOpenAI(val), {
- message: OPENAI_SCHEMA_ERROR_MESSAGE,
- }),
- modes: z.enum(["json", "git-diff"]).array().optional().default([]),
- tag: z.string().or(z.null()).default(null),
- })
- .optional(),
- mobile: z.boolean().default(false),
- parsePDF: z.boolean().default(true),
- actions: actionsSchema.optional(),
- // New
- location: locationSchema,
-
- // Deprecated
- geolocation: z
- .object({
- country: z
- .string()
- .optional()
- .refine(
- val => !val || Object.keys(countries).includes(val.toUpperCase()),
- {
- message:
- "Invalid country code. Please use a valid ISO 3166-1 alpha-2 country code.",
- },
- )
- .transform(val => (val ? val.toUpperCase() : "US-generic")),
- languages: z.string().array().optional(),
- })
- .optional(),
- skipTlsVerification: z.boolean().optional(),
- removeBase64Images: z.boolean().default(true),
- fastMode: z.boolean().default(false),
- useMock: z.string().optional(),
- blockAds: z.boolean().default(true),
- proxy: z.enum(["basic", "stealth", "auto"]).default("basic"),
- maxAge: z
- .number()
- .int()
- .gte(0)
- .safe()
- .default(1 * 24 * 60 * 60 * 1000),
- storeInCache: z.boolean().default(true),
- // @deprecated
- __experimental_cache: z.boolean().default(false).optional(),
- __searchPreviewToken: z.string().optional(),
- __experimental_omce: z.boolean().default(false).optional(),
- __experimental_omceDomain: z.string().optional(),
- })
- .strict(strictMessage);
+const baseScrapeOptions = z.strictObject({
+ formats: z
+ .enum([
+ "markdown",
+ "html",
+ "rawHtml",
+ "links",
+ "screenshot",
+ "screenshot@fullPage",
+ "extract",
+ "json",
+ "summary",
+ "changeTracking",
+ "branding",
+ ])
+ .array()
+ .optional()
+ .prefault(["markdown"])
+ .refine(
+ x => !(x.includes("screenshot") && x.includes("screenshot@fullPage")),
+ "You may only specify either screenshot or screenshot@fullPage",
+ )
+ .refine(
+ x => !x.includes("changeTracking") || x.includes("markdown"),
+ "The changeTracking format requires the markdown format to be specified as well",
+ ),
+ headers: z.record(z.string(), z.string()).optional(),
+ includeTags: z
+ .string()
+ .array()
+ .transform(tags => tags.map(transformIframeSelector))
+ .optional(),
+ excludeTags: z
+ .string()
+ .array()
+ .transform(tags => tags.map(transformIframeSelector))
+ .optional(),
+ onlyMainContent: z.boolean().prefault(true),
+ timeout: z.int().positive().finite().optional(),
+ waitFor: z.int().nonnegative().finite().max(60000).prefault(0),
+ // Deprecate this to jsonOptions
+ extract: extractOptions.optional(),
+ // New
+ jsonOptions: extractOptions.optional(),
+ changeTrackingOptions: z
+ .strictObject({
+ prompt: z.string().optional(),
+ schema: z
+ .any()
+ .optional()
+ .refine(
+ val => {
+ if (!val) return true; // Allow undefined schema
+ try {
+ const validate = ajv.compile(val);
+ return typeof validate === "function";
+ } catch (e) {
+ return false;
+ }
+ },
+ {
+ error: "Invalid JSON schema.",
+ },
+ )
+ .transform(val => normalizeSchemaForOpenAI(val))
+ .refine(val => validateSchemaForOpenAI(val), {
+ message: OPENAI_SCHEMA_ERROR_MESSAGE,
+ }),
+ modes: z.enum(["json", "git-diff"]).array().optional().prefault([]),
+ tag: z.string().or(z.null()).prefault(null),
+ })
+ .optional(),
+ mobile: z.boolean().prefault(false),
+ parsePDF: z.boolean().prefault(true),
+ actions: actionsSchema.optional(),
+ // New
+ location: locationSchema,
+
+ // Deprecated
+ geolocation: z
+ .strictObject({
+ country: z
+ .string()
+ .optional()
+ .refine(
+ val => !val || Object.keys(countries).includes(val.toUpperCase()),
+ {
+ error:
+ "Invalid country code. Please use a valid ISO 3166-1 alpha-2 country code.",
+ },
+ )
+ .transform(val => (val ? val.toUpperCase() : "US-generic")),
+ languages: z.string().array().optional(),
+ })
+ .optional(),
+ skipTlsVerification: z.boolean().optional(),
+ removeBase64Images: z.boolean().prefault(true),
+ fastMode: z.boolean().prefault(false),
+ useMock: z.string().optional(),
+ blockAds: z.boolean().prefault(true),
+ proxy: z.enum(["basic", "stealth", "auto"]).prefault("basic"),
+ maxAge: z
+ .int()
+ .gte(0)
+ .prefault(1 * 24 * 60 * 60 * 1000),
+ storeInCache: z.boolean().prefault(true),
+ // @deprecated
+ __experimental_cache: z.boolean().prefault(false).optional(),
+ __searchPreviewToken: z.string().optional(),
+ __experimental_omce: z.boolean().prefault(false).optional(),
+ __experimental_omceDomain: z.string().optional(),
+});
-const fire1Refine = obj => {
- if (
- obj.agent?.model?.toLowerCase() === "fire-1" &&
- obj.jsonOptions?.agent?.model?.toLowerCase() === "fire-1"
- ) {
- return false;
- }
- return true;
-};
const fire1RefineOpts = {
message:
"You may only specify the FIRE-1 model in agent or jsonOptions.agent, but not both.",
-};
-const waitForRefine = obj => {
- if (obj.waitFor && obj.timeout) {
- if (typeof obj.timeout !== "number" || obj.timeout <= 0) {
- return false;
- }
- return obj.waitFor <= obj.timeout / 2;
- }
- return true;
-};
+} as const;
+
const waitForRefineOpts = {
message: "waitFor must not exceed half of timeout",
- path: ["waitFor"],
-};
-const extractRefine = obj => {
- const hasExtractFormat = obj.formats?.includes("extract");
- const hasExtractOptions = obj.extract !== undefined;
- const hasJsonFormat = obj.formats?.includes("json");
- const hasJsonOptions = obj.jsonOptions !== undefined;
- return (
- ((hasExtractFormat && hasExtractOptions) ||
- (!hasExtractFormat && !hasExtractOptions)) &&
- ((hasJsonFormat && hasJsonOptions) || (!hasJsonFormat && !hasJsonOptions))
- );
+ path: ["waitFor"] as PropertyKey[],
};
+
const extractRefineOpts = {
message:
"When 'extract' or 'json' format is specified, corresponding options must be provided, and vice versa",
+} as const;
+// Type-safe wrapper for non-nullable cases (used in required scrapeOptions schema)
+const extractTransformRequired = <T extends ScrapeOptions>(obj: T): T => {
+ return extractTransform(obj) as T;
};
+
const extractTransform = (obj: ScrapeOptions) => {
// Handle timeout
if (
- (obj.formats?.includes("extract") ||
+ (includesFormat(obj.formats, "extract") ||
obj.extract ||
- obj.formats?.includes("json") ||
+ includesFormat(obj.formats, "json") ||
obj.jsonOptions) &&
obj.timeout === 30000
) {
@@ -589,13 +556,13 @@ const extractTransform = (obj: ScrapeOptions) => {
}
if (
- obj.formats?.includes("changeTracking") &&
+ includesFormat(obj.formats, "changeTracking") &&
(obj.waitFor === undefined || obj.waitFor < 5000)
) {
obj = { ...obj, waitFor: 5000 };
}
- if (obj.formats?.includes("changeTracking") && obj.timeout === 30000) {
+ if (includesFormat(obj.formats, "changeTracking") && obj.timeout === 30000) {
obj = { ...obj, timeout: 60000 };
}
@@ -610,7 +577,7 @@ const extractTransform = (obj: ScrapeOptions) => {
obj = { ...obj, timeout: 120000 };
}
- if (obj.formats?.includes("json")) {
+ if (includesFormat(obj.formats, "json")) {
obj.formats.push("extract");
}
@@ -625,20 +592,55 @@ const extractTransform = (obj: ScrapeOptions) => {
return obj;
};
-export const scrapeOptions = baseScrapeOptions
- .extend({
- agent: z
- .object({
- model: z.string().default(agentExtractModelValue),
- prompt: z.string(),
- sessionId: z.string().optional(),
- waitBeforeClosingMs: z.number().optional(),
- })
- .optional(),
- extract: extractOptionsWithAgent.optional(),
- jsonOptions: extractOptionsWithAgent.optional(),
- })
- .strict(strictMessage)
+const scrapeOptionsBase = baseScrapeOptions.extend({
+ agent: z
+ .object({
+ model: z.string().prefault(agentExtractModelValue),
+ prompt: z.string(),
+ sessionId: z.string().optional(),
+ waitBeforeClosingMs: z.number().optional(),
+ })
+ .optional(),
+ extract: extractOptionsWithAgent.optional(),
+ jsonOptions: extractOptionsWithAgent.optional(),
+});
+
+type ScrapeOptionsBase = z.infer<typeof scrapeOptionsBase>;
+
+const fire1Refine = (obj: ScrapeOptionsBase): boolean => {
+ if (
+ obj.agent?.model?.toLowerCase() === "fire-1" &&
+ obj.jsonOptions?.agent?.model?.toLowerCase() === "fire-1"
+ ) {
+ return false;
+ }
+ return true;
+};
+
+const waitForRefine = (obj?: ScrapeOptionsBase): boolean => {
+ if (obj && obj.waitFor !== undefined && obj.timeout !== undefined) {
+ if (typeof obj.timeout !== "number" || obj.timeout <= 0) {
+ return false;
+ }
+ return obj.waitFor <= obj.timeout / 2;
+ }
+ return true;
+};
+
+const extractRefine = (obj: ScrapeOptionsBase): boolean => {
+ const hasExtractFormat = includesFormat(obj.formats, "extract");
+ const hasExtractOptions = obj.extract !== undefined;
+ const hasJsonFormat = includesFormat(obj.formats, "json");
+ const hasJsonOptions = obj.jsonOptions !== undefined;
+ return (
+ ((hasExtractFormat && hasExtractOptions) ||
+ (!hasExtractFormat && !hasExtractOptions)) &&
+ ((hasJsonFormat && hasJsonOptions) || (!hasJsonFormat && !hasJsonOptions))
+ );
+};
+
+export const scrapeOptions = scrapeOptionsBase
+ .strict()
.refine(
obj => {
if (!obj.actions) return true;
@@ -674,7 +676,7 @@ export type ScrapeOptions = BaseScrapeOptions & {
const ajv = new Ajv();
const extractV1Options = z
- .object({
+ .strictObject({
urls: url
.array()
.max(10, "Maximum of 10 URLs allowed per request while in beta.")
@@ -695,42 +697,41 @@ const extractV1Options = z
}
},
{
- message: "Invalid JSON schema.",
+ error: "Invalid JSON schema.",
},
)
.transform(val => normalizeSchemaForOpenAI(val))
.refine(val => validateSchemaForOpenAI(val), {
message: OPENAI_SCHEMA_ERROR_MESSAGE,
}),
- limit: z.number().int().positive().finite().safe().optional(),
- ignoreSitemap: z.boolean().default(false),
- includeSubdomains: z.boolean().default(true),
- allowExternalLinks: z.boolean().default(false),
- enableWebSearch: z.boolean().default(false),
+ limit: z.int().positive().finite().optional(),
+ ignoreSitemap: z.boolean().prefault(false),
+ includeSubdomains: z.boolean().prefault(true),
+ allowExternalLinks: z.boolean().prefault(false),
+ enableWebSearch: z.boolean().prefault(false),
scrapeOptions: baseScrapeOptions
- .default({ onlyMainContent: false })
+ .prefault({ onlyMainContent: false })
.optional(),
- origin: z.string().optional().default("api"),
+ origin: z.string().optional().prefault("api"),
integration: integrationSchema.optional().transform(val => val || null),
- urlTrace: z.boolean().default(false),
- timeout: z.number().int().positive().finite().safe().default(60000),
- __experimental_streamSteps: z.boolean().default(false),
- __experimental_llmUsage: z.boolean().default(false),
- __experimental_showSources: z.boolean().default(false),
- showSources: z.boolean().default(false),
+ urlTrace: z.boolean().prefault(false),
+ timeout: z.int().positive().finite().prefault(60000),
+ __experimental_streamSteps: z.boolean().prefault(false),
+ __experimental_llmUsage: z.boolean().prefault(false),
+ __experimental_showSources: z.boolean().prefault(false),
+ showSources: z.boolean().prefault(false),
__experimental_cacheKey: z.string().optional(),
__experimental_cacheMode: z
.enum(["direct", "save", "load"])
- .default("direct")
+ .prefault("direct")
.optional(),
agent: agentOptionsExtract.optional(),
- __experimental_showCostTracking: z.boolean().default(false),
- ignoreInvalidURLs: z.boolean().default(false),
+ __experimental_showCostTracking: z.boolean().prefault(false),
+ ignoreInvalidURLs: z.boolean().prefault(false),
webhook: webhookSchema.optional(),
})
- .strict(strictMessage)
.refine(obj => obj.urls || obj.prompt, {
- message: "Either 'urls' or 'prompt' must be provided.",
+ error: "Either 'urls' or 'prompt' must be provided.",
})
.transform(obj => ({
...obj,
@@ -759,13 +760,13 @@ export const extractRequestSchema = extractV1Options;
export type ExtractRequest = z.infer<typeof extractRequestSchema>;
export type ExtractRequestInput = z.input<typeof extractRequestSchema>;
-export const scrapeRequestSchema = baseScrapeOptions
+const scrapeRequestSchemaBase = baseScrapeOptions
.omit({ timeout: true })
.extend({
url,
agent: z
.object({
- model: z.string().default(agentExtractModelValue),
+ model: z.string().prefault(agentExtractModelValue),
prompt: z.string(),
sessionId: z.string().optional(),
waitBeforeClosingMs: z.number().optional(),
@@ -773,12 +774,14 @@ export const scrapeRequestSchema = baseScrapeOptions
.optional(),
extract: extractOptionsWithAgent.optional(),
jsonOptions: extractOptionsWithAgent.optional(),
- origin: z.string().optional().default("api"),
+ origin: z.string().optional().prefault("api"),
integration: integrationSchema.optional().transform(val => val || null),
- timeout: z.number().int().positive().finite().safe().default(30000),
+ timeout: z.int().positive().finite().prefault(30000),
zeroDataRetention: z.boolean().optional(),
})
- .strict(strictMessage)
+ .strict();
+
+export const scrapeRequestSchema = scrapeRequestSchemaBase
.refine(extractRefine, extractRefineOpts)
.refine(fire1Refine, fire1RefineOpts)
.refine(waitForRefine, waitForRefineOpts)
@@ -789,62 +792,63 @@ export const scrapeRequestSchema = baseScrapeOptions
export type ScrapeRequest = z.infer<typeof scrapeRequestSchema>;
export type ScrapeRequestInput = z.input<typeof scrapeRequestSchema>;
-export const batchScrapeRequestSchema = baseScrapeOptions
- .extend({
- urls: url.array().min(1),
- origin: z.string().optional().default("api"),
- integration: integrationSchema.optional().transform(val => val || null),
- webhook: webhookSchema.optional(),
- appendToId: z.string().uuid().optional(),
- ignoreInvalidURLs: z.boolean().default(false),
- maxConcurrency: z.number().positive().int().optional(),
- zeroDataRetention: z.boolean().optional(),
- })
- .strict(strictMessage)
- .refine(extractRefine, extractRefineOpts)
- .refine(fire1Refine, fire1RefineOpts)
- .refine(waitForRefine, waitForRefineOpts)
- .transform(obj => extractTransform(obj) as typeof obj);
+const batchScrapeRequestSchemaBase = baseScrapeOptions.extend({
+ urls: url.array().min(1),
+ origin: z.string().optional().prefault("api"),
+ integration: integrationSchema.optional().transform(val => val || null),
+ webhook: webhookSchema.optional(),
+ appendToId: z.uuid().optional(),
+ ignoreInvalidURLs: z.boolean().prefault(false),
+ maxConcurrency: z.int().positive().optional(),
+ zeroDataRetention: z.boolean().optional(),
+});
-export const batchScrapeRequestSchemaNoURLValidation = baseScrapeOptions
- .extend({
- urls: z.string().array().min(1),
- origin: z.string().optional().default("api"),
- integration: integrationSchema.optional().transform(val => val || null),
- webhook: webhookSchema.optional(),
- appendToId: z.string().uuid().optional(),
- ignoreInvalidURLs: z.boolean().default(false),
- maxConcurrency: z.number().positive().int().optional(),
- zeroDataRetention: z.boolean().optional(),
- })
- .strict(strictMessage)
+export const batchScrapeRequestSchema = batchScrapeRequestSchemaBase
+ .strict()
.refine(extractRefine, extractRefineOpts)
.refine(fire1Refine, fire1RefineOpts)
.refine(waitForRefine, waitForRefineOpts)
.transform(obj => extractTransform(obj) as typeof obj);
+const batchScrapeRequestSchemaNoURLValidationBase = baseScrapeOptions.extend({
+ urls: z.string().array().min(1),
+ origin: z.string().optional().prefault("api"),
+ integration: integrationSchema.optional().transform(val => val || null),
+ webhook: webhookSchema.optional(),
+ appendToId: z.uuid().optional(),
+ ignoreInvalidURLs: z.boolean().prefault(false),
+ maxConcurrency: z.int().positive().optional(),
+ zeroDataRetention: z.boolean().optional(),
+});
+
+export const batchScrapeRequestSchemaNoURLValidation =
+ batchScrapeRequestSchemaNoURLValidationBase
+ .strict()
+ .refine(extractRefine, extractRefineOpts)
+ .refine(fire1Refine, fire1RefineOpts)
+ .refine(waitForRefine, waitForRefineOpts)
+ .transform(obj => extractTransform(obj) as typeof obj);
+
export type BatchScrapeRequest = z.infer<typeof batchScrapeRequestSchema>;
export type BatchScrapeRequestInput = z.input<typeof batchScrapeRequestSchema>;
-const crawlerOptions = z
- .object({
- includePaths: z.string().array().default([]),
- excludePaths: z.string().array().default([]),
- maxDepth: z.number().default(10), // default?
- maxDiscoveryDepth: z.number().optional(),
- limit: z.number().default(10000), // default?
- allowBackwardLinks: z.boolean().default(false), // DEPRECATED: use crawlEntireDomain
- crawlEntireDomain: z.boolean().optional(),
- allowExternalLinks: z.boolean().default(false),
- allowSubdomains: z.boolean().default(false),
- ignoreRobotsTxt: z.boolean().default(false),
- ignoreSitemap: z.boolean().default(false),
- deduplicateSimilarURLs: z.boolean().default(true),
- ignoreQueryParameters: z.boolean().default(false),
- regexOnFullURL: z.boolean().default(false),
- delay: z.number().positive().optional(),
- })
- .strict(strictMessage);
+const crawlerOptions = z.strictObject({
+ includePaths: z.string().array().prefault([]),
+ excludePaths: z.string().array().prefault([]),
+ maxDepth: z.number().prefault(10), // default?
+ maxDiscoveryDepth: z.number().optional(),
+ limit: z.number().prefault(10000), // default?
+ allowBackwardLinks: z.boolean().prefault(false), // DEPRECATED: use crawlEntireDomain
+ crawlEntireDomain: z.boolean().optional(),
+ allowExternalLinks: z.boolean().prefault(false),
+ allowSubdomains: z.boolean().prefault(false),
+ ignoreRobotsTxt: z.boolean().prefault(false),
+ ignoreSitemap: z.boolean().prefault(false),
+ deduplicateSimilarURLs: z.boolean().prefault(true),
+ ignoreQueryParameters: z.boolean().prefault(false),
+ regexOnFullURL: z.boolean().prefault(false),
+ delay: z.number().positive().optional(),
+});
// export type CrawlerOptions = {
// includePaths?: string[];
@@ -859,21 +863,31 @@ const crawlerOptions = z
type CrawlerOptions = z.infer<typeof crawlerOptions>;
-export const crawlRequestSchema = crawlerOptions
- .extend({
- url,
- origin: z.string().optional().default("api"),
- integration: integrationSchema.optional().transform(val => val || null),
- scrapeOptions: baseScrapeOptions.default({}),
- webhook: webhookSchema.optional(),
- limit: z.number().default(10000),
- maxConcurrency: z.number().positive().int().optional(),
- zeroDataRetention: z.boolean().optional(),
- })
- .strict(strictMessage)
- .refine(x => extractRefine(x.scrapeOptions), extractRefineOpts)
- .refine(x => fire1Refine(x.scrapeOptions), fire1RefineOpts)
- .refine(x => waitForRefine(x.scrapeOptions), waitForRefineOpts)
+const crawlRequestSchemaBase = crawlerOptions.extend({
+ url,
+ origin: z.string().optional().prefault("api"),
+ integration: integrationSchema.optional().transform(val => val || null),
+ scrapeOptions: baseScrapeOptions.prefault(() => baseScrapeOptions.parse({})),
+ webhook: webhookSchema.optional(),
+ limit: z.number().prefault(10000),
+ maxConcurrency: z.int().positive().optional(),
+ zeroDataRetention: z.boolean().optional(),
+});
+
+export const crawlRequestSchema = crawlRequestSchemaBase
+ .strict()
+ .refine(
+ x => (x.scrapeOptions ? extractRefine(x.scrapeOptions) : true),
+ extractRefineOpts,
+ )
+ .refine(
+ x => (x.scrapeOptions ? fire1Refine(x.scrapeOptions) : true),
+ fire1RefineOpts,
+ )
+ .refine(
+ x => (x.scrapeOptions ? waitForRefine(x.scrapeOptions) : true),
+ waitForRefineOpts,
+ )
.refine(
data => {
try {
@@ -892,9 +906,10 @@ export const crawlRequestSchema = crawlerOptions
if (x.crawlEntireDomain !== undefined) {
x.allowBackwardLinks = x.crawlEntireDomain;
}
+ const scrapeOptionsValue = x.scrapeOptions ?? baseScrapeOptions.parse({});
return {
...x,
- scrapeOptions: extractTransform(x.scrapeOptions),
+ scrapeOptions: extractTransformRequired(scrapeOptionsValue),
};
});
@@ -916,25 +931,26 @@ export type CrawlRequestInput = z.input<typeof crawlRequestSchema>;
export const MAX_MAP_LIMIT = 100000;
// Note: Map types have been transitioned to v2/types.ts while maintaining backwards compatibility
-export const mapRequestSchema = crawlerOptions
+const mapRequestSchemaBase = crawlerOptions
.omit({ ignoreQueryParameters: true })
.extend({
url,
- origin: z.string().optional().default("api"),
+ origin: z.string().optional().prefault("api"),
integration: integrationSchema.optional().transform(val => val || null),
- includeSubdomains: z.boolean().default(true),
+ includeSubdomains: z.boolean().prefault(true),
search: z.string().optional(),
- ignoreQueryParameters: z.boolean().default(true),
- ignoreSitemap: z.boolean().default(false),
- sitemapOnly: z.boolean().default(false),
- limit: z.number().min(1).max(MAX_MAP_LIMIT).default(5000),
+ ignoreQueryParameters: z.boolean().prefault(true),
+ ignoreSitemap: z.boolean().prefault(false),
+ sitemapOnly: z.boolean().prefault(false),
+ limit: z.number().min(1).max(MAX_MAP_LIMIT).prefault(5000),
timeout: z.number().positive().finite().optional(),
useMock: z.string().optional(),
- filterByPath: z.boolean().default(true),
- useIndex: z.boolean().default(true),
+ filterByPath: z.boolean().prefault(true),
+ useIndex: z.boolean().prefault(true),
location: locationSchema,
- })
- .strict(strictMessage);
+ });
+
+export const mapRequestSchema = mapRequestSchemaBase.strict();
// export type MapRequest = {
// url: string;
@@ -1456,26 +1472,18 @@ export function toLegacyDocument(
}
export const searchRequestSchema = z
- .object({
+ .strictObject({
query: z.string(),
- limit: z
- .number()
- .int()
- .positive()
- .finite()
- .safe()
- .max(100)
- .optional()
- .default(5),
+ limit: z.int().positive().finite().max(100).optional().prefault(5),
tbs: z.string().optional(),
filter: z.string().optional(),
- lang: z.string().optional().default("en"),
+ lang: z.string().optional().prefault("en"),
country: z.string().optional(),
location: z.string().optional(),
- origin: z.string().optional().default("api"),
+ origin: z.string().optional().prefault("api"),
integration: integrationSchema.optional().transform(val => val || null),
- timeout: z.number().int().positive().finite().safe().default(60000),
- ignoreInvalidURLs: z.boolean().optional().default(false),
+ timeout: z.int().positive().finite().prefault(60000),
+ ignoreInvalidURLs: z.boolean().optional().prefault(false),
__searchPreviewToken: z.string().optional(),
scrapeOptions: baseScrapeOptions
.extend({
@@ -1492,13 +1500,10 @@ export const searchRequestSchema = z
"json",
]),
)
- .default([]),
+ .prefault([]),
})
- .default({}),
+ .prefault({}),
})
- .strict(
- "Unrecognized key in body -- please review the v1 API documentation for request body changes",
- )
.refine(x => extractRefine(x.scrapeOptions), extractRefineOpts)
.refine(x => fire1Refine(x.scrapeOptions), fire1RefineOpts)
.refine(x => waitForRefine(x.scrapeOptions), waitForRefineOpts)
@@ -1534,15 +1539,15 @@ export const generateLLMsTextRequestSchema = z.object({
.number()
.min(1)
.max(5000)
- .default(10)
+ .prefault(10)
.describe("Maximum number of URLs to process"),
showFullText: z
.boolean()
- .default(false)
+ .prefault(false)
.describe("Whether to show the full LLMs-full.txt in the response"),
cache: z
.boolean()
- .default(true)
+ .prefault(true)
.describe("Whether to use cached content if available"),
__experimental_stream: z.boolean().optional(),
});
diff --git a/apps/api/src/controllers/v2/batch-scrape.ts b/apps/api/src/controllers/v2/batch-scrape.ts
index 02ca01a16..e530df0c3 100644
--- a/apps/api/src/controllers/v2/batch-scrape.ts
+++ b/apps/api/src/controllers/v2/batch-scrape.ts
@@ -48,7 +48,7 @@ export async function batchScrapeController(
}
const zeroDataRetention =
- req.acuc?.flags?.forceZDR || req.body.zeroDataRetention;
+ req.acuc?.flags?.forceZDR ?? req.body.zeroDataRetention ?? false;
const id = req.body.appendToId ?? uuidv7();
const logger = _logger.child({
diff --git a/apps/api/src/controllers/v2/crawl-params-preview.ts b/apps/api/src/controllers/v2/crawl-params-preview.ts
index 0f478d70d..cdeaf2b28 100644
--- a/apps/api/src/controllers/v2/crawl-params-preview.ts
+++ b/apps/api/src/controllers/v2/crawl-params-preview.ts
@@ -9,7 +9,7 @@ import { buildPromptWithWebsiteStructure } from "../../lib/map-utils";
// Define the request schema for params preview
// Only url and prompt are required/relevant for preview
const crawlParamsPreviewRequestSchema = z.object({
- url: z.string().url(),
+ url: z.url(),
prompt: z.string().max(10000),
});
@@ -117,7 +117,7 @@ export async function crawlParamsPreviewController(
code: "BAD_REQUEST",
error:
"Invalid request parameters: " +
- error.errors.map(e => e.message).join(", "),
+ error.issues.map(e => e.message).join(", "),
});
}
diff --git a/apps/api/src/controllers/v2/f-search.ts b/apps/api/src/controllers/v2/f-search.ts
index 67b56a2ee..23cc3c8ba 100644
--- a/apps/api/src/controllers/v2/f-search.ts
+++ b/apps/api/src/controllers/v2/f-search.ts
@@ -11,9 +11,12 @@ import {
// Validation schemas
const searchRequestSchema = z.object({
query: z.string().min(1).max(500),
- limit: z.number().int().min(1).max(100).optional().default(50),
- offset: z.number().int().min(0).optional().default(0),
- mode: z.enum(["hybrid", "keyword", "semantic", "bm25"]).optional().default("hybrid"),
+ limit: z.int().min(1).max(100).optional().prefault(50),
+ offset: z.int().min(0).optional().prefault(0),
+ mode: z
+ .enum(["hybrid", "keyword", "semantic", "bm25"])
+ .optional()
+ .prefault("hybrid"),
filters: z
.object({
domain: z.string().optional(),
@@ -23,18 +26,18 @@ const searchRequestSchema = z.object({
language: z.string().optional(),
})
.optional()
- .default({}),
+ .prefault({}),
});
const searchChunksRequestSchema = z.object({
query: z.string().min(1).max(500),
- limit: z.number().int().min(1).max(50).optional().default(20),
+ limit: z.int().min(1).max(50).optional().prefault(20),
filters: z
.object({
domain: z.string().optional(),
})
.optional()
- .default({}),
+ .prefault({}),
});
export async function realtimeSearchController(
@@ -55,7 +58,7 @@ export async function realtimeSearchController(
res.status(400).json({
success: false,
error: "Invalid request parameters",
- details: validationResult.error.errors,
+ details: validationResult.error.issues,
});
return;
}
@@ -71,7 +74,7 @@ export async function realtimeSearchController(
// Get search index client
const client = getSearchIndexClient();
-
+
if (!client) {
res.status(503).json({
success: false,
diff --git a/apps/api/src/controllers/v2/scrape.ts b/apps/api/src/controllers/v2/scrape.ts
index 34e524573..af2d5556d 100644
--- a/apps/api/src/controllers/v2/scrape.ts
+++ b/apps/api/src/controllers/v2/scrape.ts
@@ -77,7 +77,7 @@ export async function scrapeController(
}
const zeroDataRetention =
- req.acuc?.flags?.forceZDR || req.body.zeroDataRetention;
+ req.acuc?.flags?.forceZDR ?? req.body.zeroDataRetention ?? false;
const logger = _logger.child({
method: "scrapeController",
@@ -169,7 +169,7 @@ export async function scrapeController(
async waitSpan => {
setSpanAttributes(waitSpan, {
"wait.timeout":
- timeout !== undefined ? timeout + totalWait : null,
+ timeout !== undefined ? timeout + totalWait : undefined,
"wait.job_id": jobId,
});
@@ -185,7 +185,7 @@ export async function scrapeController(
team_id: req.auth.team_id,
scrapeOptions: {
...req.body,
- ...(req.body.__experimental_cache
+ ...((req.body as any).__experimental_cache
? {
maxAge: req.body.maxAge ?? 4 * 60 * 60 * 1000, // 4 hours
}
diff --git a/apps/api/src/controllers/v2/search.ts b/apps/api/src/controllers/v2/search.ts
index 957cd336f..98f171084 100644
--- a/apps/api/src/controllers/v2/search.ts
+++ b/apps/api/src/controllers/v2/search.ts
@@ -343,7 +343,7 @@ export async function searchController(
// Check if scraping is requested
const shouldScrape =
- req.body.scrapeOptions.formats &&
+ req.body.scrapeOptions?.formats &&
req.body.scrapeOptions.formats.length > 0;
const isAsyncScraping = req.body.asyncScraping && shouldScrape;
@@ -356,12 +356,25 @@ export async function searchController(
`Starting ${isAsyncScraping ? "async" : "sync"} search scraping`,
);
+ // Safely extract scrapeOptions with runtime check
+ if (!req.body.scrapeOptions) {
+ logger.error(
+ "scrapeOptions is undefined despite shouldScrape being true",
+ );
+ return res.status(500).json({
+ success: false,
+ error: "Internal server error: scrapeOptions is missing",
+ });
+ }
+
+ const bodyScrapeOptions = req.body.scrapeOptions;
+
// Create common options
const scrapeOptions = {
teamId: req.auth.team_id,
origin: req.body.origin,
timeout: req.body.timeout,
- scrapeOptions: req.body.scrapeOptions,
+ scrapeOptions: bodyScrapeOptions,
bypassBilling: !isAsyncScraping, // Async mode bills per job, sync mode bills manually
apiKeyId: req.acuc?.api_key_id ?? null,
zeroDataRetention: isZDROrAnon,
@@ -615,10 +628,11 @@ export async function searchController(
}
// Calculate credits
+ // bodyScrapeOptions is guaranteed to exist here because we're in the shouldScrape block
const creditPromises = allDocsWithCostTracking.map(
async docWithCost => {
return await calculateCreditsToBeBilled(
- req.body.scrapeOptions,
+ bodyScrapeOptions,
{
teamId: req.auth.team_id,
bypassBilling: true,
@@ -724,11 +738,11 @@ export async function searchController(
});
} catch (error) {
if (error instanceof z.ZodError) {
- logger.warn("Invalid request body", { error: error.errors });
+ logger.warn("Invalid request body", { error: error.issues });
return res.status(400).json({
success: false,
error: "Invalid request body",
- details: error.errors,
+ details: error.issues,
});
}
diff --git a/apps/api/src/controllers/v2/types.ts b/apps/api/src/controllers/v2/types.ts
index 093b2f1bc..f03d4d146 100644
--- a/apps/api/src/controllers/v2/types.ts
+++ b/apps/api/src/controllers/v2/types.ts
@@ -2,6 +2,7 @@ import { Request, Response } from "express";
import { z } from "zod";
import { protocolIncluded, checkUrl } from "../../lib/validateUrl";
import { countries } from "../../lib/validate-country";
+import { includesFormat } from "../../lib/format-utils";
import {
ExtractorOptions,
PageOptions,
@@ -42,7 +43,6 @@ const BASE_URL_SCHEMA = z.preprocess(
return x;
},
z
- .string()
.url()
.regex(/^https?:\/\//i, "URL uses unsupported protocol")
.refine(x => {
@@ -82,6 +82,17 @@ const CRAWL_URL = BASE_URL_SCHEMA.transform(url => modifyCrawlUrl(url));
const strictMessage =
"Unrecognized key in body -- please review the v2 API documentation for request body changes";
+// Helper function to add strict validation
+// In zod v4, .strict() doesn't accept arguments
+// The custom error message is handled in the error handler (see src/index.ts)
+// We use a type assertion to preserve the input type so optional fields with defaults remain optional
+// The 'as any' is necessary because zod v4's .strict() changes type inference in a way that makes
+// optional fields with defaults appear required, even though they're not at runtime
+function strictWithMessage<T extends z.ZodObject<any>>(schema: T): T {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ return schema.strict() as any as T;
+}
+
function normalizeSchemaForOpenAI(schema: any): any {
if (!schema || typeof schema !== "object") {
return schema;
@@ -248,7 +259,7 @@ const actionSchema = z.union([
z
.object({
type: z.literal("wait"),
- milliseconds: z.number().int().positive().finite().optional(),
+ milliseconds: z.int().positive().finite().optional(),
selector: z.string().optional(),
})
.refine(
@@ -256,23 +267,23 @@ const actionSchema = z.union([
(data.milliseconds !== undefined || data.selector !== undefined) &&
!(data.milliseconds !== undefined && data.selector !== undefined),
{
- message:
+ error:
"Either 'milliseconds' or 'selector' must be provided, but not both.",
},
),
z.object({
type: z.literal("click"),
selector: z.string(),
- all: z.boolean().default(false),
+ all: z.boolean().prefault(false),
}),
z.object({
type: z.literal("screenshot"),
- fullPage: z.boolean().default(false),
+ fullPage: z.boolean().prefault(false),
quality: z.number().min(1).max(100).optional(),
viewport: z
.object({
- width: z.number().int().positive().finite().max(7680), // 8K resolution width
- height: z.number().int().positive().finite().max(4320), // 8K resolution height
+ width: z.int().positive().finite().max(7680), // 8K resolution width
+ height: z.int().positive().finite().max(4320), // 8K resolution height
})
.optional(),
}),
@@ -286,7 +297,7 @@ const actionSchema = z.union([
}),
z.object({
type: z.literal("scroll"),
- direction: z.enum(["up", "down"]).optional().default("down"),
+ direction: z.enum(["up", "down"]).optional().prefault("down"),
selector: z.string().optional(),
}),
z.object({
@@ -298,8 +309,8 @@ const actionSchema = z.union([
}),
z.object({
type: z.literal("pdf"),
- landscape: z.boolean().default(false),
- scale: z.number().default(1),
+ landscape: z.boolean().prefault(false),
+ scale: z.number().prefault(1),
format: z
.enum([
"A0",
@@ -314,7 +325,7 @@ const actionSchema = z.union([
"Tabloid",
"Ledger",
])
- .default("Letter"),
+ .prefault("Letter"),
}),
]);
@@ -330,37 +341,33 @@ const actionsSchema = z
},
);
-const jsonFormatWithOptions = z
- .object({
- type: z.literal("json"),
- schema: z
- .any()
- .optional()
- .transform(val => normalizeSchemaForOpenAI(val))
- .refine(val => validateSchemaForOpenAI(val), {
- message: OPENAI_SCHEMA_ERROR_MESSAGE,
- }),
- prompt: z.string().max(10000).optional(),
- })
- .strict();
+const jsonFormatWithOptions = z.strictObject({
+ type: z.literal("json"),
+ schema: z
+ .any()
+ .optional()
+ .transform(val => normalizeSchemaForOpenAI(val))
+ .refine(val => validateSchemaForOpenAI(val), {
+ message: OPENAI_SCHEMA_ERROR_MESSAGE,
+ }),
+ prompt: z.string().max(10000).optional(),
+});
export type JsonFormatWithOptions = z.output<typeof jsonFormatWithOptions>;
-const changeTrackingFormatWithOptions = z
- .object({
- type: z.literal("changeTracking"),
- prompt: z.string().optional(),
- schema: z
- .any()
- .optional()
- .transform(val => normalizeSchemaForOpenAI(val))
- .refine(val => validateSchemaForOpenAI(val), {
- message: OPENAI_SCHEMA_ERROR_MESSAGE,
- }),
- modes: z.enum(["json", "git-diff"]).array().optional().default([]),
- tag: z.string().or(z.null()).default(null),
- })
- .strict();
+const changeTrackingFormatWithOptions = z.strictObject({
+ type: z.literal("changeTracking"),
+ prompt: z.string().optional(),
+ schema: z
+ .any()
+ .optional()
+ .transform(val => normalizeSchemaForOpenAI(val))
+ .refine(val => validateSchemaForOpenAI(val), {
+ message: OPENAI_SCHEMA_ERROR_MESSAGE,
+ }),
+ modes: z.enum(["json", "git-diff"]).array().optional().prefault([]),
+ tag: z.string().or(z.null()).prefault(null),
+});
type ChangeTrackingFormatWithOptions = z.output<
typeof changeTrackingFormatWithOptions
@@ -368,35 +375,33 @@ type ChangeTrackingFormatWithOptions = z.output<
const screenshotFormatWithOptions = z.object({
type: z.literal("screenshot"),
- fullPage: z.boolean().default(false),
+ fullPage: z.boolean().prefault(false),
quality: z.number().min(1).max(100).optional(),
viewport: z
.object({
- width: z.number().int().positive().finite().max(7680), // 8K resolution width
- height: z.number().int().positive().finite().max(4320), // 8K resolution height
+ width: z.int().positive().finite().max(7680), // 8K resolution width
+ height: z.int().positive().finite().max(4320), // 8K resolution height
})
.optional(),
});
type ScreenshotFormatWithOptions = z.output<typeof screenshotFormatWithOptions>;
-const attributesFormatWithOptions = z
- .object({
- type: z.literal("attributes"),
- selectors: z
- .array(
- z.object({
- selector: z.string().describe("CSS selector to find elements"),
- attribute: z
- .string()
- .describe(
- "Attribute name to extract (e.g., 'data-vehicle-name' or 'id')",
- ),
- }),
- )
- .describe("Extract specific attributes from elements"),
- })
- .strict();
+const attributesFormatWithOptions = z.strictObject({
+ type: z.literal("attributes"),
+ selectors: z
+ .array(
+ z.strictObject({
+ selector: z.string().describe("CSS selector to find elements"),
+ attribute: z
+ .string()
+ .describe(
+ "Attribute name to extract (e.g., 'data-vehicle-name' or 'id')",
+ ),
+ }),
+ )
+ .describe("Extract specific attributes from elements"),
+});
type AttributesFormatWithOptions = z.output<typeof attributesFormatWithOptions>;
@@ -413,16 +418,14 @@ export type FormatObject =
| AttributesFormatWithOptions
| { type: "branding" };
-const pdfParserWithOptions = z
- .object({
- type: z.literal("pdf"),
- maxPages: z.number().int().positive().finite().max(10000).optional(),
- })
- .strict();
+const pdfParserWithOptions = z.strictObject({
+ type: z.literal("pdf"),
+ maxPages: z.int().positive().finite().max(10000).optional(),
+});
const parsersSchema = z
.array(z.union([z.literal("pdf"), pdfParserWithOptions]))
- .default(["pdf"]);
+ .prefault(["pdf"]);
type Parsers = z.infer<typeof parsersSchema>;
@@ -480,90 +483,83 @@ const locationSchema = z
})
.optional();
-const baseScrapeOptions = z
- .object({
- formats: z
- .preprocess(
- val => {
- if (!Array.isArray(val)) return val;
- return val.map(format => {
- if (typeof format === "string") {
- return { type: format };
- }
- return format;
- });
- },
- z
- .union([
- z.object({ type: z.literal("markdown") }),
- z.object({ type: z.literal("html") }),
- z.object({ type: z.literal("rawHtml") }),
- z.object({ type: z.literal("links") }),
- z.object({ type: z.literal("images") }),
- z.object({ type: z.literal("summary") }),
- jsonFormatWithOptions,
- changeTrackingFormatWithOptions,
- screenshotFormatWithOptions,
- attributesFormatWithOptions,
- z.object({ type: z.literal("branding") }),
- ])
- .array()
- .optional()
- .default([{ type: "markdown" }]),
- )
- .refine(x => {
- return x.filter(f => f.type === "screenshot").length <= 1;
- }, "You may only specify one screenshot format")
- .refine(x => {
- const hasChangeTracking = x.find(f => f.type === "changeTracking");
- const hasMarkdown = x.find(f => f.type === "markdown");
- return !hasChangeTracking || hasMarkdown;
- }, "The changeTracking format requires the markdown format to be specified as well"),
- headers: z.record(z.string(), z.string()).optional(),
- includeTags: z
- .string()
- .array()
- .transform(tags => tags.map(transformIframeSelector))
- .optional(),
- excludeTags: z
- .string()
- .array()
- .transform(tags => tags.map(transformIframeSelector))
- .optional(),
- onlyMainContent: z.boolean().default(true),
- timeout: z.number().int().positive().finite().safe().optional(),
- waitFor: z
- .number()
- .int()
- .nonnegative()
- .finite()
- .safe()
- .max(60000)
- .default(0),
- mobile: z.boolean().default(false),
- parsers: parsersSchema.optional(),
- actions: actionsSchema.optional(),
-
- location: locationSchema,
+const baseScrapeOptions = z.strictObject({
+ formats: z
+ .preprocess(
+ val => {
+ if (!Array.isArray(val)) return val;
+ return val.map(format => {
+ if (typeof format === "string") {
+ return { type: format };
+ }
+ return format;
+ });
+ },
+ z
+ .union([
+ z.strictObject({ type: z.literal("markdown") }),
+ z.strictObject({ type: z.literal("html") }),
+ z.strictObject({ type: z.literal("rawHtml") }),
+ z.strictObject({ type: z.literal("links") }),
+ z.strictObject({ type: z.literal("images") }),
+ z.strictObject({ type: z.literal("summary") }),
+ jsonFormatWithOptions,
+ changeTrackingFormatWithOptions,
+ screenshotFormatWithOptions,
+ attributesFormatWithOptions,
+ z.strictObject({ type: z.literal("branding") }),
+ ])
+ .array()
+ .optional()
+ .prefault([{ type: "markdown" }]),
+ )
+ .refine(x => {
+ return x.filter(f => f.type === "screenshot").length <= 1;
+ }, "You may only specify one screenshot format")
+ .refine(x => {
+ const hasChangeTracking = x.find(f => f.type === "changeTracking");
+ const hasMarkdown = x.find(f => f.type === "markdown");
+ return !hasChangeTracking || hasMarkdown;
+ }, "The changeTracking format requires the markdown format to be specified as well"),
+ headers: z.record(z.string(), z.string()).optional(),
+ includeTags: z
+ .string()
+ .array()
+ .transform(tags => tags.map(transformIframeSelector))
+ .optional(),
+ excludeTags: z
+ .string()
+ .array()
+ .transform(tags => tags.map(transformIframeSelector))
+ .optional(),
+ onlyMainContent: z.boolean().prefault(true),
+ timeout: z.int().positive().finite().optional(),
+ waitFor: z.int().nonnegative().finite().max(60000).prefault(0),
+ mobile: z.boolean().prefault(false),
+ parsers: parsersSchema.optional(),
+ actions: actionsSchema.optional(),
+
+ location: locationSchema,
+
+ skipTlsVerification: z.boolean().optional(),
+ removeBase64Images: z.boolean().prefault(true),
+ fastMode: z.boolean().prefault(false),
+ useMock: z.string().optional(),
+ blockAds: z.boolean().prefault(true),
+ proxy: z.enum(["basic", "stealth", "auto"]).prefault("auto"),
+ maxAge: z.int().gte(0).optional(),
+ minAge: z.int().gte(0).optional(),
+ storeInCache: z.boolean().prefault(true),
+ // @deprecated
+ __searchPreviewToken: z.string().optional(),
+ __experimental_omce: z.boolean().prefault(false).optional(),
+ __experimental_omceDomain: z.string().optional(),
+});
- skipTlsVerification: z.boolean().optional(),
- removeBase64Images: z.boolean().default(true),
- fastMode: z.boolean().default(false),
- useMock: z.string().optional(),
- blockAds: z.boolean().default(true),
- proxy: z.enum(["basic", "stealth", "auto"]).default("auto"),
- maxAge: z.number().int().gte(0).safe().optional(),
- minAge: z.number().int().gte(0).safe().optional(),
- storeInCache: z.boolean().default(true),
- // @deprecated
- __searchPreviewToken: z.string().optional(),
- __experimental_omce: z.boolean().default(false).optional(),
- __experimental_omceDomain: z.string().optional(),
- })
- .strict(strictMessage);
+type ScrapeOptionsBase = z.infer<typeof baseScrapeOptions>;
-const waitForRefine = obj => {
- if (obj.waitFor && obj.timeout) {
+const waitForRefine = (obj?: ScrapeOptionsBase): boolean => {
+ if (obj && obj.waitFor && obj.timeout) {
if (typeof obj.timeout !== "number" || obj.timeout <= 0) {
return false;
}
@@ -575,38 +571,58 @@ const waitForRefineOpts = {
message: "waitFor must not exceed half of timeout",
path: ["waitFor"],
};
-const extractTransform = obj => {
+
+// Base transform function that handles both nullable and non-nullable cases
+// Uses generic type to preserve all fields from extended schemas
+const extractTransformImpl = <T extends ScrapeOptionsBase | undefined>(
+ obj: T,
+): T extends undefined ? undefined : T => {
+ if (!obj) return obj as T extends undefined ? undefined : T;
// Handle timeout
+ let result = { ...obj };
if (
obj.formats.find(x => typeof x === "object" && x.type === "json") &&
obj.timeout === 30000
) {
- obj = { ...obj, timeout: 60000 };
+ result = { ...result, timeout: 60000 };
}
- if (
- obj.formats?.includes("changeTracking") &&
- (obj.waitFor === undefined || obj.waitFor < 5000)
- ) {
- obj = { ...obj, waitFor: 5000 };
+ const changeTracking = obj.formats?.find(
+ x => typeof x === "object" && x.type === "changeTracking",
+ );
+
+ if (changeTracking && (obj.waitFor === undefined || obj.waitFor < 5000)) {
+ result = { ...result, waitFor: 5000 };
}
- if (obj.formats?.includes("changeTracking") && obj.timeout === 30000) {
- obj = { ...obj, timeout: 60000 };
+ if (changeTracking && obj.timeout === 30000) {
+ result = { ...result, timeout: 60000 };
}
if (
(obj.proxy === "stealth" || obj.proxy === "auto") &&
obj.timeout === 30000
) {
- obj = { ...obj, timeout: 120000 };
+ result = { ...result, timeout: 120000 };
}
- return obj;
+ return result as T extends undefined ? undefined : T;
};
-export const scrapeOptions = baseScrapeOptions
- .strict(strictMessage)
+// Type-safe wrapper for nullable cases (used in optional scrapeOptions)
+const extractTransform = (
+ obj?: ScrapeOptionsBase,
+): ScrapeOptionsBase | undefined => {
+ return extractTransformImpl(obj);
+};
+
+// Type-safe wrapper for non-nullable cases (used in required scrapeOptions schema)
+// This ensures TypeScript knows the output is always ScrapeOptionsBase, not undefined
+const extractTransformRequired = <T extends ScrapeOptionsBase>(obj: T): T => {
+ return extractTransformImpl(obj)! as T;
+};
+
+export const scrapeOptions = strictWithMessage(baseScrapeOptions)
.refine(
obj => {
if (!obj.actions) return true;
@@ -620,7 +636,7 @@ export const scrapeOptions = baseScrapeOptions
},
)
.refine(waitForRefine, waitForRefineOpts)
- .transform(extractTransform);
+ .transform(extractTransformRequired);
export type BaseScrapeOptions = z.infer<typeof baseScrapeOptions>;
@@ -629,7 +645,7 @@ export type ScrapeOptions = BaseScrapeOptions;
const ajv = new Ajv();
const extractOptions = z
- .object({
+ .strictObject({
urls: URL.array()
.max(10, "Maximum of 10 URLs allowed per request while in beta.")
.optional(),
@@ -649,42 +665,39 @@ const extractOptions = z
}
},
{
- message: "Invalid JSON schema.",
+ error: "Invalid JSON schema.",
},
)
.transform(val => normalizeSchemaForOpenAI(val))
.refine(val => validateSchemaForOpenAI(val), {
message: OPENAI_SCHEMA_ERROR_MESSAGE,
}),
- limit: z.number().int().positive().finite().safe().optional(),
- ignoreSitemap: z.boolean().default(false),
- includeSubdomains: z.boolean().default(true),
- allowExternalLinks: z.boolean().default(false),
- enableWebSearch: z.boolean().default(false),
- scrapeOptions: baseScrapeOptions
- .default({ onlyMainContent: false })
- .optional(),
- origin: z.string().optional().default("api"),
+ limit: z.int().positive().finite().optional(),
+ ignoreSitemap: z.boolean().prefault(false),
+ includeSubdomains: z.boolean().prefault(true),
+ allowExternalLinks: z.boolean().prefault(false),
+ enableWebSearch: z.boolean().prefault(false),
+ scrapeOptions: baseScrapeOptions.optional(),
+ origin: z.string().optional().prefault("api"),
integration: integrationSchema.optional().transform(val => val || null),
- urlTrace: z.boolean().default(false),
- timeout: z.number().int().positive().finite().safe().optional(),
+ urlTrace: z.boolean().prefault(false),
+ timeout: z.int().positive().finite().optional(),
agent: agentOptionsExtract.optional(),
- __experimental_streamSteps: z.boolean().default(false),
- __experimental_llmUsage: z.boolean().default(false),
- __experimental_showSources: z.boolean().default(false),
- showSources: z.boolean().default(false),
+ __experimental_streamSteps: z.boolean().prefault(false),
+ __experimental_llmUsage: z.boolean().prefault(false),
+ __experimental_showSources: z.boolean().prefault(false),
+ showSources: z.boolean().prefault(false),
__experimental_cacheKey: z.string().optional(),
__experimental_cacheMode: z
.enum(["direct", "save", "load"])
- .default("direct")
+ .prefault("direct")
.optional(),
- __experimental_showCostTracking: z.boolean().default(false),
- ignoreInvalidURLs: z.boolean().default(true),
+ __experimental_showCostTracking: z.boolean().prefault(false),
+ ignoreInvalidURLs: z.boolean().prefault(true),
webhook: webhookSchema.optional(),
})
- .strict(strictMessage)
.refine(obj => obj.urls || obj.prompt, {
- message: "Either 'urls' or 'prompt' must be provided.",
+ error: "Either 'urls' or 'prompt' must be provided.",
})
.transform(obj => ({
...obj,
@@ -696,79 +709,108 @@ const extractOptions = z
)
.transform(x => ({
...x,
- scrapeOptions: x.scrapeOptions
- ? extractTransform(x.scrapeOptions)
- : x.scrapeOptions,
+ scrapeOptions: extractTransform(x.scrapeOptions),
}));
export const extractRequestSchema = extractOptions;
export type ExtractRequest = z.infer<typeof extractRequestSchema>;
export type ExtractRequestInput = z.input<typeof extractRequestSchema>;
-export const scrapeRequestSchema = baseScrapeOptions
- .extend({
- url: URL,
- origin: z.string().optional().default("api"),
- integration: integrationSchema.optional().transform(val => val || null),
- zeroDataRetention: z.boolean().optional(),
- })
- .strict(strictMessage)
+const scrapeRequestSchemaBase = baseScrapeOptions.extend({
+ url: URL,
+ origin: z.string().optional().prefault("api"),
+ integration: integrationSchema.optional().transform(val => val || null),
+ zeroDataRetention: z.boolean().optional(),
+});
+
+export const scrapeRequestSchema = strictWithMessage(scrapeRequestSchemaBase)
.refine(waitForRefine, waitForRefineOpts)
- .transform(extractTransform);
+ .transform(extractTransformRequired);
export type ScrapeRequest = z.infer<typeof scrapeRequestSchema>;
-export type ScrapeRequestInput = z.input<typeof scrapeRequestSchema>;
+// Use z.input on the base schema before strict() to preserve optional fields with defaults
+// This is needed because zod v4's .strict() changes type inference for optional fields
+// We explicitly make formats optional since it has .prefault() which should make it optional
+export type ScrapeRequestInput = Omit<
+ z.input<typeof baseScrapeOptions>,
+ "formats"
+> & {
+ formats?: z.input<typeof baseScrapeOptions>["formats"];
+} & {
+ url: z.input<typeof URL>;
+ origin?: string;
+ integration?: z.input<typeof integrationSchema> | null;
+ zeroDataRetention?: boolean;
+};
-export const batchScrapeRequestSchema = baseScrapeOptions
- .extend({
- urls: URL.array().min(1),
- origin: z.string().optional().default("api"),
- integration: integrationSchema.optional().transform(val => val || null),
- webhook: webhookSchema.optional(),
- appendToId: z.string().uuid().optional(),
- ignoreInvalidURLs: z.boolean().default(true),
- maxConcurrency: z.number().positive().int().optional(),
- zeroDataRetention: z.boolean().optional(),
- })
- .strict(strictMessage)
+const batchScrapeRequestSchemaBase = baseScrapeOptions.extend({
+ urls: URL.array().min(1),
+ origin: z.string().optional().prefault("api"),
+ integration: integrationSchema.optional().transform(val => val || null),
+ webhook: webhookSchema.optional(),
+ appendToId: z.uuid().optional(),
+ ignoreInvalidURLs: z.boolean().prefault(true),
+ maxConcurrency: z.int().positive().optional(),
+ zeroDataRetention: z.boolean().optional(),
+});
+
+export const batchScrapeRequestSchema = strictWithMessage(
+ batchScrapeRequestSchemaBase,
+)
.refine(waitForRefine, waitForRefineOpts)
- .transform(extractTransform);
+ .transform(extractTransformRequired);
+
+const batchScrapeRequestSchemaNoURLValidationBase = baseScrapeOptions.extend({
+ urls: z.string().array().min(1),
+ origin: z.string().optional().prefault("api"),
+ integration: integrationSchema.optional().transform(val => val || null),
+ webhook: webhookSchema.optional(),
+ appendToId: z.uuid().optional(),
+ ignoreInvalidURLs: z.boolean().prefault(true),
+ maxConcurrency: z.int().positive().optional(),
+ zeroDataRetention: z.boolean().optional(),
+});
-export const batchScrapeRequestSchemaNoURLValidation = baseScrapeOptions
- .extend({
- urls: z.string().array().min(1),
- origin: z.string().optional().default("api"),
- integration: integrationSchema.optional().transform(val => val || null),
- webhook: webhookSchema.optional(),
- appendToId: z.string().uuid().optional(),
- ignoreInvalidURLs: z.boolean().default(true),
- maxConcurrency: z.number().positive().int().optional(),
- zeroDataRetention: z.boolean().optional(),
- })
- .strict(strictMessage)
+export const batchScrapeRequestSchemaNoURLValidation = strictWithMessage(
+ batchScrapeRequestSchemaNoURLValidationBase,
+)
.refine(waitForRefine, waitForRefineOpts)
- .transform(extractTransform);
+ .transform(extractTransformRequired);
export type BatchScrapeRequest = z.infer<typeof batchScrapeRequestSchema>;
-export type BatchScrapeRequestInput = z.input<typeof batchScrapeRequestSchema>;
+// Use z.input on the base schema before strict() to preserve optional fields with defaults
+// We explicitly make formats optional since it has .prefault() which should make it optional
+export type BatchScrapeRequestInput = Omit<
+ z.input<typeof baseScrapeOptions>,
+ "formats"
+> & {
+ formats?: z.input<typeof baseScrapeOptions>["formats"];
+} & {
+ urls: z.input<typeof URL>[];
+ origin?: string;
+ integration?: z.input<typeof integrationSchema> | null;
+ webhook?: z.input<typeof webhookSchema>;
+ appendToId?: string;
+ ignoreInvalidURLs?: boolean;
+ maxConcurrency?: number;
+ zeroDataRetention?: boolean;
+};
-const crawlerOptions = z
- .object({
- includePaths: z.string().array().default([]),
- excludePaths: z.string().array().default([]),
- maxDiscoveryDepth: z.number().optional(),
- limit: z.number().default(10000), // default?
- crawlEntireDomain: z.boolean().optional(),
- allowExternalLinks: z.boolean().default(false),
- allowSubdomains: z.boolean().default(false),
- ignoreRobotsTxt: z.boolean().default(false),
- sitemap: z.enum(["skip", "include"]).default("include"),
- deduplicateSimilarURLs: z.boolean().default(true),
- ignoreQueryParameters: z.boolean().default(false),
- regexOnFullURL: z.boolean().default(false),
- delay: z.number().positive().optional(),
- })
- .strict(strictMessage);
+const crawlerOptions = z.strictObject({
+ includePaths: z.string().array().prefault([]),
+ excludePaths: z.string().array().prefault([]),
+ maxDiscoveryDepth: z.number().optional(),
+ limit: z.number().prefault(10000), // default?
+ crawlEntireDomain: z.boolean().optional(),
+ allowExternalLinks: z.boolean().prefault(false),
+ allowSubdomains: z.boolean().prefault(false),
+ ignoreRobotsTxt: z.boolean().prefault(false),
+ sitemap: z.enum(["skip", "include"]).prefault("include"),
+ deduplicateSimilarURLs: z.boolean().prefault(true),
+ ignoreQueryParameters: z.boolean().prefault(false),
+ regexOnFullURL: z.boolean().prefault(false),
+ delay: z.number().positive().optional(),
+});
// export type CrawlerOptions = {
// includePaths?: string[];
@@ -782,25 +824,26 @@ const crawlerOptions = z
type CrawlerOptions = z.infer<typeof crawlerOptions>;
-export const crawlRequestSchema = crawlerOptions
- .extend({
- url: CRAWL_URL,
- origin: z.string().optional().default("api"),
- integration: integrationSchema.optional().transform(val => val || null),
- scrapeOptions: baseScrapeOptions.default({}),
- webhook: webhookSchema.optional(),
- limit: z.number().default(10000),
- maxConcurrency: z.number().positive().int().optional(),
- zeroDataRetention: z.boolean().optional(),
- prompt: z.string().max(10000).optional(),
- })
- .strict(strictMessage)
+const crawlRequestSchemaBase = crawlerOptions.extend({
+ url: CRAWL_URL,
+ origin: z.string().optional().prefault("api"),
+ integration: integrationSchema.optional().transform(val => val || null),
+ scrapeOptions: baseScrapeOptions.prefault(() => baseScrapeOptions.parse({})),
+ webhook: webhookSchema.optional(),
+ limit: z.number().prefault(10000),
+ maxConcurrency: z.int().positive().optional(),
+ zeroDataRetention: z.boolean().optional(),
+ prompt: z.string().max(10000).optional(),
+});
+
+export const crawlRequestSchema = strictWithMessage(crawlRequestSchemaBase)
.refine(x => waitForRefine(x.scrapeOptions), waitForRefineOpts)
.transform(x => {
+ const scrapeOptionsValue = x.scrapeOptions ?? baseScrapeOptions.parse({});
return {
...x,
url: x.url.url, // Extract the actual URL from the CRAWL_URL result
- scrapeOptions: extractTransform(x.scrapeOptions),
+ scrapeOptions: extractTransformRequired(scrapeOptionsValue),
};
});
@@ -821,24 +864,25 @@ export type CrawlRequestInput = z.input<typeof crawlRequestSchema>;
export const MAX_MAP_LIMIT = 100000;
-export const mapRequestSchema = crawlerOptions
+const mapRequestSchemaBase = crawlerOptions
.omit({ sitemap: true, ignoreQueryParameters: true })
.extend({
url: URL,
- origin: z.string().optional().default("api"),
+ origin: z.string().optional().prefault("api"),
integration: integrationSchema.optional().transform(val => val || null),
- includeSubdomains: z.boolean().default(true),
- ignoreQueryParameters: z.boolean().default(true),
+ includeSubdomains: z.boolean().prefault(true),
+ ignoreQueryParameters: z.boolean().prefault(true),
search: z.string().optional(),
- sitemap: z.enum(["only", "include", "skip"]).default("include"),
- limit: z.number().min(1).max(MAX_MAP_LIMIT).default(5000),
+ sitemap: z.enum(["only", "include", "skip"]).prefault("include"),
+ limit: z.number().min(1).max(MAX_MAP_LIMIT).prefault(5000),
timeout: z.number().positive().finite().optional(),
useMock: z.string().optional(),
- filterByPath: z.boolean().default(true),
- useIndex: z.boolean().default(true),
+ filterByPath: z.boolean().prefault(true),
+ useIndex: z.boolean().prefault(true),
location: locationSchema,
- })
- .strict(strictMessage);
+ });
+
+export const mapRequestSchema = strictWithMessage(mapRequestSchemaBase);
// export type MapRequest = {
// url: string;
@@ -1303,9 +1347,9 @@ export function fromV1ScrapeOptions(
// Check json first since when user specifies "json", both "json" and "extract" are present
// When user specifies "extract", only "extract" is present
let v1OriginalFormat: "extract" | "json" | undefined;
- if (v1ScrapeOptions.formats.includes("json")) {
+ if (includesFormat(v1ScrapeOptions.formats as any, "json")) {
v1OriginalFormat = "json";
- } else if (v1ScrapeOptions.formats.includes("extract")) {
+ } else if (includesFormat(v1ScrapeOptions.formats as any, "extract")) {
v1OriginalFormat = "extract";
}
@@ -1339,7 +1383,9 @@ export function fromV1ScrapeOptions(
schema: opts.schema,
prompt: opts.prompt,
};
- return v1ScrapeOptions.formats.includes("extract") ? null : fmt;
+ return includesFormat(v1ScrapeOptions.formats as any, "extract")
+ ? null
+ : fmt;
}
return null;
} else if (x === "changeTracking") {
@@ -1402,60 +1448,40 @@ export function fromV0Combo(
// These allow fine-grained control over each search source type
// Similar to how scrape formats work with jsonFormatWithOptions, etc.
-const webSearchSourceOptions = z
- .object({
- type: z.literal("web"),
- tbs: z.string().optional(), // Time-based search (e.g., "qdr:d" for past day)
- filter: z.string().optional(), // Search filter
- lang: z.string().optional(), // Language override for this source
- country: z.string().optional(), // Country override for this source
- location: z.string().optional(), // Location override for this source
- })
- .strict();
+const webSearchSourceOptions = z.strictObject({
+ type: z.literal("web"),
+ tbs: z.string().optional(), // Time-based search (e.g., "qdr:d" for past day)
+ filter: z.string().optional(), // Search filter
+ lang: z.string().optional(), // Language override for this source
+ country: z.string().optional(), // Country override for this source
+ location: z.string().optional(), // Location override for this source
+});
-const imagesSearchSourceOptions = z
- .object({
- type: z.literal("images"),
- })
- .strict();
+const imagesSearchSourceOptions = z.strictObject({
+ type: z.literal("images"),
+});
-const newsSearchSourceOptions = z
- .object({
- type: z.literal("news"),
- })
- .strict();
+const newsSearchSourceOptions = z.strictObject({
+ type: z.literal("news"),
+});
// Category source type definitions
-const githubCategoryOptions = z
- .object({
- type: z.literal("github"),
- })
- .strict();
+const githubCategoryOptions = z.strictObject({
+ type: z.literal("github"),
+});
-const researchCategoryOptions = z
- .object({
- type: z.literal("research"),
- })
- .strict();
+const researchCategoryOptions = z.strictObject({
+ type: z.literal("research"),
+});
-const pdfCategoryOptions = z
- .object({
- type: z.literal("pdf"),
- })
- .strict();
+const pdfCategoryOptions = z.strictObject({
+ type: z.literal("pdf"),
+});
export const searchRequestSchema = z
- .object({
+ .strictObject({
query: z.string(),
- limit: z
- .number()
- .int()
- .positive()
- .finite()
- .safe()
- .max(100)
- .optional()
- .default(10),
+ limit: z.int().positive().finite().max(100).optional().prefault(10),
tbs: z.string().optional(),
filter: z.string().optional(),
sources: z
@@ -1472,7 +1498,7 @@ export const searchRequestSchema = z
),
])
.optional()
- .default(["web"]),
+ .prefault(["web"]),
categories: z
.union([
// Array of strings (simple format)
@@ -1487,15 +1513,15 @@ export const searchRequestSchema = z
),
])
.optional(),
+ lang: z.string().optional().prefault("en"),
enterprise: z.array(z.enum(["default", "anon", "zdr"])).optional(),
- lang: z.string().optional().default("en"),
country: z.string().optional(),
location: z.string().optional(),
- origin: z.string().optional().default("api"),
+ origin: z.string().optional().prefault("api"),
integration: integrationSchema.optional().transform(val => val || null),
- timeout: z.number().int().positive().finite().safe().default(60000),
- ignoreInvalidURLs: z.boolean().optional().default(false),
- asyncScraping: z.boolean().optional().default(false),
+ timeout: z.int().positive().finite().prefault(60000),
+ ignoreInvalidURLs: z.boolean().optional().prefault(false),
+ asyncScraping: z.boolean().optional().prefault(false),
__searchPreviewToken: z.string().optional(),
scrapeOptions: baseScrapeOptions
.extend({
@@ -1512,28 +1538,25 @@ export const searchRequestSchema = z
},
z
.union([
- z.object({ type: z.literal("markdown") }),
- z.object({ type: z.literal("html") }),
- z.object({ type: z.literal("rawHtml") }),
- z.object({ type: z.literal("links") }),
- z.object({ type: z.literal("images") }),
- z.object({ type: z.literal("summary") }),
+ z.strictObject({ type: z.literal("markdown") }),
+ z.strictObject({ type: z.literal("html") }),
+ z.strictObject({ type: z.literal("rawHtml") }),
+ z.strictObject({ type: z.literal("links") }),
+ z.strictObject({ type: z.literal("images") }),
+ z.strictObject({ type: z.literal("summary") }),
jsonFormatWithOptions,
screenshotFormatWithOptions,
])
.array()
.optional()
- .default([]),
+ .prefault([]),
)
.refine(x => {
return x.filter(f => f.type === "screenshot").length <= 1;
}, "You may only specify one screenshot format"),
})
- .default({}),
+ .optional(),
})
- .strict(
- "Unrecognized key in body -- please review the v1 API documentation for request body changes",
- )
.refine(x => waitForRefine(x.scrapeOptions), waitForRefineOpts)
.transform(x => {
const country =
@@ -1657,15 +1680,15 @@ const generateLLMsTextRequestSchema = z.object({
.number()
.min(1)
.max(5000)
- .default(10)
+ .prefault(10)
.describe("Maximum number of URLs to process"),
showFullText: z
.boolean()
- .default(false)
+ .prefault(false)
.describe("Whether to show the full LLMs-full.txt in the response"),
cache: z
.boolean()
- .default(true)
+ .prefault(true)
.describe("Whether to use cached content if available"),
__experimental_stream: z.boolean().optional(),
});
diff --git a/apps/api/src/controllers/v2/x402-search.ts b/apps/api/src/controllers/v2/x402-search.ts
index 84953830d..81e6fdfd0 100644
--- a/apps/api/src/controllers/v2/x402-search.ts
+++ b/apps/api/src/controllers/v2/x402-search.ts
@@ -326,7 +326,7 @@ export async function x402SearchController(
// Check if scraping is requested
const shouldScrape =
- req.body.scrapeOptions.formats &&
+ req.body.scrapeOptions?.formats &&
req.body.scrapeOptions.formats.length > 0;
const isAsyncScraping = req.body.asyncScraping && shouldScrape;
@@ -339,12 +339,25 @@ export async function x402SearchController(
`Starting ${isAsyncScraping ? "async" : "sync"} search scraping [x402]`,
);
+ // Safely extract scrapeOptions with runtime check
+ if (!req.body.scrapeOptions) {
+ logger.error(
+ "scrapeOptions is undefined despite shouldScrape being true [x402]",
+ );
+ return res.status(500).json({
+ success: false,
+ error: "Internal server error: scrapeOptions is missing",
+ });
+ }
+
+ const bodyScrapeOptions = req.body.scrapeOptions;
+
// Create common options
const scrapeOptions = {
teamId: req.auth.team_id,
origin: req.body.origin,
timeout: req.body.timeout,
- scrapeOptions: req.body.scrapeOptions,
+ scrapeOptions: bodyScrapeOptions,
bypassBilling: true, // Async mode bills per job, sync mode bills manually
apiKeyId: req.acuc?.api_key_id ?? null,
};
@@ -608,11 +621,11 @@ export async function x402SearchController(
});
} catch (error) {
if (error instanceof z.ZodError) {
- logger.warn("Invalid request body [x402]", { error: error.errors });
+ logger.warn("Invalid request body [x402]", { error: error.issues });
return res.status(400).json({
success: false,
error: "Invalid request body",
- details: error.errors,
+ details: error.issues,
});
}
diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts
index 51bf7c187..1dc34ad7a 100644
--- a/apps/api/src/index.ts
+++ b/apps/api/src/index.ts
@@ -173,23 +173,34 @@ app.use(
next: NextFunction,
) => {
if (err instanceof ZodError) {
+ // In zod v4, ZodError uses 'issues' instead of 'errors'
+ const issues = err.issues;
+
if (
- Array.isArray(err.errors) &&
- err.errors.find(x => x.message === "URL uses unsupported protocol")
+ Array.isArray(issues) &&
+ issues.find(x => x.message === "URL uses unsupported protocol")
) {
logger.warn("Unsupported protocol error: " + JSON.stringify(req.body));
}
- const customErrorMessage =
- err.errors.length > 0 && err.errors[0].code === "custom"
- ? err.errors[0].message
+ // Check for unrecognized_keys errors and replace with custom message
+ const hasUnrecognizedKeys = issues.some(
+ e => e.code === "unrecognized_keys",
+ );
+ const strictMessage =
+ "Unrecognized key in body -- please review the v2 API documentation for request body changes";
+
+ const customErrorMessage = hasUnrecognizedKeys
+ ? strictMessage
+ : issues.length > 0 && issues[0].code === "custom"
+ ? issues[0].message
: "Bad Request";
res.status(400).json({
success: false,
code: "BAD_REQUEST",
error: customErrorMessage,
- details: err.errors,
+ details: issues,
});
} else {
next(err);
diff --git a/apps/api/src/lib/deep-research/deep-research-service.ts b/apps/api/src/lib/deep-research/deep-research-service.ts
index d8e480cc1..272f83e72 100644
--- a/apps/api/src/lib/deep-research/deep-research-service.ts
+++ b/apps/api/src/lib/deep-research/deep-research-service.ts
@@ -7,6 +7,7 @@ import { billTeam } from "../../services/billing/credit_billing";
import { ExtractOptions } from "../../controllers/v1/types";
import { CostTracking } from "../cost-tracking";
import { getACUCTeam } from "../../controllers/auth";
+import { includesFormat } from "../format-utils";
export interface DeepResearchServiceOptions {
researchId: string;
teamId: string;
@@ -355,7 +356,7 @@ export async function performDeepResearch(options: DeepResearchServiceOptions) {
let finalAnalysis = "";
let finalAnalysisJson = null;
- if (options.formats.includes("json")) {
+ if (includesFormat(options.formats, "json")) {
finalAnalysisJson = await llmService.generateFinalAnalysis(
options.query,
state.getFindings(),
@@ -371,7 +372,7 @@ export async function performDeepResearch(options: DeepResearchServiceOptions) {
options.jsonOptions,
);
}
- if (options.formats.includes("markdown")) {
+ if (includesFormat(options.formats, "markdown")) {
finalAnalysis = await llmService.generateFinalAnalysis(
options.query,
state.getFindings(),
diff --git a/apps/api/src/lib/deep-research/research-manager.ts b/apps/api/src/lib/deep-research/research-manager.ts
index 81389267d..e8099f6be 100644
--- a/apps/api/src/lib/deep-research/research-manager.ts
+++ b/apps/api/src/lib/deep-research/research-manager.ts
@@ -13,6 +13,7 @@ import { ExtractOptions } from "../../controllers/v1/types";
import { getModel } from "../generic-ai";
import { CostTracking } from "../cost-tracking";
+import { includesFormat } from "../format-utils";
interface AnalysisResult {
gaps: string[];
nextSteps: string[];
@@ -305,20 +306,20 @@ export class ResearchLLMService {
logger: this.logger.child({
method: "generateFinalAnalysis",
}),
- mode: formats.includes("json") ? "object" : "no-object",
+ mode: includesFormat(formats, "json") ? "object" : "no-object",
options: {
mode: "llm",
- ...(formats.includes("json") && {
+ ...(includesFormat(formats, "json") && {
...jsonOptions,
}),
- systemPrompt: formats.includes("json")
+ systemPrompt: includesFormat(formats, "json")
? "You are an expert research analyst who creates comprehensive, structured analysis following the provided JSON schema exactly."
: "You are an expert research analyst who creates comprehensive, well-structured reports. Don't begin the report by saying 'Here is the report', nor 'Below is the report', nor something similar. ALWAYS start with a great title that reflects the research topic and findings. Your reports are detailed, properly formatted in Markdown, and include clear sections with citations. Today's date is " +
new Date().toISOString().split("T")[0],
prompt: trimToTokenLimit(
analysisPrompt
? `${analysisPrompt}\n\nResearch data:\n${findings.map(f => `[From ${f.source}]: ${f.text}`).join("\n")}`
- : formats.includes("json")
+ : includesFormat(formats, "json")
? `Analyze the following research data on "${topic}" and structure the output according to the provided schema: Schema: ${JSON.stringify(jsonOptions?.schema)}\n\nFindings:\n\n${findings.map(f => `[From ${f.source}]: ${f.text}`).join("\n")}`
: `Create a comprehensive research report on "${topic}" based on the collected findings and analysis.
diff --git a/apps/api/src/lib/extract/completions/analyzeSchemaAndPrompt.ts b/apps/api/src/lib/extract/completions/analyzeSchemaAndPrompt.ts
index b126993c9..58825bda3 100644
--- a/apps/api/src/lib/extract/completions/analyzeSchemaAndPrompt.ts
+++ b/apps/api/src/lib/extract/completions/analyzeSchemaAndPrompt.ts
@@ -53,7 +53,7 @@ export async function analyzeSchemaAndPrompt(
const checkSchema = z
.object({
isMultiEntity: z.boolean(),
- multiEntityKeys: z.array(z.string()).optional().default([]),
+ multiEntityKeys: z.array(z.string()).optional().prefault([]),
reasoning: z.string(),
keyIndicators: z.array(z.string()),
})
diff --git a/apps/api/src/lib/extract/fire-0/completions/analyzeSchemaAndPrompt-f0.ts b/apps/api/src/lib/extract/fire-0/completions/analyzeSchemaAndPrompt-f0.ts
index 31e8c161e..4ef8e647c 100644
--- a/apps/api/src/lib/extract/fire-0/completions/analyzeSchemaAndPrompt-f0.ts
+++ b/apps/api/src/lib/extract/fire-0/completions/analyzeSchemaAndPrompt-f0.ts
@@ -34,7 +34,7 @@ export async function analyzeSchemaAndPrompt_F0(
const checkSchema = z
.object({
isMultiEntity: z.boolean(),
- multiEntityKeys: z.array(z.string()).optional().default([]),
+ multiEntityKeys: z.array(z.string()).optional().prefault([]),
reasoning: z.string(),
keyIndicators: z.array(z.string()),
})
diff --git a/apps/api/src/lib/extract/fire-0/llmExtract-f0.ts b/apps/api/src/lib/extract/fire-0/llmExtract-f0.ts
index ecd761672..4d235685b 100644
--- a/apps/api/src/lib/extract/fire-0/llmExtract-f0.ts
+++ b/apps/api/src/lib/extract/fire-0/llmExtract-f0.ts
@@ -3,6 +3,7 @@ import { TiktokenModel } from "@dqbd/tiktoken";
import {
Document,
ExtractOptions,
+ ExtractOptionsInput,
TokenUsage,
} from "../../../controllers/v1/types";
import { Logger } from "winston";
@@ -168,8 +169,9 @@ export async function generateCompletions_F0({
metadata,
}: {
model?: LanguageModel;
+ modelName?: string;
logger: Logger;
- options: ExtractOptions;
+ options: ExtractOptionsInput;
markdown?: string;
previousWarning?: string;
isExtractEndpoint?: boolean;
@@ -194,7 +196,9 @@ export async function generateCompletions_F0({
throw new Error("document.markdown is undefined -- this is unexpected");
}
- const { maxInputTokens, maxOutputTokens } = getModelLimits_F0(model.modelId);
+ const modelId = typeof model === "string" ? model : model.modelId;
+
+ const { maxInputTokens } = getModelLimits_F0(modelId);
// Calculate 80% of max input tokens (for content)
const maxTokensSafe = Math.floor(maxInputTokens * 0.8);
@@ -203,12 +207,7 @@ export async function generateCompletions_F0({
text: trimmedMarkdown,
numTokens,
warning: trimWarning,
- } = trimToTokenLimit_F0(
- markdown,
- maxTokensSafe,
- model.modelId,
- previousWarning,
- );
+ } = trimToTokenLimit_F0(markdown, maxTokensSafe, modelId, previousWarning);
markdown = trimmedMarkdown;
warning = trimWarning;
@@ -264,10 +263,10 @@ export async function generateCompletions_F0({
numTokens,
totalUsage: {
promptTokens: numTokens,
- completionTokens: result.usage?.completionTokens ?? 0,
- totalTokens: numTokens + (result.usage?.completionTokens ?? 0),
+ completionTokens: result.usage?.outputTokens ?? 0,
+ totalTokens: numTokens + (result.usage?.outputTokens ?? 0),
},
- model: model.modelId,
+ model: modelId,
};
}
@@ -425,7 +424,7 @@ export async function generateCompletions_F0({
// Since generateObject doesn't provide token usage, we'll estimate it
const promptTokens = numTokens;
- const completionTokens = result?.usage?.completionTokens ?? 0;
+ const completionTokens = result?.usage?.outputTokens ?? 0;
return {
extract,
@@ -436,7 +435,7 @@ export async function generateCompletions_F0({
completionTokens,
totalTokens: promptTokens + completionTokens,
},
- model: model.modelId,
+ model: modelId,
};
} catch (error) {
if (error.message?.includes("refused")) {
diff --git a/apps/api/src/lib/extract/url-processor.ts b/apps/api/src/lib/extract/url-processor.ts
index 7875ff085..c94d4e5a9 100644
--- a/apps/api/src/lib/extract/url-processor.ts
+++ b/apps/api/src/lib/extract/url-processor.ts
@@ -55,12 +55,12 @@ export async function generateBasicCompletion(
model: "openai/gpt-4o",
cost: calculateCost(
"openai/gpt-4o",
- result.usage?.promptTokens ?? 0,
- result.usage?.completionTokens ?? 0,
+ result.usage?.inputTokens ?? 0,
+ result.usage?.outputTokens ?? 0,
),
tokens: {
- input: result.usage?.promptTokens ?? 0,
- output: result.usage?.completionTokens ?? 0,
+ input: result.usage?.inputTokens ?? 0,
+ output: result.usage?.outputTokens ?? 0,
},
});
return { text: result.text };
@@ -104,12 +104,12 @@ export async function generateBasicCompletion(
model: "openai/gpt-4o-mini",
cost: calculateCost(
"openai/gpt-4o-mini",
- result.usage?.promptTokens ?? 0,
- result.usage?.completionTokens ?? 0,
+ result.usage?.inputTokens ?? 0,
+ result.usage?.outputTokens ?? 0,
),
tokens: {
- input: result.usage?.promptTokens ?? 0,
- output: result.usage?.completionTokens ?? 0,
+ input: result.usage?.inputTokens ?? 0,
+ output: result.usage?.outputTokens ?? 0,
},
});
return { text: result.text };
diff --git a/apps/api/src/lib/format-utils.ts b/apps/api/src/lib/format-utils.ts
index 598b0c561..c49ce6a43 100644
--- a/apps/api/src/lib/format-utils.ts
+++ b/apps/api/src/lib/format-utils.ts
@@ -22,3 +22,31 @@ export function hasFormatOfType<T extends FormatObject["type"]>(
const found = formats.find(f => f.type === type);
return found as Extract<FormatObject, { type: T }> | undefined;
}
+
+/**
+ * Checks if a format of a specific type exists in a formats array.
+ * Works with both v1-style string arrays and v2-style object arrays.
+ *
+ * @param formats - Array of format strings or objects
+ * @param type - The format type to check for
+ * @returns true if the format exists, false otherwise
+ *
+ * @example
+ * // v2 style (object array)
+ * includesFormat([{ type: "markdown" }, { type: "html" }], "markdown") // true
+ *
+ * // v1 style (string array)
+ * includesFormat(["markdown", "html"], "markdown") // true
+ */
+export function includesFormat(
+ formats: (string | FormatObject)[] | undefined,
+ type: string,
+): boolean {
+ if (!formats) {
+ return false;
+ }
+
+ return formats.some(f =>
+ typeof f === "string" ? f === type : f.type === type,
+ );
+}
diff --git a/apps/api/src/scraper/scrapeURL/lib/smartScrape.ts b/apps/api/src/scraper/scrapeURL/lib/smartScrape.ts
index f46c1a753..93decdaf2 100644
--- a/apps/api/src/scraper/scrapeURL/lib/smartScrape.ts
+++ b/apps/api/src/scraper/scrapeURL/lib/smartScrape.ts
@@ -11,8 +11,8 @@ configDotenv();
// Define schemas outside the function scope
const tokenUsageDetailSchema = z.object({
- input_tokens: z.number().int(),
- output_tokens: z.number().int(),
+ input_tokens: z.int(),
+ output_tokens: z.int(),
total_cost: z.number().nullable(), // Allows number or null
});
diff --git a/apps/api/src/scraper/scrapeURL/transformers/llmExtract.ts b/apps/api/src/scraper/scrapeURL/transformers/llmExtract.ts
index 00aa07c9a..a7fb738f7 100644
--- a/apps/api/src/scraper/scrapeURL/transformers/llmExtract.ts
+++ b/apps/api/src/scraper/scrapeURL/transformers/llmExtract.ts
@@ -270,9 +270,10 @@ export function calculateCost(
export type GenerateCompletionsOptions = {
model?: LanguageModel;
logger: Logger;
- options: Omit<JsonFormatWithOptions, "type"> & {
+ options: Omit<JsonFormatWithOptions, "type" | "schema"> & {
systemPrompt?: string;
temperature?: number;
+ schema?: any; // Explicitly optional to allow calls without schema
};
markdown?: string;
previousWarning?: string;
@@ -317,6 +318,9 @@ export async function generateCompletions({
let currentModel = model;
let lastError: Error | null = null;
+ let modelId =
+ typeof currentModel === "string" ? currentModel : currentModel.modelId;
+
if (markdown === undefined) {
throw new Error("document.markdown is undefined -- this is unexpected");
}
@@ -347,6 +351,9 @@ export async function generateCompletions({
llmsTxtId: metadata.llmsTxtId ?? "unspecified",
},
},
+ openai: {
+ strictJsonSchema: true,
+ },
},
experimental_telemetry: {
isEnabled: true,
@@ -389,15 +396,15 @@ export async function generateCompletions({
...costTrackingOptions.metadata,
gcDetails: "no-object",
},
- model: currentModel.modelId,
+ model: modelId,
cost: calculateCost(
- currentModel.modelId,
- result.usage?.promptTokens ?? 0,
- result.usage?.completionTokens ?? 0,
+ modelId,
+ result.usage?.inputTokens ?? 0,
+ result.usage?.outputTokens ?? 0,
),
tokens: {
- input: result.usage?.promptTokens ?? 0,
- output: result.usage?.completionTokens ?? 0,
+ input: result.usage?.inputTokens ?? 0,
+ output: result.usage?.outputTokens ?? 0,
},
});
@@ -406,15 +413,15 @@ export async function generateCompletions({
return {
extract,
warning,
- numTokens: result.usage?.promptTokens ?? 0,
+ numTokens: result.usage?.inputTokens ?? 0,
totalUsage: {
- promptTokens: result.usage?.promptTokens ?? 0,
- completionTokens: result.usage?.completionTokens ?? 0,
+ promptTokens: result.usage?.inputTokens ?? 0,
+ completionTokens: result.usage?.outputTokens ?? 0,
totalTokens:
- result.usage?.promptTokens ??
- 0 + (result.usage?.completionTokens ?? 0),
+ result.usage?.inputTokens ??
+ 0 + (result.usage?.outputTokens ?? 0),
},
- model: currentModel.modelId,
+ model: modelId,
};
} catch (error) {
lastError = error as Error;
@@ -427,6 +434,10 @@ export async function generateCompletions({
error: lastError.message,
});
currentModel = retryModel;
+ modelId =
+ typeof currentModel === "string"
+ ? currentModel
+ : currentModel.modelId;
try {
const result = await generateText({
model: currentModel,
@@ -446,6 +457,9 @@ export async function generateCompletions({
llmsTxtId: metadata.llmsTxtId ?? "unspecified",
},
},
+ openai: {
+ strictJsonSchema: true,
+ },
},
experimental_telemetry: {
isEnabled: true,
@@ -491,36 +505,36 @@ export async function generateCompletions({
...costTrackingOptions.metadata,
gcDetails: "no-object fallback",
},
- model: currentModel.modelId,
+ model: modelId,
cost: calculateCost(
- currentModel.modelId,
- result.usage?.promptTokens ?? 0,
- result.usage?.completionTokens ?? 0,
+ modelId,
+ result.usage?.inputTokens ?? 0,
+ result.usage?.outputTokens ?? 0,
),
tokens: {
- input: result.usage?.promptTokens ?? 0,
- output: result.usage?.completionTokens ?? 0,
+ input: result.usage?.inputTokens ?? 0,
+ output: result.usage?.outputTokens ?? 0,
},
});
return {
extract,
warning,
- numTokens: result.usage?.promptTokens ?? 0,
+ numTokens: result.usage?.inputTokens ?? 0,
totalUsage: {
- promptTokens: result.usage?.promptTokens ?? 0,
- completionTokens: result.usage?.completionTokens ?? 0,
+ promptTokens: result.usage?.inputTokens ?? 0,
+ completionTokens: result.usage?.outputTokens ?? 0,
totalTokens:
- result.usage?.promptTokens ??
- 0 + (result.usage?.completionTokens ?? 0),
+ result.usage?.inputTokens ??
+ 0 + (result.usage?.outputTokens ?? 0),
},
- model: currentModel.modelId,
+ model: modelId,
};
} catch (retryError) {
lastError = retryError as Error;
logger.error("Failed with fallback model", {
originalError: lastError.message,
- model: currentModel.modelId,
+ model: modelId,
});
throw lastError;
}
@@ -614,6 +628,9 @@ export async function generateCompletions({
llmsTxtId: metadata.llmsTxtId ?? "unspecified",
},
},
+ openai: {
+ strictJsonSchema: true,
+ },
},
experimental_telemetry: {
isEnabled: true,
@@ -658,14 +675,14 @@ export async function generateCompletions({
gcDetails: "repairConfig",
},
cost: calculateCost(
- currentModel.modelId,
- repairUsage?.promptTokens ?? 0,
- repairUsage?.completionTokens ?? 0,
+ modelId,
+ repairUsage?.inputTokens ?? 0,
+ repairUsage?.outputTokens ?? 0,
),
- model: currentModel.modelId,
+ model: modelId,
tokens: {
- input: repairUsage?.promptTokens ?? 0,
- output: repairUsage?.completionTokens ?? 0,
+ input: repairUsage?.inputTokens ?? 0,
+ output: repairUsage?.outputTokens ?? 0,
},
});
logger.debug("Repaired text with LLM");
@@ -695,6 +712,9 @@ export async function generateCompletions({
llmsTxtId: metadata.llmsTxtId ?? "unspecified",
},
},
+ openai: {
+ strictJsonSchema: true,
+ },
},
system: options.systemPrompt,
...(schema && {
@@ -739,7 +759,7 @@ export async function generateCompletions({
: {}),
},
},
- ...(currentModel.modelId.startsWith("gpt-5")
+ ...(modelId.startsWith("gpt-5")
? {
temperature: 1,
}
@@ -762,7 +782,16 @@ export async function generateCompletions({
retryModel,
});
- let result: { object: any; usage: TokenUsage } | undefined;
+ let result:
+ | {
+ object: any;
+ usage: {
+ inputTokens?: number;
+ outputTokens?: number;
+ totalTokens?: number;
+ };
+ }
+ | undefined;
try {
result = await generateObject(generateObjectConfig);
costTrackingOptions.costTracking.addCall({
@@ -773,14 +802,14 @@ export async function generateCompletions({
gcModel: generateObjectConfig.model.modelId,
},
tokens: {
- input: result.usage?.promptTokens ?? 0,
- output: result.usage?.completionTokens ?? 0,
+ input: result.usage?.inputTokens ?? 0,
+ output: result.usage?.outputTokens ?? 0,
},
- model: currentModel.modelId,
+ model: modelId,
cost: calculateCost(
- currentModel.modelId,
- result.usage?.promptTokens ?? 0,
- result.usage?.completionTokens ?? 0,
+ modelId,
+ result.usage?.inputTokens ?? 0,
+ result.usage?.outputTokens ?? 0,
),
});
} catch (error) {
@@ -794,6 +823,10 @@ export async function generateCompletions({
error: lastError.message,
});
currentModel = retryModel;
+ modelId =
+ typeof currentModel === "string"
+ ? currentModel
+ : currentModel.modelId;
try {
const retryConfig = {
...generateObjectConfig,
@@ -808,21 +841,21 @@ export async function generateCompletions({
gcModel: retryConfig.model.modelId,
},
tokens: {
- input: result.usage?.promptTokens ?? 0,
- output: result.usage?.completionTokens ?? 0,
+ input: result.usage?.inputTokens ?? 0,
+ output: result.usage?.outputTokens ?? 0,
},
- model: currentModel.modelId,
+ model: modelId,
cost: calculateCost(
- currentModel.modelId,
- result.usage?.promptTokens ?? 0,
- result.usage?.completionTokens ?? 0,
+ modelId,
+ result.usage?.inputTokens ?? 0,
+ result.usage?.outputTokens ?? 0,
),
});
} catch (retryError) {
lastError = retryError as Error;
logger.error("Failed with fallback model", {
originalError: lastError.message,
- model: currentModel.modelId,
+ model: modelId,
});
throw lastError;
}
@@ -840,8 +873,8 @@ export async function generateCompletions({
result = {
object: extract,
usage: {
- promptTokens: error.usage?.promptTokens ?? 0,
- completionTokens: error.usage?.completionTokens ?? 0,
+ inputTokens: error.usage?.inputTokens ?? 0,
+ outputTokens: error.usage?.outputTokens ?? 0,
totalTokens: error.usage?.totalTokens ?? 0,
},
};
@@ -873,8 +906,11 @@ export async function generateCompletions({
}
// Since generateObject doesn't provide token usage, we'll estimate it
- const promptTokens = result.usage?.promptTokens ?? 0;
- const completionTokens = result.usage?.completionTokens ?? 0;
+ if (!result) {
+ throw new Error("generateObject returned undefined result");
+ }
+ const promptTokens = result.usage?.inputTokens ?? 0;
+ const completionTokens = result.usage?.outputTokens ?? 0;
return {
extract,
@@ -885,7 +921,7 @@ export async function generateCompletions({
completionTokens,
totalTokens: promptTokens + completionTokens,
},
- model: currentModel.modelId,
+ model: modelId,
};
} catch (error) {
lastError = error as Error;
@@ -894,7 +930,7 @@ export async function generateCompletions({
}
logger.error("LLM extraction failed", {
error: lastError,
- model: currentModel.modelId,
+ model: modelId,
mode,
});
throw lastError;
@@ -1012,7 +1048,7 @@ export async function performLLMExtract(
// // Log token usage
// meta.logger.info("LLM extraction token usage", {
// model: model,
- // promptTokens: totalUsage.promptTokens,
+ // promptTokens: totalUsage.inputTokens,
// completionTokens: totalUsage.completionTokens,
// totalTokens: totalUsage.totalTokens,
// });
diff --git a/apps/api/src/services/webhook/schema.ts b/apps/api/src/services/webhook/schema.ts
index f4c1627f4..c63751446 100644
--- a/apps/api/src/services/webhook/schema.ts
+++ b/apps/api/src/services/webhook/schema.ts
@@ -5,17 +5,14 @@ const BLACKLISTED_WEBHOOK_HEADERS = ["x-firecrawl-signature"];
export const webhookSchema = z.preprocess(
x => (typeof x === "string" ? { url: x } : x),
z
- .object({
- url: z.string().url(),
- headers: z.record(z.string(), z.string()).default({}),
- metadata: z.record(z.string(), z.string()).default({}),
+ .strictObject({
+ url: z.url(),
+ headers: z.record(z.string(), z.string()).prefault({}),
+ metadata: z.record(z.string(), z.string()).prefault({}),
events: z
.array(z.enum(["completed", "failed", "page", "started"]))
- .default(["completed", "failed", "page", "started"]),
+ .prefault(["completed", "failed", "page", "started"]),
})
- .strict(
- "Unrecognized key in webhook object. Review the API documentation for webhook configuration changes.",
- )
.refine(
obj => {
const blacklistedLower = BLACKLISTED_WEBHOOK_HEADERS.map(h =>