utils.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. const text_encoder = new TextEncoder();
  2. const text_decoder = new TextDecoder();
  3. function get_relative_path(from, to) {
  4. const from_parts = from.split(/[/\\]/);
  5. const to_parts = to.split(/[/\\]/);
  6. from_parts.pop();
  7. while (from_parts[0] === to_parts[0]) {
  8. from_parts.shift();
  9. to_parts.shift();
  10. }
  11. let i = from_parts.length;
  12. while (i--) from_parts[i] = "..";
  13. return from_parts.concat(to_parts).join("/");
  14. }
  15. function base64_encode(bytes) {
  16. if (globalThis.Buffer) {
  17. return globalThis.Buffer.from(bytes).toString("base64");
  18. }
  19. let binary = "";
  20. for (let i = 0; i < bytes.length; i++) {
  21. binary += String.fromCharCode(bytes[i]);
  22. }
  23. return btoa(binary);
  24. }
  25. function base64_decode(encoded) {
  26. if (globalThis.Buffer) {
  27. const buffer = globalThis.Buffer.from(encoded, "base64");
  28. return new Uint8Array(buffer);
  29. }
  30. const binary = atob(encoded);
  31. const bytes = new Uint8Array(binary.length);
  32. for (let i = 0; i < binary.length; i++) {
  33. bytes[i] = binary.charCodeAt(i);
  34. }
  35. return bytes;
  36. }
  37. export {
  38. text_encoder as a,
  39. base64_encode as b,
  40. base64_decode as c,
  41. get_relative_path as g,
  42. text_decoder as t
  43. };