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
fix(common): resolve environment variables in inherited collection headers (#6447)
Sahilc0276e076ce2
diff --git a/packages/hoppscotch-common/src/components/collections/Properties.vue b/packages/hoppscotch-common/src/components/collections/Properties.vueindex 5edb531c2..f97f94ad4 100644--- a/packages/hoppscotch-common/src/components/collections/Properties.vue+++ b/packages/hoppscotch-common/src/components/collections/Properties.vue@@ -21,6 +21,7 @@<HttpHeadersv-model="editableCollection":is-collection-property="true"+ :envs="envs"@change-tab="changeOptionTab"/><div@@ -41,6 +42,7 @@:is-collection-property="true":is-root-collection="editingProperties.isRootCollection":inherited-properties="editingProperties.inheritedProperties"+ :envs="envs":source="source"/><div@@ -61,6 +63,7 @@v-model="editableCollection.variables":inherited-properties="editingProperties.inheritedProperties":has-team-write-access="hasTeamWriteAccess"+ :collection-store-key="collectionStoreKey"/></HoppSmartTab>@@ -228,6 +231,12 @@ import preRequestLinter from "~/helpers/editor/linting/preRequest"import testScriptLinter from "~/helpers/editor/linting/testScript"import { copyToClipboard } from "~/helpers/utils/clipboard"import { useService } from "dioc/vue"+import { useReadonlyStream } from "@composables/stream"+import {+ aggregateEnvsWithCurrentValue$,+ getAggregateEnvsWithCurrentValue,+} from "~/newstore/environments"+import { transformInheritedCollectionVariablesToAggregateEnv } from "~/helpers/utils/inheritedCollectionVarTransformer"import {HoppCollection,@@ -255,6 +264,9 @@ export type EditingProperties = {isRootCollection: booleanpath: stringinheritedProperties?: HoppInheritedProperty+ // Key the collection's secret/current values are stored under, computed+ // authoritatively by `editProperties` (team → `id`, personal → `_ref_id`).+ collectionStoreKey?: string}type HoppCollectionAuth = HoppRESTAuth | HoppGQLAuthtype HoppCollectionHeaders = HoppRESTHeaders | GQLHeader[]@@ -307,6 +319,38 @@ const copyIcon = refAutoReset<typeof IconCopy | typeof IconCheck>(const activeTab = useVModel(props, "modelValue", emit)const activeScriptsTab = ref<"pre-request" | "test-script">("pre-request")+const aggregateEnvs = useReadonlyStream(+ aggregateEnvsWithCurrentValue$,+ getAggregateEnvsWithCurrentValue()+)++// Surfaces the prop's already-keyed store ID so `envs` can pass it as+// `sourceEnvID` — lets the env tooltip resolve the collection's own secrets.+const collectionStoreKey = computed(+ () => props.editingProperties.collectionStoreKey ?? ""+)++const envs = computed(() => {+ const collectionVars = editableCollection.value.variables.map((v) => ({+ key: v.key,+ currentValue: v.currentValue,+ initialValue: v.initialValue,+ sourceEnv: "CollectionVariable",+ sourceEnvID: collectionStoreKey.value,+ secret: v.secret,+ }))++ const inheritedVars = transformInheritedCollectionVariablesToAggregateEnv(+ props.editingProperties.inheritedProperties?.variables ?? [],+ true+ )++ // Note: request-level variables are intentionally NOT merged here since+ // there is no single active request in scope when editing collection-level+ // properties.+ return [...collectionVars, ...inheritedVars, ...aggregateEnvs.value]+})+const activeTabIsDetails = computed(() => activeTab.value === "details")const EXPERIMENTAL_SCRIPTING_SANDBOX = useSetting(@@ -375,6 +419,7 @@ const persistUnsavedChanges = async (isRootCollection: props.editingProperties.isRootCollection ?? false,path: props.editingProperties.path,inheritedProperties: props.editingProperties.inheritedProperties,+ collectionStoreKey: props.editingProperties.collectionStoreKey,}))}diff --git a/packages/hoppscotch-common/src/components/collections/Variables.vue b/packages/hoppscotch-common/src/components/collections/Variables.vueindex 9fe8a66c0..07cabe108 100644--- a/packages/hoppscotch-common/src/components/collections/Variables.vue+++ b/packages/hoppscotch-common/src/components/collections/Variables.vue@@ -223,6 +223,9 @@ const props = defineProps<{modelValue: HoppCollectionVariable[]inheritedProperties?: HoppInheritedPropertyhasTeamWriteAccess: boolean+ // Store key this collection's secret/current values are saved under; lets the+ // env tooltip resolve own-collection secrets (set by Properties.vue).+ collectionStoreKey?: string}>()type SelectedEnv = "variables" | "secret"@@ -290,6 +293,7 @@ const liveEnvs = computed(() => {A.map((env) => ({...env,sourceEnv: "CollectionVariable",+ sourceEnvID: props.collectionStoreKey ?? "",})))const parentInheritedVariables =diff --git a/packages/hoppscotch-common/src/components/collections/index.vue b/packages/hoppscotch-common/src/components/collections/index.vueindex 0c731018d..efa2785e9 100644--- a/packages/hoppscotch-common/src/components/collections/index.vue+++ b/packages/hoppscotch-common/src/components/collections/index.vue@@ -3442,10 +3442,11 @@ const editProperties = async (payload: {)}+ const storeID = (collection as HoppCollection)._ref_id ?? collectionId!+const collectionVariables = pipe((collection as HoppCollection).variables ?? [],A.mapWithIndex((index, e) => {- const storeID = (collection as HoppCollection)._ref_id ?? collectionId!const stored = getSecretValues(e.secret, index, storeID)return {...e,@@ -3466,6 +3467,10 @@ const editProperties = async (payload: {isRootCollection: isAlreadyInRoot(collectionIndex),path: collectionIndex,inheritedProperties,+ // Persist the exact key secrets/current values were read under, so the+ // properties modal resolves them without re-deriving (and diverging from)+ // this keying.+ collectionStoreKey: storeID,}} else {const parentIndex = collectionIndex.split("/").slice(0, -1).join("/") // remove last folder to get parent folder@@ -3539,6 +3544,8 @@ const editProperties = async (payload: {isRootCollection: isAlreadyInRoot(collectionIndex),path: collectionIndex,inheritedProperties,+ // Team collections are keyed by `id` (mirrors the save-side keying).+ collectionStoreKey: collectionId ?? "",}}diff --git a/packages/hoppscotch-common/src/components/embeds/Request.vue b/packages/hoppscotch-common/src/components/embeds/Request.vueindex efa515a13..dea18bb7b 100644--- a/packages/hoppscotch-common/src/components/embeds/Request.vue+++ b/packages/hoppscotch-common/src/components/embeds/Request.vue@@ -65,6 +65,7 @@ import { HoppRESTResponse } from "~/helpers/types/HoppRESTResponse"import { runRESTRequest$ } from "~/helpers/RequestRunner"import { HoppTab } from "~/services/tab"import { HoppRequestDocument } from "~/helpers/rest/document"+import { transformRequestVariablesToAggregateEnv } from "~/helpers/utils/environments"const toast = useToast()const t = useI18n()@@ -80,14 +81,11 @@ const requestCancelFunc: Ref<(() => void) | null> = ref(null)const loading = ref(false)-const tabRequestVariables = computed(() => {- return tab.value.document.request.requestVariables.map(({ key, value }) => ({- key,- value,- secret: false,- sourceEnv: "RequestVariable",- }))-})+const tabRequestVariables = computed(() =>+ transformRequestVariablesToAggregateEnv(+ tab.value.document.request.requestVariables+ )+)const { subscribeToStream } = useStreamSubscriber()diff --git a/packages/hoppscotch-common/src/components/embeds/index.vue b/packages/hoppscotch-common/src/components/embeds/index.vueindex 30f6cc676..f1460ab6a 100644--- a/packages/hoppscotch-common/src/components/embeds/index.vue+++ b/packages/hoppscotch-common/src/components/embeds/index.vue@@ -36,6 +36,7 @@ import { HoppTab } from "~/services/tab"import { HoppRequestDocument } from "~/helpers/rest/document"import { platform } from "~/platform"import { RESTOptionTabs } from "../http/RequestOptions.vue"+import { transformRequestVariablesToAggregateEnv } from "~/helpers/utils/environments"const props = defineProps<{modelTab: HoppTab<HoppRequestDocument>@@ -55,14 +56,11 @@ const sharedRequestURL = computed(() => {return `${shortcodeBaseURL.value}/r/${props.sharedRequestID}`})-const tabRequestVariables = computed(() => {- return tab.value.document.request.requestVariables.map(({ key, value }) => ({- key,- value,- secret: false,- sourceEnv: "RequestVariable",- }))-})+const tabRequestVariables = computed(() =>+ transformRequestVariablesToAggregateEnv(+ tab.value.document.request.requestVariables+ )+)const showCustomEmbedsView = computed(() => {const { organization, ui } = platformdiff --git a/packages/hoppscotch-common/src/components/http/Codegen.vue b/packages/hoppscotch-common/src/components/http/Codegen.vueindex 42e31e14a..912dfa49e 100644--- a/packages/hoppscotch-common/src/components/http/Codegen.vue+++ b/packages/hoppscotch-common/src/components/http/Codegen.vue@@ -131,10 +131,8 @@ import {getEffectiveRESTRequest,resolvesEnvsInBody,} from "~/helpers/utils/EffectiveURL"-import {- AggregateEnvironment,- getAggregateEnvsWithCurrentValue,-} from "~/newstore/environments"+import { getAggregateEnvsWithCurrentValue } from "~/newstore/environments"+import { getEffectiveVariablesForRequest } from "~/helpers/utils/environments"import { useService } from "dioc/vue"import cloneDeep from "lodash-es/cloneDeep"@@ -147,15 +145,11 @@ import IconCheck from "~icons/lucide/check"import IconWrapText from "~icons/lucide/wrap-text"import { asyncComputed } from "@vueuse/core"import { getDefaultRESTRequest } from "~/helpers/rest/default"-import { CurrentValueService } from "~/services/current-environment-value.service"-import { getCurrentEnvironment } from "../../newstore/environments"-import { transformInheritedCollectionVariablesToAggregateEnv } from "~/helpers/utils/inheritedCollectionVarTransformer"import { filterNonEmptyEnvironmentVariables } from "~/helpers/RequestRunner"const t = useI18n()const tabs = useService(RESTTabService)-const currentEnvironmentValueService = useService(CurrentValueService)// Get the current active request if the current active tab is a request else get the original request from the response tabconst currentActiveRequest = computed(() => {@@ -195,18 +189,6 @@ const emit = defineEmits<{(e: "request-code", value: string): void}>()-const getCurrentValue = (env: AggregateEnvironment) => {- const currentSelectedEnvironment = getCurrentEnvironment()-- if (env && env.secret) {- return env.currentValue- }- return currentEnvironmentValueService.getEnvironmentByKey(- env?.sourceEnv !== "Global" ? currentSelectedEnvironment.id : "Global",- env?.key ?? ""- )?.currentValue-}-const getFinalURL = (input: string): string => {// If the URL is empty, return "https://"// This is to ensure that the URL is always valid and can be used in code generation@@ -244,39 +226,13 @@ const buildFinalEnvironment = (): Environment => {const inheritedVariables =currentActiveTabDocument.value.inheritedProperties?.variables || []- const requestVariables = (currentActiveRequest.value?.requestVariables || [])- .filter((variable) => variable.active)- .map((variable) => ({- key: variable.key,- initialValue: variable.value,- currentValue: variable.value,- secret: false,- }))-- const collectionVariables =- transformInheritedCollectionVariablesToAggregateEnv(inheritedVariables).map(- ({ key, initialValue, currentValue, secret }) => ({- key,- initialValue,- currentValue,- secret,- })- )-- const environmentVariables = aggregateEnvs.map((env) => ({- key: env.key,- secret: env.secret,- initialValue: env.initialValue,- currentValue: getCurrentValue(env) || env.initialValue,- }))-- const allVariables = [- ...requestVariables,- ...collectionVariables,- ...environmentVariables,- ]+ const resolvedEnvs = getEffectiveVariablesForRequest(+ currentActiveRequest.value?.requestVariables,+ inheritedVariables,+ aggregateEnvs+ )- const filteredVariables = filterNonEmptyEnvironmentVariables(allVariables)+ const filteredVariables = filterNonEmptyEnvironmentVariables(resolvedEnvs)return {v: 2,diff --git a/packages/hoppscotch-common/src/components/http/Headers.vue b/packages/hoppscotch-common/src/components/http/Headers.vueindex 5675fa272..3ffa1d982 100644--- a/packages/hoppscotch-common/src/components/http/Headers.vue+++ b/packages/hoppscotch-common/src/components/http/Headers.vue@@ -263,7 +263,7 @@ import { flow, pipe } from "fp-ts/function"import * as O from "fp-ts/Option"import * as RA from "fp-ts/ReadonlyArray"import { cloneDeep, isEqual } from "lodash-es"-import { reactive, Ref, ref, toRef, watch } from "vue"+import { computed, reactive, Ref, ref, toRef, watch } from "vue"import draggable from "vuedraggable-es"import { useVModel } from "@vueuse/core"@@ -279,10 +279,12 @@ import {getComputedHeaders,} from "~/helpers/utils/EffectiveURL"import { isDragDropAllowed, DragDropEvent } from "~/helpers/dragDropValidation"+import { filterNonEmptyEnvironmentVariables } from "~/helpers/RequestRunner"+import { normalizeAggregateEnvs } from "~/helpers/utils/environments"import {AggregateEnvironment,- aggregateEnvs$,- getAggregateEnvs,+ aggregateEnvsWithCurrentValue$,+ getAggregateEnvsWithCurrentValue,getCurrentEnvironment,} from "~/newstore/environments"import { toggleNestedSetting } from "~/newstore/settings"@@ -553,7 +555,10 @@ const clearContent = () => {bulkHeaders.value = ""}-const aggregateEnvs = useReadonlyStream(aggregateEnvs$, getAggregateEnvs())+const aggregateEnvs = useReadonlyStream(+ aggregateEnvsWithCurrentValue$,+ getAggregateEnvsWithCurrentValue()+)const computedHeaders: Ref<{@@ -572,10 +577,12 @@ const inheritedProperty = ref<}[]>([])-const currentSelectedEnvironment = getCurrentEnvironment()--watch([props.modelValue, aggregateEnvs], async () => {- const resolvedEnvs = aggregateEnvs.value.map((env) => {+const resolvedEnvs = computed(() => {+ // Normalize to the v2 env shape so any legacy `{ key, value }` rows still+ // resolve correctly in the computed headers/auth below.+ if (props.envs) return normalizeAggregateEnvs(props.envs)+ const currentSelectedEnvironment = getCurrentEnvironment()+ return aggregateEnvs.value.map((env) => {return {...env,currentValue:@@ -589,20 +596,45 @@ watch([props.modelValue, aggregateEnvs], async () => {)?.currentValue ?? ""),}})- computedHeaders.value = (- await getComputedHeaders(props.modelValue, resolvedEnvs)- ).map((header, index) => ({- id: `header-${index}`,- ...header,- }))})watch(- () => [props.inheritedProperties, request.value],- async () => {- if (!props.inheritedProperties) return+ [() => props.modelValue, resolvedEnvs],+ async (_newVals, _oldVals, onCleanup) => {+ let isStale = false+ onCleanup(() => {+ isStale = true+ })++ const headers = await getComputedHeaders(+ props.modelValue,+ filterNonEmptyEnvironmentVariables(resolvedEnvs.value)+ )+ if (isStale) return++ computedHeaders.value = headers.map((header, index) => ({+ id: `header-${index}`,+ ...header,+ }))+ },+ { immediate: true, deep: true }+)++watch(+ [() => props.inheritedProperties, request, resolvedEnvs],+ async (_newVals, _oldVals, onCleanup) => {+ let isStale = false+ onCleanup(() => {+ isStale = true+ })++ if (!props.inheritedProperties) {+ // Clear any previously-computed inherited rows so they don't linger when+ // the request switches to one without inherited collection settings.+ inheritedProperty.value = []+ return+ }- //filter out headers that are already in the request headersconst inheritedHeaders = props.inheritedProperties.headers.filter((header) =>!request.value.headers.some(@@ -611,9 +643,9 @@ watch(requestHeader.active))- inheritedProperty.value = inheritedHeaders.map((header, index) => ({- inheritedFrom: props.inheritedProperties!.headers[index].parentName!,- source: "headers",+ const headersList = inheritedHeaders.map((header, index) => ({+ inheritedFrom: header.parentName,+ source: "headers" as const,id: `header-${index}`,header: header.inheritedHeader,}))@@ -628,20 +660,24 @@ watch()) {const [computedAuthHeader] = await getComputedAuthHeaders(- aggregateEnvs.value,+ filterNonEmptyEnvironmentVariables(resolvedEnvs.value),request.value,props.inheritedProperties.auth.inheritedAuth,false)+ if (isStale) return+if (computedAuthHeader) {- inheritedProperty.value.push({+ headersList.push({inheritedFrom: props.inheritedProperties.auth.parentName,- source: "auth",+ source: "auth" as const,id: `header-auth`,header: computedAuthHeader,})}}++ inheritedProperty.value = headersList},{ immediate: true, deep: true })diff --git a/packages/hoppscotch-common/src/components/http/RequestTab.vue b/packages/hoppscotch-common/src/components/http/RequestTab.vueindex 66352e572..ce25ae0e8 100644--- a/packages/hoppscotch-common/src/components/http/RequestTab.vue+++ b/packages/hoppscotch-common/src/components/http/RequestTab.vue@@ -6,6 +6,7 @@v-model="tab.document.request"v-model:option-tab="tab.document.optionTabPreference!"v-model:inherited-properties="tab.document.inheritedProperties"+ :envs="resolvedEnvs"/></template><template #secondary>@@ -19,14 +20,18 @@</template><script setup lang="ts">-import { watch } from "vue"+import { watch, computed } from "vue"import { useVModel } from "@vueuse/core"import { cloneDeep } from "lodash-es"import { isEqualHoppRESTRequest } from "@hoppscotch/data"import { HoppTab } from "~/services/tab"import { HoppRequestDocument } from "~/helpers/rest/document"--// TODO: Move Response and Request execution code to over here+import { useReadonlyStream } from "@composables/stream"+import {+ aggregateEnvsWithCurrentValue$,+ getAggregateEnvsWithCurrentValue,+} from "~/newstore/environments"+import { getEffectiveVariablesForRequest } from "~/helpers/utils/environments"const props = defineProps<{ modelValue: HoppTab<HoppRequestDocument> }>()@@ -36,6 +41,19 @@ const emit = defineEmits<{const tab = useVModel(props, "modelValue", emit)+const envs = useReadonlyStream(+ aggregateEnvsWithCurrentValue$,+ getAggregateEnvsWithCurrentValue()+)++const resolvedEnvs = computed(() => {+ return getEffectiveVariablesForRequest(+ tab.value.document.request.requestVariables,+ tab.value.document.inheritedProperties?.variables,+ envs.value+ )+})+// TODO: Come up with a better dirty checklet oldRequest = cloneDeep(tab.value.document.request)watch(diff --git a/packages/hoppscotch-common/src/components/http/example/ResponseTab.vue b/packages/hoppscotch-common/src/components/http/example/ResponseTab.vueindex 3c415318e..33e5e1dea 100644--- a/packages/hoppscotch-common/src/components/http/example/ResponseTab.vue+++ b/packages/hoppscotch-common/src/components/http/example/ResponseTab.vue@@ -5,6 +5,8 @@<HttpRequestOptionsv-model="tab.document.response.originalRequest"v-model:option-tab="optionTabPreference"+ v-model:inherited-properties="tab.document.inheritedProperties"+ :envs="resolvedEnvs"/></template><template #secondary>@@ -14,13 +16,18 @@</template><script setup lang="ts">-import { watch, ref } from "vue"+import { watch, ref, computed } from "vue"import { useVModel } from "@vueuse/core"-import { cloneDeep } from "lodash-es"+import { cloneDeep, isEqual } from "lodash-es"import { HoppTab } from "~/services/tab"import { HoppSavedExampleDocument } from "~/helpers/rest/document"import { RESTOptionTabs } from "../RequestOptions.vue"-import { isEqual } from "lodash-es"+import { useReadonlyStream } from "@composables/stream"+import {+ aggregateEnvsWithCurrentValue$,+ getAggregateEnvsWithCurrentValue,+} from "~/newstore/environments"+import { getEffectiveVariablesForRequest } from "~/helpers/utils/environments"const props = defineProps<{ modelValue: HoppTab<HoppSavedExampleDocument> }>()@@ -32,6 +39,19 @@ const tab = useVModel(props, "modelValue", emit)const optionTabPreference = ref<RESTOptionTabs>("params")+const envs = useReadonlyStream(+ aggregateEnvsWithCurrentValue$,+ getAggregateEnvsWithCurrentValue()+)++const resolvedEnvs = computed(() => {+ return getEffectiveVariablesForRequest(+ tab.value.document.response.originalRequest.requestVariables,+ tab.value.document.inheritedProperties?.variables,+ envs.value+ )+})+// TODO: Come up with a better dirty checklet oldResponse = cloneDeep(tab.value.document.response)watch(diff --git a/packages/hoppscotch-common/src/components/smart/EnvInput.vue b/packages/hoppscotch-common/src/components/smart/EnvInput.vueindex 4138885e6..c9487df64 100644--- a/packages/hoppscotch-common/src/components/smart/EnvInput.vue+++ b/packages/hoppscotch-common/src/components/smart/EnvInput.vue@@ -101,7 +101,7 @@ import { useService } from "dioc/vue"import { RESTTabService } from "~/services/tab/rest"import { syntaxTree } from "@codemirror/language"import { uniqueID } from "~/helpers/utils/uniqueID"-import { transformInheritedCollectionVariablesToAggregateEnv } from "~/helpers/utils/inheritedCollectionVarTransformer"+import { getEffectiveVariablesForRequest } from "~/helpers/utils/environments"const t = useI18n()@@ -392,14 +392,24 @@ const aggregateEnvs = useReadonlyStream(const tabs = useService(RESTTabService)const envVars = computed(() => {- // If envs are passed directly as props, mask secrets and return them+ // If envs are passed directly as props, mask secrets and return them.+ // Keep sourceEnvID: the env tooltip uses it to look up secret/current values+ // for collection-scoped variables (otherwise they show as "Empty").if (props.envs?.length) {return props.envs.map(- ({ key, currentValue, initialValue, secret, sourceEnv }) => ({+ ({+ key,+ currentValue,+ initialValue,+ secret,+ sourceEnv,+ sourceEnvID,+ }) => ({key,currentValue: secret ? "********" : currentValue,initialValue: secret ? "********" : initialValue,sourceEnv: sourceEnv ?? "",+ sourceEnvID,secret,}))@@ -410,34 +420,23 @@ const envVars = computed(() => {const isRequest = document.type === "request"const isExample = document.type === "example-response"- // variables inherited from the collection if we're in a request or example- const collectionVariables =- isRequest || isExample- ? transformInheritedCollectionVariablesToAggregateEnv(- document.inheritedProperties?.variables ?? [],- false- )- : []-- // request-level variables- const rawRequestVars = isRequest+ const requestVariables = isRequest? document.request.requestVariables: isExample? document.response.originalRequest.requestVariables: []- // formated request variables- const requestVariables = rawRequestVars- .filter((v) => v.active)- .map(({ key, value }) => ({- key,- currentValue: value,- initialValue: value,- sourceEnv: "RequestVariable",- secret: false,- }))-- return [...requestVariables, ...collectionVariables, ...aggregateEnvs.value]+ const inheritedVariables =+ isRequest || isExample ? document.inheritedProperties?.variables : []++ // Merge in precedence order (request → collection → environment).+ // Collection secrets stay masked here (showSecretCollectionValues = false).+ return getEffectiveVariablesForRequest(+ requestVariables,+ inheritedVariables,+ aggregateEnvs.value,+ false+ )})function envAutoCompletion(context: CompletionContext) {diff --git a/packages/hoppscotch-common/src/helpers/editor/extensions/HoppEnvironment.ts b/packages/hoppscotch-common/src/helpers/editor/extensions/HoppEnvironment.tsindex 23564fd29..ffc04c7cc 100644--- a/packages/hoppscotch-common/src/helpers/editor/extensions/HoppEnvironment.ts+++ b/packages/hoppscotch-common/src/helpers/editor/extensions/HoppEnvironment.ts@@ -7,10 +7,7 @@ import {hoverTooltip,} from "@codemirror/view"import { StreamSubscriberFunc } from "@composables/stream"-import {- parseTemplateStringE,- HoppRESTRequestVariables,-} from "@hoppscotch/data"+import { parseTemplateStringE } from "@hoppscotch/data"import * as E from "fp-ts/Either"import { Ref, watch } from "vue"@@ -35,8 +32,7 @@ import IconVariable from "~icons/lucide/variable?raw"import IconLibrary from "~icons/lucide/library?raw"import { isComment } from "./helpers"-import { transformInheritedCollectionVariablesToAggregateEnv } from "~/helpers/utils/inheritedCollectionVarTransformer"-import { HoppInheritedProperty } from "~/helpers/types/HoppInheritedProperties"+import { getEffectiveVariablesForRequest } from "~/helpers/utils/environments"import {ENV_VAR_NAME_REGEX,HOPP_ENVIRONMENT_REGEX,@@ -370,34 +366,6 @@ export const environmentHighlightStyle = ()}-/**- * Function to get the request variables and collection variables in AggregateEnvironment type- * @param requestVariables Request Variables defined in the request- * @param collectionVariables Inherited Collection Variables- * @returns Transforms the request and collection variables to AggregateEnvironment type- */-const getRequestAndCollectionVariables = (- requestVariables: HoppRESTRequestVariables,- collectionVariables: HoppInheritedProperty["variables"]-) => {- const reqVars = requestVariables- .filter((v) => v.active)- .map(({ key, value }) => ({- key,- currentValue: value,- initialValue: value,- sourceEnv: "RequestVariable",- secret: false,- }))-- const collVars = transformInheritedCollectionVariablesToAggregateEnv(- collectionVariables,- false- )-- return [...reqVars, ...collVars]-}-export class HoppEnvironmentPlugin {private compartment = new Compartment()private envs: AggregateEnvironment[] = []@@ -429,14 +397,13 @@ export class HoppEnvironmentPlugin {? request.requestVariables: []- const requestAndCollVars = getRequestAndCollectionVariables(+ this.envs = getEffectiveVariablesForRequest(requestVariables,- collectionVariables+ collectionVariables,+ getAggregateEnvsWithCurrentValue(),+ false)- const currentAggregateEnvs = getAggregateEnvsWithCurrentValue()- this.envs = [...requestAndCollVars, ...currentAggregateEnvs]-this.editorView.value?.dispatch({effects: this.compartment.reconfigure([cursorTooltipField(this.envs),@@ -460,13 +427,13 @@ export class HoppEnvironmentPlugin {const requestVariables =request && "requestVariables" in request ? request.requestVariables : []- const freshRequestAndCollVars = getRequestAndCollectionVariables(+ this.envs = getEffectiveVariablesForRequest(requestVariables,- inheritedProperties?.variables ?? []+ inheritedProperties?.variables ?? [],+ envs,+ false)- this.envs = [...freshRequestAndCollVars, ...envs]-this.editorView.value?.dispatch({effects: this.compartment.reconfigure([cursorTooltipField(this.envs),diff --git a/packages/hoppscotch-common/src/helpers/utils/__tests__/variablePrecedence.spec.ts b/packages/hoppscotch-common/src/helpers/utils/__tests__/variablePrecedence.spec.tsnew file mode 100644index 000000000..353d6f7f0--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/utils/__tests__/variablePrecedence.spec.ts@@ -0,0 +1,178 @@+import { describe, expect, test } from "vitest"+import { Environment, HoppRESTAuth } from "@hoppscotch/data"+import {+ getEffectiveVariablesForRequest,+ normalizeAggregateEnvs,+} from "../environments"+import { getComputedAuthHeaders } from "../EffectiveURL"+import { filterNonEmptyEnvironmentVariables } from "~/helpers/RequestRunner"+import { AggregateEnvironment } from "~/newstore/environments"+import { HoppInheritedProperty } from "../../types/HoppInheritedProperties"++// A request that inherits auth from a parent collection resolves `<<var>>` from+// three sources, highest precedence first:+// request variable > collection variable > environment variable+// `getEffectiveVariablesForRequest` builds that ordered list; the preview and the+// request runner then pass it through `filterNonEmptyEnvironmentVariables`, so an+// empty high-precedence value falls through to a non-empty lower one.+// Tests use Basic auth with username "<<token>>", so the encoded header shows+// which source won.++const collectionAuth: HoppRESTAuth = {+ authType: "basic",+ authActive: true,+ username: "<<token>>",+ password: "pw",+}++const envVar = (key: string, value: string): AggregateEnvironment => ({+ key,+ currentValue: value,+ initialValue: value,+ secret: false,+ sourceEnv: "Test Env",+})++const collectionVar = (+ key: string,+ value: string+): HoppInheritedProperty["variables"] => [+ {+ parentID: "parent-coll",+ parentName: "Parent Coll",+ inheritedVariables: [+ { key, currentValue: value, initialValue: value, secret: false },+ ],+ },+]++// Pass auth via a request-like object so the context stays a real `{ auth, headers }`+// value — keeps working if an auth type starts reading the surrounding request.+const authHeaderFor = async (vars: Environment["variables"]) => {+ const headers = await getComputedAuthHeaders(vars, {+ auth: collectionAuth,+ headers: [],+ })+ return headers.find((h) => h.key === "Authorization")?.value+}++describe("getEffectiveVariablesForRequest", () => {+ test("orders sources request → collection → environment and drops inactive request vars", () => {+ const vars = getEffectiveVariablesForRequest(+ [+ { key: "a", value: "reqA", active: true },+ { key: "b", value: "reqB", active: false },+ ],+ collectionVar("c", "collC"),+ [envVar("d", "envD")]+ )++ expect(vars.map((v) => v.key)).toEqual(["a", "c", "d"])+ expect(vars[0]).toMatchObject({+ key: "a",+ currentValue: "reqA",+ initialValue: "reqA",+ sourceEnv: "RequestVariable",+ secret: false,+ })+ })++ test("treats undefined request and collection inputs as just the environment list", () => {+ const vars = getEffectiveVariablesForRequest(undefined, undefined, [+ envVar("d", "envD"),+ ])++ expect(vars).toEqual([+ expect.objectContaining({ key: "d", currentValue: "envD" }),+ ])+ })+})++describe("inherited collection auth — variable precedence in the preview", () => {+ test("request variable wins over collection and environment", async () => {+ const vars = getEffectiveVariablesForRequest(+ [{ key: "token", value: "request-token", active: true }],+ collectionVar("token", "coll-token"),+ [envVar("token", "env-token")]+ )++ expect(await authHeaderFor(vars)).toBe(`Basic ${btoa("request-token:pw")}`)+ })++ test("collection variable wins over environment", async () => {+ const vars = getEffectiveVariablesForRequest(+ [],+ collectionVar("token", "coll-token"),+ [envVar("token", "env-token")]+ )++ expect(await authHeaderFor(vars)).toBe(`Basic ${btoa("coll-token:pw")}`)+ })++ test("falls back to the environment variable when nothing else defines the key", async () => {+ const vars = getEffectiveVariablesForRequest(+ [],+ [],+ [envVar("token", "env-token")]+ )++ expect(await authHeaderFor(vars)).toBe(`Basic ${btoa("env-token:pw")}`)+ })++ test("raw list: an empty request variable still shadows the env var (first match wins)", async () => {+ const vars = getEffectiveVariablesForRequest(+ [{ key: "token", value: "", active: true }],+ [],+ [envVar("token", "env-token")]+ )++ expect(await authHeaderFor(vars)).toBe(`Basic ${btoa(":pw")}`)+ })++ test("filtered list: the empty request variable falls through to the env var (matches runtime)", async () => {+ const vars = filterNonEmptyEnvironmentVariables(+ getEffectiveVariablesForRequest(+ [{ key: "token", value: "", active: true }],+ [],+ [envVar("token", "env-token")]+ )+ )++ expect(await authHeaderFor(vars)).toBe(`Basic ${btoa("env-token:pw")}`)+ })+})++describe("normalizeAggregateEnvs (legacy { key, value } rows)", () => {+ test("fills currentValue/initialValue from a legacy `value`, leaving v2 rows intact", () => {+ const [normalized] = normalizeAggregateEnvs([+ {+ key: "token",+ value: "legacy",+ secret: false,+ sourceEnv: "RequestVariable",+ },+ ])+ expect(normalized).toMatchObject({+ key: "token",+ currentValue: "legacy",+ initialValue: "legacy",+ })++ const v2 = envVar("env", "v2-val")+ expect(normalizeAggregateEnvs([v2])[0]).toMatchObject(v2)+ })++ test("a normalized legacy row resolves in computed auth instead of empty", async () => {+ const legacy = [+ {+ key: "token",+ value: "legacy-token",+ secret: false,+ sourceEnv: "RequestVariable",+ },+ ]+ expect(await authHeaderFor(normalizeAggregateEnvs(legacy))).toBe(+ `Basic ${btoa("legacy-token:pw")}`+ )+ })+})diff --git a/packages/hoppscotch-common/src/helpers/utils/environments.ts b/packages/hoppscotch-common/src/helpers/utils/environments.tsindex c466e2a3f..cb705924f 100644--- a/packages/hoppscotch-common/src/helpers/utils/environments.ts+++ b/packages/hoppscotch-common/src/helpers/utils/environments.ts@@ -1,13 +1,16 @@-import { Environment } from "@hoppscotch/data"+import { Environment, HoppRESTRequestVariable } from "@hoppscotch/data"import { cloneDeep } from "lodash-es"import { getService } from "~/modules/dioc"import {getCurrentEnvironment,getGlobalVariables,+ AggregateEnvironment,} from "~/newstore/environments"import { CurrentValueService } from "~/services/current-environment-value.service"import { SecretEnvironmentService } from "~/services/secret-environment.service"+import { HoppInheritedProperty } from "~/helpers/types/HoppInheritedProperties"+import { transformInheritedCollectionVariablesToAggregateEnv } from "./inheritedCollectionVarTransformer"const secretEnvironmentService = getService(SecretEnvironmentService)const currentEnvironmentValueService = getService(CurrentValueService)@@ -87,3 +90,60 @@ export const getCombinedEnvVariables = (temp?: Environment["variables"]) => {temp: temp ? cloneDeep(temp) : [],}}++// Active request variables → `AggregateEnvironment` rows; `value` populates both+// `currentValue` and `initialValue`.+export const transformRequestVariablesToAggregateEnv = (+ requestVariables: HoppRESTRequestVariable[] | undefined+): AggregateEnvironment[] =>+ (requestVariables ?? [])+ .filter((v) => v.active)+ .map((v) => ({+ key: v.key,+ currentValue: v.value,+ initialValue: v.value,+ sourceEnv: "RequestVariable",+ secret: false,+ }))++// Builds the precedence-ordered variable list for resolving `<<var>>` templates:+// request → collection → environment (highest first). Matches the runtime's+// `combineEnvVariables` ordering, so previews stay in sync with execution. Not+// de-duplicated — wrap with `filterNonEmptyEnvironmentVariables` for the runtime's+// empty-value fall-through. `showSecretCollectionValues=false` keeps inherited+// collection secrets masked (used by the inspector / autocomplete).+export const getEffectiveVariablesForRequest = (+ requestVariables: HoppRESTRequestVariable[] | undefined,+ inheritedVariables: HoppInheritedProperty["variables"] | undefined,+ environmentVars: AggregateEnvironment[],+ showSecretCollectionValues = true+): AggregateEnvironment[] => {+ const requestVars = transformRequestVariablesToAggregateEnv(requestVariables)++ const collectionVars = transformInheritedCollectionVariablesToAggregateEnv(+ inheritedVariables ?? [],+ showSecretCollectionValues+ )++ return [...requestVars, ...collectionVars, ...environmentVars]+}++/**+ * Defensively normalizes possibly-legacy env rows to the v2 `AggregateEnvironment`+ * shape (preserving any extra fields), so consumers like+ * `filterNonEmptyEnvironmentVariables` / `parseTemplateString` always see a+ * `currentValue`/`initialValue`. Legacy rows shaped `{ key, value }` (e.g. older+ * embed callers) lack those fields and would otherwise resolve to an empty string.+ */+export const normalizeAggregateEnvs = (+ envs: ReadonlyArray<+ Partial<AggregateEnvironment> & { key: string; value?: string }+ >+): AggregateEnvironment[] =>+ envs.map((env) => ({+ ...env,+ currentValue: env.currentValue ?? env.value ?? "",+ initialValue: env.initialValue ?? env.value ?? "",+ sourceEnv: env.sourceEnv ?? "",+ secret: env.secret ?? false,+ }))diff --git a/packages/hoppscotch-common/src/services/inspection/inspectors/environment.inspector.ts b/packages/hoppscotch-common/src/services/inspection/inspectors/environment.inspector.tsindex 4d92260ee..f9f41c7b1 100644--- a/packages/hoppscotch-common/src/services/inspection/inspectors/environment.inspector.ts+++ b/packages/hoppscotch-common/src/services/inspection/inspectors/environment.inspector.ts@@ -23,7 +23,7 @@ import { useStreamStatic } from "~/composables/stream"import { SecretEnvironmentService } from "~/services/secret-environment.service"import { RESTTabService } from "~/services/tab/rest"import { CurrentValueService } from "~/services/current-environment-value.service"-import { transformInheritedCollectionVariablesToAggregateEnv } from "~/helpers/utils/inheritedCollectionVarTransformer"+import { getEffectiveVariablesForRequest } from "~/helpers/utils/environments"import { HOPP_ENVIRONMENT_REGEX } from "~/helpers/environment-regex"const isENVInString = (str: string) => HOPP_ENVIRONMENT_REGEX.test(str)@@ -81,33 +81,16 @@ export class EnvironmentInspectorService extends Service implements Inspector {? currentTab.document.response.originalRequest: null- // inherited collection-level variables- const collectionVariables =+ // request → collection → environment, in the same precedence order the+ // request runner uses (single source of truth)+ const environmentVariables = getEffectiveVariablesForRequest(+ currentTabRequest?.requestVariables,currentTab.document.type === "request" ||- currentTab.document.type === "example-response"- ? transformInheritedCollectionVariablesToAggregateEnv(- currentTab.document.inheritedProperties?.variables ?? []- )- : []-- // request variables (active only)- const requestVariables =- currentTabRequest?.requestVariables- .filter((v) => v.active)- .map(({ key, value }) => ({- key,- currentValue: value,- initialValue: value,- sourceEnv: "RequestVariable",- secret: false,- })) ?? []-- // combine everything into one list- const environmentVariables = [- ...requestVariables,- ...collectionVariables,- ...this.aggregateEnvsWithValue.value,- ]+ currentTab.document.type === "example-response"+ ? currentTab.document.inheritedProperties?.variables+ : [],+ this.aggregateEnvsWithValue.value+ )const envKeysSet = new Set(environmentVariables.map((e) => e.key))// Scan each string for <<VAR>> patterns@@ -217,34 +200,19 @@ export class EnvironmentInspectorService extends Service implements Inspector {? currentTab.document.response.originalRequest: null- // request variables (active only)- const requestVariables =- currentTabRequest?.requestVariables- .filter((v) => v.active)- .map(({ key, value }) => ({- key,- currentValue: value,- initialValue: value,- sourceEnv: "RequestVariable",- secret: false,- })) ?? []-- // inherited collection variables- const collectionVariables =- currentTab.document.type === "request" ||- currentTab.document.type === "example-response"- ? transformInheritedCollectionVariablesToAggregateEnv(- currentTab.document.inheritedProperties?.variables ?? [],- false- )- : []-- // Merge all variables- const environmentVariables = this.filterNonEmptyEnvironmentVariables([- ...requestVariables,- ...collectionVariables,- ...this.aggregateEnvsWithValue.value,- ])+ // request → collection → environment, matching the request runner's+ // precedence and non-empty resolution (single source of truth)+ const environmentVariables = this.filterNonEmptyEnvironmentVariables(+ getEffectiveVariablesForRequest(+ currentTabRequest?.requestVariables,+ currentTab.document.type === "request" ||+ currentTab.document.type === "example-response"+ ? currentTab.document.inheritedProperties?.variables+ : [],+ this.aggregateEnvsWithValue.value,+ false+ )+ )// Check each variable for missing valuesenvironmentVariables.forEach((env) => {