Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
import { expect, describe, it } from "vitest";
import * as utils from "./index";
// fn value, expected value
const testCases: [fnValue: string, expectedValue: string][] = [
[ "testName", "testName" ],
[ "test_name", "test_name" ],
[ "test with space", "test_with_space" ],
[ "test:with:colon", "test:with:colon" ],
// numbers
[ "123456", "123456" ],
[ "123:456", "123:456" ],
[ "123456 abc", "123456_abc" ],
// non-latin characters
[ "ε", "ε" ],
[ "attribute ε", "attribute_ε" ],
// special characters
[ "test/name", "test_name" ],
[ "test%name", "test_name" ],
[ "\/", "_" ],
// empty string
[ "", "unnamed" ]
];
describe("sanitizeAttributeName unit tests", () => {
testCases.forEach((testCase) => {
return it(`'${testCase[0]}' should return '${testCase[1]}'`, () => {
const [ value, expected ] = testCase;
const actual = utils.sanitizeAttributeName(value);
expect(actual).toStrictEqual(expected);
});
});
});
type TestCase<T extends (...args: any) => any> = [desc: string, fnParams: Parameters<T>, expected: ReturnType<T>];
describe("#newEntityId", () => {
it("should return a string with a length of 12", () => {
const result = utils.newEntityId();
expect(result).toBeTypeOf("string");
expect(result).toHaveLength(12);
});
});
describe("#isValidEntityId", () => {
it("accepts only letters, digits and underscores with a length of 4 to 128", () => {
const accepted = [ "root", "_hidden", "abcDEF012345", "a".repeat(128) ];
for (const id of accepted) {
expect(utils.isValidEntityId(id), id).toBe(true);
}
const dashedId = "0d8949e4-6fe3-4f4b-82c1-679baf64fccb";
const rejected = [ "", "abc", "a".repeat(129), dashedId, "bad/id01", "bad id01" ];
for (const id of rejected) {
expect(utils.isValidEntityId(id), id).toBe(false);
}
});
});
describe("#randomString", () => {
it("should return a string with a length as per argument", () => {
const stringLength = 5;
const result = utils.randomString(stringLength);
expect(result).toBeTypeOf("string");
expect(result).toHaveLength(stringLength);
});
});
// TriliumNextTODO: should use mocks and assert that functions get called
describe("#randomSecureToken", () => {
// base64 -> 4 * (bytes/3) length -> if padding and rounding up is ignored for simplicity
// https://stackoverflow.com/a/13378842
const byteToBase64Length = (bytes: number) => 4 * (bytes / 3);
it("should return a string and use 32 bytes by default", () => {
const result = utils.randomSecureToken();
expect(result).toBeTypeOf("string");
expect(result.length).toBeGreaterThanOrEqual(byteToBase64Length(32));
});
it("should return a string and use passed byte length", () => {
const bytes = 16;
const result = utils.randomSecureToken(bytes);
expect(result).toBeTypeOf("string");
expect(result.length).toBeGreaterThanOrEqual(byteToBase64Length(bytes));
expect(result.length).toBeLessThan(44); // default argument uses 32 bytes -> which translates to 44 base64 legal chars
});
});
// TriliumNextTODO: should use mocks and assert that functions get called
describe.todo("#md5", () => {});
// TriliumNextTODO: should use mocks and assert that functions get called
describe.todo("#hashedBlobId", () => {});
// TriliumNextTODO: should use mocks and assert that functions get called
describe.todo("#toBase64", () => {});
// TriliumNextTODO: should use mocks and assert that functions get called
describe.todo("#fromBase64", () => {});
// TriliumNextTODO: should use mocks and assert that functions get called
describe.todo("#hmac", () => {});
// TriliumNextTODO: should use mocks and assert that functions get called
describe.todo("#hash", () => {});
describe("#isEmptyOrWhitespace", () => {
const testCases: TestCase<typeof utils.isEmptyOrWhitespace>[] = [
[ "w/ 'null' it should return true", [ null ], true ],
[ "w/ 'null' it should return true", [ null ], true ],
[ "w/ undefined it should return true", [ undefined ], true ],
[ "w/ empty string '' it should return true", [ "" ], true ],
[ "w/ single whitespace string ' ' it should return true", [ " " ], true ],
[ "w/ multiple whitespace string ' ' it should return true", [ " " ], true ],
[ "w/ non-empty string ' t ' it should return false", [ " t " ], false ]
];
testCases.forEach((testCase) => {
const [ desc, fnParams, expected ] = testCase;
it(desc, () => {
const result = utils.isEmptyOrWhitespace(...fnParams);
expect(result).toStrictEqual(expected);
});
});
});
describe("#sanitizeSqlIdentifier", () => {
const testCases: TestCase<typeof utils.sanitizeSqlIdentifier>[] = [
[ "w/ 'test' it should not strip anything", [ "test" ], "test" ],
[ "w/ 'test123' it should not strip anything", [ "test123" ], "test123" ],
[ "w/ 'tEst_TeSt' it should not strip anything", [ "tEst_TeSt" ], "tEst_TeSt" ],
[ "w/ 'test_test' it should not strip '_'", [ "test_test" ], "test_test" ],
[ "w/ 'test-' it should strip the '-'", [ "test-" ], "test" ],
[ "w/ 'test-test' it should strip the '-'", [ "test-test" ], "testtest" ],
[ "w/ 'test; --test' it should strip the '; --'", [ "test; --test" ], "testtest" ],
[ "w/ 'test test' it should strip the ' '", [ "test test" ], "testtest" ]
];
testCases.forEach((testCase) => {
const [ desc, fnParams, expected ] = testCase;
it(desc, () => {
const result = utils.sanitizeSqlIdentifier(...fnParams);
expect(result).toStrictEqual(expected);
});
});
});
describe("#escapeHtml", () => {
it("escapes the five markup characters and leaves everything else alone", () => {
expect(utils.escapeHtml(`<a href="x?a=1&b=2" title='t'>`))
.toBe("<a href="x?a=1&b=2" title='t'>");
expect(utils.escapeHtml("& is escaped again")).toBe("&amp; is escaped again");
expect(utils.escapeHtml("plain text, ünïcödé")).toBe("plain text, ünïcödé");
expect(utils.escapeHtml("")).toBe("");
});
});
describe("#unescapeHtml", () => {
it("decodes the five default HTML entities (named and numeric short forms)", () => {
expect(utils.unescapeHtml("a & b")).toBe("a & b");
expect(utils.unescapeHtml("&")).toBe("&");
expect(utils.unescapeHtml("x < y > z")).toBe("x < y > z");
expect(utils.unescapeHtml("< >")).toBe("< >");
expect(utils.unescapeHtml(""hi" "")).toBe("\"hi\" \"");
expect(utils.unescapeHtml("it's '")).toBe("it's '");
});
it("leaves entities outside the default set untouched", () => {
// other numeric, hex, nbsp, unknown-named and wrong-case are NOT decoded
expect(utils.unescapeHtml("© © & … &"))
.toBe("© © & … &");
});
it("handles double-escaped entities and query-string URLs", () => {
expect(utils.unescapeHtml("&amp;")).toBe("&");
expect(utils.unescapeHtml("http://x/?a=1&b=2")).toBe("http://x/?a=1&b=2");
});
it("returns an empty string for empty or non-string input", () => {
expect(utils.unescapeHtml("")).toBe("");
expect(utils.unescapeHtml(null as unknown as string)).toBe("");
expect(utils.unescapeHtml(undefined as unknown as string)).toBe("");
});
});
describe("#toObject", () => {
it("should return an object with keys and value being set from the supplied Function", () => {
type TestListEntry = { testPropA: string; testPropB: string };
type TestListFn = (testListEntry: TestListEntry) => [string, string];
const testList: [TestListEntry, TestListEntry] = [
{ testPropA: "keyA", testPropB: "valueA" },
{ testPropA: "keyB", testPropB: "valueB" }
];
const fn: TestListFn = (testListEntry: TestListEntry) => [ `${testListEntry.testPropA }_fn`, `${testListEntry.testPropB }_fn` ];
const result = utils.toObject(testList, fn);
expect(result).toStrictEqual({
keyA_fn: "valueA_fn",
keyB_fn: "valueB_fn"
});
});
});
describe("#stripTags", () => {
//prettier-ignore
const htmlWithNewlines =
`<p>abc
def</p>
<p>ghi</p>`;
const testCases: TestCase<typeof utils.stripTags>[] = [
[ "should strip all tags and only return the content, leaving new lines and spaces in tact", [ htmlWithNewlines ], "abc\ndef\nghi" ],
//TriliumNextTODO: should this actually insert a space between content to prevent concatenated text?
[ "should strip all tags and only return the content", [ "<h1>abc</h1><p>def</p>" ], "abcdef" ]
];
testCases.forEach((testCase) => {
const [ desc, fnParams, expected ] = testCase;
it(desc, () => {
const result = utils.stripTags(...fnParams);
expect(result).toStrictEqual(expected);
});
});
});
describe.todo("#escapeRegExp", () => {});
describe.todo("#crash", () => {});
describe("#getContentDisposition", () => {
// "attachment" is one of the two disposition types defined by RFC 6266 — Safari renders
// responses with an unknown type (e.g. the former "file") inline instead of downloading them.
const defaultFallBackDisposition = `attachment; filename="file"; filename*=UTF-8''file`;
const testCases: TestCase<typeof utils.getContentDisposition>[] = [
[
"when passed filename is empty, it should fallback to default value 'file'",
[ " " ],
defaultFallBackDisposition
],
[
"when passed filename '..' would cause sanitized filename to be empty, it should fallback to default value 'file'",
[ ".." ],
defaultFallBackDisposition
],
// COM1 is a Windows specific "illegal filename" that sanitize filename strips away
[
"when passed filename 'COM1' would cause sanitized filename to be empty, it should fallback to default value 'file'",
[ "COM1" ],
defaultFallBackDisposition
],
[
"sanitized passed filename should be returned URIEncoded",
[ "test file.csv" ],
`attachment; filename="test%20file.csv"; filename*=UTF-8''test%20file.csv`
]
];
testCases.forEach(testCase => {
const [ desc, fnParams, expected ] = testCase;
it(desc, () => {
const result = utils.getContentDisposition(...fnParams);
expect(result).toStrictEqual(expected);
});
});
});
describe("#isStringNote", () => {
const testCases: TestCase<typeof utils.isStringNote>[] = [
[
"w/ 'undefined' note type, but a string mime type, it should return true",
[ undefined, "application/javascript" ],
true
],
[
"w/ non-string note type, it should return false",
[ "image", "image/jpeg" ],
false
],
[
"w/ string note type (text), it should return true",
[ "text", "text/html" ],
true
],
[
"w/ string note type (code), it should return true",
[ "code", "application/json" ],
true
],
[
"w/ non-string note type (file), but string mime type, it should return true",
[ "file", "application/json" ],
true
],
[
"w/ non-string note type (file), but mime type starting with 'text/', it should return true",
[ "file", "text/html" ],
true
],
[
"w/ 'undefined' note type and the InkML mime type, it should return true",
[ undefined, "application/inkml+xml" ],
true
],
[
"w/ 'undefined' note type and the mime type of a canvas drawing, it should return true",
[ undefined, "application/vnd.excalidraw+json" ],
true
]
];
testCases.forEach((testCase) => {
const [ desc, fnParams, expected ] = testCase;
it(desc, () => {
const result = utils.isStringNote(...fnParams);
expect(result).toStrictEqual(expected);
});
});
});
describe.todo("#quoteRegex", () => {});
describe.todo("#replaceAll", () => {});
describe("#removeFileExtension", () => {
const testCases: TestCase<typeof utils.removeFileExtension>[] = [
[ "w/ 'test.md' it should strip '.md'", [ "test.md" ], "test" ],
[ "w/ 'test.markdown' it should strip '.markdown'", [ "test.markdown" ], "test" ],
[ "w/ 'test.html' it should strip '.html'", [ "test.html" ], "test" ],
[ "w/ 'test.htm' it should strip '.htm'", [ "test.htm" ], "test" ],
[ "w/ 'test.xlsx' it should strip '.xlsx'", [ "test.xlsx" ], "test" ],
[ "w/ 'test.csv' it should strip '.csv'", [ "test.csv" ], "test" ],
[ "w/ 'test.gpx' it should strip '.gpx'", [ "test.gpx" ], "test" ],
[ "w/ 'test.zip' it should NOT strip '.zip'", [ "test.zip" ], "test.zip" ]
];
testCases.forEach((testCase) => {
const [ desc, fnParams, expected ] = testCase;
it(desc, () => {
const result = utils.removeFileExtension(...fnParams);
expect(result).toStrictEqual(expected);
});
});
});
describe("#getNoteTitle", () => {
const testCases: TestCase<typeof utils.getNoteTitle>[] = [
[
"when file has no spaces, and no special file extension, it should return the filename unaltered",
[ "test.json", true, undefined ],
"test.json"
],
[
"when replaceUnderscoresWithSpaces is false, it should keep the underscores in the title",
[ "test_file.json", false, undefined ],
"test_file.json"
],
[
"when replaceUnderscoresWithSpaces is true, it should replace the underscores in the title",
[ "test_file.json", true, undefined ],
"test file.json"
],
[
"when filePath ends with one of the extra handled endings (.md), it should strip the file extension from the title",
[ "test_file.md", false, undefined ],
"test_file"
],
[
"when filePath ends with one of the extra handled endings (.md) and replaceUnderscoresWithSpaces is true, it should strip the file extension from the title and replace underscores",
[ "test_file.md", true, undefined ],
"test file"
],
[
"when filepath contains a full path, it should only return the basename of the file",
[ "Trilium Demo/Scripting examples/Statistics/Most cloned notes/template.zip", true, undefined ],
"template.zip"
],
[
"when filepath contains a full path and has extra handled ending (.html), it should only return the basename of the file and strip the file extension",
[ "Trilium Demo/Scripting examples/Statistics/Most cloned notes/template.html", true, undefined ],
"template"
],
[
"when a noteMeta object is passed, it should use the title from the noteMeta, if present",
[ "test_file.md", true, { title: "some other title" } ],
"some other title"
],
[
"when a noteMeta object is passed with an empty title, it should keep the note untitled",
[ "note.html", true, { title: "" } ],
""
],
[
"when a noteMeta object is passed with a blank title, it should keep the note untitled",
[ "1_note.html", false, { title: " " } ],
""
],
[
"when a noteMeta object is passed without a title, it should handle the filename as if no noteMeta was passed",
[ "test_file.md", true, { mime: "text/markdown" } ],
"test file"
]
];
testCases.forEach(testCase => {
const [ desc, fnParams, expected ] = testCase;
it(desc, () => {
const result = utils.getNoteTitle(...fnParams);
expect(result).toStrictEqual(expected);
});
});
});
describe("#timeLimit", () => {
it("when promise execution does NOT exceed timeout, it should resolve with promises' value", async () => {
const resolvedValue = `resolved: ${new Date().toISOString()}`;
const testPromise = new Promise((res, rej) => {
setTimeout(() => {
return res(resolvedValue);
}, 200);
//rej("rejected!");
});
await expect(utils.timeLimit(testPromise, 1_000)).resolves.toBe(resolvedValue);
});
it("does nothing when the internal timeout fires after the promise already resolved", async () => {
// Resolve well within the limit, then wait past the limit so the internal
// setTimeout callback runs with `resolved === true` (the no-op else path).
const fast = new Promise((res) => setTimeout(() => res("fast"), 5));
await expect(utils.timeLimit(fast, 20)).resolves.toBe("fast");
// give the 20ms internal timer time to fire on the already-resolved promise
await new Promise((res) => setTimeout(res, 40));
});
it("when promise execution rejects within timeout, it should return the original promises' rejected value, not the custom set one", async () => {
const rejectedValue = `rejected: ${new Date().toISOString()}`;
const testPromise = new Promise((res, rej) => {
setTimeout(() => {
//return res("resolved");
rej(rejectedValue);
}, 100);
});
await expect(utils.timeLimit(testPromise, 200, "Custom Error")).rejects.toThrow(rejectedValue);
});
it("when promise execution exceeds the set timeout, and 'errorMessage' is NOT set, it should reject the promise and display default error message", async () => {
const testPromise = new Promise((res, rej) => {
setTimeout(() => {
return res("resolved");
}, 500);
//rej("rejected!");
});
await expect(utils.timeLimit(testPromise, 200)).rejects.toThrow(`Process exceeded time limit 200`);
});
it("when promise execution exceeds the set timeout, and 'errorMessage' is set, it should reject the promise and display set error message", async () => {
const customErrorMsg = "Custom Error";
const testPromise = new Promise((res, rej) => {
setTimeout(() => {
return res("resolved");
}, 500);
//rej("rejected!");
});
await expect(utils.timeLimit(testPromise, 200, customErrorMsg)).rejects.toThrow(customErrorMsg);
});
// TriliumNextTODO: since TS avoids this from ever happening – do we need this check?
it("when the passed promise is not a promise but 'undefined', it should return 'undefined'", async () => {
//@ts-expect-error - passing in illegal type 'undefined'
expect(utils.timeLimit(undefined, 200)).toBe(undefined);
});
// TriliumNextTODO: since TS avoids this from ever happening – do we need this check?
it("when the passed promise is not a promise, it should return the passed value", async () => {
//@ts-expect-error - passing in illegal type 'object'
expect(utils.timeLimit({ test: 1 }, 200)).toStrictEqual({ test: 1 });
});
});
describe("#removeDiacritic", () => {
const testCases: TestCase<typeof utils.removeDiacritic>[] = [
[ "w/ 'Äpfel' it should replace the 'Ä'", [ "Äpfel" ], "Apfel" ],
[ "w/ 'Été' it should replace the 'É' and 'é'", [ "Été" ], "Ete" ],
[ "w/ 'Fête' it should replace the 'ê'", [ "Fête" ], "Fete" ],
[ "w/ 'Αλφαβήτα' it should replace the 'ή'", [ "Αλφαβήτα" ], "Αλφαβητα" ],
[ "w/ '' (empty string) it should return empty string", [ "" ], "" ]
];
testCases.forEach((testCase) => {
const [ desc, fnParams, expected ] = testCase;
it(desc, () => {
const result = utils.removeDiacritic(...fnParams);
expect(result).toStrictEqual(expected);
});
});
});
describe("#normalize", () => {
const testCases: TestCase<typeof utils.normalize>[] = [
[ "w/ 'Äpfel' it should replace the 'Ä' and return lowercased", [ "Äpfel" ], "apfel" ],
[ "w/ 'Été' it should replace the 'É' and 'é' and return lowercased", [ "Été" ], "ete" ],
[ "w/ 'FêTe' it should replace the 'ê' and return lowercased", [ "FêTe" ], "fete" ],
[ "w/ 'ΑλΦαβήΤα' it should replace the 'ή' and return lowercased", [ "ΑλΦαβήΤα" ], "αλφαβητα" ],
[ "w/ '' (empty string) it should return empty string", [ "" ], "" ]
];
testCases.forEach((testCase) => {
const [ desc, fnParams, expected ] = testCase;
it(desc, () => {
const result = utils.normalize(...fnParams);
expect(result).toStrictEqual(expected);
});
});
});
describe("#toMap", () => {
it("should return an instace of Map, with the correct size and keys, when supplied with a list and existing keys", () => {
const testList = [ { title: "test", propA: "text", propB: 123 }, { title: "test2", propA: "prop2", propB: 456 } ];
const result = utils.toMap(testList, "title");
expect(result).toBeInstanceOf(Map);
expect(result.size).toBe(2);
expect(Array.from(result.keys())).toStrictEqual([ "test", "test2" ]);
});
it("should return an instace of Map, with an empty size, when the supplied list does not contain the supplied key", () => {
const testList = [ { title: "test", propA: "text", propB: 123 }, { title: "test2", propA: "prop2", propB: 456 } ];
//@ts-expect-error - key is non-existing on supplied list type
const result = utils.toMap(testList, "nonExistingKey");
expect(result).toBeInstanceOf(Map);
expect(result.size).toBe(0);
});
it("collapses entries when keys collide (last write wins)", () => {
// Documents the current contract of toMap: when two entries share a
// key, the later entry overwrites the earlier one. See the TODO in
// toMap itself — if the contract ever changes to preserve duplicates
// (e.g. returning Map<K, T[]>), update this test along with the change.
const testList = [
{ title: "testDupeTitle", propA: "text", propB: 123 },
{ title: "testDupeTitle", propA: "prop2", propB: 456 }
];
const result = utils.toMap(testList, "title");
expect(result).toBeInstanceOf(Map);
expect(result.size).toBe(1);
expect(result.get("testDupeTitle")?.propA).toBe("prop2");
});
});
describe("#envToBoolean", () => {
const testCases: TestCase<typeof utils.envToBoolean>[] = [
[ "w/ 'true' it should return boolean 'true'", [ "true" ], true ],
[ "w/ 'True' it should return boolean 'true'", [ "True" ], true ],
[ "w/ 'TRUE' it should return boolean 'true'", [ "TRUE" ], true ],
[ "w/ 'true ' it should return boolean 'true'", [ "true " ], true ],
[ "w/ 'false' it should return boolean 'false'", [ "false" ], false ],
[ "w/ 'False' it should return boolean 'false'", [ "False" ], false ],
[ "w/ 'FALSE' it should return boolean 'false'", [ "FALSE" ], false ],
[ "w/ 'false ' it should return boolean 'false'", [ "false " ], false ],
[ "w/ 'whatever' (non-boolean string) it should return undefined", [ "whatever" ], undefined ],
[ "w/ '-' (non-boolean string) it should return undefined", [ "-" ], undefined ],
[ "w/ '' (empty string) it should return undefined", [ "" ], undefined ],
[ "w/ ' ' (white space string) it should return undefined", [ " " ], undefined ],
[ "w/ undefined it should return undefined", [ undefined ], undefined ],
//@ts-expect-error - pass wrong type as param
[ "w/ number 1 it should return undefined", [ 1 ], undefined ]
];
testCases.forEach((testCase) => {
const [ desc, fnParams, expected ] = testCase;
it(desc, () => {
const result = utils.envToBoolean(...fnParams);
expect(result).toStrictEqual(expected);
});
});
});
describe.todo("#getResourceDir", () => {});
describe("#isElectron", () => {
it("should export a boolean", () => {
expect(utils.isElectron()).toBeTypeOf("boolean");
});
});
describe("#isMac", () => {
it("should export a boolean", () => {
expect(utils.isMac()).toBeTypeOf("boolean");
});
});
describe("#isWindows", () => {
it("should export a boolean", () => {
expect(utils.isWindows()).toBeTypeOf("boolean");
});
});
describe("#isLinux", () => {
it("should export a boolean", () => {
expect(utils.isLinux()).toBeTypeOf("boolean");
});
});
describe("#safeExtractMessageAndStackFromError", () => {
it("should correctly extract the message and stack property if it gets passed an instance of an Error", () => {
const testMessage = "Test Message";
const testError = new Error(testMessage);
const actual = utils.safeExtractMessageAndStackFromError(testError);
expect(actual[0]).toBe(testMessage);
expect(actual[1]).not.toBeUndefined();
});
it("should pass a thrown string through as the message, with no stack", () => {
const testString = "this is not an instance of an Error, but JS technically allows us to throw this anyways";
const actual = utils.safeExtractMessageAndStackFromError(testString);
expect(actual[0]).toBe(testString);
expect(actual[1]).toBeUndefined();
});
it("should use the fallback 'Unknown Error' message, if it gets passed something that is neither an Error nor a string", () => {
const testNonError = { not: "an error" };
const actual = utils.safeExtractMessageAndStackFromError(testNonError);
expect(actual[0]).toBe("Unknown Error");
expect(actual[1]).toBeUndefined();
});
});
describe("#formatDownloadTitle", () => {
//prettier-ignore
const testCases: [fnValue: Parameters<typeof utils.formatDownloadTitle>, expectedValue: ReturnType<typeof utils.formatDownloadTitle>][] = [
// empty fileName tests
[
[ "", "text", "" ],
"untitled.html"
],
[
[ "", "canvas", "" ],
"untitled.json"
],
[
[ "", null, "" ],
"untitled"
],
// json extension from type tests
[
[ "test_file", "canvas", "" ],
"test_file.json"
],
[
[ "test_file", "relationMap", "" ],
"test_file.json"
],
[
[ "test_file", "search", "" ],
"test_file.json"
],
// extension based on mime type
[
[ "test_file", null, "text/csv" ],
"test_file.csv"
],
[
[ "test_file_wo_ext", "image", "image/svg+xml" ],
"test_file_wo_ext.svg"
],
[
[ "test_file_wo_ext", "file", "application/json" ],
"test_file_wo_ext.json"
],
[
[ "test_file_w_fake_ext.ext", "image", "image/svg+xml" ],
"test_file_w_fake_ext.ext.svg"
],
[
[ "test_file_w_correct_ext.svg", "image", "image/svg+xml" ],
"test_file_w_correct_ext.svg"
],
[
[ "test_file_w_correct_ext.svgz", "image", "image/svg+xml" ],
"test_file_w_correct_ext.svgz"
],
[
[ "test_file.zip", "file", "application/zip" ],
"test_file.zip"
],
[
[ "test_file", "file", "application/zip" ],
"test_file.zip"
],
// application/octet-stream tests
[
[ "test_file", "file", "application/octet-stream" ],
"test_file"
],
[
[ "test_file.zip", "file", "application/octet-stream" ],
"test_file.zip"
],
[
[ "test_file.unknown", null, "application/octet-stream" ],
"test_file.unknown"
],
// sanitized filename tests
[
[ "test/file", null, "application/octet-stream" ],
"testfile"
],
[
[ "test:file.zip", "file", "application/zip" ],
"testfile.zip"
],
[
[ ":::", "file", "application/zip" ],
".zip"
],
[
[ ":::a", "file", "application/zip" ],
"a.zip"
],
// mime type that maps to no known extension -> filename returned unchanged
[
[ "test_file", "file", "application/x-this-mime-has-no-extension" ],
"test_file"
]
];
testCases.forEach((testCase) => {
const [ fnParams, expected ] = testCase;
return it(`With args '${JSON.stringify(fnParams)}', it should return '${expected}'`, () => {
const actual = utils.formatDownloadTitle(...fnParams);
expect(actual).toStrictEqual(expected);
});
});
});
describe("#normalizeUrl", () => {
const testCases: TestCase<typeof utils.normalizeUrl>[] = [
[ "should remove trailing slash from simple URL", [ "https://example.com/" ], "https://example.com" ],
[ "should remove trailing slash from URL with path", [ "https://example.com/path/" ], "https://example.com/path" ],
[ "should preserve URL without trailing slash", [ "https://example.com" ], "https://example.com" ],
[ "should preserve URL without trailing slash with path", [ "https://example.com/path" ], "https://example.com/path" ],
[ "should preserve protocol-only URLs", [ "https://" ], "https://" ],
[ "should preserve protocol-only URLs", [ "http://" ], "http://" ],
[ "should fix double slashes in path", [ "https://example.com//api//test" ], "https://example.com/api/test" ],
[ "should handle multiple double slashes", [ "https://example.com///api///test" ], "https://example.com/api/test" ],
[ "should handle trailing slash with double slashes", [ "https://example.com//api//" ], "https://example.com/api" ],
[ "should preserve protocol double slash", [ "https://example.com/api" ], "https://example.com/api" ],
[ "should handle empty string", [ "" ], "" ],
[ "should handle whitespace-only string", [ " " ], "" ],
[ "should trim whitespace", [ " https://example.com/ " ], "https://example.com" ],
[ "should handle null as empty", [ null as any ], null ],
[ "should handle undefined as empty", [ undefined as any ], undefined ]
];
testCases.forEach((testCase) => {
const [ desc, fnParams, expected ] = testCase;
it(desc, () => {
const result = utils.normalizeUrl(...fnParams);
expect(result).toStrictEqual(expected);
});
});
});
describe("#trimTrailingSlashes", () => {
it("removes every trailing slash and nothing else", () => {
expect(utils.trimTrailingSlashes("http://localhost:8888///")).toBe("http://localhost:8888");
expect(utils.trimTrailingSlashes("https://example.com/a//b")).toBe("https://example.com/a//b");
expect(utils.trimTrailingSlashes("///")).toBe("");
expect(utils.trimTrailingSlashes("")).toBe("");
});
it("stays linear on a long run of slashes", () => {
const start = performance.now();
utils.trimTrailingSlashes(`${"/".repeat(100_000)}x`);
expect(performance.now() - start).toBeLessThan(100);
});
});
describe("#normalizeCustomHandlerPattern", () => {
const testCases: TestCase<typeof utils.normalizeCustomHandlerPattern>[] = [
[ "should handle pattern without ending - add both versions", [ "foo" ], [ "foo", "foo/" ] ],
[ "should handle pattern with trailing slash - add both versions", [ "foo/" ], [ "foo", "foo/" ] ],
[ "should handle pattern ending with $ - add optional slash", [ "foo$" ], [ "foo/?$" ] ],
[ "should handle pattern with trailing slash and $ - add both versions", [ "foo/$" ], [ "foo$", "foo/$" ] ],
[ "should preserve existing optional slash pattern", [ "foo/?$" ], [ "foo/?$" ] ],
[ "should preserve existing optional slash pattern (alternative)", [ "foo/?)" ], [ "foo/?)" ] ],
[ "should handle regex pattern with special chars", [ "api/[a-z]+$" ], [ "api/[a-z]+/?$" ] ],
[ "should handle complex regex pattern", [ "user/([0-9]+)/profile$" ], [ "user/([0-9]+)/profile/?$" ] ],
[ "should handle empty string", [ "" ], [ "" ] ],
[ "should handle whitespace-only string", [ " " ], [ "" ] ],
[ "should handle null", [ null as any ], [ null ] ],
[ "should handle undefined", [ undefined as any ], [ undefined ] ]
];
testCases.forEach((testCase) => {
const [ desc, fnParams, expected ] = testCase;
it(desc, () => {
const result = utils.normalizeCustomHandlerPattern(...fnParams);
expect(result).toStrictEqual(expected);
});
});
});
describe("#slugify", () => {
it("should return a slugified string", () => {
const testString = "This is a Test String! With unicode & Special #Chars.";
const expectedSlug = "this-is-a-test-string-with-unicode-special-chars";
const result = utils.slugify(testString);
expect(result).toBe(expectedSlug);
});
it("supports CJK characters without alteration", () => {
const testString = "测试中文字符";
const expectedSlug = "测试中文字符";
const result = utils.slugify(testString);
expect(result).toBe(expectedSlug);
});
it("supports Cyrillic characters without alteration", () => {
const testString = "Тестирование кириллических символов";
const expectedSlug = "тестирование-кириллических-символов";
const result = utils.slugify(testString);
expect(result).toBe(expectedSlug);
});
// preserves diacritic marks
it("preserves diacritic marks", () => {
const testString = "Café naïve façade jalapeño";
const expectedSlug = "café-naïve-façade-jalapeño";
const result = utils.slugify(testString);
expect(result).toBe(expectedSlug);
});
});
describe("#slugifyHeadings", () => {
it("slugifies each heading in order", () => {
expect(utils.slugifyHeadings(["First Section", "Second Section"])).toStrictEqual(["first-section", "second-section"]);
});
it("disambiguates duplicate titles with a numeric suffix", () => {
expect(utils.slugifyHeadings(["Notes", "Notes", "Notes"])).toStrictEqual(["notes", "notes-1", "notes-2"]);
});
it("avoids colliding a suffix with an existing slug", () => {
// "Notes 1" naturally slugifies to "notes-1", so the second "Notes" must skip to "notes-2"
expect(utils.slugifyHeadings(["Notes", "Notes 1", "Notes"])).toStrictEqual(["notes", "notes-1", "notes-2"]);
});
it("skips the reserved slugs", () => {
expect(utils.slugifyHeadings(["Notes", "Notes"], ["notes", "notes-1"])).toStrictEqual(["notes-2", "notes-3"]);
});
it("strips HTML tags before slugifying", () => {
expect(utils.slugifyHeadings(["<b>Bold</b> Heading"])).toStrictEqual(["bold-heading"]);
});
it("returns an empty array for no headings", () => {
expect(utils.slugifyHeadings([])).toStrictEqual([]);
});
});
describe("#sanitizeSvg", () => {
it("should remove script elements", () => {
const maliciousSvg = '<svg><script>alert("XSS")</script><rect width="100" height="100"/></svg>';
const result = utils.sanitizeSvg(maliciousSvg);
expect(result).toBe('<svg><rect width="100" height="100"/></svg>');
});
it("should remove script elements with attributes", () => {
const maliciousSvg = '<svg><script type="text/javascript">alert("XSS")</script></svg>';
const result = utils.sanitizeSvg(maliciousSvg);
expect(result).toBe('<svg></svg>');
});
it("should remove multiline script elements", () => {
const maliciousSvg = `<svg><script>
var x = 1;
alert(x);
</script></svg>`;
const result = utils.sanitizeSvg(maliciousSvg);
expect(result).toBe('<svg></svg>');
});
it("should remove onclick event handlers with double quotes", () => {
const maliciousSvg = '<svg><rect onclick="doEvil()" width="100"/></svg>';
const result = utils.sanitizeSvg(maliciousSvg);
expect(result).toBe('<svg><rect width="100"/></svg>');
});
it("should remove onclick event handlers with single quotes", () => {
const maliciousSvg = "<svg><rect onclick='doEvil()' width=\"100\"/></svg>";
const result = utils.sanitizeSvg(maliciousSvg);
expect(result).toBe('<svg><rect width="100"/></svg>');
});
it("should remove onload event handlers", () => {
const maliciousSvg = '<svg onload="doEvil()"><rect width="100"/></svg>';
const result = utils.sanitizeSvg(maliciousSvg);
expect(result).toBe('<svg><rect width="100"/></svg>');
});
it("should remove onerror event handlers", () => {
const maliciousSvg = '<svg><image onerror="alert(1)" href="invalid.jpg"/></svg>';
const result = utils.sanitizeSvg(maliciousSvg);
expect(result).toBe('<svg><image href="invalid.jpg"/></svg>');
});
it("should remove onmouseover event handlers", () => {
const maliciousSvg = '<svg><rect onmouseover="alert(1)" width="100"/></svg>';
const result = utils.sanitizeSvg(maliciousSvg);
expect(result).toBe('<svg><rect width="100"/></svg>');
});
it("should remove event handlers without quotes", () => {
const maliciousSvg = '<svg><rect onclick=alert(1) width="100"/></svg>';
const result = utils.sanitizeSvg(maliciousSvg);
expect(result).toBe('<svg><rect width="100"/></svg>');
});
it("should replace javascript: URLs in href with #", () => {
const maliciousSvg = '<svg><a href="javascript:alert(1)"><text>Click me</text></a></svg>';
const result = utils.sanitizeSvg(maliciousSvg);
expect(result).toBe('<svg><a href="#"><text>Click me</text></a></svg>');
});
it("should replace javascript: URLs in xlink:href with #", () => {
const maliciousSvg = '<svg><a xlink:href="javascript:alert(1)"><text>Click me</text></a></svg>';
const result = utils.sanitizeSvg(maliciousSvg);
expect(result).toBe('<svg><a xlink:href="#"><text>Click me</text></a></svg>');
});
it("should preserve valid SVG content", () => {
const validSvg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><rect x="10" y="10" width="80" height="80" fill="blue"/><circle cx="50" cy="50" r="30" fill="red"/></svg>';
const result = utils.sanitizeSvg(validSvg);
expect(result).toBe(validSvg);
});
it("should preserve valid href URLs", () => {
const validSvg = '<svg><a href="https://example.com"><text>Link</text></a></svg>';
const result = utils.sanitizeSvg(validSvg);
expect(result).toBe(validSvg);
});
it("should handle multiple malicious elements", () => {
const maliciousSvg = '<svg onload="evil()"><script>evil()</script><rect onclick="bad()" width="100"/><a href="javascript:attack()">link</a></svg>';
const result = utils.sanitizeSvg(maliciousSvg);
expect(result).toBe('<svg><rect width="100"/><a href="#">link</a></svg>');
});
it("should handle empty SVG", () => {
const emptySvg = '<svg></svg>';
const result = utils.sanitizeSvg(emptySvg);
expect(result).toBe('<svg></svg>');
});
it("should be case insensitive for script tags", () => {
const maliciousSvg = '<svg><SCRIPT>alert(1)</SCRIPT><Script>alert(2)</Script></svg>';
const result = utils.sanitizeSvg(maliciousSvg);
expect(result).toBe('<svg></svg>');
});
it("should be case insensitive for event handlers", () => {
const maliciousSvg = '<svg><rect ONCLICK="alert(1)" width="100"/></svg>';
const result = utils.sanitizeSvg(maliciousSvg);
expect(result).toBe('<svg><rect width="100"/></svg>');
});
});
describe("#isDev", () => {
it("returns a boolean derived from the TRILIUM_ENV platform var", () => {
expect(utils.isDev()).toBeTypeOf("boolean");
});
});
describe("#md5", () => {
it("produces the canonical lowercase hex digest", () => {
// RFC 1321 / well-known vectors
expect(utils.md5("")).toBe("d41d8cd98f00b204e9800998ecf8427e");
expect(utils.md5("abc")).toBe("900150983cd24fb0d6963f7d28e17f72");
});
it("accepts a byte buffer and yields a 32-char hex string", () => {
const digest = utils.md5(new Uint8Array([0x61, 0x62, 0x63])); // "abc"
expect(digest).toBe("900150983cd24fb0d6963f7d28e17f72");
});
});
describe("#hashedBlobId", () => {
it("returns a 20-char id without '+' or '/' characters", () => {
const id = utils.hashedBlobId("some content");
expect(id).toHaveLength(20);
expect(id).not.toMatch(/[+/]/);
});
it("is deterministic for identical content", () => {
expect(utils.hashedBlobId("repeatable")).toBe(utils.hashedBlobId("repeatable"));
});
it("treats null and undefined content as empty string", () => {
const emptyId = utils.hashedBlobId("");
//@ts-expect-error - exercising the nullish guard
expect(utils.hashedBlobId(null)).toBe(emptyId);
//@ts-expect-error - exercising the nullish guard
expect(utils.hashedBlobId(undefined)).toBe(emptyId);
});
});
describe("#quoteRegex", () => {
it("escapes regex metacharacters", () => {
expect(utils.quoteRegex("a.b*c")).toBe("a\\.b\\*c");
expect(utils.quoteRegex("(x)[y]{z}")).toBe("\\(x\\)\\[y\\]\\{z\\}");
});
});
describe("#replaceAll", () => {
it("replaces every occurrence, escaping the search term", () => {
expect(utils.replaceAll("a-b-c", "-", "+")).toBe("a+b+c");
// the search term contains regex metacharacters that must be treated literally
expect(utils.replaceAll("a.b.c", ".", "_")).toBe("a_b_c");
});
});
describe("#escapeRegExp", () => {
it("escapes regex metacharacters in a string", () => {
expect(utils.escapeRegExp("a.b")).toBe("a\\.b");
expect(utils.escapeRegExp("1+1=2")).toBe("1\\+1\\=2");
});
});
describe("#stringToInt", () => {
const testCases: TestCase<typeof utils.stringToInt>[] = [
[ "w/ a numeric string it returns the parsed integer", [ "42" ], 42 ],
[ "w/ a decimal string it truncates at the decimal point", [ "12.9" ], 12 ],
[ "w/ a non-numeric string it returns undefined", [ "abc" ], undefined ],
[ "w/ an empty string it returns undefined", [ "" ], undefined ],
[ "w/ undefined it returns undefined", [ undefined ], undefined ]
];
testCases.forEach((testCase) => {
const [ desc, fnParams, expected ] = testCase;
it(desc, () => {
expect(utils.stringToInt(...fnParams)).toStrictEqual(expected);
});
});
});
describe("#formatUtcTime", () => {
it("replaces the ISO 'T' separator and truncates to seconds", () => {
expect(utils.formatUtcTime("2023-08-21T23:38:51.110Z")).toBe("2023-08-21 23:38:51");
});
});
describe("#formatSize", () => {
const testCases: TestCase<typeof utils.formatSize>[] = [
[ "w/ null it returns an empty string", [ null ], "" ],
[ "w/ undefined it returns an empty string", [ undefined ], "" ],
[ "w/ 0 bytes it rounds up to the 1 KiB minimum", [ 0 ], "1 KiB" ],
[ "w/ a sub-MiB value it reports KiB", [ 2048 ], "2 KiB" ],
[ "w/ a multi-MiB value it reports MiB", [ 5 * 1024 * 1024 ], "5 MiB" ]
];
testCases.forEach((testCase) => {
const [ desc, fnParams, expected ] = testCase;
it(desc, () => {
expect(utils.formatSize(...fnParams)).toBe(expected);
});
});
});
describe("#removeFileExtension (media types)", () => {
it("strips the extension for video and audio mime types", () => {
expect(utils.removeFileExtension("clip.mov", "video/quicktime")).toBe("clip");
expect(utils.removeFileExtension("song.flac", "audio/flac")).toBe("song");
});
it("strips the extension for the fonts Trilium draws, and leaves the rest alone", () => {
expect(utils.removeFileExtension("Iosevka-Regular.ttf", "font/ttf")).toBe("Iosevka-Regular");
expect(utils.removeFileExtension("Inter.woff2", "font/woff2")).toBe("Inter");
expect(utils.removeFileExtension("Legacy.ttf", "application/x-font-ttf")).toBe("Legacy");
// Neither an EOT nor a font arriving as an opaque binary is one Trilium can draw, so the
// name it was uploaded under is all there is to say what it holds.
expect(utils.removeFileExtension("Old.eot", "application/vnd.ms-fontobject")).toBe("Old.eot");
expect(utils.removeFileExtension("Mystery.ttf", "application/octet-stream")).toBe("Mystery.ttf");
});
});
describe("#compareVersions", () => {
const testCases: TestCase<typeof utils.compareVersions>[] = [
[ "equal versions return 0", [ "1.2.3", "1.2.3" ], 0 ],
[ "greater major returns 1", [ "2.0.0", "1.9.9" ], 1 ],
[ "lesser major returns -1", [ "1.0.0", "2.0.0" ], -1 ],
[ "greater minor returns 1", [ "1.3.0", "1.2.9" ], 1 ],
[ "lesser minor returns -1", [ "1.2.0", "1.3.0" ], -1 ],
[ "greater patch returns 1", [ "1.2.4", "1.2.3" ], 1 ],
[ "lesser patch returns -1", [ "1.2.3", "1.2.4" ], -1 ],
[ "strips a leading 'v' prefix", [ "v1.2.3", "1.2.3" ], 0 ],
[ "ignores a pre-release suffix after a dash", [ "1.2.3-beta", "1.2.3" ], 0 ],
[ "pads a shorter first version with zeros", [ "1.2", "1.2.0" ], 0 ],
[ "pads a shorter second version with zeros", [ "1.2.0", "1.2" ], 0 ]
];
testCases.forEach((testCase) => {
const [ desc, fnParams, expected ] = testCase;
it(desc, () => {
expect(utils.compareVersions(...fnParams)).toBe(expected);
});
});
});
describe("#escapeCssString", () => {
it("hex-escapes the characters that could escape a double-quoted CSS string", () => {
expect(utils.escapeCssString(`a"b\\c'd`)).toBe("a\\22 b\\5c c\\27 d");
expect(utils.escapeCssString("a\nb")).toBe("a\\a b");
});
it("hex-escapes the markup characters that could end the surrounding <style> element", () => {
expect(utils.escapeCssString("</style><script>x</script>")).toBe(
"\\3c /style\\3e \\3c script\\3e x\\3c /script\\3e "
);
});
it("leaves the private-use glyphs an icon pack actually carries untouched", () => {
expect(utils.escapeCssString("")).toBe("");
});
});
describe("#decodeCssEscapes", () => {
it("decodes a hex escape with or without its terminating space", () => {
expect(utils.decodeCssEscapes("\\30 ")).toBe("0");
expect(utils.decodeCssEscapes("\\f015")).toBe("\uf015");
expect(utils.decodeCssEscapes("\\1F600")).toBe("\u{1F600}");
expect(utils.decodeCssEscapes("\\61\\62")).toBe("ab");
});
it("resolves the code points CSS maps to the replacement character", () => {
expect(utils.decodeCssEscapes("\\0")).toBe("\uFFFD");
expect(utils.decodeCssEscapes("\\d800 ")).toBe("\uFFFD");
expect(utils.decodeCssEscapes("\\ffffff")).toBe("\uFFFD");
});
it("leaves text carrying no hex escape untouched", () => {
expect(utils.decodeCssEscapes("")).toBe("");
expect(utils.decodeCssEscapes("\uf015")).toBe("\uf015");
expect(utils.decodeCssEscapes("</style>")).toBe("</style>");
expect(utils.decodeCssEscapes("\\")).toBe("\\");
});
it("cannot widen what the generated stylesheet emits, since escaping follows it", () => {
// A glyph spelling `</style>` as escapes decodes to the markup, then escapes back to it.
const smuggled = "\\3c /style\\3e ";
expect(utils.decodeCssEscapes(smuggled)).toBe("</style>");
expect(utils.escapeCssString(utils.decodeCssEscapes(smuggled))).toBe("\\3c /style\\3e ");
// A backslash reaching the output would let the glyph end its own CSS string.
expect(utils.escapeCssString(utils.decodeCssEscapes("\\5c "))).toBe("\\5c ");
});
});
describe("#escapeInlineStylesheet", () => {
it("escapes every closing style tag, whatever its casing", () => {
const escaped = utils.escapeInlineStylesheet(`.a::before { content: "</style><SCRIPT>x</STYLE>"; }`);
expect(escaped).not.toMatch(/<\/style/i);
expect(escaped).toBe(`.a::before { content: "\\3c /style><SCRIPT>x\\3c /STYLE>"; }`);
});
it("leaves a stylesheet without a closing style tag byte-identical", () => {
const css = `.bx.bx-ball::before { content: ""; }\n@media (width > 40em) { .a { color: red; } }`;
expect(utils.escapeInlineStylesheet(css)).toBe(css);
});
});