Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@ import { loadBuilderQuery } from "./use-query-state-sync"

describe("loadBuilderQuery", () => {
test("loads a parseable query as its tree", () => {
const loaded = loadBuilderQuery(`{ name: "x" }`)
const loaded = loadBuilderQuery(`{ name: "x" };`)
expect(loaded.error).toBeUndefined()
expect(loaded.state.root).toMatchObject({ type: "group", children: [{ type: "condition" }] })
})

test("an empty query in any spelling loads as an empty tree", () => {
for (const query of ["", " ", "{}", "{ }", "{\n}"]) {
for (const query of ["", " ", "{}", "{ }", "{\n}", "{ /* nothing */ }", "{};"]) {
const loaded = loadBuilderQuery(query)
expect(loaded.error).toBeUndefined()
expect(loaded.state.root).toMatchObject({ type: "group", children: [] })
Expand All @@ -21,6 +21,7 @@ describe("loadBuilderQuery", () => {
test("an unparseable query gives an error and an empty tree, never a previous one", () => {
for (const query of [
`{ name: "x"`,
`{ name: "x" }; {}`,
`[1]`,
`{ $boost: 2 }`,
`{ $must: { a: 1 }, $should: { b: 2 } }`,
Expand Down
58 changes: 57 additions & 1 deletion src/lib/utils.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,62 @@
import { describe, expect, test } from "bun:test"

import { fromKeySearchPattern, matchesGlob, toKeySearchPattern } from "./utils"
import {
fromKeySearchPattern,
matchesGlob,
parseJSObjectLiteral,
toKeySearchPattern,
} from "./utils"

describe("parseJSObjectLiteral", () => {
test("never rewrites string contents", () => {
expect(parseJSObjectLiteral<unknown>(`{ title: "Error, code: 42" }`)).toEqual({
title: "Error, code: 42",
})
expect(parseJSObjectLiteral<unknown>(`{ title: "a,}", }`)).toEqual({ title: "a,}" })
expect(parseJSObjectLiteral<unknown>(`{ a: "x\\'y" }`)).toEqual({ a: "x'y" })
expect(parseJSObjectLiteral<unknown>(`{ a: "// not a comment" }`)).toEqual({
a: "// not a comment",
})
// A raw tab is valid in a JS string but not in JSON
expect(parseJSObjectLiteral<unknown>(`{ a: "x\ty", b: 'x\u0001y' }`)).toEqual({
a: "x\ty",
b: "x\u0001y",
})
})

test("supports single quotes, comments and trailing commas", () => {
expect(
parseJSObjectLiteral<unknown>(`{
// comment
'name': 'it\\'s "x"', /* block */
$and: [1, 2,],
}`)
).toEqual({ name: `it's "x"`, $and: [1, 2] })
})

test("supports semicolons ending the statement", () => {
expect(parseJSObjectLiteral<unknown>(`{ name: "foo" };`)).toEqual({ name: "foo" })
expect(parseJSObjectLiteral<unknown>(`{ name: "foo" } ;\n\n`)).toEqual({ name: "foo" })
expect(parseJSObjectLiteral<unknown>(`{ name: "foo" }; // done`)).toEqual({ name: "foo" })
expect(parseJSObjectLiteral<unknown>(`{ a: ";" };;`)).toEqual({ a: ";" })
expect(parseJSObjectLiteral<unknown>(`{};`)).toEqual({})
expect(parseJSObjectLiteral<unknown>(`;`)).toBeUndefined()
expect(parseJSObjectLiteral<unknown>(`{ a: 1 }; { b: 2 }`)).toBeUndefined()
expect(parseJSObjectLiteral<unknown>(`{ a: 1; }`)).toBeUndefined()
})

test("returns undefined for invalid input", () => {
expect(parseJSObjectLiteral<unknown>(`{ title: "unterminated }`)).toBeUndefined()
expect(parseJSObjectLiteral<unknown>(`{ a: undefined }`)).toBeUndefined()
expect(parseJSObjectLiteral<unknown>(`{,}`)).toBeUndefined()
expect(parseJSObjectLiteral<unknown>(`{ a: [,] }`)).toBeUndefined()
expect(parseJSObjectLiteral<unknown>(`{ a: "x\ny" }`)).toBeUndefined()
// Unclosed block comments
expect(parseJSObjectLiteral<unknown>(`{ a: 1 } /* x`)).toBeUndefined()
expect(parseJSObjectLiteral<unknown>(`{ a: 1 }; /* x`)).toBeUndefined()
expect(parseJSObjectLiteral<unknown>(`{ a: 1 /* x`)).toBeUndefined()
})
})

describe("toKeySearchPattern", () => {
test("matches plain text literally as a prefix", () => {
Expand Down
116 changes: 109 additions & 7 deletions src/lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,41 @@ export function safeParseJSON<T>(value: string): T | undefined {
}
}

/** Index of the next character that is not whitespace or a comment, -1 for an unclosed comment */
const skipWhitespaceAndComments = (value: string, index: number): number => {
while (index < value.length) {
if (/\s/.test(value[index])) {
index++
} else if (value.startsWith("//", index)) {
const end = value.indexOf("\n", index)
index = end === -1 ? value.length : end + 1
} else if (value.startsWith("/*", index)) {
const end = value.indexOf("*/", index + 2)
if (end === -1) return -1
index = end + 2
} else {
break
}
}
return index
}

/** Whether only semicolons, whitespace and comments are left from index on */
const isStatementEnd = (value: string, index: number): boolean => {
while (index < value.length) {
const next = skipWhitespaceAndComments(value, index)
if (next === -1) return false
if (next !== index) {
index = next
} else if (value[index] === ";") {
index++
} else {
return false
}
}
return true
}

/**
* Turns search box text into a SCAN MATCH pattern. Text containing `*` is used as a glob;
* plain text is matched literally as a prefix, so `[`, `]` and `?` are escaped.
Expand Down Expand Up @@ -44,15 +79,82 @@ export function fromKeySearchPattern(pattern: string): string {
}

/**
* Parses a JavaScript object literal string (with unquoted keys) into a JS object.
* Adds double quotes around unquoted keys like `$and:` -> `"$and":`
* Parses a JavaScript object literal string into a JS object.
* Supports unquoted keys like `$and:`, single quoted strings, comments, trailing commas,
* and semicolons ending the statement.
* String contents are never rewritten. Returns undefined if the value is not valid.
*/
export function parseJSObjectLiteral<T>(value: string): T | undefined {
// Add double quotes around unquoted keys (handles $ prefixed and regular identifiers)
let jsonified = value.replaceAll(/([,{]\s*)(\$?[A-Z_a-z]\w*)\s*:/g, '$1"$2":')
// Remove trailing commas before closing braces/brackets (valid in JS, invalid in JSON)
jsonified = jsonified.replaceAll(/,\s*([\]}])/g, "$1")
return safeParseJSON(jsonified)
let json = ""
let index = 0

while (index < value.length) {
const char = value[index]

if (char === '"' || char === "'") {
// Copy the string as a double quoted JSON string
let content = ""
index++
while (index < value.length && value[index] !== char) {
if (value[index] === "\\") {
const escaped = value[index + 1] ?? ""
// \' is valid JS in any string but not JSON
content += escaped === "'" ? "'" : `\\${escaped}`
index += 2
} else {
const code = value.codePointAt(index)!
// JS strings may hold a raw tab (and other control characters but line breaks),
// JSON strings may not
if (code < 0x20 && value[index] !== "\n" && value[index] !== "\r") {
content += String.raw`\u` + code.toString(16).padStart(4, "0")
} else {
content += value[index] === '"' ? String.raw`\"` : value[index]
}
index++
}
}
if (index >= value.length) return
index++
json += `"${content}"`
continue
}

const next = skipWhitespaceAndComments(value, index)
if (next === -1) return
if (next !== index) {
json += " "
index = next
continue
}

const identifier = /^[$A-Z_a-z][\w$]*/.exec(value.slice(index))?.[0]
if (identifier) {
index += identifier.length
// An identifier followed by a colon is an unquoted key
json +=
value[skipWhitespaceAndComments(value, index)] === ":" ? `"${identifier}"` : identifier
continue
}

// The editor holds a statement, so trailing semicolons are valid there but not in JSON
if (char === ";" && isStatementEnd(value, index)) break

// Drop trailing commas before closing braces/brackets (valid in JS, invalid in JSON),
// but not a lone comma like {,} which is invalid in JS too
if (char === ",") {
const after = value[skipWhitespaceAndComments(value, index + 1)]
const before = json.trimEnd().at(-1)
if ((after === "}" || after === "]") && before !== "{" && before !== "[" && before !== ",") {
index++
continue
}
}

json += char
index++
}

return safeParseJSON(json)
}

const units = {
Expand Down
Loading