All files / src/worker/handlers handleScript.ts

100% Statements 4/4
100% Branches 3/3
100% Functions 1/1
100% Lines 4/4

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                                                                              6x   1x                 1x             4x      
// This bundles the instrumentor code with the worker: https://vite.dev/guide/assets.html#importing-asset-as-string
import instrumentorCode from '../../../dist/instrumentor/instrumentor.iife.js?raw'
import agentProcessorCode from '../../../dist/agent-processor/agent-processor.iife.js?raw'
import { LogLevel, ProtectedApi } from '../../shared/types'
import { getAgentLoader } from '../fingerprint/agent'
import { Script } from '../../shared/scripts'
import { createWorkerScriptResponse } from '../scripts'
 
type HandleScriptParams = {
  request: Request
  script: Script
  publicApiKey: string
  cdnHost: string
  protectedApis: ProtectedApi[]
  routePrefix: string
  logLevel: LogLevel
}
 
/**
 * Handles fetching of the specific scripts based on the provided parameters.
 *
 * @param {Object} params - The parameters for handling the script.
 * @param {Request} params.request - The incoming HTTP request.
 * @param {string} params.script - The name of the script to be handled.
 * @param {string} params.publicApiKey - The public API key used for fetching the agent loader.
 * @param {string} params.cdnHost - Hostname of the Fingerprint CDN.
 * @param {string} params.routePrefix - Path prefix for worker requests.
 * @param {ProtectedApi[]} params.protectedApis - Array of protected APIs to be injected into the instrumentation code.
 * @return {Promise<Response>} A promise that resolves to the script response.
 */
export async function handleScript({
  request,
  script,
  publicApiKey,
  cdnHost,
  protectedApis,
  routePrefix,
  logLevel,
}: HandleScriptParams): Promise<Response> {
  switch (script) {
    case 'instrumentor.iife.js': {
      return createWorkerScriptResponse(instrumentorCode, {
        '<WORKER_ROUTE_PREFIX>': routePrefix,
        // The " quotes are intentional here to prevent the template from being parsed as a string literal
        '"<PROTECTED_APIS>"': JSON.stringify(protectedApis),
        '<LOG_LEVEL>': logLevel,
      })
    }
 
    case 'agent-processor.iife.js': {
      return createWorkerScriptResponse(agentProcessorCode, {
        '<WORKER_ROUTE_PREFIX>': routePrefix,
        '<LOG_LEVEL>': logLevel,
      })
    }
 
    case 'loader.js':
      return getAgentLoader(request, publicApiKey, cdnHost)
  }
}