All files / src/internal blob-listing.ts

92.3% Statements 24/26
80.76% Branches 21/26
100% Functions 7/7
92.3% Lines 24/26

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 83 84 85                      2x 2x       2x 2x 2x 2x                               5x   6x     6x     6x       6x 6x 6x   6x   6x 6x   6x                 6x     5x 2x 2x         2x     3x       6x    
import { paginate } from './paging'
import type { ListOptions } from './paging'
import { storageRequestError } from './storage-request'
import type { StorageTransport } from './storage-request'
 
export interface NamePage {
  names: string[]
  continuationToken: string
}
 
// The Blob service returns at most 5,000 items per list request.
const maxListPageSize = 5000
const itemPatterns = {
  Blob: /<Blob>([\s\S]*?)<\/Blob>/gu,
  Container: /<Container>([\s\S]*?)<\/Container>/gu,
}
const namePattern = /<Name(?<encoded> Encoded="true")?>(?<name>[^<]*)<\/Name>/u
const nextMarkerPattern = /<NextMarker>([^<]*)<\/NextMarker>/u
const xmlEntity = /&(?:#x([\da-f]+)|#(\d+)|([a-z]+));/giu
const namedEntities = new Map([
  ['lt', '<'],
  ['gt', '>'],
  ['quot', '"'],
  ['apos', "'"],
  ['amp', '&'],
])
 
/** Lists blob or container names page by page with the Blob service marker protocol. */
export function listNames(
  transport: StorageTransport,
  url: string,
  item: 'Blob' | 'Container',
  query: Partial<Record<string, string>>,
  options: ListOptions = {},
): AsyncIterableIterator<NamePage> {
  return paginate(async (marker) => {
    const maxresults =
      options.maxPageSize === undefined
        ? undefined
        : String(Math.min(options.maxPageSize, maxListPageSize))
    const response = await transport.send('GET', url, {
      query: { ...query, comp: 'list', maxresults, marker },
    })
    Iif (!response.ok) {
      throw storageRequestError(`${item} list`, response)
    }
 
    const xml = await response.text()
    const continuationToken = nextMarkerPattern.exec(xml)?.[1]?.trim() ?? ''
    const names = Array.from(
      xml.matchAll(itemPatterns[item]),
      ([, content = '']) => namePattern.exec(content)?.groups,
    )
      .filter((groups) => groups?.['name'] !== undefined)
      .map((groups) => decodeName(groups?.['name'] ?? '', groups?.['encoded'] !== undefined))
 
    return {
      page: { names, continuationToken },
      continuationToken: continuationToken === '' ? undefined : continuationToken,
    }
  }, options.continuationToken)
}
 
/** Names with characters that XML cannot carry are percent-encoded and flagged with Encoded="true". */
function decodeName(raw: string, encoded: boolean): string {
  const name = raw.replaceAll(
    xmlEntity,
    (entity, hex: string | undefined, decimal: string | undefined, named: string | undefined) => {
      if (hex !== undefined || decimal !== undefined) {
        const codePoint = hex === undefined ? Number(decimal) : Number.parseInt(hex, 16)
        Iif (codePoint > 0x10ffff) {
          throw new RangeError(
            'Blob Storage listing contains an out-of-range XML character reference',
          )
        }
        return String.fromCodePoint(codePoint)
      }
 
      return namedEntities.get(named ?? '') ?? entity
    },
  )
 
  return encoded ? decodeURIComponent(name) : name
}