index.d.ts 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350
  1. // The following definitions have been copied (almost) as-is from:
  2. // https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/hapi__joi
  3. //
  4. // Note: This file is expected to change dramatically in the next major release and have been
  5. // imported here to make migrating back to the "joi" module name simpler. It include known bugs
  6. // and other issues. It does not include some new features included in version 17.2.0 or newer.
  7. //
  8. // TypeScript Version: 2.8
  9. // TODO express type of Schema in a type-parameter (.default, .valid, .example etc)
  10. declare namespace Joi {
  11. type Types =
  12. | 'any'
  13. | 'alternatives'
  14. | 'array'
  15. | 'boolean'
  16. | 'binary'
  17. | 'date'
  18. | 'function'
  19. | 'link'
  20. | 'number'
  21. | 'object'
  22. | 'string'
  23. | 'symbol';
  24. type BasicType = boolean | number | string | any[] | object | null;
  25. type LanguageMessages = Record<string, string>;
  26. type PresenceMode = 'optional' | 'required' | 'forbidden';
  27. interface ErrorFormattingOptions {
  28. /**
  29. * when true, error message templates will escape special characters to HTML entities, for security purposes.
  30. *
  31. * @default false
  32. */
  33. escapeHtml?: boolean;
  34. /**
  35. * defines the value used to set the label context variable.
  36. */
  37. label?: 'path' | 'key' | false;
  38. /**
  39. * The preferred language code for error messages.
  40. * The value is matched against keys at the root of the messages object, and then the error code as a child key of that.
  41. * Can be a reference to the value, global context, or local context which is the root value passed to the validation function.
  42. *
  43. * Note that references to the value are usually not what you want as they move around the value structure relative to where the error happens.
  44. * Instead, either use the global context, or the absolute value (e.g. `Joi.ref('/variable')`)
  45. */
  46. language?: keyof LanguageMessages;
  47. /**
  48. * when false, skips rendering error templates. Useful when error messages are generated elsewhere to save processing time.
  49. *
  50. * @default true
  51. */
  52. render?: boolean;
  53. /**
  54. * when true, the main error will possess a stack trace, otherwise it will be disabled.
  55. * Defaults to false for performances reasons. Has no effect on platforms other than V8/node.js as it uses the Stack trace API.
  56. *
  57. * @default false
  58. */
  59. stack?: boolean;
  60. /**
  61. * overrides the way values are wrapped (e.g. `[]` around arrays, `""` around labels).
  62. * Each key can be set to a string with one (same character before and after the value) or two characters (first character
  63. * before and second character after), or `false` to disable wrapping.
  64. */
  65. wrap?: {
  66. /**
  67. * the characters used around `{#label}` references. Defaults to `'"'`.
  68. *
  69. * @default '"'
  70. */
  71. label?: string | false,
  72. /**
  73. * the characters used around array values. Defaults to `'[]'`
  74. *
  75. * @default '[]'
  76. */
  77. array?: string | false
  78. /**
  79. * the characters used around array string values. Defaults to no wrapping.
  80. *
  81. * @default false
  82. */
  83. string?: string | false
  84. };
  85. }
  86. interface BaseValidationOptions {
  87. /**
  88. * when true, stops validation on the first error, otherwise returns all the errors found.
  89. *
  90. * @default true
  91. */
  92. abortEarly?: boolean;
  93. /**
  94. * when true, allows object to contain unknown keys which are ignored.
  95. *
  96. * @default false
  97. */
  98. allowUnknown?: boolean;
  99. /**
  100. * when true, return artifacts alongside the value.
  101. *
  102. * @default false
  103. */
  104. artifacts?: boolean;
  105. /**
  106. * when true, schema caching is enabled (for schemas with explicit caching rules).
  107. *
  108. * @default false
  109. */
  110. cache?: boolean;
  111. /**
  112. * provides an external data set to be used in references
  113. */
  114. context?: Context;
  115. /**
  116. * when true, attempts to cast values to the required types (e.g. a string to a number).
  117. *
  118. * @default true
  119. */
  120. convert?: boolean;
  121. /**
  122. * sets the string format used when converting dates to strings in error messages and casting.
  123. *
  124. * @default 'iso'
  125. */
  126. dateFormat?: 'date' | 'iso' | 'string' | 'time' | 'utc';
  127. /**
  128. * when true, valid results and throw errors are decorated with a debug property which includes an array of the validation steps used to generate the returned result.
  129. *
  130. * @default false
  131. */
  132. debug?: boolean;
  133. /**
  134. * error formatting settings.
  135. */
  136. errors?: ErrorFormattingOptions;
  137. /**
  138. * if false, the external rules set with `any.external()` are ignored, which is required to ignore any external validations in synchronous mode (or an exception is thrown).
  139. *
  140. * @default true
  141. */
  142. externals?: boolean;
  143. /**
  144. * when true, do not apply default values.
  145. *
  146. * @default false
  147. */
  148. noDefaults?: boolean;
  149. /**
  150. * when true, inputs are shallow cloned to include non-enumerable properties.
  151. *
  152. * @default false
  153. */
  154. nonEnumerables?: boolean;
  155. /**
  156. * sets the default presence requirements. Supported modes: 'optional', 'required', and 'forbidden'.
  157. *
  158. * @default 'optional'
  159. */
  160. presence?: PresenceMode;
  161. /**
  162. * when true, ignores unknown keys with a function value.
  163. *
  164. * @default false
  165. */
  166. skipFunctions?: boolean;
  167. /**
  168. * remove unknown elements from objects and arrays.
  169. * - when true, all unknown elements will be removed
  170. * - when an object:
  171. * - objects - set to true to remove unknown keys from objects
  172. *
  173. * @default false
  174. */
  175. stripUnknown?: boolean | { arrays?: boolean; objects?: boolean };
  176. }
  177. interface ValidationOptions extends BaseValidationOptions {
  178. /**
  179. * overrides individual error messages. Defaults to no override (`{}`).
  180. * Messages use the same rules as templates.
  181. * Variables in double braces `{{var}}` are HTML escaped if the option `errors.escapeHtml` is set to true.
  182. *
  183. * @default {}
  184. */
  185. messages?: LanguageMessages;
  186. }
  187. interface AsyncValidationOptions extends ValidationOptions {
  188. /**
  189. * when true, artifacts are returned alongside the value (i.e. `{ value, artifacts }`)
  190. *
  191. * @default false
  192. */
  193. artifacts?: boolean;
  194. /**
  195. * when true, warnings are returned alongside the value (i.e. `{ value, warning }`).
  196. *
  197. * @default false
  198. */
  199. warnings?: boolean;
  200. }
  201. interface LanguageMessageTemplate {
  202. source: string;
  203. rendered: string;
  204. }
  205. interface ErrorValidationOptions extends BaseValidationOptions {
  206. messages?: Record<string, LanguageMessageTemplate>;
  207. }
  208. interface RenameOptions {
  209. /**
  210. * if true, does not delete the old key name, keeping both the new and old keys in place.
  211. *
  212. * @default false
  213. */
  214. alias?: boolean;
  215. /**
  216. * if true, allows renaming multiple keys to the same destination where the last rename wins.
  217. *
  218. * @default false
  219. */
  220. multiple?: boolean;
  221. /**
  222. * if true, allows renaming a key over an existing key.
  223. *
  224. * @default false
  225. */
  226. override?: boolean;
  227. /**
  228. * if true, skip renaming of a key if it's undefined.
  229. *
  230. * @default false
  231. */
  232. ignoreUndefined?: boolean;
  233. }
  234. interface TopLevelDomainOptions {
  235. /**
  236. * - `true` to use the IANA list of registered TLDs. This is the default value.
  237. * - `false` to allow any TLD not listed in the `deny` list, if present.
  238. * - A `Set` or array of the allowed TLDs. Cannot be used together with `deny`.
  239. */
  240. allow?: Set<string> | string[] | boolean;
  241. /**
  242. * - A `Set` or array of the forbidden TLDs. Cannot be used together with a custom `allow` list.
  243. */
  244. deny?: Set<string> | string[];
  245. }
  246. interface HierarchySeparatorOptions {
  247. /**
  248. * overrides the default `.` hierarchy separator. Set to false to treat the key as a literal value.
  249. *
  250. * @default '.'
  251. */
  252. separator?: string | false;
  253. }
  254. interface DependencyOptions extends HierarchySeparatorOptions {
  255. /**
  256. * overrides the default check for a present value.
  257. *
  258. * @default (resolved) => resolved !== undefined
  259. */
  260. isPresent?: (resolved: any) => boolean;
  261. }
  262. interface EmailOptions {
  263. /**
  264. * if `true`, domains ending with a `.` character are permitted
  265. *
  266. * @default false
  267. */
  268. allowFullyQualified?: boolean;
  269. /**
  270. * If `true`, Unicode characters are permitted
  271. *
  272. * @default true
  273. */
  274. allowUnicode?: boolean;
  275. /**
  276. * if `true`, ignore invalid email length errors.
  277. *
  278. * @default false
  279. */
  280. ignoreLength?: boolean;
  281. /**
  282. * if true, allows multiple email addresses in a single string, separated by , or the separator characters.
  283. *
  284. * @default false
  285. */
  286. multiple?: boolean;
  287. /**
  288. * when multiple is true, overrides the default , separator. String can be a single character or multiple separator characters.
  289. *
  290. * @default ','
  291. */
  292. separator?: string | string[];
  293. /**
  294. * Options for TLD (top level domain) validation. By default, the TLD must be a valid name listed on the [IANA registry](http://data.iana.org/TLD/tlds-alpha-by-domain.txt)
  295. *
  296. * @default { allow: true }
  297. */
  298. tlds?: TopLevelDomainOptions | false;
  299. /**
  300. * Number of segments required for the domain. Be careful since some domains, such as `io`, directly allow email.
  301. *
  302. * @default 2
  303. */
  304. minDomainSegments?: number;
  305. /**
  306. * The maximum number of domain segments (e.g. `x.y.z` has 3 segments) allowed. Defaults to no limit.
  307. *
  308. * @default Infinity
  309. */
  310. maxDomainSegments?: number;
  311. }
  312. interface DomainOptions {
  313. /**
  314. * if `true`, domains ending with a `.` character are permitted
  315. *
  316. * @default false
  317. */
  318. allowFullyQualified?: boolean;
  319. /**
  320. * If `true`, Unicode characters are permitted
  321. *
  322. * @default true
  323. */
  324. allowUnicode?: boolean;
  325. /**
  326. * Options for TLD (top level domain) validation. By default, the TLD must be a valid name listed on the [IANA registry](http://data.iana.org/TLD/tlds-alpha-by-domain.txt)
  327. *
  328. * @default { allow: true }
  329. */
  330. tlds?: TopLevelDomainOptions | false;
  331. /**
  332. * Number of segments required for the domain.
  333. *
  334. * @default 2
  335. */
  336. minDomainSegments?: number;
  337. /**
  338. * The maximum number of domain segments (e.g. `x.y.z` has 3 segments) allowed. Defaults to no limit.
  339. *
  340. * @default Infinity
  341. */
  342. maxDomainSegments?: number;
  343. }
  344. interface HexOptions {
  345. /**
  346. * hex decoded representation must be byte aligned.
  347. * @default false
  348. */
  349. byteAligned?: boolean;
  350. }
  351. interface IpOptions {
  352. /**
  353. * One or more IP address versions to validate against. Valid values: ipv4, ipv6, ipvfuture
  354. */
  355. version?: string | string[];
  356. /**
  357. * Used to determine if a CIDR is allowed or not. Valid values: optional, required, forbidden
  358. */
  359. cidr?: PresenceMode;
  360. }
  361. type GuidVersions = 'uuidv1' | 'uuidv2' | 'uuidv3' | 'uuidv4' | 'uuidv5' | 'uuidv6' | 'uuidv7' | 'uuidv8';
  362. interface GuidOptions {
  363. version?: GuidVersions[] | GuidVersions;
  364. separator?: boolean | '-' | ':';
  365. }
  366. interface UriOptions {
  367. /**
  368. * Specifies one or more acceptable Schemes, should only include the scheme name.
  369. * Can be an Array or String (strings are automatically escaped for use in a Regular Expression).
  370. */
  371. scheme?: string | RegExp | Array<string | RegExp>;
  372. /**
  373. * Allow relative URIs.
  374. *
  375. * @default false
  376. */
  377. allowRelative?: boolean;
  378. /**
  379. * Restrict only relative URIs.
  380. *
  381. * @default false
  382. */
  383. relativeOnly?: boolean;
  384. /**
  385. * Allows unencoded square brackets inside the query string.
  386. * This is NOT RFC 3986 compliant but query strings like abc[]=123&abc[]=456 are very common these days.
  387. *
  388. * @default false
  389. */
  390. allowQuerySquareBrackets?: boolean;
  391. /**
  392. * Validate the domain component using the options specified in `string.domain()`.
  393. */
  394. domain?: DomainOptions;
  395. }
  396. interface DataUriOptions {
  397. /**
  398. * optional parameter defaulting to true which will require `=` padding if true or make padding optional if false
  399. *
  400. * @default true
  401. */
  402. paddingRequired?: boolean;
  403. }
  404. interface Base64Options extends Pick<DataUriOptions, 'paddingRequired'> {
  405. /**
  406. * if true, uses the URI-safe base64 format which replaces `+` with `-` and `\` with `_`.
  407. *
  408. * @default false
  409. */
  410. urlSafe?: boolean;
  411. }
  412. interface SwitchCases {
  413. /**
  414. * the required condition joi type.
  415. */
  416. is: SchemaLike;
  417. /**
  418. * the alternative schema type if the condition is true.
  419. */
  420. then: SchemaLike;
  421. }
  422. interface SwitchDefault {
  423. /**
  424. * the alternative schema type if no cases matched.
  425. * Only one otherwise statement is allowed in switch as the last array item.
  426. */
  427. otherwise: SchemaLike;
  428. }
  429. interface WhenOptions {
  430. /**
  431. * the required condition joi type.
  432. */
  433. is?: SchemaLike;
  434. /**
  435. * the negative version of `is` (`then` and `otherwise` have reverse
  436. * roles).
  437. */
  438. not?: SchemaLike;
  439. /**
  440. * the alternative schema type if the condition is true. Required if otherwise or switch are missing.
  441. */
  442. then?: SchemaLike;
  443. /**
  444. * the alternative schema type if the condition is false. Required if then or switch are missing.
  445. */
  446. otherwise?: SchemaLike;
  447. /**
  448. * the list of cases. Required if then is missing. Required if then or otherwise are missing.
  449. */
  450. switch?: Array<SwitchCases | SwitchDefault>;
  451. /**
  452. * whether to stop applying further conditions if the condition is true.
  453. */
  454. break?: boolean;
  455. }
  456. interface WhenSchemaOptions {
  457. /**
  458. * the alternative schema type if the condition is true. Required if otherwise is missing.
  459. */
  460. then?: SchemaLike;
  461. /**
  462. * the alternative schema type if the condition is false. Required if then is missing.
  463. */
  464. otherwise?: SchemaLike;
  465. }
  466. interface Cache {
  467. /**
  468. * Add an item to the cache.
  469. *
  470. * Note that key and value can be anything including objects, array, etc.
  471. */
  472. set(key: any, value: any): void;
  473. /**
  474. * Retrieve an item from the cache.
  475. *
  476. * Note that key and value can be anything including objects, array, etc.
  477. */
  478. get(key: any): any;
  479. }
  480. interface CacheProvisionOptions {
  481. /**
  482. * number of items to store in the cache before the least used items are dropped.
  483. *
  484. * @default 1000
  485. */
  486. max: number;
  487. }
  488. interface CacheConfiguration {
  489. /**
  490. * Provisions a simple LRU cache for caching simple inputs (`undefined`, `null`, strings, numbers, and booleans).
  491. */
  492. provision(options?: CacheProvisionOptions): void;
  493. }
  494. interface CompileOptions {
  495. /**
  496. * If true and the provided schema is (or contains parts) using an older version of joi, will return a compiled schema that is compatible with the older version.
  497. * If false, the schema is always compiled using the current version and if older schema components are found, an error is thrown.
  498. */
  499. legacy: boolean;
  500. }
  501. interface IsSchemaOptions {
  502. /**
  503. * If true, will identify schemas from older versions of joi, otherwise will throw an error.
  504. *
  505. * @default false
  506. */
  507. legacy: boolean;
  508. }
  509. interface ReferenceOptions extends HierarchySeparatorOptions {
  510. /**
  511. * a function with the signature `function(value)` where `value` is the resolved reference value and the return value is the adjusted value to use.
  512. * Note that the adjust feature will not perform any type validation on the adjusted value and it must match the value expected by the rule it is used in.
  513. * Cannot be used with `map`.
  514. *
  515. * @example `(value) => value + 5`
  516. */
  517. adjust?: (value: any) => any;
  518. /**
  519. * an array of array pairs using the format `[[key, value], [key, value]]` used to maps the resolved reference value to another value.
  520. * If the resolved value is not in the map, it is returned as-is.
  521. * Cannot be used with `adjust`.
  522. */
  523. map?: Array<[any, any]>;
  524. /**
  525. * overrides default prefix characters.
  526. */
  527. prefix?: {
  528. /**
  529. * references to the globally provided context preference.
  530. *
  531. * @default '$'
  532. */
  533. global?: string;
  534. /**
  535. * references to error-specific or rule specific context.
  536. *
  537. * @default '#'
  538. */
  539. local?: string;
  540. /**
  541. * references to the root value being validated.
  542. *
  543. * @default '/'
  544. */
  545. root?: string;
  546. };
  547. /**
  548. * If set to a number, sets the reference relative starting point.
  549. * Cannot be combined with separator prefix characters.
  550. * Defaults to the reference key prefix (or 1 if none present)
  551. */
  552. ancestor?: number;
  553. /**
  554. * creates an in-reference.
  555. */
  556. in?: boolean;
  557. /**
  558. * when true, the reference resolves by reaching into maps and sets.
  559. */
  560. iterables?: boolean;
  561. /**
  562. * when true, the value of the reference is used instead of its name in error messages
  563. * and template rendering. Defaults to false.
  564. */
  565. render?: boolean;
  566. }
  567. interface StringRegexOptions {
  568. /**
  569. * optional pattern name.
  570. */
  571. name?: string;
  572. /**
  573. * when true, the provided pattern will be disallowed instead of required.
  574. *
  575. * @default false
  576. */
  577. invert?: boolean;
  578. }
  579. interface RuleOptions {
  580. /**
  581. * if true, the rules will not be replaced by the same unique rule later.
  582. *
  583. * For example, `Joi.number().min(1).rule({ keep: true }).min(2)` will keep both `min()` rules instead of the later rule overriding the first.
  584. *
  585. * @default false
  586. */
  587. keep?: boolean;
  588. /**
  589. * a single message string or a messages object where each key is an error code and corresponding message string as value.
  590. *
  591. * The object is the same as the messages used as an option in `any.validate()`.
  592. * The strings can be plain messages or a message template.
  593. */
  594. message?: string | LanguageMessages;
  595. /**
  596. * if true, turns any error generated by the ruleset to warnings.
  597. */
  598. warn?: boolean;
  599. }
  600. interface ErrorReport extends Error {
  601. code: string;
  602. flags: Record<string, ExtensionFlag>;
  603. path: string[];
  604. prefs: ErrorValidationOptions;
  605. messages: LanguageMessages;
  606. state: State;
  607. value: any;
  608. local: any;
  609. }
  610. interface ValidationError extends Error {
  611. name: 'ValidationError';
  612. isJoi: boolean;
  613. /**
  614. * array of errors.
  615. */
  616. details: ValidationErrorItem[];
  617. /**
  618. * function that returns a string with an annotated version of the object pointing at the places where errors occurred.
  619. *
  620. * NOTE: This method does not exist in browser builds of Joi
  621. *
  622. * @param stripColors - if truthy, will strip the colors out of the output.
  623. */
  624. annotate(stripColors?: boolean): string;
  625. _original: any;
  626. }
  627. interface ValidationErrorItem {
  628. message: string;
  629. path: Array<string | number>;
  630. type: string;
  631. context?: Context;
  632. }
  633. type ValidationErrorFunction = (errors: ErrorReport[]) => string | ValidationErrorItem | Error | ErrorReport[];
  634. interface ValidationWarning {
  635. message: string;
  636. details: ValidationErrorItem[];
  637. }
  638. type ValidationResult<TSchema = any> = {
  639. error: undefined;
  640. warning?: ValidationError;
  641. value: TSchema;
  642. } | {
  643. error: ValidationError;
  644. warning?: ValidationError;
  645. value: any;
  646. }
  647. interface CreateErrorOptions {
  648. flags?: boolean;
  649. messages?: LanguageMessages;
  650. }
  651. interface ModifyOptions {
  652. each?: boolean;
  653. once?: boolean;
  654. ref?: boolean;
  655. schema?: boolean;
  656. }
  657. interface MutateRegisterOptions {
  658. family?: any;
  659. key?: any;
  660. }
  661. interface SetFlagOptions {
  662. clone: boolean;
  663. }
  664. interface CustomHelpers<V = any> {
  665. schema: ExtensionBoundSchema;
  666. state: State;
  667. prefs: ValidationOptions;
  668. original: V;
  669. warn: (code: string, local?: Context) => void;
  670. error: (code: string, local?: Context) => ErrorReport;
  671. message: (messages: LanguageMessages, local?: Context) => ErrorReport;
  672. }
  673. type CustomValidator<V = any, R = V> = (value: V, helpers: CustomHelpers<R>) => R | ErrorReport;
  674. interface ExternalHelpers<V = any> {
  675. schema: ExtensionBoundSchema;
  676. linked: ExtensionBoundSchema | null;
  677. state: State;
  678. prefs: ValidationOptions;
  679. original: V;
  680. warn: (code: string, local?: Context) => void;
  681. error: (code: string, local?: Context) => ErrorReport;
  682. message: (messages: LanguageMessages, local?: Context) => ErrorReport;
  683. }
  684. type ExternalValidationFunction<V = any, R = V> = (value: V, helpers: ExternalHelpers<R>) => R | undefined;
  685. type SchemaLikeWithoutArray = string | number | boolean | null | Schema | SchemaMap;
  686. type SchemaLike = SchemaLikeWithoutArray | object;
  687. type NullableType<T> = undefined | null | T
  688. type IsPrimitiveSubset<T> =
  689. [T] extends [string]
  690. ? true
  691. : [T] extends [number]
  692. ? true
  693. : [T] extends [bigint]
  694. ? true
  695. : [T] extends [boolean]
  696. ? true
  697. : [T] extends [symbol]
  698. ? true
  699. : [T] extends [null]
  700. ? true
  701. : [T] extends [undefined]
  702. ? true
  703. : false;
  704. type IsUnion<T, U extends T = T> =
  705. T extends unknown ? [U] extends [T] ? false : true : false;
  706. type IsNonPrimitiveSubsetUnion<T> = true extends IsUnion<T> ? true extends IsPrimitiveSubset<T> ? false : true : false;
  707. type ObjectPropertiesSchema<T = any> =
  708. true extends IsNonPrimitiveSubsetUnion<Exclude<T, undefined | null>>
  709. ? Joi.AlternativesSchema
  710. : T extends NullableType<string>
  711. ? Joi.StringSchema
  712. : T extends NullableType<number>
  713. ? Joi.NumberSchema
  714. : T extends NullableType<bigint>
  715. ? Joi.NumberSchema
  716. : T extends NullableType<boolean>
  717. ? Joi.BooleanSchema
  718. : T extends NullableType<Date>
  719. ? Joi.DateSchema
  720. : T extends NullableType<Buffer>
  721. ? Joi.BinarySchema
  722. : T extends NullableType<Array<any>>
  723. ? Joi.ArraySchema
  724. : T extends NullableType<object>
  725. ? (StrictSchemaMap<T> | ObjectSchema<T>)
  726. : never
  727. type PartialSchemaMap<TSchema = any> = {
  728. [key in keyof TSchema]?: SchemaLike | SchemaLike[];
  729. }
  730. type StrictSchemaMap<TSchema = any> = {
  731. [key in keyof TSchema]-?: ObjectPropertiesSchema<TSchema[key]>
  732. };
  733. type SchemaMap<TSchema = any, isStrict = false> = isStrict extends true ? StrictSchemaMap<TSchema> : PartialSchemaMap<TSchema>
  734. type Schema<P = any> =
  735. | AnySchema<P>
  736. | ArraySchema<P>
  737. | AlternativesSchema<P>
  738. | BinarySchema<P>
  739. | BooleanSchema<P>
  740. | DateSchema<P>
  741. | FunctionSchema<P>
  742. | NumberSchema<P>
  743. | ObjectSchema<P>
  744. | StringSchema<P>
  745. | LinkSchema<P>
  746. | SymbolSchema<P>;
  747. type SchemaFunction = (schema: Schema) => Schema;
  748. interface AddRuleOptions {
  749. name: string;
  750. args?: {
  751. [key: string]: any;
  752. };
  753. }
  754. interface GetRuleOptions {
  755. args?: Record<string, any>;
  756. method?: string;
  757. name: string;
  758. operator?: string;
  759. }
  760. interface SchemaInternals {
  761. /**
  762. * Parent schema object.
  763. */
  764. $_super: Schema;
  765. /**
  766. * Terms of current schema.
  767. */
  768. $_terms: Record<string, any>;
  769. /**
  770. * Adds a rule to current validation schema.
  771. */
  772. $_addRule(rule: string | AddRuleOptions): Schema;
  773. /**
  774. * Internally compiles schema.
  775. */
  776. $_compile(schema: SchemaLike, options?: CompileOptions): Schema;
  777. /**
  778. * Creates a joi error object.
  779. */
  780. $_createError(
  781. code: string,
  782. value: any,
  783. context: Context,
  784. state: State,
  785. prefs: ValidationOptions,
  786. options?: CreateErrorOptions,
  787. ): Err;
  788. /**
  789. * Get value from given flag.
  790. */
  791. $_getFlag(name: string): any;
  792. /**
  793. * Retrieve some rule configuration.
  794. */
  795. $_getRule(name: string): GetRuleOptions | undefined;
  796. $_mapLabels(path: string | string[]): string;
  797. /**
  798. * Returns true if validations runs fine on given value.
  799. */
  800. $_match(value: any, state: State, prefs: ValidationOptions): boolean;
  801. $_modify(options?: ModifyOptions): Schema;
  802. /**
  803. * Resets current schema.
  804. */
  805. $_mutateRebuild(): this;
  806. $_mutateRegister(schema: Schema, options?: MutateRegisterOptions): void;
  807. /**
  808. * Get value from given property.
  809. */
  810. $_property(name: string): any;
  811. /**
  812. * Get schema at given path.
  813. */
  814. $_reach(path: string[]): Schema;
  815. /**
  816. * Get current schema root references.
  817. */
  818. $_rootReferences(): any;
  819. /**
  820. * Set flag to given value.
  821. */
  822. $_setFlag(flag: string, value: any, options?: SetFlagOptions): void;
  823. /**
  824. * Runs internal validations against given value.
  825. */
  826. $_validate(value: any, state: State, prefs: ValidationOptions): ValidationResult;
  827. }
  828. interface AnySchema<TSchema = any> extends SchemaInternals {
  829. /**
  830. * Flags of current schema.
  831. */
  832. _flags: Record<string, any>;
  833. /**
  834. * Starts a ruleset in order to apply multiple rule options. The set ends when `rule()`, `keep()`, `message()`, or `warn()` is called.
  835. */
  836. $: this;
  837. /**
  838. * Starts a ruleset in order to apply multiple rule options. The set ends when `rule()`, `keep()`, `message()`, or `warn()` is called.
  839. */
  840. ruleset: this;
  841. type?: Types | string;
  842. /**
  843. * Whitelists a value
  844. */
  845. allow(...values: any[]): this;
  846. /**
  847. * Assign target alteration options to a schema that are applied when `any.tailor()` is called.
  848. * @param targets - an object where each key is a target name, and each value is a function that takes an schema and returns an schema.
  849. */
  850. alter(targets: Record<string, (schema: this) => Schema>): this;
  851. /**
  852. * Assigns the schema an artifact id which is included in the validation result if the rule passed validation.
  853. * @param id - any value other than undefined which will be returned as-is in the result artifacts map.
  854. */
  855. artifact(id: any): this;
  856. /**
  857. * By default, some Joi methods to function properly need to rely on the Joi instance they are attached to because
  858. * they use `this` internally.
  859. * So `Joi.string()` works but if you extract the function from it and call `string()` it won't.
  860. * `bind()` creates a new Joi instance where all the functions relying on `this` are bound to the Joi instance.
  861. */
  862. bind(): this;
  863. /**
  864. * Adds caching to the schema which will attempt to cache the validation results (success and failures) of incoming inputs.
  865. * If no cache is passed, a default cache is provisioned by using `cache.provision()` internally.
  866. */
  867. cache(cache?: Cache): this;
  868. /**
  869. * Casts the validated value to the specified type.
  870. */
  871. cast(to: 'map' | 'number' | 'set' | 'string'): this;
  872. /**
  873. * Returns a new type that is the result of adding the rules of one type to another.
  874. */
  875. concat(schema: this): this;
  876. /**
  877. * Adds a custom validation function.
  878. */
  879. custom(fn: CustomValidator, description?: string): this;
  880. /**
  881. * Sets a default value if the original value is `undefined` where:
  882. * @param value - the default value. One of:
  883. * - a literal value (string, number, object, etc.)
  884. * - a [references](#refkey-options)
  885. * - a function which returns the default value using the signature `function(parent, helpers)` where:
  886. * - `parent` - a clone of the object containing the value being validated. Note that since specifying a
  887. * `parent` argument performs cloning, do not declare format arguments if you are not using them.
  888. * - `helpers` - same as those described in [`any.custom()`](anycustomermethod_description)
  889. *
  890. * When called without any `value` on an object schema type, a default value will be automatically generated
  891. * based on the default values of the object keys.
  892. *
  893. * Note that if value is an object, any changes to the object after `default()` is called will change the
  894. * reference and any future assignment.
  895. */
  896. default(value?: BasicType | Reference | ((parent: any, helpers: CustomHelpers) => BasicType | Reference)): this;
  897. /**
  898. * Returns a plain object representing the schema's rules and properties
  899. */
  900. describe(): Description;
  901. /**
  902. * Annotates the key
  903. */
  904. description(desc: string): this;
  905. /**
  906. * Disallows values.
  907. */
  908. disallow(...values: any[]): this;
  909. /**
  910. * Considers anything that matches the schema to be empty (undefined).
  911. * @param schema - any object or joi schema to match. An undefined schema unsets that rule.
  912. */
  913. empty(schema?: SchemaLike): this;
  914. /**
  915. * Adds the provided values into the allowed whitelist and marks them as the only valid values allowed.
  916. */
  917. equal(...values: any[]): this;
  918. /**
  919. * Overrides the default joi error with a custom error if the rule fails where:
  920. * @param err - can be:
  921. * an instance of `Error` - the override error.
  922. * a `function(errors)`, taking an array of errors as argument, where it must either:
  923. * return a `string` - substitutes the error message with this text
  924. * return a single ` object` or an `Array` of it, where:
  925. * `type` - optional parameter providing the type of the error (eg. `number.min`).
  926. * `message` - optional parameter if `template` is provided, containing the text of the error.
  927. * `template` - optional parameter if `message` is provided, containing a template string, using the same format as usual joi language errors.
  928. * `context` - optional parameter, to provide context to your error if you are using the `template`.
  929. * return an `Error` - same as when you directly provide an `Error`, but you can customize the error message based on the errors.
  930. *
  931. * Note that if you provide an `Error`, it will be returned as-is, unmodified and undecorated with any of the
  932. * normal joi error properties. If validation fails and another error is found before the error
  933. * override, that error will be returned and the override will be ignored (unless the `abortEarly`
  934. * option has been set to `false`).
  935. */
  936. error(err: Error | ValidationErrorFunction): this;
  937. /**
  938. * Annotates the key with an example value, must be valid.
  939. */
  940. example(value: any, options?: { override: boolean }): this;
  941. /**
  942. * Marks a key as required which will not allow undefined as value. All keys are optional by default.
  943. */
  944. exist(): this;
  945. /**
  946. * Adds an external validation rule.
  947. *
  948. * Note that external validation rules are only called after the all other validation rules for the entire schema (from the value root) are checked.
  949. * This means that any changes made to the value by the external rules are not available to any other validation rules during the non-external validation phase.
  950. * If schema validation failed, no external validation rules are called.
  951. */
  952. external(method: ExternalValidationFunction, description?: string): this;
  953. /**
  954. * Returns a sub-schema based on a path of object keys or schema ids.
  955. *
  956. * @param path - a dot `.` separated path string or a pre-split array of path keys. The keys must match the sub-schema id or object key (if no id was explicitly set).
  957. */
  958. extract(path: string | string[]): Schema;
  959. /**
  960. * Sets a failover value if the original value fails passing validation.
  961. *
  962. * @param value - the failover value. value supports references. value may be assigned a function which returns the default value.
  963. *
  964. * If value is specified as a function that accepts a single parameter, that parameter will be a context object that can be used to derive the resulting value.
  965. * Note that if value is an object, any changes to the object after `failover()` is called will change the reference and any future assignment.
  966. * Use a function when setting a dynamic value (e.g. the current time).
  967. * Using a function with a single argument performs some internal cloning which has a performance impact.
  968. * If you do not need access to the context, define the function without any arguments.
  969. */
  970. failover(value: any): this;
  971. /**
  972. * Marks a key as forbidden which will not allow any value except undefined. Used to explicitly forbid keys.
  973. */
  974. forbidden(): this;
  975. /**
  976. * Returns a new schema where each of the path keys listed have been modified.
  977. *
  978. * @param key - an array of key strings, a single key string, or an array of arrays of pre-split key strings.
  979. * @param adjuster - a function which must return a modified schema.
  980. */
  981. fork(key: string | string[] | string[][], adjuster: SchemaFunction): this;
  982. /**
  983. * Sets a schema id for reaching into the schema via `any.extract()`.
  984. * If no id is set, the schema id defaults to the object key it is associated with.
  985. * If the schema is used in an array or alternatives type and no id is set, the schema in unreachable.
  986. */
  987. id(name?: string): this;
  988. /**
  989. * Disallows values.
  990. */
  991. invalid(...values: any[]): this;
  992. /**
  993. * Same as `rule({ keep: true })`.
  994. *
  995. * Note that `keep()` will terminate the current ruleset and cannot be followed by another rule option.
  996. * Use `rule()` to apply multiple rule options.
  997. */
  998. keep(): this;
  999. /**
  1000. * Overrides the key name in error messages.
  1001. */
  1002. label(name: string): this;
  1003. /**
  1004. * Same as `rule({ message })`.
  1005. *
  1006. * Note that `message()` will terminate the current ruleset and cannot be followed by another rule option.
  1007. * Use `rule()` to apply multiple rule options.
  1008. */
  1009. message(message: string): this;
  1010. /**
  1011. * Same as `any.prefs({ messages })`.
  1012. * Note that while `any.message()` applies only to the last rule or ruleset, `any.messages()` applies to the entire schema.
  1013. */
  1014. messages(messages: LanguageMessages): this;
  1015. /**
  1016. * Attaches metadata to the key.
  1017. */
  1018. meta(meta: object): this;
  1019. /**
  1020. * Disallows values.
  1021. */
  1022. not(...values: any[]): this;
  1023. /**
  1024. * Annotates the key
  1025. */
  1026. note(...notes: string[]): this;
  1027. /**
  1028. * Requires the validated value to match of the provided `any.allow()` values.
  1029. * It has not effect when called together with `any.valid()` since it already sets the requirements.
  1030. * When used with `any.allow()` it converts it to an `any.valid()`.
  1031. */
  1032. only(): this;
  1033. /**
  1034. * Marks a key as optional which will allow undefined as values. Used to annotate the schema for readability as all keys are optional by default.
  1035. */
  1036. optional(): this;
  1037. /**
  1038. * Overrides the global validate() options for the current key and any sub-key.
  1039. */
  1040. options(options: ValidationOptions): this;
  1041. /**
  1042. * Overrides the global validate() options for the current key and any sub-key.
  1043. */
  1044. prefs(options: ValidationOptions): this;
  1045. /**
  1046. * Overrides the global validate() options for the current key and any sub-key.
  1047. */
  1048. preferences(options: ValidationOptions): this;
  1049. /**
  1050. * Sets the presence mode for the schema.
  1051. */
  1052. presence(mode: PresenceMode): this;
  1053. /**
  1054. * Outputs the original untouched value instead of the casted value.
  1055. */
  1056. raw(enabled?: boolean): this;
  1057. /**
  1058. * Marks a key as required which will not allow undefined as value. All keys are optional by default.
  1059. */
  1060. required(): this;
  1061. /**
  1062. * Applies a set of rule options to the current ruleset or last rule added.
  1063. *
  1064. * When applying rule options, the last rule (e.g. `min()`) is used unless there is an active ruleset defined (e.g. `$.min().max()`)
  1065. * in which case the options are applied to all the provided rules.
  1066. * Once `rule()` is called, the previous rules can no longer be modified and any active ruleset is terminated.
  1067. *
  1068. * Rule modifications can only be applied to supported rules.
  1069. * Most of the `any` methods do not support rule modifications because they are implemented using schema flags (e.g. `required()`) or special
  1070. * internal implementation (e.g. `valid()`).
  1071. * In those cases, use the `any.messages()` method to override the error codes for the errors you want to customize.
  1072. */
  1073. rule(options: RuleOptions): this;
  1074. /**
  1075. * Registers a schema to be used by descendants of the current schema in named link references.
  1076. */
  1077. shared(ref: Schema): this;
  1078. /**
  1079. * Sets the options.convert options to false which prevent type casting for the current key and any child keys.
  1080. */
  1081. strict(isStrict?: boolean): this;
  1082. /**
  1083. * Marks a key to be removed from a resulting object or array after validation. Used to sanitize output.
  1084. * @param [enabled=true] - if true, the value is stripped, otherwise the validated value is retained. Defaults to true.
  1085. */
  1086. strip(enabled?: boolean): this;
  1087. /**
  1088. * Annotates the key
  1089. */
  1090. tag(...tags: string[]): this;
  1091. /**
  1092. * Applies any assigned target alterations to a copy of the schema that were applied via `any.alter()`.
  1093. */
  1094. tailor(targets: string | string[]): Schema;
  1095. /**
  1096. * Annotates the key with an unit name.
  1097. */
  1098. unit(name: string): this;
  1099. /**
  1100. * Adds the provided values into the allowed whitelist and marks them as the only valid values allowed.
  1101. */
  1102. valid(...values: any[]): this;
  1103. /**
  1104. * Validates a value using the schema and options.
  1105. */
  1106. validate(value: any, options?: ValidationOptions): ValidationResult<TSchema>;
  1107. /**
  1108. * Validates a value using the schema and options.
  1109. */
  1110. validateAsync<TOpts extends AsyncValidationOptions>(
  1111. value: any,
  1112. options?: TOpts
  1113. ): Promise<
  1114. TOpts extends { artifacts: true } | { warnings: true }
  1115. ? { value: TSchema } & (TOpts extends { artifacts: true }
  1116. ? { artifacts: Map<any, string[][]> }
  1117. : {}) &
  1118. (TOpts extends { warnings: true }
  1119. ? { warning: ValidationWarning }
  1120. : {})
  1121. : TSchema
  1122. >;
  1123. /**
  1124. * Same as `rule({ warn: true })`.
  1125. * Note that `warn()` will terminate the current ruleset and cannot be followed by another rule option.
  1126. * Use `rule()` to apply multiple rule options.
  1127. */
  1128. warn(): this;
  1129. /**
  1130. * Generates a warning.
  1131. * When calling `any.validateAsync()`, set the `warning` option to true to enable warnings.
  1132. * Warnings are reported separately from errors alongside the result value via the warning key (i.e. `{ value, warning }`).
  1133. * Warning are always included when calling `any.validate()`.
  1134. */
  1135. warning(code: string, context: Context): this;
  1136. /**
  1137. * Converts the type into an alternatives type where the conditions are merged into the type definition where:
  1138. */
  1139. when(ref: string | Reference, options: WhenOptions | WhenOptions[]): this;
  1140. /**
  1141. * Converts the type into an alternatives type where the conditions are merged into the type definition where:
  1142. */
  1143. when(ref: Schema, options: WhenSchemaOptions): this;
  1144. }
  1145. interface Description {
  1146. type?: Types | string;
  1147. label?: string;
  1148. description?: string;
  1149. flags?: object;
  1150. notes?: string[];
  1151. tags?: string[];
  1152. metas?: any[];
  1153. example?: any[];
  1154. valids?: any[];
  1155. invalids?: any[];
  1156. unit?: string;
  1157. options?: ValidationOptions;
  1158. [key: string]: any;
  1159. }
  1160. interface Context {
  1161. [key: string]: any;
  1162. key?: string;
  1163. label?: string;
  1164. value?: any;
  1165. }
  1166. interface State {
  1167. key?: string;
  1168. path?: string;
  1169. parent?: any;
  1170. reference?: any;
  1171. ancestors?: any;
  1172. localize?(...args: any[]): State;
  1173. }
  1174. interface BooleanSchema<TSchema = boolean> extends AnySchema<TSchema> {
  1175. /**
  1176. * Allows for additional values to be considered valid booleans by converting them to false during validation.
  1177. * String comparisons are by default case insensitive,
  1178. * see `boolean.sensitive()` to change this behavior.
  1179. * @param values - strings, numbers or arrays of them
  1180. */
  1181. falsy(...values: Array<string | number | null>): this;
  1182. /**
  1183. * Allows the values provided to truthy and falsy as well as the "true" and "false" default conversion
  1184. * (when not in `strict()` mode) to be matched in a case insensitive manner.
  1185. */
  1186. sensitive(enabled?: boolean): this;
  1187. /**
  1188. * Allows for additional values to be considered valid booleans by converting them to true during validation.
  1189. * String comparisons are by default case insensitive, see `boolean.sensitive()` to change this behavior.
  1190. * @param values - strings, numbers or arrays of them
  1191. */
  1192. truthy(...values: Array<string | number | null>): this;
  1193. }
  1194. interface NumberSchema<TSchema = number> extends AnySchema<TSchema> {
  1195. /**
  1196. * Specifies that the value must be greater than limit.
  1197. * It can also be a reference to another field.
  1198. */
  1199. greater(limit: number | Reference): this;
  1200. /**
  1201. * Requires the number to be an integer (no floating point).
  1202. */
  1203. integer(): this;
  1204. /**
  1205. * Specifies that the value must be less than limit.
  1206. * It can also be a reference to another field.
  1207. */
  1208. less(limit: number | Reference): this;
  1209. /**
  1210. * Specifies the maximum value.
  1211. * It can also be a reference to another field.
  1212. */
  1213. max(limit: number | Reference): this;
  1214. /**
  1215. * Specifies the minimum value.
  1216. * It can also be a reference to another field.
  1217. */
  1218. min(limit: number | Reference): this;
  1219. /**
  1220. * Specifies that the value must be a multiple of base.
  1221. */
  1222. multiple(base: number | Reference): this;
  1223. /**
  1224. * Requires the number to be negative.
  1225. */
  1226. negative(): this;
  1227. /**
  1228. * Requires the number to be a TCP port, so between 0 and 65535.
  1229. */
  1230. port(): this;
  1231. /**
  1232. * Requires the number to be positive.
  1233. */
  1234. positive(): this;
  1235. /**
  1236. * Specifies the maximum number of decimal places where:
  1237. * @param limit - the maximum number of decimal places allowed.
  1238. */
  1239. precision(limit: number): this;
  1240. /**
  1241. * Requires the number to be negative or positive.
  1242. */
  1243. sign(sign: 'positive' | 'negative'): this;
  1244. /**
  1245. * Allows the number to be outside of JavaScript's safety range (Number.MIN_SAFE_INTEGER & Number.MAX_SAFE_INTEGER).
  1246. */
  1247. unsafe(enabled?: any): this;
  1248. }
  1249. interface StringSchema<TSchema = string> extends AnySchema<TSchema> {
  1250. /**
  1251. * Requires the string value to only contain a-z, A-Z, and 0-9.
  1252. */
  1253. alphanum(): this;
  1254. /**
  1255. * Requires the string value to be a valid base64 string; does not check the decoded value.
  1256. */
  1257. base64(options?: Base64Options): this;
  1258. /**
  1259. * Sets the required string case.
  1260. */
  1261. case(direction: 'upper' | 'lower'): this;
  1262. /**
  1263. * Requires the number to be a credit card number (Using Luhn Algorithm).
  1264. */
  1265. creditCard(): this;
  1266. /**
  1267. * Requires the string value to be a valid data URI string.
  1268. */
  1269. dataUri(options?: DataUriOptions): this;
  1270. /**
  1271. * Requires the string value to be a valid domain.
  1272. */
  1273. domain(options?: DomainOptions): this;
  1274. /**
  1275. * Requires the string value to be a valid email address.
  1276. */
  1277. email(options?: EmailOptions): this;
  1278. /**
  1279. * Requires the string value to be a valid GUID.
  1280. */
  1281. guid(options?: GuidOptions): this;
  1282. /**
  1283. * Requires the string value to be a valid hexadecimal string.
  1284. */
  1285. hex(options?: HexOptions): this;
  1286. /**
  1287. * Requires the string value to be a valid hostname as per RFC1123.
  1288. */
  1289. hostname(): this;
  1290. /**
  1291. * Allows the value to match any whitelist of blacklist item in a case insensitive comparison.
  1292. */
  1293. insensitive(): this;
  1294. /**
  1295. * Requires the string value to be a valid ip address.
  1296. */
  1297. ip(options?: IpOptions): this;
  1298. /**
  1299. * Requires the string value to be in valid ISO 8601 date format.
  1300. */
  1301. isoDate(): this;
  1302. /**
  1303. * Requires the string value to be in valid ISO 8601 duration format.
  1304. */
  1305. isoDuration(): this;
  1306. /**
  1307. * Specifies the exact string length required
  1308. * @param limit - the required string length. It can also be a reference to another field.
  1309. * @param encoding - if specified, the string length is calculated in bytes using the provided encoding.
  1310. */
  1311. length(limit: number | Reference, encoding?: string): this;
  1312. /**
  1313. * Requires the string value to be all lowercase. If the validation convert option is on (enabled by default), the string will be forced to lowercase.
  1314. */
  1315. lowercase(): this;
  1316. /**
  1317. * Specifies the maximum number of string characters.
  1318. * @param limit - the maximum number of string characters allowed. It can also be a reference to another field.
  1319. * @param encoding - if specified, the string length is calculated in bytes using the provided encoding.
  1320. */
  1321. max(limit: number | Reference, encoding?: string): this;
  1322. /**
  1323. * Specifies the minimum number string characters.
  1324. * @param limit - the minimum number of string characters required. It can also be a reference to another field.
  1325. * @param encoding - if specified, the string length is calculated in bytes using the provided encoding.
  1326. */
  1327. min(limit: number | Reference, encoding?: string): this;
  1328. /**
  1329. * Requires the string value to be in a unicode normalized form. If the validation convert option is on (enabled by default), the string will be normalized.
  1330. * @param [form='NFC'] - The unicode normalization form to use. Valid values: NFC [default], NFD, NFKC, NFKD
  1331. */
  1332. normalize(form?: 'NFC' | 'NFD' | 'NFKC' | 'NFKD'): this;
  1333. /**
  1334. * Defines a regular expression rule.
  1335. * @param pattern - a regular expression object the string value must match against.
  1336. * @param options - optional, can be:
  1337. * Name for patterns (useful with multiple patterns). Defaults to 'required'.
  1338. * An optional configuration object with the following supported properties:
  1339. * name - optional pattern name.
  1340. * invert - optional boolean flag. Defaults to false behavior. If specified as true, the provided pattern will be disallowed instead of required.
  1341. */
  1342. pattern(pattern: RegExp, options?: string | StringRegexOptions): this;
  1343. /**
  1344. * Defines a regular expression rule.
  1345. * @param pattern - a regular expression object the string value must match against.
  1346. * @param options - optional, can be:
  1347. * Name for patterns (useful with multiple patterns). Defaults to 'required'.
  1348. * An optional configuration object with the following supported properties:
  1349. * name - optional pattern name.
  1350. * invert - optional boolean flag. Defaults to false behavior. If specified as true, the provided pattern will be disallowed instead of required.
  1351. */
  1352. regex(pattern: RegExp, options?: string | StringRegexOptions): this;
  1353. /**
  1354. * Replace characters matching the given pattern with the specified replacement string where:
  1355. * @param pattern - a regular expression object to match against, or a string of which all occurrences will be replaced.
  1356. * @param replacement - the string that will replace the pattern.
  1357. */
  1358. replace(pattern: RegExp | string, replacement: string): this;
  1359. /**
  1360. * Requires the string value to only contain a-z, A-Z, 0-9, and underscore _.
  1361. */
  1362. token(): this;
  1363. /**
  1364. * Requires the string value to contain no whitespace before or after. If the validation convert option is on (enabled by default), the string will be trimmed.
  1365. * @param [enabled=true] - optional parameter defaulting to true which allows you to reset the behavior of trim by providing a falsy value.
  1366. */
  1367. trim(enabled?: any): this;
  1368. /**
  1369. * Specifies whether the string.max() limit should be used as a truncation.
  1370. * @param [enabled=true] - optional parameter defaulting to true which allows you to reset the behavior of truncate by providing a falsy value.
  1371. */
  1372. truncate(enabled?: boolean): this;
  1373. /**
  1374. * Requires the string value to be all uppercase. If the validation convert option is on (enabled by default), the string will be forced to uppercase.
  1375. */
  1376. uppercase(): this;
  1377. /**
  1378. * Requires the string value to be a valid RFC 3986 URI.
  1379. */
  1380. uri(options?: UriOptions): this;
  1381. /**
  1382. * Requires the string value to be a valid GUID.
  1383. */
  1384. uuid(options?: GuidOptions): this;
  1385. }
  1386. interface SymbolSchema<TSchema = Symbol> extends AnySchema<TSchema> {
  1387. // TODO: support number and symbol index
  1388. map(iterable: Iterable<[string | number | boolean | symbol, symbol]> | { [key: string]: symbol }): this;
  1389. }
  1390. interface ArraySortOptions {
  1391. /**
  1392. * @default 'ascending'
  1393. */
  1394. order?: 'ascending' | 'descending';
  1395. by?: string | Reference;
  1396. }
  1397. interface ArrayUniqueOptions extends HierarchySeparatorOptions {
  1398. /**
  1399. * if true, undefined values for the dot notation string comparator will not cause the array to fail on uniqueness.
  1400. *
  1401. * @default false
  1402. */
  1403. ignoreUndefined?: boolean;
  1404. }
  1405. type ComparatorFunction = (a: any, b: any) => boolean;
  1406. interface ArraySchema<TSchema = any[]> extends AnySchema<TSchema> {
  1407. /**
  1408. * Verifies that an assertion passes for at least one item in the array, where:
  1409. * `schema` - the validation rules required to satisfy the assertion. If the `schema` includes references, they are resolved against
  1410. * the array item being tested, not the value of the `ref` target.
  1411. */
  1412. has(schema: SchemaLike): this;
  1413. /**
  1414. * List the types allowed for the array values.
  1415. * If a given type is .required() then there must be a matching item in the array.
  1416. * If a type is .forbidden() then it cannot appear in the array.
  1417. * Required items can be added multiple times to signify that multiple items must be found.
  1418. * Errors will contain the number of items that didn't match.
  1419. * Any unmatched item having a label will be mentioned explicitly.
  1420. *
  1421. * @param type - a joi schema object to validate each array item against.
  1422. */
  1423. items(...types: SchemaLikeWithoutArray[]): this;
  1424. /**
  1425. * Specifies the exact number of items in the array.
  1426. */
  1427. length(limit: number | Reference): this;
  1428. /**
  1429. * Specifies the maximum number of items in the array.
  1430. */
  1431. max(limit: number | Reference): this;
  1432. /**
  1433. * Specifies the minimum number of items in the array.
  1434. */
  1435. min(limit: number | Reference): this;
  1436. /**
  1437. * Lists the types in sequence order for the array values where:
  1438. * @param type - a joi schema object to validate against each array item in sequence order. type can be multiple values passed as individual arguments.
  1439. * If a given type is .required() then there must be a matching item with the same index position in the array.
  1440. * Errors will contain the number of items that didn't match.
  1441. * Any unmatched item having a label will be mentioned explicitly.
  1442. */
  1443. ordered(...types: SchemaLikeWithoutArray[]): this;
  1444. /**
  1445. * Allow single values to be checked against rules as if it were provided as an array.
  1446. * enabled can be used with a falsy value to go back to the default behavior.
  1447. */
  1448. single(enabled?: any): this;
  1449. /**
  1450. * Sorts the array by given order.
  1451. */
  1452. sort(options?: ArraySortOptions): this;
  1453. /**
  1454. * Allow this array to be sparse.
  1455. * enabled can be used with a falsy value to go back to the default behavior.
  1456. */
  1457. sparse(enabled?: any): this;
  1458. /**
  1459. * Requires the array values to be unique.
  1460. * Remember that if you provide a custom comparator function,
  1461. * different types can be passed as parameter depending on the rules you set on items.
  1462. * Be aware that a deep equality is performed on elements of the array having a type of object,
  1463. * a performance penalty is to be expected for this kind of operation.
  1464. */
  1465. unique(comparator?: string | ComparatorFunction, options?: ArrayUniqueOptions): this;
  1466. }
  1467. interface ObjectPatternOptions {
  1468. fallthrough?: boolean;
  1469. matches: SchemaLike | Reference;
  1470. }
  1471. interface ObjectSchema<TSchema = any> extends AnySchema<TSchema> {
  1472. /**
  1473. * Defines an all-or-nothing relationship between keys where if one of the peers is present, all of them are required as well.
  1474. *
  1475. * Optional settings must be the last argument.
  1476. */
  1477. and(...peers: Array<string | DependencyOptions>): this;
  1478. /**
  1479. * Appends the allowed object keys. If schema is null, undefined, or {}, no changes will be applied.
  1480. */
  1481. append(schema?: SchemaMap<TSchema>): this;
  1482. append<TSchemaExtended = any, T = TSchemaExtended>(schema?: SchemaMap<T>): ObjectSchema<T>
  1483. /**
  1484. * Verifies an assertion where.
  1485. */
  1486. assert(ref: string | Reference, schema: SchemaLike, message?: string): this;
  1487. /**
  1488. * Requires the object to be an instance of a given constructor.
  1489. *
  1490. * @param constructor - the constructor function that the object must be an instance of.
  1491. * @param name - an alternate name to use in validation errors. This is useful when the constructor function does not have a name.
  1492. */
  1493. // tslint:disable-next-line:ban-types
  1494. instance(constructor: Function, name?: string): this;
  1495. /**
  1496. * Sets or extends the allowed object keys.
  1497. */
  1498. keys(schema?: SchemaMap<TSchema>): this;
  1499. /**
  1500. * Specifies the exact number of keys in the object.
  1501. */
  1502. length(limit: number): this;
  1503. /**
  1504. * Specifies the maximum number of keys in the object.
  1505. */
  1506. max(limit: number | Reference): this;
  1507. /**
  1508. * Specifies the minimum number of keys in the object.
  1509. */
  1510. min(limit: number | Reference): this;
  1511. /**
  1512. * Defines a relationship between keys where not all peers can be present at the same time.
  1513. *
  1514. * Optional settings must be the last argument.
  1515. */
  1516. nand(...peers: Array<string | DependencyOptions>): this;
  1517. /**
  1518. * Defines a relationship between keys where one of the peers is required (and more than one is allowed).
  1519. *
  1520. * Optional settings must be the last argument.
  1521. */
  1522. or(...peers: Array<string | DependencyOptions>): this;
  1523. /**
  1524. * Defines an exclusive relationship between a set of keys where only one is allowed but none are required.
  1525. *
  1526. * Optional settings must be the last argument.
  1527. */
  1528. oxor(...peers: Array<string | DependencyOptions>): this;
  1529. /**
  1530. * Specify validation rules for unknown keys matching a pattern.
  1531. *
  1532. * @param pattern - a pattern that can be either a regular expression or a joi schema that will be tested against the unknown key names
  1533. * @param schema - the schema object matching keys must validate against
  1534. */
  1535. pattern(pattern: RegExp | SchemaLike, schema: SchemaLike, options?: ObjectPatternOptions): this;
  1536. /**
  1537. * Requires the object to be a Joi reference.
  1538. */
  1539. ref(): this;
  1540. /**
  1541. * Requires the object to be a `RegExp` object.
  1542. */
  1543. regex(): this;
  1544. /**
  1545. * Renames a key to another name (deletes the renamed key).
  1546. */
  1547. rename(from: string | RegExp, to: string, options?: RenameOptions): this;
  1548. /**
  1549. * Requires the object to be a Joi schema instance.
  1550. */
  1551. schema(type?: SchemaLike): this;
  1552. /**
  1553. * Overrides the handling of unknown keys for the scope of the current object only (does not apply to children).
  1554. */
  1555. unknown(allow?: boolean): this;
  1556. /**
  1557. * Requires the presence of other keys whenever the specified key is present.
  1558. */
  1559. with(key: string, peers: string | string[], options?: DependencyOptions): this;
  1560. /**
  1561. * Forbids the presence of other keys whenever the specified is present.
  1562. */
  1563. without(key: string, peers: string | string[], options?: DependencyOptions): this;
  1564. /**
  1565. * Defines an exclusive relationship between a set of keys. one of them is required but not at the same time.
  1566. *
  1567. * Optional settings must be the last argument.
  1568. */
  1569. xor(...peers: Array<string | DependencyOptions>): this;
  1570. }
  1571. interface BinarySchema<TSchema = Buffer> extends AnySchema<TSchema> {
  1572. /**
  1573. * Sets the string encoding format if a string input is converted to a buffer.
  1574. */
  1575. encoding(encoding: string): this;
  1576. /**
  1577. * Specifies the minimum length of the buffer.
  1578. */
  1579. min(limit: number | Reference): this;
  1580. /**
  1581. * Specifies the maximum length of the buffer.
  1582. */
  1583. max(limit: number | Reference): this;
  1584. /**
  1585. * Specifies the exact length of the buffer:
  1586. */
  1587. length(limit: number | Reference): this;
  1588. }
  1589. interface DateSchema<TSchema = Date> extends AnySchema<TSchema> {
  1590. /**
  1591. * Specifies that the value must be greater than date.
  1592. * Notes: 'now' can be passed in lieu of date so as to always compare relatively to the current date,
  1593. * allowing to explicitly ensure a date is either in the past or in the future.
  1594. * It can also be a reference to another field.
  1595. */
  1596. greater(date: 'now' | Date | number | string | Reference): this;
  1597. /**
  1598. * Requires the string value to be in valid ISO 8601 date format.
  1599. */
  1600. iso(): this;
  1601. /**
  1602. * Specifies that the value must be less than date.
  1603. * Notes: 'now' can be passed in lieu of date so as to always compare relatively to the current date,
  1604. * allowing to explicitly ensure a date is either in the past or in the future.
  1605. * It can also be a reference to another field.
  1606. */
  1607. less(date: 'now' | Date | number | string | Reference): this;
  1608. /**
  1609. * Specifies the oldest date allowed.
  1610. * Notes: 'now' can be passed in lieu of date so as to always compare relatively to the current date,
  1611. * allowing to explicitly ensure a date is either in the past or in the future.
  1612. * It can also be a reference to another field.
  1613. */
  1614. min(date: 'now' | Date | number | string | Reference): this;
  1615. /**
  1616. * Specifies the latest date allowed.
  1617. * Notes: 'now' can be passed in lieu of date so as to always compare relatively to the current date,
  1618. * allowing to explicitly ensure a date is either in the past or in the future.
  1619. * It can also be a reference to another field.
  1620. */
  1621. max(date: 'now' | Date | number | string | Reference): this;
  1622. /**
  1623. * Requires the value to be a timestamp interval from Unix Time.
  1624. * @param type - the type of timestamp (allowed values are unix or javascript [default])
  1625. */
  1626. timestamp(type?: 'javascript' | 'unix'): this;
  1627. }
  1628. interface FunctionSchema<TSchema = Function> extends ObjectSchema<TSchema> {
  1629. /**
  1630. * Specifies the arity of the function where:
  1631. * @param n - the arity expected.
  1632. */
  1633. arity(n: number): this;
  1634. /**
  1635. * Requires the function to be a class.
  1636. */
  1637. class(): this;
  1638. /**
  1639. * Specifies the minimal arity of the function where:
  1640. * @param n - the minimal arity expected.
  1641. */
  1642. minArity(n: number): this;
  1643. /**
  1644. * Specifies the minimal arity of the function where:
  1645. * @param n - the minimal arity expected.
  1646. */
  1647. maxArity(n: number): this;
  1648. }
  1649. interface AlternativesSchema<TSchema = any> extends AnySchema<TSchema> {
  1650. /**
  1651. * Adds a conditional alternative schema type, either based on another key value, or a schema peeking into the current value.
  1652. */
  1653. conditional(ref: string | Reference, options: WhenOptions | WhenOptions[]): this;
  1654. conditional(ref: Schema, options: WhenSchemaOptions): this;
  1655. /**
  1656. * Requires the validated value to match a specific set of the provided alternative.try() schemas.
  1657. * Cannot be combined with `alternatives.conditional()`.
  1658. */
  1659. match(mode: 'any' | 'all' | 'one'): this;
  1660. /**
  1661. * Adds an alternative schema type for attempting to match against the validated value.
  1662. */
  1663. try(...types: SchemaLikeWithoutArray[]): this;
  1664. }
  1665. interface LinkSchema<TSchema = any> extends AnySchema<TSchema> {
  1666. /**
  1667. * Same as `any.concat()` but the schema is merged after the link is resolved which allows merging with schemas of the same type as the resolved link.
  1668. * Will throw an exception during validation if the merged types are not compatible.
  1669. */
  1670. concat(schema: Schema): this;
  1671. /**
  1672. * Initializes the schema after constructions for cases where the schema has to be constructed first and then initialized.
  1673. * If `ref` was not passed to the constructor, `link.ref()` must be called prior to usage.
  1674. */
  1675. ref(ref: string): this;
  1676. }
  1677. interface Reference extends Exclude<ReferenceOptions, 'prefix'> {
  1678. depth: number;
  1679. type: string;
  1680. key: string;
  1681. root: string;
  1682. path: string[];
  1683. display: string;
  1684. toString(): string;
  1685. }
  1686. type ExtensionBoundSchema = Schema & SchemaInternals;
  1687. interface RuleArgs {
  1688. name: string;
  1689. ref?: boolean;
  1690. assert?: ((value: any) => boolean) | AnySchema;
  1691. message?: string;
  1692. /**
  1693. * Undocumented properties
  1694. */
  1695. normalize?(value: any): any;
  1696. }
  1697. type RuleMethod = (...args: any[]) => any;
  1698. interface ExtensionRule {
  1699. /**
  1700. * alternative name for this rule.
  1701. */
  1702. alias?: string;
  1703. /**
  1704. * whether rule supports multiple invocations.
  1705. */
  1706. multi?: boolean;
  1707. /**
  1708. * Dual rule: converts or validates.
  1709. */
  1710. convert?: boolean;
  1711. /**
  1712. * list of arguments accepted by `method`.
  1713. */
  1714. args?: Array<RuleArgs | string>;
  1715. /**
  1716. * rule body.
  1717. */
  1718. method?: RuleMethod | false;
  1719. /**
  1720. * validation function.
  1721. */
  1722. validate?(value: any, helpers: any, args: Record<string, any>, options: any): any;
  1723. /**
  1724. * undocumented flags.
  1725. */
  1726. priority?: boolean;
  1727. manifest?: boolean;
  1728. }
  1729. interface CoerceResult {
  1730. errors?: ErrorReport[];
  1731. value?: any;
  1732. }
  1733. type CoerceFunction = (value: any, helpers: CustomHelpers) => CoerceResult;
  1734. interface CoerceObject {
  1735. method: CoerceFunction;
  1736. from?: string | string[];
  1737. }
  1738. interface ExtensionFlag {
  1739. setter?: string;
  1740. default?: any;
  1741. }
  1742. interface ExtensionTermManifest {
  1743. mapped: {
  1744. from: string;
  1745. to: string;
  1746. };
  1747. }
  1748. interface ExtensionTerm {
  1749. init: any[] | null;
  1750. register?: any;
  1751. manifest?: Record<string, 'schema' | 'single' | ExtensionTermManifest>;
  1752. }
  1753. interface Extension {
  1754. type: string | RegExp;
  1755. args?(...args: SchemaLike[]): Schema;
  1756. base?: Schema;
  1757. coerce?: CoerceFunction | CoerceObject;
  1758. flags?: Record<string, ExtensionFlag>;
  1759. manifest?: {
  1760. build?(obj: ExtensionBoundSchema, desc: Record<string, any>): any;
  1761. };
  1762. messages?: LanguageMessages | string;
  1763. modifiers?: Record<string, (rule: any, enabled?: boolean) => any>;
  1764. overrides?: Record<string, (value: any) => Schema>;
  1765. prepare?(value: any, helpers: CustomHelpers): any;
  1766. rebuild?(schema: ExtensionBoundSchema): void;
  1767. rules?: Record<string, ExtensionRule & ThisType<SchemaInternals>>;
  1768. terms?: Record<string, ExtensionTerm>;
  1769. validate?(value: any, helpers: CustomHelpers): any;
  1770. /**
  1771. * undocumented options
  1772. */
  1773. cast?: Record<string, { from(value: any): any; to(value: any, helpers: CustomHelpers): any }>;
  1774. properties?: Record<string, any>;
  1775. }
  1776. type ExtensionFactory = (joi: Root) => Extension;
  1777. interface Err {
  1778. toString(): string;
  1779. }
  1780. // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
  1781. interface Root {
  1782. /**
  1783. * Current version of the joi package.
  1784. */
  1785. version: string;
  1786. ValidationError: new (message: string, details: ValidationErrorItem[], original: any) => ValidationError;
  1787. /**
  1788. * Generates a schema object that matches any data type.
  1789. */
  1790. any<TSchema = any>(): AnySchema<TSchema>;
  1791. /**
  1792. * Generates a schema object that matches an array data type.
  1793. */
  1794. array<TSchema = any[]>(): ArraySchema<TSchema>;
  1795. /**
  1796. * Generates a schema object that matches a boolean data type (as well as the strings 'true', 'false', 'yes', and 'no'). Can also be called via boolean().
  1797. */
  1798. bool<TSchema = boolean>(): BooleanSchema<TSchema>;
  1799. /**
  1800. * Generates a schema object that matches a boolean data type (as well as the strings 'true', 'false', 'yes', and 'no'). Can also be called via bool().
  1801. */
  1802. boolean<TSchema = boolean>(): BooleanSchema<TSchema>;
  1803. /**
  1804. * Generates a schema object that matches a Buffer data type (as well as the strings which will be converted to Buffers).
  1805. */
  1806. binary<TSchema = Buffer>(): BinarySchema<TSchema>;
  1807. /**
  1808. * Generates a schema object that matches a date type (as well as a JavaScript date string or number of milliseconds).
  1809. */
  1810. date<TSchema = Date>(): DateSchema<TSchema>;
  1811. /**
  1812. * Generates a schema object that matches a function type.
  1813. */
  1814. func<TSchema = Function>(): FunctionSchema<TSchema>;
  1815. /**
  1816. * Generates a schema object that matches a function type.
  1817. */
  1818. function<TSchema = Function>(): FunctionSchema<TSchema>;
  1819. /**
  1820. * Generates a schema object that matches a number data type (as well as strings that can be converted to numbers).
  1821. */
  1822. number<TSchema = number>(): NumberSchema<TSchema>;
  1823. /**
  1824. * Generates a schema object that matches an object data type (as well as JSON strings that have been parsed into objects).
  1825. */
  1826. // tslint:disable-next-line:no-unnecessary-generics
  1827. object<TSchema = any, isStrict = false, T = TSchema>(schema?: SchemaMap<T, isStrict>): ObjectSchema<TSchema>;
  1828. /**
  1829. * Generates a schema object that matches a string data type. Note that empty strings are not allowed by default and must be enabled with allow('').
  1830. */
  1831. string<TSchema = string>(): StringSchema<TSchema>;
  1832. /**
  1833. * Generates a schema object that matches any symbol.
  1834. */
  1835. symbol<TSchema = Symbol>(): SymbolSchema<TSchema>;
  1836. /**
  1837. * Generates a type that will match one of the provided alternative schemas
  1838. */
  1839. alternatives<TSchema = any>(types: SchemaLike[]): AlternativesSchema<TSchema>;
  1840. alternatives<TSchema = any>(...types: SchemaLike[]): AlternativesSchema<TSchema>;
  1841. /**
  1842. * Alias for `alternatives`
  1843. */
  1844. alt<TSchema = any>(types: SchemaLike[]): AlternativesSchema<TSchema>;
  1845. alt<TSchema = any>(...types: SchemaLike[]): AlternativesSchema<TSchema>;
  1846. /**
  1847. * Links to another schema node and reuses it for validation, typically for creative recursive schemas.
  1848. *
  1849. * @param ref - the reference to the linked schema node.
  1850. * Cannot reference itself or its children as well as other links.
  1851. * Links can be expressed in relative terms like value references (`Joi.link('...')`),
  1852. * in absolute terms from the schema run-time root (`Joi.link('/a')`),
  1853. * or using schema ids implicitly using object keys or explicitly using `any.id()` (`Joi.link('#a.b.c')`).
  1854. */
  1855. link<TSchema = any>(ref?: string): LinkSchema<TSchema>;
  1856. /**
  1857. * Validates a value against a schema and throws if validation fails.
  1858. *
  1859. * @param value - the value to validate.
  1860. * @param schema - the schema object.
  1861. * @param message - optional message string prefix added in front of the error message. may also be an Error object.
  1862. */
  1863. assert(value: any, schema: Schema, options?: ValidationOptions): void;
  1864. assert(value: any, schema: Schema, message: string | Error, options?: ValidationOptions): void;
  1865. /**
  1866. * Validates a value against a schema, returns valid object, and throws if validation fails.
  1867. *
  1868. * @param value - the value to validate.
  1869. * @param schema - the schema object.
  1870. * @param message - optional message string prefix added in front of the error message. may also be an Error object.
  1871. */
  1872. attempt<TSchema extends Schema>(value: any, schema: TSchema, options?: ValidationOptions): TSchema extends Schema<infer Value> ? Value : never;
  1873. attempt<TSchema extends Schema>(value: any, schema: TSchema, message: string | Error, options?: ValidationOptions): TSchema extends Schema<infer Value> ? Value : never;
  1874. cache: CacheConfiguration;
  1875. /**
  1876. * Converts literal schema definition to joi schema object (or returns the same back if already a joi schema object).
  1877. */
  1878. compile(schema: SchemaLike, options?: CompileOptions): Schema;
  1879. /**
  1880. * Checks if the provided preferences are valid.
  1881. *
  1882. * Throws an exception if the prefs object is invalid.
  1883. *
  1884. * The method is provided to perform inputs validation for the `any.validate()` and `any.validateAsync()` methods.
  1885. * Validation is not performed automatically for performance reasons. Instead, manually validate the preferences passed once and reuse.
  1886. */
  1887. checkPreferences(prefs: ValidationOptions): void;
  1888. /**
  1889. * Creates a custom validation schema.
  1890. */
  1891. custom(fn: CustomValidator, description?: string): Schema;
  1892. /**
  1893. * Creates a new Joi instance that will apply defaults onto newly created schemas
  1894. * through the use of the fn function that takes exactly one argument, the schema being created.
  1895. *
  1896. * @param fn - The function must always return a schema, even if untransformed.
  1897. */
  1898. defaults(fn: SchemaFunction): Root;
  1899. /**
  1900. * Generates a dynamic expression using a template string.
  1901. */
  1902. expression(template: string, options?: ReferenceOptions): any;
  1903. /**
  1904. * Creates a new Joi instance customized with the extension(s) you provide included.
  1905. */
  1906. extend(...extensions: Array<Extension | ExtensionFactory>): any;
  1907. /**
  1908. * Creates a reference that when resolved, is used as an array of values to match against the rule.
  1909. */
  1910. in(ref: string, options?: ReferenceOptions): Reference;
  1911. /**
  1912. * Checks whether or not the provided argument is an instance of ValidationError
  1913. */
  1914. isError(error: any): error is ValidationError;
  1915. /**
  1916. * Checks whether or not the provided argument is an expression.
  1917. */
  1918. isExpression(expression: any): boolean;
  1919. /**
  1920. * Checks whether or not the provided argument is a reference. It's especially useful if you want to post-process error messages.
  1921. */
  1922. isRef(ref: any): ref is Reference;
  1923. /**
  1924. * Checks whether or not the provided argument is a joi schema.
  1925. */
  1926. isSchema(schema: any, options?: CompileOptions): schema is AnySchema;
  1927. /**
  1928. * A special value used with `any.allow()`, `any.invalid()`, and `any.valid()` as the first value to reset any previously set values.
  1929. */
  1930. override: symbol;
  1931. /**
  1932. * Generates a reference to the value of the named key.
  1933. */
  1934. ref(key: string, options?: ReferenceOptions): Reference;
  1935. /**
  1936. * Returns an object where each key is a plain joi schema type.
  1937. * Useful for creating type shortcuts using deconstruction.
  1938. * Note that the types are already formed and do not need to be called as functions (e.g. `string`, not `string()`).
  1939. */
  1940. types(): {
  1941. alternatives: AlternativesSchema;
  1942. any: AnySchema;
  1943. array: ArraySchema;
  1944. binary: BinarySchema;
  1945. boolean: BooleanSchema;
  1946. date: DateSchema;
  1947. function: FunctionSchema;
  1948. link: LinkSchema;
  1949. number: NumberSchema;
  1950. object: ObjectSchema;
  1951. string: StringSchema;
  1952. symbol: SymbolSchema;
  1953. };
  1954. /**
  1955. * Generates a dynamic expression using a template string.
  1956. */
  1957. x(template: string, options?: ReferenceOptions): any;
  1958. // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
  1959. // Below are undocumented APIs. use at your own risk
  1960. // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
  1961. /**
  1962. * Whitelists a value
  1963. */
  1964. allow(...values: any[]): Schema;
  1965. /**
  1966. * Adds the provided values into the allowed whitelist and marks them as the only valid values allowed.
  1967. */
  1968. valid(...values: any[]): Schema;
  1969. equal(...values: any[]): Schema;
  1970. /**
  1971. * Blacklists a value
  1972. */
  1973. invalid(...values: any[]): Schema;
  1974. disallow(...values: any[]): Schema;
  1975. not(...values: any[]): Schema;
  1976. /**
  1977. * Marks a key as required which will not allow undefined as value. All keys are optional by default.
  1978. */
  1979. required(): Schema;
  1980. /**
  1981. * Alias of `required`.
  1982. */
  1983. exist(): Schema;
  1984. /**
  1985. * Marks a key as optional which will allow undefined as values. Used to annotate the schema for readability as all keys are optional by default.
  1986. */
  1987. optional(): Schema;
  1988. /**
  1989. * Marks a key as forbidden which will not allow any value except undefined. Used to explicitly forbid keys.
  1990. */
  1991. forbidden(): Schema;
  1992. /**
  1993. * Overrides the global validate() options for the current key and any sub-key.
  1994. */
  1995. preferences(options: ValidationOptions): Schema;
  1996. /**
  1997. * Overrides the global validate() options for the current key and any sub-key.
  1998. */
  1999. prefs(options: ValidationOptions): Schema;
  2000. /**
  2001. * Converts the type into an alternatives type where the conditions are merged into the type definition where:
  2002. */
  2003. when(ref: string | Reference, options: WhenOptions | WhenOptions[]): AlternativesSchema;
  2004. when(ref: Schema, options: WhenSchemaOptions): AlternativesSchema;
  2005. /**
  2006. * Unsure, maybe alias for `compile`?
  2007. */
  2008. build(...args: any[]): any;
  2009. /**
  2010. * Unsure, maybe alias for `preferences`?
  2011. */
  2012. options(...args: any[]): any;
  2013. /**
  2014. * Unsure, maybe leaked from `@hapi/lab/coverage/initialize`
  2015. */
  2016. trace(...args: any[]): any;
  2017. untrace(...args: any[]): any;
  2018. }
  2019. }
  2020. declare const Joi: Joi.Root;
  2021. export = Joi;