mirror of
https://github.com/mountain-loop/yaak.git
synced 2026-11-22 16:24:11 +01:00
Fix Insomnia template and GraphQL import fidelity (#693)
This commit is contained in:
1 parent
6fc43a60e2
commit
34815f327a
15 files changed
+921
-35
No files matched your search
@@ -34,13 +34,15 @@ export function importHttpBodyAndHeaders(obj: any) {
|
||||
const { headers } = importHeaders(obj);
|
||||
const { body, bodyType } = importHttpBody(obj.body);
|
||||
const mimeType = typeof obj.body?.mimeType === "string" ? obj.body.mimeType.trim() : "";
|
||||
// Insomnia uses application/graphql as an editor marker, but sends a JSON envelope.
|
||||
const contentType = bodyType === "graphql" ? "application/json" : mimeType;
|
||||
|
||||
if (
|
||||
bodyType != null &&
|
||||
mimeType !== "" &&
|
||||
!headers.some((header: { name: string }) => header.name.toLowerCase() === "content-type")
|
||||
) {
|
||||
headers.push({ enabled: true, name: "Content-Type", value: mimeType });
|
||||
headers.push({ enabled: true, name: "Content-Type", value: contentType });
|
||||
}
|
||||
|
||||
return { body, bodyType, headers };
|
||||
@@ -93,7 +95,36 @@ function importHttpBody(rawBody: any) {
|
||||
}
|
||||
|
||||
if (normalizedMimeType === "application/graphql") {
|
||||
return { bodyType: "graphql", body: { text: rawBody.text ?? "" } };
|
||||
const text = typeof rawBody.text === "string" ? rawBody.text : "";
|
||||
try {
|
||||
const parsed = JSON.parse(text);
|
||||
if (typeof parsed?.query === "string") {
|
||||
return {
|
||||
bodyType: "graphql",
|
||||
body: {
|
||||
query: parsed.query,
|
||||
variables:
|
||||
typeof parsed.variables === "string"
|
||||
? parsed.variables
|
||||
: parsed.variables == null
|
||||
? ""
|
||||
: JSON.stringify(parsed.variables, null, 2),
|
||||
...(typeof parsed.operationName === "string"
|
||||
? { operationName: parsed.operationName }
|
||||
: {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
// A raw GraphQL document is also valid; preserve it verbatim. An envelope that
|
||||
// failed to parse is usually one with template tags in it, so recover its parts
|
||||
// rather than dropping the whole envelope into the query editor.
|
||||
const recovered = recoverGraphQLEnvelope(text);
|
||||
if (recovered != null) {
|
||||
return { bodyType: "graphql", body: recovered };
|
||||
}
|
||||
}
|
||||
return { bodyType: "graphql", body: { query: text, variables: "" } };
|
||||
}
|
||||
|
||||
if (normalizedMimeType === "application/json" || normalizedMimeType.endsWith("+json")) {
|
||||
@@ -115,6 +146,109 @@ function importHttpBody(rawBody: any) {
|
||||
return { bodyType: null, body: {} };
|
||||
}
|
||||
|
||||
/**
|
||||
* Pull the parts out of a GraphQL envelope that isn't valid JSON.
|
||||
*
|
||||
* Insomnia lets template tags be written straight into the envelope
|
||||
* ({"query":"{me{id}}","variables":{"id":{{ _.id }}}}), which makes the text
|
||||
* unparseable. Members are read as raw text so the tags survive the trip.
|
||||
*/
|
||||
function recoverGraphQLEnvelope(
|
||||
text: string,
|
||||
): { query: string; variables: string; operationName?: string } | null {
|
||||
const members = readTopLevelMembers(text);
|
||||
if (members == null) return null;
|
||||
|
||||
const query = parseJSONString(members.get("query"));
|
||||
if (query == null) return null;
|
||||
|
||||
const variables = members.get("variables") ?? "";
|
||||
const operationName = parseJSONString(members.get("operationName"));
|
||||
return {
|
||||
query,
|
||||
variables: variables === "null" ? "" : variables,
|
||||
...(operationName == null ? {} : { operationName }),
|
||||
};
|
||||
}
|
||||
|
||||
function parseJSONString(raw: string | undefined): string | null {
|
||||
if (raw == null || !raw.startsWith('"')) return null;
|
||||
try {
|
||||
const parsed = JSON.parse(raw);
|
||||
return typeof parsed === "string" ? parsed : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The raw text of each member of the outermost object, without parsing the values.
|
||||
* Returns null unless the whole object is well-formed enough to walk.
|
||||
*/
|
||||
function readTopLevelMembers(text: string): Map<string, string> | null {
|
||||
const trimmed = text.trim();
|
||||
if (!trimmed.startsWith("{")) return null;
|
||||
|
||||
const members = new Map<string, string>();
|
||||
let offset = 1;
|
||||
while (offset < trimmed.length) {
|
||||
while (/[\s,]/.test(trimmed[offset] ?? "")) offset++;
|
||||
if (trimmed[offset] === "}") return members;
|
||||
|
||||
const keyEnd = scanJSONString(trimmed, offset);
|
||||
if (keyEnd == null) return null;
|
||||
const key = parseJSONString(trimmed.slice(offset, keyEnd));
|
||||
if (key == null) return null;
|
||||
|
||||
offset = keyEnd;
|
||||
while (/\s/.test(trimmed[offset] ?? "")) offset++;
|
||||
if (trimmed[offset] !== ":") return null;
|
||||
offset++;
|
||||
while (/\s/.test(trimmed[offset] ?? "")) offset++;
|
||||
|
||||
const valueEnd = scanJSONValue(trimmed, offset);
|
||||
if (valueEnd == null) return null;
|
||||
members.set(key, trimmed.slice(offset, valueEnd).trim());
|
||||
offset = valueEnd;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Offset just past the string starting at `start`, or null if it never closes. */
|
||||
function scanJSONString(text: string, start: number): number | null {
|
||||
if (text[start] !== '"') return null;
|
||||
for (let i = start + 1; i < text.length; i++) {
|
||||
if (text[i] === "\\") i++;
|
||||
else if (text[i] === '"') return i + 1;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Offset just past the value starting at `start`. Nesting is tracked so template
|
||||
* tags come back whole, but the value itself is not validated.
|
||||
*/
|
||||
function scanJSONValue(text: string, start: number): number | null {
|
||||
let depth = 0;
|
||||
for (let i = start; i < text.length; i++) {
|
||||
const char = text[i]!;
|
||||
if (char === '"') {
|
||||
const end = scanJSONString(text, i);
|
||||
if (end == null) return null;
|
||||
i = end - 1;
|
||||
} else if (char === "{" || char === "[") {
|
||||
depth++;
|
||||
} else if (char === "}" || char === "]") {
|
||||
if (depth === 0) return i; // The member ended with the enclosing object
|
||||
depth--;
|
||||
if (depth === 0) return i + 1;
|
||||
} else if (depth === 0 && char === ",") {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function deleteUndefinedAttrs<T>(obj: T): T {
|
||||
if (Array.isArray(obj) && obj != null) {
|
||||
return obj.map(deleteUndefinedAttrs) as T;
|
||||
@@ -128,20 +262,3 @@ export function deleteUndefinedAttrs<T>(obj: T): T {
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
|
||||
/** Recursively render all nested object properties */
|
||||
export function convertTemplateSyntax<T>(obj: T): T {
|
||||
if (typeof obj === "string") {
|
||||
// oxlint-disable-next-line no-template-curly-in-string -- Yaak template syntax
|
||||
return obj.replaceAll(/{{\s*(_\.)?([^}]+)\s*}}/g, "${[$2]}") as T;
|
||||
}
|
||||
if (Array.isArray(obj) && obj != null) {
|
||||
return obj.map(convertTemplateSyntax) as T;
|
||||
}
|
||||
if (typeof obj === "object" && obj != null) {
|
||||
return Object.fromEntries(
|
||||
Object.entries(obj).map(([k, v]) => [k, convertTemplateSyntax(v)]),
|
||||
) as T;
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import { Buffer } from "node:buffer";
|
||||
import { convertId } from "./common";
|
||||
|
||||
// Convert only syntax with a native equivalent. Leave filters, expressions and third-party
|
||||
// tags intact rather than importing something that looks valid but means something different.
|
||||
const identifier = /^[\p{L}\p{N}_][\p{L}\p{N}_.-]*$/u;
|
||||
|
||||
function argument(value: string): string {
|
||||
return `b64'${Buffer.from(value).toString("base64url")}'`;
|
||||
}
|
||||
|
||||
function decodeArgument(value: string): string | null {
|
||||
if (!value.startsWith("b64::")) return value;
|
||||
const match = /^b64::([A-Za-z0-9+/_-]*={0,2})(?:::[^:]*)?$/.exec(value);
|
||||
if (!match) return null;
|
||||
const bytes = Buffer.from(match[1]!, "base64");
|
||||
const normalized = match[1]!.replace(/=+$/, "").replaceAll("+", "-").replaceAll("/", "_");
|
||||
if (bytes.toString("base64url") !== normalized) return null;
|
||||
const decoded = bytes.toString("utf8");
|
||||
return Buffer.from(decoded).equals(bytes) ? decoded : null;
|
||||
}
|
||||
|
||||
/** Literal arguments only; never evaluate Nunjucks or silently skip unexpected tokens. */
|
||||
function parseArgs(input: string): string[] | null {
|
||||
const args: string[] = [];
|
||||
const token =
|
||||
/\s*(?:'((?:[^'\\]|\\['"\\nrt])*)'|"((?:[^"\\]|\\['"\\nrt])*)"|(-?\d+(?:\.\d+)?))\s*/y;
|
||||
let offset = 0;
|
||||
while (offset < input.length) {
|
||||
token.lastIndex = offset;
|
||||
const match = token.exec(input);
|
||||
if (!match) return input.trim() === "" ? [] : null;
|
||||
const literal = (match[1] ?? match[2] ?? match[3]!).replace(
|
||||
/\\(['"\\nrt])/g,
|
||||
(_, char: string) => ({ n: "\n", r: "\r", t: "\t" })[char] ?? char,
|
||||
);
|
||||
const decoded = decodeArgument(literal);
|
||||
if (decoded == null) return null;
|
||||
args.push(decoded);
|
||||
offset = token.lastIndex;
|
||||
if (offset === input.length) break;
|
||||
if (input[offset] !== ",") return null;
|
||||
offset++;
|
||||
if (input.slice(offset).trim() === "") return null;
|
||||
}
|
||||
return args;
|
||||
}
|
||||
|
||||
function convertTag(name: string, input: string, requestIds: Set<string>): string | null {
|
||||
const args = parseArgs(input);
|
||||
if (args == null) return null;
|
||||
if (name === "uuid" && args.length === 1 && ["v1", "v4"].includes(args[0]!)) {
|
||||
return `uuid.${args[0]}()`;
|
||||
}
|
||||
if (name === "faker" && args.length === 1 && args[0] === "randomUUID") {
|
||||
return "uuid.v4()";
|
||||
}
|
||||
if (name !== "response" || args.length < 3 || args.length > 5) return null;
|
||||
const [attribute, request, filter = "", behavior = "never", maxAge = "0"] = args;
|
||||
if (!request || !requestIds.has(convertId(request))) return null;
|
||||
const behaviors: Record<string, string> = {
|
||||
never: "never",
|
||||
"no-history": "smart",
|
||||
always: "always",
|
||||
"when-expired": "ttl",
|
||||
};
|
||||
const convertedBehavior = Object.hasOwn(behaviors, behavior) ? behaviors[behavior] : null;
|
||||
if (!convertedBehavior || !/^\d+$/.test(maxAge)) return null;
|
||||
// Insomnia treats zero as immediately expired; Yaak uses zero for never expiring.
|
||||
if (convertedBehavior === "ttl" && Number(maxAge) === 0) return null;
|
||||
const common = `request=${argument(convertId(request))}, behavior='${convertedBehavior}', ttl='${maxAge}'`;
|
||||
if (attribute === "raw") {
|
||||
return `response.body.raw(${common})`;
|
||||
}
|
||||
if (attribute === "body") {
|
||||
// Insomnia returns a scalar for one match, but an array for several. Yaak's first/all
|
||||
// modes cannot express that automatically. Only convert definite paths for now.
|
||||
if (!/^\$(?:\.[\p{L}\p{N}_-]+|\[(?:0|[1-9]\d*)\])*$/u.test(filter.trim())) return null;
|
||||
return `response.body.path(${common}, path=${argument(filter.trim())}, result='first')`;
|
||||
}
|
||||
if (attribute === "header" && filter !== "") {
|
||||
return `response.header(${common}, header=${argument(filter.trim())})`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function convertTemplateSyntax<T>(obj: T, requestIds = new Set<string>()): T {
|
||||
if (typeof obj === "string") {
|
||||
return obj
|
||||
.replace(/{{\s*([\s\S]*?)\s*}}/g, (full, expression: string) => {
|
||||
const trimmed = expression.trim();
|
||||
const bracket = /^_\s*\[\s*(['"])([^'"\\]+)\1\s*\]$/.exec(trimmed);
|
||||
const name = bracket?.[2] ?? trimmed.replace(/^_\./, "");
|
||||
return identifier.test(name) && !["true", "false", "null"].includes(name)
|
||||
? `\${[ ${name} ]}`
|
||||
: full;
|
||||
})
|
||||
.replace(
|
||||
/{%\s*(\w+)\s*((?:'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|[^'"])*?)%}/g,
|
||||
(full, name: string, input: string) => {
|
||||
const converted = convertTag(name, input, requestIds);
|
||||
return converted == null ? full : `\${[ ${converted} ]}`;
|
||||
},
|
||||
) as T;
|
||||
}
|
||||
if (Array.isArray(obj)) return obj.map((value) => convertTemplateSyntax(value, requestIds)) as T;
|
||||
if (typeof obj === "object" && obj != null) {
|
||||
return Object.fromEntries(
|
||||
Object.entries(obj).map(([key, value]) => [key, convertTemplateSyntax(value, requestIds)]),
|
||||
) as T;
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
@@ -2,12 +2,12 @@
|
||||
import type { PartialImportResources } from "@yaakapp/api";
|
||||
import {
|
||||
convertId,
|
||||
convertTemplateSyntax,
|
||||
createSourceKeys,
|
||||
importHttpBodyAndHeaders,
|
||||
isJSObject,
|
||||
type SourceKeys,
|
||||
} from "./common";
|
||||
import { convertTemplateSyntax } from "./templates";
|
||||
|
||||
export function convertInsomniaV4(parsed: any) {
|
||||
if (!Array.isArray(parsed.resources)) return null;
|
||||
@@ -68,7 +68,10 @@ export function convertInsomniaV4(parsed: any) {
|
||||
resources.environments = resources.environments.filter(Boolean);
|
||||
resources.workspaces = resources.workspaces.filter(Boolean);
|
||||
|
||||
return { resources: convertTemplateSyntax(resources), sourceKeys: keys.all() };
|
||||
return {
|
||||
resources: convertTemplateSyntax(resources, new Set(resources.httpRequests.map((r) => r.id))),
|
||||
sourceKeys: keys.all(),
|
||||
};
|
||||
}
|
||||
|
||||
function importHttpRequest(
|
||||
@@ -78,12 +81,12 @@ function importHttpRequest(
|
||||
): PartialImportResources["httpRequests"][0] {
|
||||
let authenticationType: string | null = null;
|
||||
let authentication = {};
|
||||
if (r.authentication.type === "bearer") {
|
||||
if (r.authentication?.type === "bearer") {
|
||||
authenticationType = "bearer";
|
||||
authentication = {
|
||||
token: r.authentication.token,
|
||||
};
|
||||
} else if (r.authentication.type === "basic") {
|
||||
} else if (r.authentication?.type === "basic") {
|
||||
authenticationType = "basic";
|
||||
authentication = {
|
||||
username: r.authentication.username,
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
import type { PartialImportResources } from "@yaakapp/api";
|
||||
import {
|
||||
convertId,
|
||||
convertTemplateSyntax,
|
||||
createSourceKeys,
|
||||
importHeaders,
|
||||
importHttpBodyAndHeaders,
|
||||
isJSObject,
|
||||
type SourceKeys,
|
||||
} from "./common";
|
||||
import { convertTemplateSyntax } from "./templates";
|
||||
|
||||
export function convertInsomniaV5(parsed: any) {
|
||||
// Assert parsed is object
|
||||
@@ -80,7 +80,10 @@ export function convertInsomniaV5(parsed: any) {
|
||||
resources.environments = resources.environments.filter(Boolean);
|
||||
resources.workspaces = resources.workspaces.filter(Boolean);
|
||||
|
||||
return { resources: convertTemplateSyntax(resources), sourceKeys: keys.all() };
|
||||
return {
|
||||
resources: convertTemplateSyntax(resources, new Set(resources.httpRequests.map((r) => r.id))),
|
||||
sourceKeys: keys.all(),
|
||||
};
|
||||
}
|
||||
|
||||
function importHttpRequest(
|
||||
|
||||
@@ -2,6 +2,78 @@ import { describe, expect, test } from "vite-plus/test";
|
||||
import { importHttpBodyAndHeaders } from "../src/common";
|
||||
|
||||
describe("importHttpBodyAndHeaders", () => {
|
||||
test.each([{ id: "123" }, '{"id":"123"}', '{"id":{{ _.id }}}'])(
|
||||
"imports GraphQL variables into the sendable body shape: %j",
|
||||
(variables) => {
|
||||
const result = importHttpBodyAndHeaders({
|
||||
body: {
|
||||
mimeType: "application/graphql",
|
||||
text: JSON.stringify({
|
||||
query: "query Get($id: ID!) { node(id: $id) { id } }",
|
||||
variables,
|
||||
operationName: "Get",
|
||||
}),
|
||||
},
|
||||
});
|
||||
expect(result.bodyType).toBe("graphql");
|
||||
expect(result.body).toEqual({
|
||||
query: "query Get($id: ID!) { node(id: $id) { id } }",
|
||||
variables: typeof variables === "string" ? variables : JSON.stringify(variables, null, 2),
|
||||
operationName: "Get",
|
||||
});
|
||||
expect(result.headers).toEqual([
|
||||
{ name: "Content-Type", value: "application/json", enabled: true },
|
||||
]);
|
||||
},
|
||||
);
|
||||
|
||||
test.each(["query Get { viewer { id } }", "", "{ malformed"])(
|
||||
"preserves raw or malformed GraphQL text rather than discarding it: %s",
|
||||
(query) => {
|
||||
expect(
|
||||
importHttpBodyAndHeaders({ body: { mimeType: "application/graphql", text: query } }).body,
|
||||
).toEqual({ query, variables: "" });
|
||||
},
|
||||
);
|
||||
|
||||
test("preserves GraphQL operation and defaults absent variables", () => {
|
||||
expect(
|
||||
importHttpBodyAndHeaders({
|
||||
body: { mimeType: "application/graphql; charset=utf-8", text: '{"query":"{ me { id } }"}' },
|
||||
}).body,
|
||||
).toEqual({ query: "{ me { id } }", variables: "" });
|
||||
});
|
||||
|
||||
test("recovers a GraphQL envelope holding template tags that break JSON parsing", () => {
|
||||
expect(
|
||||
importHttpBodyAndHeaders({
|
||||
body: {
|
||||
mimeType: "application/graphql",
|
||||
text: '{"query":"{me{id}}","operationName":"Get","variables":{"id":{{ _.id }}}}',
|
||||
},
|
||||
}).body,
|
||||
).toEqual({
|
||||
query: "{me{id}}",
|
||||
variables: '{"id":{{ _.id }}}',
|
||||
operationName: "Get",
|
||||
});
|
||||
});
|
||||
|
||||
test("defaults variables to empty when an unparseable envelope has none", () => {
|
||||
expect(
|
||||
importHttpBodyAndHeaders({
|
||||
body: { mimeType: "application/graphql", text: '{"query":"{me{id}}","meta":{{ _.meta }}}' },
|
||||
}).body,
|
||||
).toEqual({ query: "{me{id}}", variables: "" });
|
||||
});
|
||||
|
||||
test("keeps an envelope-looking document in the query when no query member is readable", () => {
|
||||
const text = "{ query { me { id } } }";
|
||||
expect(
|
||||
importHttpBodyAndHeaders({ body: { mimeType: "application/graphql", text } }).body,
|
||||
).toEqual({ query: text, variables: "" });
|
||||
});
|
||||
|
||||
test("imports XML text using the native XML body type", () => {
|
||||
const result = importHttpBodyAndHeaders({
|
||||
body: {
|
||||
|
||||
@@ -112,7 +112,7 @@
|
||||
"method": "GET",
|
||||
"model": "http_request",
|
||||
"name": "New Request",
|
||||
"url": "${[BASE_URL ]}/foo/:id",
|
||||
"url": "${[ BASE_URL ]}/foo/:id",
|
||||
"urlParameters": [
|
||||
{
|
||||
"name": "query",
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
# Synthetic regression based on the migration cases described by
|
||||
# https://github.com/w33ble/insomnia-yaak-converter (no customer data).
|
||||
type: collection.insomnia.rest/5.0
|
||||
name: Chained GraphQL
|
||||
meta:
|
||||
id: wrk_chained
|
||||
environments:
|
||||
name: Base
|
||||
meta:
|
||||
id: env_base
|
||||
data:
|
||||
host: https://example.com
|
||||
collection:
|
||||
- name: GraphQL
|
||||
meta:
|
||||
id: req_query
|
||||
method: POST
|
||||
url: "{{ _['host'] }}/graphql"
|
||||
authentication:
|
||||
type: bearer
|
||||
token: "{% response 'body', 'req_login', 'b64::JC50b2tlbg==::nonce', 'when-expired', 60 %}"
|
||||
body:
|
||||
mimeType: application/graphql
|
||||
text: '{"query":"query Get($id: ID!) { node(id: $id) { id } }","variables":"{\"id\":\"123\"}","operationName":"Get"}'
|
||||
- name: Login
|
||||
meta:
|
||||
id: req_login
|
||||
method: POST
|
||||
url: "{{ _.host }}/login"
|
||||
@@ -0,0 +1,85 @@
|
||||
{
|
||||
"resources": {
|
||||
"environments": [
|
||||
{
|
||||
"id": "GENERATE_ID::env_base",
|
||||
"workspaceId": "GENERATE_ID::wrk_chained",
|
||||
"public": true,
|
||||
"parentModel": "workspace",
|
||||
"parentId": null,
|
||||
"model": "environment",
|
||||
"name": "Base",
|
||||
"variables": [
|
||||
{
|
||||
"enabled": true,
|
||||
"name": "host",
|
||||
"value": "https://example.com"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"folders": [],
|
||||
"grpcRequests": [],
|
||||
"httpRequests": [
|
||||
{
|
||||
"id": "GENERATE_ID::req_query",
|
||||
"workspaceId": "GENERATE_ID::wrk_chained",
|
||||
"folderId": null,
|
||||
"model": "http_request",
|
||||
"name": "GraphQL",
|
||||
"url": "${[ host ]}/graphql",
|
||||
"urlParameters": [],
|
||||
"body": {
|
||||
"query": "query Get($id: ID!) { node(id: $id) { id } }",
|
||||
"variables": "{\"id\":\"123\"}",
|
||||
"operationName": "Get"
|
||||
},
|
||||
"bodyType": "graphql",
|
||||
"headers": [
|
||||
{
|
||||
"enabled": true,
|
||||
"name": "Content-Type",
|
||||
"value": "application/json"
|
||||
}
|
||||
],
|
||||
"method": "POST",
|
||||
"authenticationType": "bearer",
|
||||
"authentication": {
|
||||
"token": "${[ response.body.path(request=b64'R0VORVJBVEVfSUQ6OnJlcV9sb2dpbg', behavior='ttl', ttl='60', path=b64'JC50b2tlbg', result='first') ]}"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "GENERATE_ID::req_login",
|
||||
"workspaceId": "GENERATE_ID::wrk_chained",
|
||||
"folderId": null,
|
||||
"model": "http_request",
|
||||
"name": "Login",
|
||||
"url": "${[ host ]}/login",
|
||||
"urlParameters": [],
|
||||
"body": {},
|
||||
"bodyType": null,
|
||||
"headers": [],
|
||||
"method": "POST",
|
||||
"authenticationType": null,
|
||||
"authentication": {}
|
||||
}
|
||||
],
|
||||
"websocketRequests": [],
|
||||
"workspaces": [
|
||||
{
|
||||
"id": "GENERATE_ID::wrk_chained",
|
||||
"model": "workspace",
|
||||
"name": "Chained GraphQL",
|
||||
"headers": [],
|
||||
"authenticationType": null,
|
||||
"authentication": {}
|
||||
}
|
||||
]
|
||||
},
|
||||
"sourceKeys": {
|
||||
"GENERATE_ID::wrk_chained": "wrk_chained",
|
||||
"GENERATE_ID::env_base": "env_base",
|
||||
"GENERATE_ID::req_query": "req_query",
|
||||
"GENERATE_ID::req_login": "req_login"
|
||||
}
|
||||
}
|
||||
@@ -130,8 +130,8 @@
|
||||
},
|
||||
{
|
||||
"enabled": true,
|
||||
"name": "${[ApiHeaderName ]}",
|
||||
"value": "${[ApiKey ]}"
|
||||
"name": "${[ ApiHeaderName ]}",
|
||||
"value": "${[ ApiKey ]}"
|
||||
}
|
||||
],
|
||||
"id": "GENERATE_ID::req_d72fff2a6b104b91a2ebe9de9edd2785",
|
||||
@@ -139,7 +139,7 @@
|
||||
"model": "http_request",
|
||||
"name": "New Request",
|
||||
"sortPriority": -1736781406672,
|
||||
"url": "${[BASE_URL ]}/foo/:id",
|
||||
"url": "${[ BASE_URL ]}/foo/:id",
|
||||
"urlParameters": [
|
||||
{
|
||||
"name": "query",
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import { Buffer } from "node:buffer";
|
||||
import { describe, expect, test } from "vite-plus/test";
|
||||
import YAML from "yaml";
|
||||
import { convertInsomnia } from "../src";
|
||||
|
||||
describe.each([4, 5])("Insomnia v%i migration", (version) => {
|
||||
test("imports GraphQL, credentials and forward response references together", () => {
|
||||
const requests = [
|
||||
{
|
||||
_id: "req_query",
|
||||
meta: { id: "req_query" },
|
||||
_type: "request",
|
||||
parentId: "wrk_test",
|
||||
name: "Query",
|
||||
method: "POST",
|
||||
url: "{{ _['host'] }}/graphql",
|
||||
authentication: {
|
||||
type: "bearer",
|
||||
token: "{% response 'body', 'req_login', 'b64::JC50b2tlbg==::abc', 'when-expired', 60 %}",
|
||||
},
|
||||
headers: [{ name: "X-Request-ID", value: "{% uuid 'v4' %}" }],
|
||||
parameters: [{ name: "id", value: '{{ _["id"] }}' }],
|
||||
body: {
|
||||
mimeType: "application/graphql",
|
||||
text: JSON.stringify({
|
||||
query: "query Get($id: ID!) { node(id: $id) { id } }",
|
||||
variables: '{"id":"{{ _.id }}"}',
|
||||
operationName: "Get",
|
||||
}),
|
||||
},
|
||||
},
|
||||
{
|
||||
_id: "req_login",
|
||||
meta: { id: "req_login" },
|
||||
_type: "request",
|
||||
parentId: "wrk_test",
|
||||
name: "Login",
|
||||
method: "POST",
|
||||
url: "{{ _.host }}/login",
|
||||
// Missing authentication is normal in minimal exports.
|
||||
},
|
||||
];
|
||||
const source =
|
||||
version === 5
|
||||
? YAML.stringify({
|
||||
type: "collection.insomnia.rest/5.0",
|
||||
name: "Migration",
|
||||
meta: { id: "wrk_test" },
|
||||
environments: {
|
||||
meta: { id: "env_base" },
|
||||
data: { host: "https://example.com", id: "123" },
|
||||
},
|
||||
collection: requests,
|
||||
})
|
||||
: JSON.stringify({
|
||||
_type: "export",
|
||||
__export_format: 4,
|
||||
resources: [
|
||||
{ _type: "workspace", _id: "wrk_test", name: "Migration" },
|
||||
{
|
||||
_type: "environment",
|
||||
_id: "env_base",
|
||||
parentId: "wrk_test",
|
||||
data: { host: "https://example.com", id: "123" },
|
||||
},
|
||||
...requests,
|
||||
],
|
||||
});
|
||||
const imported = convertInsomnia(source)!;
|
||||
const [query, login] = imported.resources.httpRequests;
|
||||
expect(query?.body).toEqual({
|
||||
query: "query Get($id: ID!) { node(id: $id) { id } }",
|
||||
variables: '{"id":"${[ id ]}"}',
|
||||
operationName: "Get",
|
||||
});
|
||||
expect(query?.url).toBe("${[ host ]}/graphql");
|
||||
expect(query?.urlParameters?.[0]?.value).toBe("${[ id ]}");
|
||||
expect(query?.headers).toContainEqual({
|
||||
name: "X-Request-ID",
|
||||
value: "${[ uuid.v4() ]}",
|
||||
enabled: true,
|
||||
});
|
||||
expect(query?.headers).toContainEqual({
|
||||
name: "Content-Type",
|
||||
value: "application/json",
|
||||
enabled: true,
|
||||
});
|
||||
const ref = `b64'${Buffer.from(login!.id).toString("base64url")}'`;
|
||||
expect(query?.authentication?.token).toBe(
|
||||
`\${[ response.body.path(request=${ref}, behavior='ttl', ttl='60', path=b64'JC50b2tlbg', result='first') ]}`,
|
||||
);
|
||||
expect(imported.sourceKeys[login!.id]).toBe("req_login");
|
||||
expect(imported.sourceKeys[query!.id]).toBe("req_query");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,88 @@
|
||||
import { Buffer } from "node:buffer";
|
||||
import { describe, expect, test } from "vite-plus/test";
|
||||
import { convertTemplateSyntax } from "../src/templates";
|
||||
|
||||
const requestIds = new Set(["GENERATE_ID::req_login"]);
|
||||
const convert = (text: string) => convertTemplateSyntax(text, requestIds);
|
||||
const encoded = (text: string) => `b64'${Buffer.from(text).toString("base64url")}'`;
|
||||
|
||||
describe("Insomnia templates", () => {
|
||||
test.each(["{{ _.token }}", "{{ token }}", "{{ _['token'] }}", '{{ _ [ "token" ] }}'])(
|
||||
"converts %s",
|
||||
(input) => expect(convert(input)).toBe("${[ token ]}"),
|
||||
);
|
||||
|
||||
test.each([
|
||||
"{{ _.token | default('fallback') }}",
|
||||
"{{ _['two words'] }}",
|
||||
"{{ _['a']['b'] }}",
|
||||
"{{ _.a + _.b }}",
|
||||
"{{ true }}",
|
||||
"{% uuid 'v7' %}",
|
||||
"{% faker 'name' %}",
|
||||
"{% dopplersecret 'project', 'config', 'secret' %}",
|
||||
"{% response 'body', 'req_missing', '$.token', 'always', 60 %}",
|
||||
"{% response 'body', 'req_login', '$.token', 'unknown', 60 %}",
|
||||
"{% response 'body', 'req_login', '$.token', 'always', -1 %}",
|
||||
"{% response 'body' garbage, 'req_login', '$.token', 'always', 60 %}",
|
||||
"{% response 'body', 'req_login', 'b64::!!::nonce', 'always', 60 %}",
|
||||
"{% response 'body', 'req_login', '$.token', 'always', 60, %}",
|
||||
"{% response 'body', 'req_login', '$.tokens[*]', 'always', 60 %}",
|
||||
"{% response 'body', 'req_login', '$..token', 'always', 60 %}",
|
||||
"{% response 'body', 'req_login', '/root/token', 'always', 60 %}",
|
||||
"{% response 'body', 'req_login', '', 'never', 0 %}",
|
||||
"{% response 'body', 'req_login', '$.token', 'when-expired', 0 %}",
|
||||
])("preserves unsupported or malformed syntax: %s", (input) => {
|
||||
expect(convert(input)).toBe(input);
|
||||
});
|
||||
|
||||
test.each(["v1", "v4"])("converts UUID %s", (version) => {
|
||||
expect(convert(`{% uuid '${version}' %}`)).toBe(`\${[ uuid.${version}() ]}`);
|
||||
});
|
||||
test("converts only the equivalent Faker UUID function", () => {
|
||||
expect(convert("{% faker 'randomUUID' %}")).toBe("${[ uuid.v4() ]}");
|
||||
});
|
||||
|
||||
test.each([
|
||||
["never", "never"],
|
||||
["no-history", "smart"],
|
||||
["always", "always"],
|
||||
["when-expired", "ttl"],
|
||||
])("preserves %s sending behavior", (source, target) => {
|
||||
expect(convert(`{% response 'body', 'req_login', '$.token', '${source}', 60 %}`)).toBe(
|
||||
`\${[ response.body.path(request=${encoded("GENERATE_ID::req_login")}, behavior='${target}', ttl='60', path=${encoded("$.token")}, result='first') ]}`,
|
||||
);
|
||||
});
|
||||
|
||||
test("decodes Insomnia's UTF-8 base64 filters and emits URL-safe Yaak arguments", () => {
|
||||
const path = "$.clé[0].token";
|
||||
const base64 = Buffer.from(path).toString("base64");
|
||||
expect(
|
||||
convert(`{% response 'body', 'req_login', 'b64::${base64}::nonce', 'never', 0 %}`),
|
||||
).toContain(`path=${encoded(path)}`);
|
||||
expect(convert(`{% response 'body', 'req_login', '${path}', 'never', 0 %}`)).toContain(
|
||||
`path=${encoded(path)}`,
|
||||
);
|
||||
});
|
||||
|
||||
test("maps raw body and headers, including quotes/commas in literal arguments", () => {
|
||||
expect(convert("{% response 'raw', 'req_login', '', 'never', 0 %}")).toContain(
|
||||
"response.body.raw(",
|
||||
);
|
||||
expect(
|
||||
convert("{% response 'header', 'req_login', 'x-\\'quoted,header', 'never', 0 %}"),
|
||||
).toContain(`header=${encoded("x-'quoted,header")}`);
|
||||
});
|
||||
|
||||
test("converts nested resource fields without changing the input", () => {
|
||||
const input = {
|
||||
authentication: { token: "{{ _['token'] }}" },
|
||||
body: { form: [{ value: "{% uuid 'v4' %}" }] },
|
||||
};
|
||||
expect(convertTemplateSyntax(input)).toEqual({
|
||||
authentication: { token: "${[ token ]}" },
|
||||
body: { form: [{ value: "${[ uuid.v4() ]}" }] },
|
||||
});
|
||||
expect(input.authentication.token).toBe("{{ _['token'] }}");
|
||||
});
|
||||
});
|
||||
@@ -16,6 +16,7 @@ import { filterXPath } from "../../template-function-xml";
|
||||
const BEHAVIOR_TTL = "ttl";
|
||||
const BEHAVIOR_ALWAYS = "always";
|
||||
const BEHAVIOR_SMART = "smart";
|
||||
const BEHAVIOR_NEVER = "never";
|
||||
|
||||
const RETURN_FIRST = "first";
|
||||
const RETURN_ALL = "all";
|
||||
@@ -33,6 +34,7 @@ const behaviorArgs: DynamicTemplateFunctionArg = {
|
||||
{ label: "When no responses", value: BEHAVIOR_SMART },
|
||||
{ label: "Always", value: BEHAVIOR_ALWAYS },
|
||||
{ label: "When expired", value: BEHAVIOR_TTL },
|
||||
{ label: "Never", value: BEHAVIOR_NEVER },
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -300,7 +302,7 @@ async function getResponse(
|
||||
|
||||
const responses = await ctx.httpResponse.find({ requestId: httpRequest.id, limit: 1 });
|
||||
|
||||
if (behavior === "never" && responses.length === 0) {
|
||||
if (behavior === BEHAVIOR_NEVER && responses.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -308,12 +310,13 @@ async function getResponse(
|
||||
|
||||
// Previews happen a ton, and we don't want to send too many times on "always," so treat
|
||||
// it as "smart" during preview.
|
||||
const finalBehavior = behavior === "always" && purpose === "preview" ? "smart" : behavior;
|
||||
const finalBehavior =
|
||||
behavior === BEHAVIOR_ALWAYS && purpose === "preview" ? BEHAVIOR_SMART : behavior;
|
||||
|
||||
// Send if no responses and "smart," or "always"
|
||||
if (
|
||||
(finalBehavior === "smart" && response == null) ||
|
||||
finalBehavior === "always" ||
|
||||
(finalBehavior === BEHAVIOR_SMART && response == null) ||
|
||||
finalBehavior === BEHAVIOR_ALWAYS ||
|
||||
(finalBehavior === BEHAVIOR_TTL && shouldSendExpired(response, ttl))
|
||||
) {
|
||||
// Explicitly render the request before send (instead of relying on send() to render) so that we can
|
||||
|
||||
Reference in new issue
Block a user