util.cjs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.Class = exports.BIGINT_FORMAT_RANGES = exports.NUMBER_FORMAT_RANGES = exports.primitiveTypes = exports.propertyKeyTypes = exports.getParsedType = exports.allowsEval = exports.captureStackTrace = void 0;
  4. exports.assertEqual = assertEqual;
  5. exports.assertNotEqual = assertNotEqual;
  6. exports.assertIs = assertIs;
  7. exports.assertNever = assertNever;
  8. exports.assert = assert;
  9. exports.getEnumValues = getEnumValues;
  10. exports.joinValues = joinValues;
  11. exports.jsonStringifyReplacer = jsonStringifyReplacer;
  12. exports.cached = cached;
  13. exports.nullish = nullish;
  14. exports.cleanRegex = cleanRegex;
  15. exports.floatSafeRemainder = floatSafeRemainder;
  16. exports.defineLazy = defineLazy;
  17. exports.objectClone = objectClone;
  18. exports.assignProp = assignProp;
  19. exports.mergeDefs = mergeDefs;
  20. exports.cloneDef = cloneDef;
  21. exports.getElementAtPath = getElementAtPath;
  22. exports.promiseAllObject = promiseAllObject;
  23. exports.randomString = randomString;
  24. exports.esc = esc;
  25. exports.slugify = slugify;
  26. exports.isObject = isObject;
  27. exports.isPlainObject = isPlainObject;
  28. exports.shallowClone = shallowClone;
  29. exports.numKeys = numKeys;
  30. exports.escapeRegex = escapeRegex;
  31. exports.clone = clone;
  32. exports.normalizeParams = normalizeParams;
  33. exports.createTransparentProxy = createTransparentProxy;
  34. exports.stringifyPrimitive = stringifyPrimitive;
  35. exports.optionalKeys = optionalKeys;
  36. exports.pick = pick;
  37. exports.omit = omit;
  38. exports.extend = extend;
  39. exports.safeExtend = safeExtend;
  40. exports.merge = merge;
  41. exports.partial = partial;
  42. exports.required = required;
  43. exports.aborted = aborted;
  44. exports.prefixIssues = prefixIssues;
  45. exports.unwrapMessage = unwrapMessage;
  46. exports.finalizeIssue = finalizeIssue;
  47. exports.getSizableOrigin = getSizableOrigin;
  48. exports.getLengthableOrigin = getLengthableOrigin;
  49. exports.parsedType = parsedType;
  50. exports.issue = issue;
  51. exports.cleanEnum = cleanEnum;
  52. exports.base64ToUint8Array = base64ToUint8Array;
  53. exports.uint8ArrayToBase64 = uint8ArrayToBase64;
  54. exports.base64urlToUint8Array = base64urlToUint8Array;
  55. exports.uint8ArrayToBase64url = uint8ArrayToBase64url;
  56. exports.hexToUint8Array = hexToUint8Array;
  57. exports.uint8ArrayToHex = uint8ArrayToHex;
  58. // functions
  59. function assertEqual(val) {
  60. return val;
  61. }
  62. function assertNotEqual(val) {
  63. return val;
  64. }
  65. function assertIs(_arg) { }
  66. function assertNever(_x) {
  67. throw new Error("Unexpected value in exhaustive check");
  68. }
  69. function assert(_) { }
  70. function getEnumValues(entries) {
  71. const numericValues = Object.values(entries).filter((v) => typeof v === "number");
  72. const values = Object.entries(entries)
  73. .filter(([k, _]) => numericValues.indexOf(+k) === -1)
  74. .map(([_, v]) => v);
  75. return values;
  76. }
  77. function joinValues(array, separator = "|") {
  78. return array.map((val) => stringifyPrimitive(val)).join(separator);
  79. }
  80. function jsonStringifyReplacer(_, value) {
  81. if (typeof value === "bigint")
  82. return value.toString();
  83. return value;
  84. }
  85. function cached(getter) {
  86. const set = false;
  87. return {
  88. get value() {
  89. if (!set) {
  90. const value = getter();
  91. Object.defineProperty(this, "value", { value });
  92. return value;
  93. }
  94. throw new Error("cached value already set");
  95. },
  96. };
  97. }
  98. function nullish(input) {
  99. return input === null || input === undefined;
  100. }
  101. function cleanRegex(source) {
  102. const start = source.startsWith("^") ? 1 : 0;
  103. const end = source.endsWith("$") ? source.length - 1 : source.length;
  104. return source.slice(start, end);
  105. }
  106. function floatSafeRemainder(val, step) {
  107. const valDecCount = (val.toString().split(".")[1] || "").length;
  108. const stepString = step.toString();
  109. let stepDecCount = (stepString.split(".")[1] || "").length;
  110. if (stepDecCount === 0 && /\d?e-\d?/.test(stepString)) {
  111. const match = stepString.match(/\d?e-(\d?)/);
  112. if (match?.[1]) {
  113. stepDecCount = Number.parseInt(match[1]);
  114. }
  115. }
  116. const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
  117. const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
  118. const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
  119. return (valInt % stepInt) / 10 ** decCount;
  120. }
  121. const EVALUATING = Symbol("evaluating");
  122. function defineLazy(object, key, getter) {
  123. let value = undefined;
  124. Object.defineProperty(object, key, {
  125. get() {
  126. if (value === EVALUATING) {
  127. // Circular reference detected, return undefined to break the cycle
  128. return undefined;
  129. }
  130. if (value === undefined) {
  131. value = EVALUATING;
  132. value = getter();
  133. }
  134. return value;
  135. },
  136. set(v) {
  137. Object.defineProperty(object, key, {
  138. value: v,
  139. // configurable: true,
  140. });
  141. // object[key] = v;
  142. },
  143. configurable: true,
  144. });
  145. }
  146. function objectClone(obj) {
  147. return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));
  148. }
  149. function assignProp(target, prop, value) {
  150. Object.defineProperty(target, prop, {
  151. value,
  152. writable: true,
  153. enumerable: true,
  154. configurable: true,
  155. });
  156. }
  157. function mergeDefs(...defs) {
  158. const mergedDescriptors = {};
  159. for (const def of defs) {
  160. const descriptors = Object.getOwnPropertyDescriptors(def);
  161. Object.assign(mergedDescriptors, descriptors);
  162. }
  163. return Object.defineProperties({}, mergedDescriptors);
  164. }
  165. function cloneDef(schema) {
  166. return mergeDefs(schema._zod.def);
  167. }
  168. function getElementAtPath(obj, path) {
  169. if (!path)
  170. return obj;
  171. return path.reduce((acc, key) => acc?.[key], obj);
  172. }
  173. function promiseAllObject(promisesObj) {
  174. const keys = Object.keys(promisesObj);
  175. const promises = keys.map((key) => promisesObj[key]);
  176. return Promise.all(promises).then((results) => {
  177. const resolvedObj = {};
  178. for (let i = 0; i < keys.length; i++) {
  179. resolvedObj[keys[i]] = results[i];
  180. }
  181. return resolvedObj;
  182. });
  183. }
  184. function randomString(length = 10) {
  185. const chars = "abcdefghijklmnopqrstuvwxyz";
  186. let str = "";
  187. for (let i = 0; i < length; i++) {
  188. str += chars[Math.floor(Math.random() * chars.length)];
  189. }
  190. return str;
  191. }
  192. function esc(str) {
  193. return JSON.stringify(str);
  194. }
  195. function slugify(input) {
  196. return input
  197. .toLowerCase()
  198. .trim()
  199. .replace(/[^\w\s-]/g, "")
  200. .replace(/[\s_-]+/g, "-")
  201. .replace(/^-+|-+$/g, "");
  202. }
  203. exports.captureStackTrace = ("captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { });
  204. function isObject(data) {
  205. return typeof data === "object" && data !== null && !Array.isArray(data);
  206. }
  207. exports.allowsEval = cached(() => {
  208. // @ts-ignore
  209. if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) {
  210. return false;
  211. }
  212. try {
  213. const F = Function;
  214. new F("");
  215. return true;
  216. }
  217. catch (_) {
  218. return false;
  219. }
  220. });
  221. function isPlainObject(o) {
  222. if (isObject(o) === false)
  223. return false;
  224. // modified constructor
  225. const ctor = o.constructor;
  226. if (ctor === undefined)
  227. return true;
  228. if (typeof ctor !== "function")
  229. return true;
  230. // modified prototype
  231. const prot = ctor.prototype;
  232. if (isObject(prot) === false)
  233. return false;
  234. // ctor doesn't have static `isPrototypeOf`
  235. if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) {
  236. return false;
  237. }
  238. return true;
  239. }
  240. function shallowClone(o) {
  241. if (isPlainObject(o))
  242. return { ...o };
  243. if (Array.isArray(o))
  244. return [...o];
  245. return o;
  246. }
  247. function numKeys(data) {
  248. let keyCount = 0;
  249. for (const key in data) {
  250. if (Object.prototype.hasOwnProperty.call(data, key)) {
  251. keyCount++;
  252. }
  253. }
  254. return keyCount;
  255. }
  256. const getParsedType = (data) => {
  257. const t = typeof data;
  258. switch (t) {
  259. case "undefined":
  260. return "undefined";
  261. case "string":
  262. return "string";
  263. case "number":
  264. return Number.isNaN(data) ? "nan" : "number";
  265. case "boolean":
  266. return "boolean";
  267. case "function":
  268. return "function";
  269. case "bigint":
  270. return "bigint";
  271. case "symbol":
  272. return "symbol";
  273. case "object":
  274. if (Array.isArray(data)) {
  275. return "array";
  276. }
  277. if (data === null) {
  278. return "null";
  279. }
  280. if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
  281. return "promise";
  282. }
  283. if (typeof Map !== "undefined" && data instanceof Map) {
  284. return "map";
  285. }
  286. if (typeof Set !== "undefined" && data instanceof Set) {
  287. return "set";
  288. }
  289. if (typeof Date !== "undefined" && data instanceof Date) {
  290. return "date";
  291. }
  292. // @ts-ignore
  293. if (typeof File !== "undefined" && data instanceof File) {
  294. return "file";
  295. }
  296. return "object";
  297. default:
  298. throw new Error(`Unknown data type: ${t}`);
  299. }
  300. };
  301. exports.getParsedType = getParsedType;
  302. exports.propertyKeyTypes = new Set(["string", "number", "symbol"]);
  303. exports.primitiveTypes = new Set(["string", "number", "bigint", "boolean", "symbol", "undefined"]);
  304. function escapeRegex(str) {
  305. return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  306. }
  307. // zod-specific utils
  308. function clone(inst, def, params) {
  309. const cl = new inst._zod.constr(def ?? inst._zod.def);
  310. if (!def || params?.parent)
  311. cl._zod.parent = inst;
  312. return cl;
  313. }
  314. function normalizeParams(_params) {
  315. const params = _params;
  316. if (!params)
  317. return {};
  318. if (typeof params === "string")
  319. return { error: () => params };
  320. if (params?.message !== undefined) {
  321. if (params?.error !== undefined)
  322. throw new Error("Cannot specify both `message` and `error` params");
  323. params.error = params.message;
  324. }
  325. delete params.message;
  326. if (typeof params.error === "string")
  327. return { ...params, error: () => params.error };
  328. return params;
  329. }
  330. function createTransparentProxy(getter) {
  331. let target;
  332. return new Proxy({}, {
  333. get(_, prop, receiver) {
  334. target ?? (target = getter());
  335. return Reflect.get(target, prop, receiver);
  336. },
  337. set(_, prop, value, receiver) {
  338. target ?? (target = getter());
  339. return Reflect.set(target, prop, value, receiver);
  340. },
  341. has(_, prop) {
  342. target ?? (target = getter());
  343. return Reflect.has(target, prop);
  344. },
  345. deleteProperty(_, prop) {
  346. target ?? (target = getter());
  347. return Reflect.deleteProperty(target, prop);
  348. },
  349. ownKeys(_) {
  350. target ?? (target = getter());
  351. return Reflect.ownKeys(target);
  352. },
  353. getOwnPropertyDescriptor(_, prop) {
  354. target ?? (target = getter());
  355. return Reflect.getOwnPropertyDescriptor(target, prop);
  356. },
  357. defineProperty(_, prop, descriptor) {
  358. target ?? (target = getter());
  359. return Reflect.defineProperty(target, prop, descriptor);
  360. },
  361. });
  362. }
  363. function stringifyPrimitive(value) {
  364. if (typeof value === "bigint")
  365. return value.toString() + "n";
  366. if (typeof value === "string")
  367. return `"${value}"`;
  368. return `${value}`;
  369. }
  370. function optionalKeys(shape) {
  371. return Object.keys(shape).filter((k) => {
  372. return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional";
  373. });
  374. }
  375. exports.NUMBER_FORMAT_RANGES = {
  376. safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],
  377. int32: [-2147483648, 2147483647],
  378. uint32: [0, 4294967295],
  379. float32: [-3.4028234663852886e38, 3.4028234663852886e38],
  380. float64: [-Number.MAX_VALUE, Number.MAX_VALUE],
  381. };
  382. exports.BIGINT_FORMAT_RANGES = {
  383. int64: [/* @__PURE__*/ BigInt("-9223372036854775808"), /* @__PURE__*/ BigInt("9223372036854775807")],
  384. uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt("18446744073709551615")],
  385. };
  386. function pick(schema, mask) {
  387. const currDef = schema._zod.def;
  388. const checks = currDef.checks;
  389. const hasChecks = checks && checks.length > 0;
  390. if (hasChecks) {
  391. throw new Error(".pick() cannot be used on object schemas containing refinements");
  392. }
  393. const def = mergeDefs(schema._zod.def, {
  394. get shape() {
  395. const newShape = {};
  396. for (const key in mask) {
  397. if (!(key in currDef.shape)) {
  398. throw new Error(`Unrecognized key: "${key}"`);
  399. }
  400. if (!mask[key])
  401. continue;
  402. newShape[key] = currDef.shape[key];
  403. }
  404. assignProp(this, "shape", newShape); // self-caching
  405. return newShape;
  406. },
  407. checks: [],
  408. });
  409. return clone(schema, def);
  410. }
  411. function omit(schema, mask) {
  412. const currDef = schema._zod.def;
  413. const checks = currDef.checks;
  414. const hasChecks = checks && checks.length > 0;
  415. if (hasChecks) {
  416. throw new Error(".omit() cannot be used on object schemas containing refinements");
  417. }
  418. const def = mergeDefs(schema._zod.def, {
  419. get shape() {
  420. const newShape = { ...schema._zod.def.shape };
  421. for (const key in mask) {
  422. if (!(key in currDef.shape)) {
  423. throw new Error(`Unrecognized key: "${key}"`);
  424. }
  425. if (!mask[key])
  426. continue;
  427. delete newShape[key];
  428. }
  429. assignProp(this, "shape", newShape); // self-caching
  430. return newShape;
  431. },
  432. checks: [],
  433. });
  434. return clone(schema, def);
  435. }
  436. function extend(schema, shape) {
  437. if (!isPlainObject(shape)) {
  438. throw new Error("Invalid input to extend: expected a plain object");
  439. }
  440. const checks = schema._zod.def.checks;
  441. const hasChecks = checks && checks.length > 0;
  442. if (hasChecks) {
  443. // Only throw if new shape overlaps with existing shape
  444. // Use getOwnPropertyDescriptor to check key existence without accessing values
  445. const existingShape = schema._zod.def.shape;
  446. for (const key in shape) {
  447. if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) {
  448. throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.");
  449. }
  450. }
  451. }
  452. const def = mergeDefs(schema._zod.def, {
  453. get shape() {
  454. const _shape = { ...schema._zod.def.shape, ...shape };
  455. assignProp(this, "shape", _shape); // self-caching
  456. return _shape;
  457. },
  458. });
  459. return clone(schema, def);
  460. }
  461. function safeExtend(schema, shape) {
  462. if (!isPlainObject(shape)) {
  463. throw new Error("Invalid input to safeExtend: expected a plain object");
  464. }
  465. const def = mergeDefs(schema._zod.def, {
  466. get shape() {
  467. const _shape = { ...schema._zod.def.shape, ...shape };
  468. assignProp(this, "shape", _shape); // self-caching
  469. return _shape;
  470. },
  471. });
  472. return clone(schema, def);
  473. }
  474. function merge(a, b) {
  475. const def = mergeDefs(a._zod.def, {
  476. get shape() {
  477. const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };
  478. assignProp(this, "shape", _shape); // self-caching
  479. return _shape;
  480. },
  481. get catchall() {
  482. return b._zod.def.catchall;
  483. },
  484. checks: [], // delete existing checks
  485. });
  486. return clone(a, def);
  487. }
  488. function partial(Class, schema, mask) {
  489. const currDef = schema._zod.def;
  490. const checks = currDef.checks;
  491. const hasChecks = checks && checks.length > 0;
  492. if (hasChecks) {
  493. throw new Error(".partial() cannot be used on object schemas containing refinements");
  494. }
  495. const def = mergeDefs(schema._zod.def, {
  496. get shape() {
  497. const oldShape = schema._zod.def.shape;
  498. const shape = { ...oldShape };
  499. if (mask) {
  500. for (const key in mask) {
  501. if (!(key in oldShape)) {
  502. throw new Error(`Unrecognized key: "${key}"`);
  503. }
  504. if (!mask[key])
  505. continue;
  506. // if (oldShape[key]!._zod.optin === "optional") continue;
  507. shape[key] = Class
  508. ? new Class({
  509. type: "optional",
  510. innerType: oldShape[key],
  511. })
  512. : oldShape[key];
  513. }
  514. }
  515. else {
  516. for (const key in oldShape) {
  517. // if (oldShape[key]!._zod.optin === "optional") continue;
  518. shape[key] = Class
  519. ? new Class({
  520. type: "optional",
  521. innerType: oldShape[key],
  522. })
  523. : oldShape[key];
  524. }
  525. }
  526. assignProp(this, "shape", shape); // self-caching
  527. return shape;
  528. },
  529. checks: [],
  530. });
  531. return clone(schema, def);
  532. }
  533. function required(Class, schema, mask) {
  534. const def = mergeDefs(schema._zod.def, {
  535. get shape() {
  536. const oldShape = schema._zod.def.shape;
  537. const shape = { ...oldShape };
  538. if (mask) {
  539. for (const key in mask) {
  540. if (!(key in shape)) {
  541. throw new Error(`Unrecognized key: "${key}"`);
  542. }
  543. if (!mask[key])
  544. continue;
  545. // overwrite with non-optional
  546. shape[key] = new Class({
  547. type: "nonoptional",
  548. innerType: oldShape[key],
  549. });
  550. }
  551. }
  552. else {
  553. for (const key in oldShape) {
  554. // overwrite with non-optional
  555. shape[key] = new Class({
  556. type: "nonoptional",
  557. innerType: oldShape[key],
  558. });
  559. }
  560. }
  561. assignProp(this, "shape", shape); // self-caching
  562. return shape;
  563. },
  564. });
  565. return clone(schema, def);
  566. }
  567. // invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom
  568. function aborted(x, startIndex = 0) {
  569. if (x.aborted === true)
  570. return true;
  571. for (let i = startIndex; i < x.issues.length; i++) {
  572. if (x.issues[i]?.continue !== true) {
  573. return true;
  574. }
  575. }
  576. return false;
  577. }
  578. function prefixIssues(path, issues) {
  579. return issues.map((iss) => {
  580. var _a;
  581. (_a = iss).path ?? (_a.path = []);
  582. iss.path.unshift(path);
  583. return iss;
  584. });
  585. }
  586. function unwrapMessage(message) {
  587. return typeof message === "string" ? message : message?.message;
  588. }
  589. function finalizeIssue(iss, ctx, config) {
  590. const full = { ...iss, path: iss.path ?? [] };
  591. // for backwards compatibility
  592. if (!iss.message) {
  593. const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??
  594. unwrapMessage(ctx?.error?.(iss)) ??
  595. unwrapMessage(config.customError?.(iss)) ??
  596. unwrapMessage(config.localeError?.(iss)) ??
  597. "Invalid input";
  598. full.message = message;
  599. }
  600. // delete (full as any).def;
  601. delete full.inst;
  602. delete full.continue;
  603. if (!ctx?.reportInput) {
  604. delete full.input;
  605. }
  606. return full;
  607. }
  608. function getSizableOrigin(input) {
  609. if (input instanceof Set)
  610. return "set";
  611. if (input instanceof Map)
  612. return "map";
  613. // @ts-ignore
  614. if (input instanceof File)
  615. return "file";
  616. return "unknown";
  617. }
  618. function getLengthableOrigin(input) {
  619. if (Array.isArray(input))
  620. return "array";
  621. if (typeof input === "string")
  622. return "string";
  623. return "unknown";
  624. }
  625. function parsedType(data) {
  626. const t = typeof data;
  627. switch (t) {
  628. case "number": {
  629. return Number.isNaN(data) ? "nan" : "number";
  630. }
  631. case "object": {
  632. if (data === null) {
  633. return "null";
  634. }
  635. if (Array.isArray(data)) {
  636. return "array";
  637. }
  638. const obj = data;
  639. if (obj && Object.getPrototypeOf(obj) !== Object.prototype && "constructor" in obj && obj.constructor) {
  640. return obj.constructor.name;
  641. }
  642. }
  643. }
  644. return t;
  645. }
  646. function issue(...args) {
  647. const [iss, input, inst] = args;
  648. if (typeof iss === "string") {
  649. return {
  650. message: iss,
  651. code: "custom",
  652. input,
  653. inst,
  654. };
  655. }
  656. return { ...iss };
  657. }
  658. function cleanEnum(obj) {
  659. return Object.entries(obj)
  660. .filter(([k, _]) => {
  661. // return true if NaN, meaning it's not a number, thus a string key
  662. return Number.isNaN(Number.parseInt(k, 10));
  663. })
  664. .map((el) => el[1]);
  665. }
  666. // Codec utility functions
  667. function base64ToUint8Array(base64) {
  668. const binaryString = atob(base64);
  669. const bytes = new Uint8Array(binaryString.length);
  670. for (let i = 0; i < binaryString.length; i++) {
  671. bytes[i] = binaryString.charCodeAt(i);
  672. }
  673. return bytes;
  674. }
  675. function uint8ArrayToBase64(bytes) {
  676. let binaryString = "";
  677. for (let i = 0; i < bytes.length; i++) {
  678. binaryString += String.fromCharCode(bytes[i]);
  679. }
  680. return btoa(binaryString);
  681. }
  682. function base64urlToUint8Array(base64url) {
  683. const base64 = base64url.replace(/-/g, "+").replace(/_/g, "/");
  684. const padding = "=".repeat((4 - (base64.length % 4)) % 4);
  685. return base64ToUint8Array(base64 + padding);
  686. }
  687. function uint8ArrayToBase64url(bytes) {
  688. return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
  689. }
  690. function hexToUint8Array(hex) {
  691. const cleanHex = hex.replace(/^0x/, "");
  692. if (cleanHex.length % 2 !== 0) {
  693. throw new Error("Invalid hex string length");
  694. }
  695. const bytes = new Uint8Array(cleanHex.length / 2);
  696. for (let i = 0; i < cleanHex.length; i += 2) {
  697. bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);
  698. }
  699. return bytes;
  700. }
  701. function uint8ArrayToHex(bytes) {
  702. return Array.from(bytes)
  703. .map((b) => b.toString(16).padStart(2, "0"))
  704. .join("");
  705. }
  706. // instanceof
  707. class Class {
  708. constructor(..._args) { }
  709. }
  710. exports.Class = Class;