(func, args)
| 533 | * @returns {String} [result.error] - The validation error message if validation has failed. |
| 534 | */ |
| 535 | const validate = function (func, args) { |
| 536 | if (p5.disableFriendlyErrors) { |
| 537 | return; // skip FES |
| 538 | } |
| 539 | |
| 540 | if (!Array.isArray(args)) { |
| 541 | args = Array.from(args); |
| 542 | } |
| 543 | |
| 544 | // An edge case: even when all arguments are optional and therefore, |
| 545 | // theoretically allowed to stay undefined and valid, it is likely that the |
| 546 | // user intended to call the function with non-undefined arguments. Skip |
| 547 | // regular workflow and return a friendly error message right away. |
| 548 | if ( |
| 549 | Array.isArray(args) && |
| 550 | args.length > 0 && |
| 551 | args.every(arg => arg === undefined) |
| 552 | ) { |
| 553 | const undefinedErrorMessage = `🌸 p5.js says: All arguments for ${func}() are undefined. There is likely an error in the code.`; |
| 554 | |
| 555 | return { |
| 556 | success: false, |
| 557 | error: undefinedErrorMessage |
| 558 | }; |
| 559 | } |
| 560 | |
| 561 | let funcSchemas = schemaRegistry.get(func); |
| 562 | if (!funcSchemas) { |
| 563 | funcSchemas = generateZodSchemasForFunc(func); |
| 564 | if (!funcSchemas) return; |
| 565 | schemaRegistry.set(func, funcSchemas); |
| 566 | } |
| 567 | |
| 568 | try { |
| 569 | return { |
| 570 | success: true, |
| 571 | data: funcSchemas.parse(args) |
| 572 | }; |
| 573 | } catch (error) { |
| 574 | const closestSchema = findClosestSchema(funcSchemas, args); |
| 575 | const zodError = closestSchema.safeParse(args).error; |
| 576 | const errorMessage = friendlyParamError(zodError, func, args); |
| 577 | |
| 578 | return { |
| 579 | success: false, |
| 580 | error: errorMessage |
| 581 | }; |
| 582 | } |
| 583 | }; |
| 584 | |
| 585 | fn._validate = validate; // TEMP: For unit tests |
| 586 |
no test coverage detected