All files / src meridian-delivery-uri.ts

82.92% Statements 68/82
72.72% Branches 24/33
81.48% Functions 22/27
82.92% Lines 68/82

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 831x 1x 1x 1x 1x 2x 2x 2x 1x 2x 2x     2x 2x 2x     2x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 2x 2x 2x 2x     2x 2x     2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 1x          
import * as path from "node:path"
 
export const MERIDIAN_DOCUMENT_SCHEME = "meridian"
const ROOT_PATH_PREFIX = "/r/"
 
function packageRootHex(packageRoot: string): string {
  return Buffer.from(path.resolve(packageRoot), "utf-8").toString("hex")
}
 
function packageRootFromHex(hex: string): string | null {
  if (!/^[0-9a-f]+$/i.test(hex)) {
    return null
  }
  try {
    return Buffer.from(hex, "hex").toString("utf-8")
  } catch {
    return null
  }
}
 
export type MeridianDeliveryUriParts = {
  scheme: typeof MERIDIAN_DOCUMENT_SCHEME
  path: string
}
 
export function buildMeridianDeliveryUriParts(
  packageRoot: string,
  relativePath: string,
): MeridianDeliveryUriParts {
  const normalized = relativePath.replace(/\\/g, "/").replace(/^\//, "")
  return {
    scheme: MERIDIAN_DOCUMENT_SCHEME,
    path: `${ROOT_PATH_PREFIX}${packageRootHex(packageRoot)}/${normalized}`,
  }
}
 
export function parseMeridianDeliveryUriPath(
  uriPath: string,
): { packageRoot: string; relativePath: string } | null {
  const match = uriPath.match(/^\/r\/([0-9a-f]+)\/(.+)$/i)
  if (!match) {
    return null
  }
  const packageRoot = packageRootFromHex(match[1])
  if (!packageRoot) {
    return null
  }
  return { packageRoot, relativePath: match[2] }
}
 
export function relativePathFromMeridianUriPath(uriPath: string): string {
  const parsed = parseMeridianDeliveryUriPath(uriPath)
  return parsed?.relativePath ?? uriPath.replace(/^\//, "")
}
 
const contentCache = new Map<string, string>()
 
export function meridianDeliveryCacheKey(parts: MeridianDeliveryUriParts): string {
  return `${parts.scheme}:${parts.path}`
}
 
export function primeMeridianDeliveryContent(key: string, content: string): void {
  contentCache.set(key, content)
}
 
export function readMeridianDeliveryContent(key: string): string | undefined {
  return contentCache.get(key)
}
 
export function deleteMeridianDeliveryContent(key: string): void {
  contentCache.delete(key)
}
 
export function clearMeridianDeliveryCache(): void {
  contentCache.clear()
}
 
export function storeMeridianDeliveryContent(key: string, content: string): void {
  if (content) {
    contentCache.set(key, content)
  }
}