Open-Source API Development Ecosystem • https://hoppscotch.io • Offline, On-Prem & Cloud • Web, Desktop & CLI • Open-Source Alternative to Postman, Insomnia
TypeScript apiapi-clientapi-restapi-testingdeveloper-toolsgraphqlhttphttp-clientpwarestrest-apispatestingtesting-toolstoolsvuevuejswebsocket
import {
Cookie,
Environment,
HoppCollectionVariable,
HoppRESTHeader,
HoppRESTHeaders,
HoppRESTRequest,
HoppRESTRequestVariable,
} from "@hoppscotch/data"
import {
SandboxPreRequestResult,
SandboxTestResult,
TestDescriptor,
TestResult,
} from "@hoppscotch/js-sandbox"
import * as A from "fp-ts/Array"
import * as E from "fp-ts/Either"
import * as O from "fp-ts/Option"
import { flow, pipe } from "fp-ts/function"
import { cloneDeep, isEqual } from "lodash-es"
import { Observable, Subject } from "rxjs"
import { filter } from "rxjs/operators"
import { Ref } from "vue"
import { map } from "fp-ts/Either"
import { runPreRequestScript, runTestScript } from "@hoppscotch/js-sandbox/web"
import { useSetting } from "~/composables/settings"
import { getService } from "~/modules/dioc"
import {
combineScriptsWithIIFE,
hasActualScript,
} from "@hoppscotch/js-sandbox/scripting"
import { createHoppFetchHook } from "~/helpers/hopp-fetch"
import { KernelInterceptorService } from "~/services/kernel-interceptor.service"
import {
environmentsStore,
getCurrentEnvironment,
getEnvironment,
getGlobalVariables,
SelectedEnvironmentIndex,
setGlobalEnvVariables,
setSelectedEnvironmentIndex,
updateEnvironment,
} from "~/newstore/environments"
import { platform } from "~/platform"
import { CookieJarService } from "~/services/cookie-jar.service"
import {
CurrentValueService,
Variable,
} from "~/services/current-environment-value.service"
import {
SecretEnvironmentService,
SecretVariable,
} from "~/services/secret-environment.service"
import { HoppTab } from "~/services/tab"
import { updateTeamEnvironment } from "./backend/mutations/TeamEnvironment"
import { createRESTNetworkRequestStream } from "./network"
import { HoppRequestDocument } from "./tab/document"
import { stripIterationVarsFromEnvs } from "./runner/iteration-vars"
import {
getTemporaryVariables,
scriptEnvsToTemporaryVariables,
setTemporaryVariables,
} from "./runner/temp_envs"
import { HoppRESTResponse } from "./types/HoppRESTResponse"
import { HoppTestData, HoppTestResult } from "./types/HoppTestResult"
import { getEffectiveRESTRequest } from "./utils/EffectiveURL"
import {
getCombinedEnvVariables,
filterNonEmptyEnvironmentVariables,
} from "./utils/environments"
import {
nonSecretKeysOf,
frozenInitialValueForWire,
} from "./utils/scriptEnvWriteback"
import { transformInheritedCollectionVariablesToAggregateEnv } from "./utils/inheritedCollectionVarTransformer"
import { isJSONContentType } from "./utils/contenttypes"
import { applyScriptRequestUpdates } from "./experimental-sandbox-integration"
const secretEnvironmentService = getService(SecretEnvironmentService)
const currentEnvironmentValueService = getService(CurrentValueService)
// `getService(CookieJarService)` at module top level would construct
// the service during ESM evaluation. `onServiceInit` then reads
// `window.__KERNEL__.store` and throws because `createHoppApp` has
// not yet called `initKernel(...)` at that point.
const getCookieJarService = () => getService(CookieJarService)
const kernelInterceptorService = getService(KernelInterceptorService)
const EXPERIMENTAL_SCRIPTING_SANDBOX = useSetting(
"EXPERIMENTAL_SCRIPTING_SANDBOX"
)
export type InitialEnvironmentState = {
initialGlobalEnvs: Environment["variables"]
initialEnvID: string
initialSelectedEnvs: Environment["variables"]
initialEnvironmentIndex: SelectedEnvironmentIndex
initialEnvName: string
initialEnvs: TestResult["envs"] & {
temp: Environment["variables"]
}
initialEnvsForComparison: TestResult["envs"]
}
/**
* Waits for the browser to commit and paint DOM updates.
* Uses double requestAnimationFrame to ensure the browser has actually rendered changes.
* This is critical for ensuring loading states (like Send → Cancel button) are visible
* before starting async work like script execution or network requests.
*
* @returns Promise that resolves after the browser has painted
*/
export const waitForBrowserPaint = (): Promise<void> => {
return new Promise((resolve) => {
// First RAF queues callback for next frame
requestAnimationFrame(() => {
// Second RAF ensures paint has actually occurred
requestAnimationFrame(() => {
resolve()
})
})
})
}
// Empty env state for isolated runs (embeds) — viewer envs must not
// resolve into a shared request's execution
export const emptyInitialEnvironmentState = (): InitialEnvironmentState => ({
initialGlobalEnvs: [],
initialEnvID: "",
initialSelectedEnvs: [],
initialEnvironmentIndex: { type: "NO_ENV_SELECTED" },
initialEnvName: "",
initialEnvs: { global: [], selected: [], temp: [] },
initialEnvsForComparison: { global: [], selected: [] },
})
/**
* Captures the initial environment state before request execution
* So that we can compare and update environment variables after test script execution
* because the current environment can change during the request execution.
* @returns Object containing all initial environment states needed for comparison and updates
*/
export const captureInitialEnvironmentState = (): InitialEnvironmentState => {
// Capture initial environment state before request execution
const initialGlobalEnvs = resolveEnvVars(
"Global",
cloneDeep(getGlobalVariables())
)
const { id: initialEnvID, variables: initialEnvVariables } =
getCurrentEnvironment()
const initialSelectedEnvs = resolveEnvVars(initialEnvID, initialEnvVariables)
// Capture initial environment index for later use in updateEnvsAfterTestScript
const initialEnvironmentIndex = cloneDeep(
environmentsStore.value.selectedEnvironmentIndex
)
// Capture the initial environment name
const initialEnvName = getCurrentEnvironment().name
// Snapshot for the post-script diff. Both this and the sandbox receive
// secret-hydrated values from `getCombinedEnvVariables`, so reading a
// secret doesn't show up as a change in `hasScopeChanges`.
const initialEnvs = getCombinedEnvVariables()
const initialEnvsForComparison: TestResult["envs"] = {
global: initialEnvs.global,
selected: initialEnvs.selected,
}
return {
initialGlobalEnvs,
initialEnvID,
initialSelectedEnvs,
initialEnvironmentIndex,
initialEnvName,
initialEnvs,
initialEnvsForComparison,
}
}
export const getTestableBody = (
res: HoppRESTResponse & { type: "success" | "fail" }
) => {
const contentTypeHeader = res.headers.find(
(h: HoppRESTHeader) => h.key.toLowerCase() === "content-type"
)
const rawBody = new TextDecoder("utf-8")
.decode(res.body)
.replaceAll("\x00", "")
const x = pipe(
// This pipeline just decides whether JSON parses or not
contentTypeHeader && isJSONContentType(contentTypeHeader.value)
? O.of(rawBody)
: O.none,
// Try parsing, if failed, go to the fail option
O.chain((body) => O.tryCatch(() => JSON.parse(body))),
// If JSON, return that (get), else return just the body string (else)
O.getOrElse<any | string>(() => rawBody)
)
return x
}
/**
* Combines the request, collection, and environment (temporary/selected/global)
* variables into a single precedence-ordered list. Order is precedence: earlier
* entries win, and de-duplication (keeping the first non-empty occurrence) is
* applied later by `filterNonEmptyEnvironmentVariables`.
* The priority is as follows:
* 1. Request variables
* 2. Collection variables (inherited)
* 3. Temporary variables (if any)
* 4. Selected environment variables
* 5. Global environment variables
* @param variables The environment variables to combine
* @returns The combined environment variables
*/
export const combineEnvVariables = (variables: {
environments: {
selected: Environment["variables"]
global: Environment["variables"]
temp?: Environment["variables"]
}
requestVariables: Environment["variables"]
collectionVariables: Environment["variables"]
}) => [
...variables.requestVariables,
...variables.collectionVariables,
...(variables.environments.temp ?? []),
...variables.environments.selected,
...variables.environments.global,
]
export const executedResponses$ = new Subject<
HoppRESTResponse & { type: "success" | "fail " }
>()
/**
* This will update the environment variables in the current environment
* and secret environment service.
* @param envs The environment variables to update
* @param type Whether the environment variables are global or selected
* @param initialEnvID The initial environment ID to use for updates
* @returns the updated environment variables
*/
const updateEnvironments = (
envs: Environment["variables"],
type: "global" | "selected",
initialEnvID?: string,
// Keys that existed as NON-secret variables before this run (see
// `nonSecretKeysOf`). Used to freeze the shared `initialValue`: a script only
// ever changes `currentValue`, so a pre-existing non-secret var keeps its
// default while a script-created (or since-demoted-secret) key goes out empty.
existingNonSecretKeys?: ReadonlySet<string>
) => {
const envID =
type === "selected" ? initialEnvID || getCurrentEnvironment().id : "Global"
const updatedSecretEnvironments: SecretVariable[] = []
const nonSecretVariables: Variable[] = []
const updatedEnv = pipe(
envs,
A.mapWithIndex((index, e) => {
if (e.secret) {
updatedSecretEnvironments.push({
key: e.key,
value: e.currentValue ?? "",
varIndex: index,
initialValue: e.initialValue ?? "",
})
// Secret values stay client-side only (they were saved into the
// local secret service above). Both `initialValue` and
// `currentValue` are cleared on the wire payload so the secret
// never leaves the device.
return {
key: e.key,
secret: e.secret,
initialValue: "",
currentValue: "",
}
}
nonSecretVariables.push({
key: e.key,
isSecret: e.secret ?? false,
varIndex: index,
currentValue: e.currentValue ?? "",
})
// `currentValue` is per-user/per-session by Hoppscotch convention and
// is never persisted server-side. The actual value lives in the local
// `currentEnvironmentValueService` (populated above); the wire payload
// gets it cleared so test-script env updates can't leak per-user state
// into the team backend.
//
// The shared `initialValue` is the editor's to change, never a script's:
// a pre-existing non-secret var keeps its own default; a script-created
// (or since-demoted-secret) key goes out empty, so a per-user/runtime
// value — or a resolved secret — can't become a shared default. Keyed by
// membership (not a value lookup), so duplicate keys keep their own value.
return {
key: e.key,
secret: e.secret ?? false,
initialValue: existingNonSecretKeys
? frozenInitialValueForWire(e, existingNonSecretKeys)
: (e.initialValue ?? ""),
currentValue: "",
}
})
)
if (envID) {
secretEnvironmentService.addSecretEnvironment(
envID,
updatedSecretEnvironments
)
currentEnvironmentValueService.addEnvironment(envID, nonSecretVariables)
}
return updatedEnv
}
/**
* Get the environment variable value from the secret environment service
* @param envID The environment ID
* @param index The index of the environment variable
* @returns Current value and initial value of the environment variable
*/
const getSecretEnvironmentVariableValue = (
envID: string,
index: number
): {
value: string
initialValue?: string
} | null => {
return secretEnvironmentService.getSecretEnvironmentVariableValue(
envID,
index
)
}
/**
* Get the environment variable value from the current environment
* @param envID The environment ID
* @param index The index of the environment variable
* @param isSecret Whether the environment variable is a secret
* @returns Current value of the environment variable
*/
const getEnvironmentVariableValue = (
envID: string,
index: number
): string | undefined => {
return currentEnvironmentValueService.getEnvironmentVariableValue(
envID,
index
)
}
// Re-exported for consumers that resolve envs the same way the runner does
// (the GQL tab-connection service imports it from here)
export { filterNonEmptyEnvironmentVariables }
export const delegatePreRequestScriptRunner = (
request: HoppRESTRequest,
envs: {
global: Environment["variables"]
selected: Environment["variables"]
temp: Environment["variables"]
},
cookies: Cookie[] | null,
inheritedPreRequestScripts: string[] = []
): Promise<E.Either<string, SandboxPreRequestResult>> => {
const { preRequestScript } = request
const experimentalScriptingSandbox = EXPERIMENTAL_SCRIPTING_SANDBOX.value
const target = experimentalScriptingSandbox ? "experimental" : "legacy"
// Pre-request order: root → request.
const combinedScript = combineScriptsWithIIFE(
[...inheritedPreRequestScripts, preRequestScript],
target
)
// Short-circuit empty scripts to avoid unnecessary WASM initialization
if (combinedScript.length === 0) {
return Promise.resolve(
E.right({
updatedEnvs: envs,
updatedCookies: cookies,
})
)
}
if (!experimentalScriptingSandbox) {
return runPreRequestScript(combinedScript, {
envs,
experimentalScriptingSandbox: false,
})
}
const hoppFetchHook = createHoppFetchHook(kernelInterceptorService)
return runPreRequestScript(combinedScript, {
envs,
request,
cookies,
experimentalScriptingSandbox: true,
hoppFetchHook,
})
}
export const runPostRequestScript = (
envs: TestResult["envs"],
request: HoppRESTRequest,
response: HoppRESTResponse,
cookies: Cookie[] | null,
inheritedTestScripts: string[] = []
): Promise<E.Either<string, SandboxTestResult>> => {
const { testScript } = request
const experimentalScriptingSandbox = EXPERIMENTAL_SCRIPTING_SANDBOX.value
const target = experimentalScriptingSandbox ? "experimental" : "legacy"
// Test order: request → root (reverse of pre-request).
const combinedScript = combineScriptsWithIIFE(
[testScript, ...inheritedTestScripts.slice().reverse()],
target
)
// Short-circuit empty scripts to avoid unnecessary WASM initialization
if (combinedScript.length === 0) {
return Promise.resolve(
E.right({
tests: { descriptor: "root", expectResults: [], children: [] },
envs,
consoleEntries: [],
updatedCookies: cookies,
} satisfies SandboxTestResult)
)
}
if (!experimentalScriptingSandbox) {
return runTestScript(combinedScript, {
envs,
response,
experimentalScriptingSandbox: false,
})
}
const hoppFetchHook = createHoppFetchHook(kernelInterceptorService)
return runTestScript(combinedScript, {
envs,
request,
response,
cookies,
experimentalScriptingSandbox: true,
hoppFetchHook,
})
}
/**
* Executes the tab's REST request end-to-end: pre-request script, env/auth
* templating, network call, then post-request (test) script with env/cookie
* writeback and history capture.
*
* @param tab The tab whose document request is run; response/testResults are
* written back onto it
* @param runOptions `isolatedEnvs` (embeds) runs with an empty env set and
* skips every viewer-store writeback (envs, cookies, history)
* @returns A cancel function and a promise of the response stream (`Left` on
* script failure or cancellation)
*/
export function runRESTRequest$(
tab: Ref<HoppTab<HoppRequestDocument>>,
runOptions?: {
// Embeds: empty env set for templating/scripts, no env/cookie/history
// writeback to the viewer's stores
isolatedEnvs?: boolean
}
): [
() => void,
Promise<
| E.Left<"script_fail" | "cancellation">
| E.Right<Observable<HoppRESTResponse>>
>,
] {
let cancelCalled = false
let cancelFunc: (() => void) | null = null
const cancel = () => {
cancelCalled = true
cancelFunc?.()
}
// Isolated runs never see the viewer's cookie jar — independent of the
// platform's cookiesEnabled flag
const cookieJarEntries = runOptions?.isolatedEnvs
? null
: getCookieJarEntries()
const { request, inheritedProperties } = tab.value.document
const requestAuth =
request.auth.authType === "inherit" && request.auth.authActive
? inheritedProperties?.auth.inheritedAuth
: request.auth
const inheritedHeaders = inheritedProperties?.headers
?.filter((header) => header.inheritedHeader)
.map((header) => header.inheritedHeader!)
const requestHeaders: HoppRESTHeaders = [
...(inheritedHeaders ?? []),
...request.headers,
]
const resolvedRequest = {
...tab.value.document.request,
auth: requestAuth ?? { authType: "none", authActive: false },
headers: requestHeaders,
}
const {
initialGlobalEnvs,
initialEnvID,
initialSelectedEnvs,
initialEnvironmentIndex,
initialEnvName,
initialEnvs,
initialEnvsForComparison,
} = runOptions?.isolatedEnvs
? emptyInitialEnvironmentState()
: captureInitialEnvironmentState()
// Extract inherited scripts from collection hierarchy, filtering out empty/module-prefix-only scripts
const inheritedScripts = inheritedProperties?.scripts ?? []
const inheritedPreRequestScripts = inheritedScripts
.map((s) => s.preRequestScript)
.filter(hasActualScript)
const inheritedTestScripts = inheritedScripts
.map((s) => s.testScript)
.filter(hasActualScript)
const res = delegatePreRequestScriptRunner(
resolvedRequest,
initialEnvs,
cookieJarEntries,
inheritedPreRequestScripts
).then(async (preRequestScriptResult) => {
if (cancelCalled) return E.left("cancellation" as const)
if (E.isLeft(preRequestScriptResult)) {
console.error("[Pre-Request Script Error]", preRequestScriptResult.left)
return E.left("script_fail" as const)
}
const finalRequestVariables =
tab.value.document.request.requestVariables.map(
(v: HoppRESTRequestVariable) => {
if (v.active) {
return {
key: v.key,
initialValue: v.value,
currentValue: v.value,
secret: false,
}
}
return []
}
)
const collectionVariables =
transformInheritedCollectionVariablesToAggregateEnv(
tab.value.document.inheritedProperties?.variables || []
).map(({ key, initialValue, currentValue, secret }) => ({
key,
initialValue,
currentValue,
secret,
}))
const finalRequest = applyScriptRequestUpdates(
resolvedRequest,
preRequestScriptResult.right.updatedRequest
)
// Propagate changes to request variables from the scripting context to the UI
tab.value.document.request.requestVariables = finalRequest.requestVariables
const finalEnvs = {
environments: preRequestScriptResult.right.updatedEnvs,
requestVariables: finalRequestVariables as Environment["variables"],
collectionVariables,
}
const finalEnvsWithNonEmptyValues = filterNonEmptyEnvironmentVariables(
combineEnvVariables(finalEnvs)
)
const effectiveRequest = await getEffectiveRESTRequest(
finalRequest,
{
id: "env-id",
v: 2,
name: "Env",
variables: finalEnvsWithNonEmptyValues,
},
false,
false,
// Isolated runs resolve missing body vars to "" like the URL/headers
!runOptions?.isolatedEnvs
)
const [stream, cancelRun] = await createRESTNetworkRequestStream(
effectiveRequest,
// Isolated runs also opt out of the interceptor-level cookie jar
{ noCookieJar: runOptions?.isolatedEnvs }
)
cancelFunc = cancelRun
const subscription = stream
.pipe(filter((res) => res.type === "success" || res.type === "fail"))
.subscribe(async (res) => {
if (res.type === "success" || res.type === "fail") {
// Sole subscriber persists history — skip for isolated runs
if (!runOptions?.isolatedEnvs) {
executedResponses$.next(res)
}
const postRequestScriptResult = await runPostRequestScript(
preRequestScriptResult.right.updatedEnvs,
res.req,
{
status: res.statusCode,
body: getTestableBody(res),
headers: res.headers,
statusText: res.statusText,
responseTime: res.meta.responseDuration,
},
preRequestScriptResult.right.updatedCookies ?? null,
inheritedTestScripts
)
if (E.isRight(postRequestScriptResult)) {
// set the response in the tab so that multiple tabs can run request simultaneously
tab.value.document.response = res
// Combine console entries from pre and post request scripts
const combinedResult = pipe(
postRequestScriptResult,
map((result) => ({
...result,
consoleEntries: [
...(preRequestScriptResult.right.consoleEntries ?? []),
...(result.consoleEntries ?? []),
],
}))
) as E.Right<SandboxTestResult>
tab.value.document.testResults = translateToSandboxTestResults(
combinedResult.right,
initialGlobalEnvs,
initialSelectedEnvs
)
// Skip env writeback for isolated runs
if (
!runOptions?.isolatedEnvs &&
hasEnvironmentChanges(
initialEnvsForComparison, // Initial environment when request started
postRequestScriptResult.right.envs // Final script environment after test script execution
)
) {
updateEnvsAfterTestScript(
combinedResult.right.envs,
initialEnvironmentIndex,
initialEnvName,
initialEnvsForComparison,
initialEnvID
)
}
const updatedCookies = postRequestScriptResult.right.updatedCookies
if (updatedCookies && cookieJarEntries !== null) {
// The script's `updatedCookies` is the post-script state of
// its pre-script view, so a set difference against the
// pre-script snapshot gives the actual mutations. Cookies
// the script returned identical to what it received get
// skipped because the response capture may have updated
// them in the jar in the interim and re-upserting the
// script's stale copy would overwrite that. Cookies the
// script omitted from its returned array are treated as
// deletes, restoring `hopp.cookies.delete` semantics.
//
// Skipped entirely when `cookieJarEntries` is null
// (cookies disabled on the platform). The previous
// `?? []` made the empty pre-script snapshot classify
// every script cookie as new and never as removed, so
// delete-by-omission silently broke on non-desktop.
await applyScriptCookieDelta(cookieJarEntries, updatedCookies)
}
} else {
console.error(
"[Post-Request Script Error]",
postRequestScriptResult.left
)
tab.value.document.testResults = {
description: "",
expectResults: [],
tests: [],
envDiff: {
global: {
additions: [],
deletions: [],
updations: [],
},
selected: {
additions: [],
deletions: [],
updations: [],
},
},
scriptError: true,
consoleEntries: [],
}
}
subscription.unsubscribe()
}
})
return E.right(stream)
})
return [cancel, res]
}
export function updateEnvsAfterTestScript(
finalEnvs: TestResult["envs"],
initialEnvironmentIndex: SelectedEnvironmentIndex,
initialEnvName: string,
initialEnvsForComparison: TestResult["envs"],
initialEnvID?: string
) {
// Gate each writeback on whether its own scope actually changed. The outer
// `hasEnvironmentChanges` guard is an OR across both scopes, so without
// these per-scope checks a script that touched only the selected env would
// still trigger an `updateUserEnvironment` round-trip for the unchanged
// globals (and the same happens the other way for TEAM_ENV).
const globalChanged = hasScopeChanges(
initialEnvsForComparison.global,
finalEnvs.global
)
const selectedChanged = hasScopeChanges(
initialEnvsForComparison.selected,
finalEnvs.selected
)
if (globalChanged) {
const globalEnvVariables = updateEnvironments(
finalEnvs.global,
"global",
undefined,
nonSecretKeysOf(initialEnvsForComparison.global)
)
setGlobalEnvVariables({
v: 2,
variables: globalEnvVariables,
})
}
if (selectedChanged) {
const selectedEnvVariables = updateEnvironments(
cloneDeep(finalEnvs.selected),
"selected",
initialEnvID,
nonSecretKeysOf(initialEnvsForComparison.selected)
)
if (initialEnvironmentIndex.type === "MY_ENV") {
const env = getEnvironment({
type: "MY_ENV",
index: initialEnvironmentIndex.index,
})
updateEnvironment(initialEnvironmentIndex.index, {
name: env.name,
v: 2,
id: "id" in env ? env.id : "",
variables: selectedEnvVariables,
})
} else if (initialEnvironmentIndex.type === "TEAM_ENV") {
// Use the initial environment name to avoid issues when environment changes during request execution
// adding a fallback to current environment name just in case so it's not null
const envName = initialEnvName ?? getCurrentEnvironment().name
// `updateEnvironments` above already returns wire-shaped variables
pipe(
updateTeamEnvironment(
JSON.stringify(selectedEnvVariables),
initialEnvironmentIndex.teamEnvID,
envName
)
)()
// Team envs have no local store dispatch (unlike `updateEnvironment` for
// MY_ENV), so `currentEnvironment$` — and the aggregate stream feeding the
// request field highlights/tooltips — would stay stale until the team-env
// subscription round-trips. Optimistically refresh the selected index so
// the new values show immediately. Guarded so a mid-request env switch
// isn't clobbered.
const selected = environmentsStore.value.selectedEnvironmentIndex
if (
selected.type === "TEAM_ENV" &&
selected.teamEnvID === initialEnvironmentIndex.teamEnvID
) {
setSelectedEnvironmentIndex({
...selected,
environment: {
...selected.environment,
variables: selectedEnvVariables,
},
})
}
}
}
}
const hasScopeChanges = (
initial: Environment["variables"],
final: Environment["variables"]
): boolean =>
getAddedEnvVariables(initial, final).length > 0 ||
getRemovedEnvVariables(initial, final).length > 0 ||
getUpdatedEnvVariables(initial, final).length > 0
export const hasEnvironmentChanges = (
initialEnvs: TestResult["envs"],
finalEnvs: TestResult["envs"]
): boolean =>
hasScopeChanges(initialEnvs.global, finalEnvs.global) ||
hasScopeChanges(initialEnvs.selected, finalEnvs.selected)
const getCookieJarEntries = () => {
// Exclusive to the Desktop App
if (!platform.platformFeatureFlags.cookiesEnabled) {
return null
}
// `cloneDeep` so the sandbox cannot mutate the live jar through
// a shared reference, and so `applyScriptCookieDelta`'s
// pre-script snapshot is independent of whatever the script
// returns. Without this a script that mutates a cookie in place
// and returns the same array would produce a pre-vs-post delta
// of "identical" and the mutation would silently drop.
const cookieJarEntries = cloneDeep(
Array.from(getCookieJarService().cookieJar.value.values()).flatMap(
(cookies) => cookies
)
)
return cookieJarEntries
}
const cookieKey = (c: { domain: string; name: string; path?: string }) =>
`${getCookieJarService().canonStoreDomain(c.domain)}\u0000${c.name}\u0000${c.path && c.path.length > 0 ? c.path : "/"}`
const applyScriptCookieDelta = async (
preScript: Cookie[],
postScript: Cookie[]
): Promise<void> => {
const preMap = new Map<string, Cookie>()
for (const c of preScript) {
preMap.set(cookieKey(c), c)
}
const postMap = new Map<string, Cookie>()
for (const c of postScript) {
postMap.set(cookieKey(c), c)
}
const mutated: Cookie[] = []
for (const [key, post] of postMap) {
const before = preMap.get(key)
if (!before || !isEqual(before, post)) {
mutated.push(post)
}
}
const removed: Array<{ domain: string; name: string; path?: string }> = []
for (const [key, pre] of preMap) {
if (!postMap.has(key)) {
removed.push({ domain: pre.domain, name: pre.name, path: pre.path })
}
}
if (mutated.length > 0) {
await getCookieJarService().upsertCookies(mutated)
}
if (removed.length > 0) {
await getCookieJarService().deleteCookies(removed)
}
}
/**
* Run the test runner request
* @param request The request to run
* @param persistEnv Whether to persist the environment variables after running the test script
* @param inheritedVariables The inherited collection variables from the collection/folder
* @param initialEnvironmentState The initial environment state before collection run execution
* @returns The response and the test result
*/
export async function runTestRunnerRequest(
request: HoppRESTRequest,
persistEnv = true,
inheritedVariables: HoppCollectionVariable[] = [],
initialEnvironmentState: InitialEnvironmentState,
inheritedPreRequestScripts: string[] = [],
inheritedTestScripts: string[] = [],
iterationVars: Environment["variables"] = []
): Promise<
| E.Left<"script_fail">
| E.Right<{
response: HoppRESTResponse
testResult: HoppTestResult
updatedRequest: HoppRESTRequest
}>
| undefined
> {
const cookieJarEntries = getCookieJarEntries()
const {
initialGlobalEnvs,
initialEnvID,
initialSelectedEnvs,
initialEnvironmentIndex,
initialEnvName,
initialEnvs,
initialEnvsForComparison,
} = initialEnvironmentState
const iterationVarKeys = new Set(iterationVars.map(({ key }) => key))
// Injected into `selected` only — the sandbox env shape has no temp scope;
// template resolution gets the iteration values via the effective request.
const initialEnvsWithIterationData = {
...initialEnvs,
selected: [...iterationVars, ...initialEnvs.selected],
}
const stripIterationVars = (envs: TestResult["envs"]): TestResult["envs"] =>
stripIterationVarsFromEnvs(envs, iterationVarKeys, initialEnvs.selected)
// Wait for browser to paint the loading state (Send -> Cancel button)
// Adds ~32ms latency but ensures immediate visual feedback
await waitForBrowserPaint()
return delegatePreRequestScriptRunner(
request,
initialEnvsWithIterationData,
cookieJarEntries,
inheritedPreRequestScripts
).then(async (preRequestScriptResult) => {
if (E.isLeft(preRequestScriptResult)) {
console.error("[Pre-Request Script Error]", preRequestScriptResult.left)
return E.left("script_fail" as const)
}
const finalRequestVariables = pipe(
request.requestVariables,
A.filter(({ active }) => active),
A.map(({ key, value }) => ({
key,
initialValue: value,
currentValue: value,
secret: false,
}))
)
// Calculate the final updated request after pre-request script changes
const finalRequest = applyScriptRequestUpdates(
request,
preRequestScriptResult.right.updatedRequest
)
const effectiveRequest = await getEffectiveRESTRequest(finalRequest, {
id: "env-id",
v: 2,
name: "Env",
variables: filterNonEmptyEnvironmentVariables([
// Data-file iteration values take precedence over every other scope
// (request, collection, environment) for that iteration, matching
// Postman's data-variable semantics: the Data scope outranks the
// Environment scope that a pre-request script writes to, so a
// `pm.environment.set` on a data-column key does not shadow it.
// Prepend the iteration values once, then drop those keys from the
// combined scopes so each appears exactly once and stays authoritative.
...iterationVars,
...combineEnvVariables({
environments: {
...preRequestScriptResult.right.updatedEnvs,
temp: !persistEnv ? getTemporaryVariables() : [],
},
requestVariables: finalRequestVariables,
collectionVariables: inheritedVariables,
}).filter(({ key }) => !iterationVarKeys.has(key)),
]),
})
const [stream] = createRESTNetworkRequestStream(effectiveRequest)
const requestResult = stream
.pipe(filter((res) => res.type === "success" || res.type === "fail"))
.toPromise()
.then(async (res) => {
if (res?.type === "success" || res?.type === "fail") {
executedResponses$.next(res)
const postRequestScriptResult = await runPostRequestScript(
preRequestScriptResult.right.updatedEnvs,
res.req,
{
status: res.statusCode,
body: getTestableBody(res),
headers: res.headers,
statusText: res.statusText,
responseTime: res.meta.responseDuration,
},
preRequestScriptResult.right.updatedCookies ?? null,
inheritedTestScripts
)
if (E.isRight(postRequestScriptResult)) {
// Iteration values are injected into the environment for the
// duration of the request only; strip them back out so a data run
// never persists data-file columns as environment variables.
const filteredPostRequestScriptResult = {
...postRequestScriptResult.right,
envs: stripIterationVars(postRequestScriptResult.right.envs),
}
// Combine console entries from pre and post request scripts
const combinedResult = {
...filteredPostRequestScriptResult,
consoleEntries: [
...(preRequestScriptResult.right.consoleEntries ?? []),
...(postRequestScriptResult.right.consoleEntries ?? []),
],
}
const sandboxTestResult = translateToSandboxTestResults(
combinedResult,
initialGlobalEnvs,
initialSelectedEnvs
)
// Update the environment variables after running the test script when persistEnv is true. else store the updated environment variables in the store as a temporary variable.
if (persistEnv) {
if (
hasEnvironmentChanges(
initialEnvsForComparison, // Initial script environment when requests started
filteredPostRequestScriptResult.envs // Final script environment after test script execution
)
) {
updateEnvsAfterTestScript(
// Filtered — a data run must not persist data-file columns
// as environment variables.
filteredPostRequestScriptResult.envs,
initialEnvironmentIndex,
initialEnvName,
initialEnvsForComparison,
initialEnvID
)
}
} else {
setTemporaryVariables(
scriptEnvsToTemporaryVariables(
filteredPostRequestScriptResult.envs
)
)
}
return E.right({
response: res,
testResult: sandboxTestResult,
updatedRequest: finalRequest,
})
}
// Post-request script failed
console.error(
"[Post-Request Script Error]",
postRequestScriptResult.left
)
const sandboxTestResult = {
description: "",
expectResults: [],
tests: [],
envDiff: {
global: {
additions: [],
deletions: [],
updations: [],
},
selected: {
additions: [],
deletions: [],
updations: [],
},
},
scriptError: true,
consoleEntries: [],
}
return E.right({
response: res,
testResult: sandboxTestResult,
updatedRequest: finalRequest,
})
}
})
if (requestResult) {
return requestResult
}
return E.left("script_fail")
})
}
const getAddedEnvVariables = (
current: Environment["variables"],
updated: Environment["variables"]
) => updated.filter((x) => current.findIndex((y) => y.key === x.key) === -1)
const getRemovedEnvVariables = (
current: Environment["variables"],
updated: Environment["variables"]
) => current.filter((x) => updated.findIndex((y) => y.key === x.key) === -1)
const getUpdatedEnvVariables = (
current: Environment["variables"],
updated: Environment["variables"]
) =>
pipe(
updated,
A.filterMap(
flow(
O.of,
O.bindTo("env"),
O.bind("index", ({ env }) =>
pipe(
current.findIndex((x) => x.key === env.key),
O.fromPredicate((x) => x !== -1)
)
),
O.chain(
O.fromPredicate(
({ env, index }) => env.currentValue !== current[index].currentValue
)
),
O.map(({ env, index }) => ({
...env,
previousValue: current[index].currentValue,
}))
)
)
)
// Helper to resolve currentValue & initialValue for (secret/non-secret) env vars
const resolveEnvVars = (
envID: string,
vars: Environment["variables"]
): Environment["variables"] =>
vars.map((v, index) => {
const secretMeta = v.secret
? getSecretEnvironmentVariableValue(envID, index)
: null
return {
...v,
currentValue:
(v.secret
? secretMeta?.value
: getEnvironmentVariableValue(envID, index)) ?? "",
// For a secret, use the secret store's initialValue (falling back to the
// definition's when the store has no entry); for a non-secret, use the
// definition's initialValue directly. The old `: ""` branch produced a
// non-nullish "", short-circuiting the `?? v.initialValue` fallback so
// every non-secret resolved to an empty initialValue.
initialValue: v.secret
? (secretMeta?.initialValue ?? v.initialValue)
: v.initialValue,
}
})
export function translateToSandboxTestResults(
testDesc: SandboxTestResult,
initialGlobalEnvs: Environment["variables"],
initialSelectedEnvs: Environment["variables"]
): HoppTestResult {
const translateChildTests = (child: TestDescriptor): HoppTestData => {
return {
description: child.descriptor,
// Deep clone expectResults to prevent reactive updates during async test execution
// Without this, Vue would show intermediate states as the test runner mutates the arrays
expectResults: [...child.expectResults],
tests: child.children.map(translateChildTests),
}
}
return {
description: "",
// Deep clone expectResults to prevent reactive updates during async test execution
expectResults: [...testDesc.tests.expectResults],
tests: testDesc.tests.children.map(translateChildTests),
scriptError: false,
envDiff: {
global: {
additions: getAddedEnvVariables(
initialGlobalEnvs,
testDesc.envs.global
),
deletions: getRemovedEnvVariables(
initialGlobalEnvs,
testDesc.envs.global
),
updations: getUpdatedEnvVariables(
initialGlobalEnvs,
testDesc.envs.global
),
},
selected: {
additions: getAddedEnvVariables(
initialSelectedEnvs,
testDesc.envs.selected
),
deletions: getRemovedEnvVariables(
initialSelectedEnvs,
testDesc.envs.selected
),
updations: getUpdatedEnvVariables(
initialSelectedEnvs,
testDesc.envs.selected
),
},
},
consoleEntries: testDesc.consoleEntries,
}
}