app

Local-first trade for farms and co-ops
git clone https://radroots.dev/git/app.git
Log | Files | Refs | README | LICENSE

text.ts (1670B)


      1 import { canonicalFoodAmount, type CanonicalFoodAmount } from './values.ts';
      2 const encoder = new TextEncoder();
      3 export function boundedUtf8(value: string, maximum: number): boolean {
      4   return (
      5     value.length <= maximum &&
      6     value.isWellFormed() &&
      7     encoder.encode(value).length <= maximum
      8   );
      9 }
     10 export function foodTextValid(value: string): boolean {
     11   return (
     12     value.length > 0 &&
     13     boundedUtf8(value, 4096) &&
     14     !/[\p{Cc}\p{Cf}]/u.test(value) &&
     15     !/^\p{White_Space}|\p{White_Space}$/u.test(value)
     16   );
     17 }
     18 export function foodIdentifierValid(value: string): boolean {
     19   return (
     20     value.length > 0 &&
     21     boundedUtf8(value, 512) &&
     22     !/[\p{White_Space}\p{Cc}\p{Cf}]/u.test(value)
     23   );
     24 }
     25 export function foodContentPresent(value: string): boolean {
     26   // Rust contract whitespace also includes U+001C..U+001F.
     27   return Array.from(value).some(
     28     (character) =>
     29       !/\p{White_Space}/u.test(character) &&
     30       !(character.codePointAt(0)! >= 28 && character.codePointAt(0)! <= 31)
     31   );
     32 }
     33 export function incomingAmount(value: string): CanonicalFoodAmount | undefined {
     34   if (
     35     value.length === 0 ||
     36     value.length > 29 ||
     37     !/^[0-9]+(?:\.[0-9]+)?$/u.test(value)
     38   )
     39     return undefined;
     40   if (value.length - (value.includes('.') ? 1 : 0) > 28) return undefined;
     41   const [integer, fraction] = value.split('.');
     42   let start = 0;
     43   while (start < integer.length && integer[start] === '0') start++;
     44   const whole = integer.slice(start) || '0';
     45   let end = fraction?.length ?? 0;
     46   while (end > 0 && fraction?.[end - 1] === '0') end--;
     47   const tail = fraction?.slice(0, end);
     48   return canonicalFoodAmount(tail ? `${whole}.${tail}` : whole);
     49 }