* Returns compiled condition. * @param {string} path current path * @param {RuleSetLoaderOptions} condition user provided condition value * @returns {Condition} compiled condition
(path, condition)
| 294 | * @returns {Condition} compiled condition |
| 295 | */ |
| 296 | compileCondition(path, condition) { |
| 297 | if (condition === "") { |
| 298 | return { |
| 299 | matchWhenEmpty: true, |
| 300 | fn: (str) => str === "" |
| 301 | }; |
| 302 | } |
| 303 | if (!condition) { |
| 304 | throw this.error( |
| 305 | path, |
| 306 | condition, |
| 307 | "Expected condition but got falsy value" |
| 308 | ); |
| 309 | } |
| 310 | if (typeof condition === "string") { |
| 311 | return { |
| 312 | matchWhenEmpty: condition.length === 0, |
| 313 | fn: (str) => typeof str === "string" && str.startsWith(condition) |
| 314 | }; |
| 315 | } |
| 316 | if (typeof condition === "function") { |
| 317 | try { |
| 318 | return { |
| 319 | matchWhenEmpty: condition(""), |
| 320 | fn: /** @type {RuleConditionFunction} */ (condition) |
| 321 | }; |
| 322 | } catch (_err) { |
| 323 | throw this.error( |
| 324 | path, |
| 325 | condition, |
| 326 | "Evaluation of condition function threw error" |
| 327 | ); |
| 328 | } |
| 329 | } |
| 330 | if (condition instanceof RegExp) { |
| 331 | return { |
| 332 | matchWhenEmpty: condition.test(""), |
| 333 | fn: (v) => typeof v === "string" && condition.test(v) |
| 334 | }; |
| 335 | } |
| 336 | if (Array.isArray(condition)) { |
| 337 | const items = condition.map((c, i) => |
| 338 | this.compileCondition(`${path}[${i}]`, c) |
| 339 | ); |
| 340 | return this.combineConditionsOr(items); |
| 341 | } |
| 342 | |
| 343 | if (typeof condition !== "object") { |
| 344 | throw this.error( |
| 345 | path, |
| 346 | condition, |
| 347 | `Unexpected ${typeof condition} when condition was expected` |
| 348 | ); |
| 349 | } |
| 350 | |
| 351 | /** @type {Condition[]} */ |
| 352 | const conditions = []; |
| 353 | for (const key of Object.keys(condition)) { |
no test coverage detected