fix(mongodb): replace the typed new when completing constructors

This commit is contained in:
Loc Nguyen authored and GitHub committed 2026-10-04 17:37:48 +08:00
1 parent 827c934b18
commit 4fadbb9801
2 files changed
+122 -5

No files matched your search

+32 -5
View File
@@ -25,6 +25,9 @@ import {
type MongoOperatorSpec, type MongoOperatorSpec,
} from "@/lib/mongo/mongoCompletionTables"; } from "@/lib/mongo/mongoCompletionTables";
/** Snippets callable with `new` — every shell constructor accepts it (bare `Date(` is the only rejected spelling); literals like `null` do not. */
const NEW_CONSTRUCTIBLE_VALUE_SNIPPETS: readonly MongoOperatorSpec[] = VALUE_SNIPPETS.filter((spec) => spec.label === "new Date" || /^[A-Z]/.test(spec.label));
/** /**
* What the cursor may usefully be completed with. Each mode maps to exactly one * What the cursor may usefully be completed with. Each mode maps to exactly one
* item source, so `buildMongoCompletionItemsFromContext` never has to re-derive * item source, so `buildMongoCompletionItemsFromContext` never has to re-derive
@@ -442,8 +445,11 @@ export function getMongoCompletionContext(text: string, cursor: number): MongoCo
const classified = classifyCursorInCall(call.method, scan); const classified = classifyCursorInCall(call.method, scan);
const variables = classified.mode === "fieldRef" || classified.mode === "expression" ? collectScopeVariables(scan) : undefined; const variables = classified.mode === "fieldRef" || classified.mode === "expression" ? collectScopeVariables(scan) : undefined;
const valuePrefix = classified.mode === "value" ? adjustValuePrefixForNew(text, safeCursor, from) : { prefix, from };
return { return {
...at(classified.mode, classified.stage, classified.method, classified.bulkWriteOperation, classified.keyMap), ...at(classified.mode, classified.stage, classified.method, classified.bulkWriteOperation, classified.keyMap),
prefix: valuePrefix.prefix,
from: valuePrefix.from,
...(classified.operator ? { operator: classified.operator } : {}), ...(classified.operator ? { operator: classified.operator } : {}),
...(classified.enumKey ? { enumKey: classified.enumKey } : {}), ...(classified.enumKey ? { enumKey: classified.enumKey } : {}),
...(classified.pipelineKind ? { pipelineKind: classified.pipelineKind } : {}), ...(classified.pipelineKind ? { pipelineKind: classified.pipelineKind } : {}),
@@ -534,6 +540,12 @@ export function buildMongoCompletionItemsFromContext(context: MongoCompletionCon
items = indexNameItems(prefix, input.indexes ?? [], context.method); items = indexNameItems(prefix, input.indexes ?? [], context.method);
break; break;
case "value": case "value":
if (/^new\s+/i.test(prefix)) {
// Match against what follows `new ` so `new O` still finds `ObjectId("…")`;
// the replacement range already covers the typed keyword via adjustValuePrefixForNew.
items = specItems(NEW_CONSTRUCTIBLE_VALUE_SNIPPETS, normalizeMongoKeyPrefix(prefix).replace(/^new\s+/i, ""), "value", 100);
break;
}
// Shell constructors first; the extended JSON spellings need their own braces here. // Shell constructors first; the extended JSON spellings need their own braces here.
items = [...specItems(VALUE_SNIPPETS, prefix, "value", 100), ...specItems(BRACED_EXTENDED_JSON_VALUES, prefix, "extended JSON value", 90)]; items = [...specItems(VALUE_SNIPPETS, prefix, "value", 100), ...specItems(BRACED_EXTENDED_JSON_VALUES, prefix, "extended JSON value", 90)];
break; break;
@@ -625,7 +637,9 @@ export function shouldAutoOpenMongoCompletion(text: string, cursor: number): boo
if (!previousChar) return false; if (!previousChar) return false;
if (text.slice(0, cursor).endsWith("db.")) return true; if (text.slice(0, cursor).endsWith("db.")) return true;
// `use ` and `show ` name a database or subcommand next; open the list as soon as the space is typed. // `use ` and `show ` name a database or subcommand next; open the list as soon as the space is typed.
if (previousChar === " " && (matchUseDatabasePrefix(text.slice(0, cursor)) || matchShowSubcommandPrefix(text.slice(0, cursor)))) return true; if (previousChar === " " && (matchUseDatabasePrefix(text.slice(0, cursor)) || matchShowSubcommandPrefix(text.slice(0, cursor)) || (/(?:^|[^\w$.])new\s+$/.test(text.slice(0, cursor)) && getMongoCompletionContext(text, cursor).mode === "value"))) {
return true;
}
if (previousChar === ".") { if (previousChar === ".") {
return getMongoCompletionContext(text, cursor).mode !== "none"; return getMongoCompletionContext(text, cursor).mode !== "none";
} }
@@ -672,7 +686,8 @@ export function getMongoDocumentQueryCompletionContext(text: string, cursor: num
const classified = kind === "filter" ? classifyFilter(scan, 0) : classifyKeyMap(scan, 0, "sort"); const classified = kind === "filter" ? classifyFilter(scan, 0) : classifyKeyMap(scan, 0, "sort");
if (classified.mode === "none") return nothing; if (classified.mode === "none") return nothing;
const { prefix, from } = readMongoPropertyPrefix(text, safeCursor); const rawPrefix = readMongoPropertyPrefix(text, safeCursor);
const { prefix, from } = classified.mode === "value" ? adjustValuePrefixForNew(text, safeCursor, rawPrefix.from) : rawPrefix;
const variables = classified.mode === "fieldRef" || classified.mode === "expression" ? collectScopeVariables(scan) : undefined; const variables = classified.mode === "fieldRef" || classified.mode === "expression" ? collectScopeVariables(scan) : undefined;
return { return {
...classified, ...classified,
@@ -766,7 +781,10 @@ export function shouldAutoOpenMongoDocumentQueryCompletion(text: string, cursor:
* of the identifier and are safe to keep. * of the identifier and are safe to keep.
*/ */
export function getMongoCompletionResultValidFor(context?: MongoCompletionContext): RegExp { export function getMongoCompletionResultValidFor(context?: MongoCompletionContext): RegExp {
if (!context || !DOT_SCOPED_MODES.has(context.mode)) return /["']?[\w_$.-]*$/; if (!context || !DOT_SCOPED_MODES.has(context.mode)) {
if (context?.mode === "value") return /(?:new\s+)?["']?[\w_$.-]*$/;
return /["']?[\w_$.-]*$/;
}
const segments = context.prefix.split(".").length; const segments = context.prefix.split(".").length;
return new RegExp(`["']?[\\w_$-]*${"\\.[\\w_$-]*".repeat(segments - 1)}$`); return new RegExp(`["']?[\\w_$-]*${"\\.[\\w_$-]*".repeat(segments - 1)}$`);
} }
@@ -1993,6 +2011,15 @@ export function readMongoPropertyPrefix(text: string, cursor: number): { prefix:
return { prefix: text.slice(from, safeCursor), from }; return { prefix: text.slice(from, safeCursor), from };
} }
export function adjustValuePrefixForNew(text: string, cursor: number, from: number): { prefix: string; from: number } {
const beforeFrom = text.slice(0, from);
const match = /(?:^|[^\w$.])(new\s+)$/.exec(beforeFrom);
if (!match || !match[1]) return { prefix: text.slice(from, cursor), from };
const newStart = from - match[1].length;
if (isInsideMongoComment(text, newStart)) return { prefix: text.slice(from, cursor), from };
return { prefix: text.slice(newStart, cursor), from: newStart };
}
function findOpenMongoQuoteStart(text: string, cursor: number): number | null { function findOpenMongoQuoteStart(text: string, cursor: number): number | null {
for (let index = 0; index < cursor; index++) { for (let index = 0; index < cursor; index++) {
const char = text[index]; const char = text[index];
@@ -2536,11 +2563,11 @@ function escapeSingleQuoted(value: string): string {
} }
function startsWithPrefix(value: string, prefix: string): boolean { function startsWithPrefix(value: string, prefix: string): boolean {
return value.toLowerCase().startsWith(prefix.toLowerCase()); return value.toLowerCase().startsWith(prefix.toLowerCase().replace(/\s+/g, " "));
} }
function matchesFuzzyPrefix(value: string, prefix: string): boolean { function matchesFuzzyPrefix(value: string, prefix: string): boolean {
const normalizedPrefix = normalizeMongoKeyPrefix(prefix).toLowerCase(); const normalizedPrefix = normalizeMongoKeyPrefix(prefix).toLowerCase().replace(/\s+/g, " ");
if (!normalizedPrefix) return true; if (!normalizedPrefix) return true;
return value.toLowerCase().includes(normalizedPrefix); return value.toLowerCase().includes(normalizedPrefix);
} }
+90
View File
@@ -2072,6 +2072,96 @@ test("keeps the find chain completable when a comment holds an unbalanced parent
assert.deepEqual(labels('db.users.find({ note: "(x" }).li', { fields }), ["limit"]); assert.deepEqual(labels('db.users.find({ note: "(x" }).li', { fields }), ["limit"]);
}); });
test("replaces typed new keyword when completing new Date", () => {
// Bad case 1: cursor after `new D`
const text1 = "db.users.find({ name: new D";
const cursor1 = text1.length;
const context1 = getMongoCompletionContext(text1, cursor1);
const items1 = buildMongoCompletionItems(text1, cursor1, { fields });
const item1 = items1.find((candidate) => candidate.label === "new Date");
assert.ok(item1);
assert.equal(context1.from, text1.indexOf("new D"));
assert.equal(context1.prefix, "new D");
assert.equal(item1.apply, 'new Date("${date}")');
const inserted1 = text1.slice(0, context1.from) + item1.apply + text1.slice(cursor1);
assert.equal(inserted1, 'db.users.find({ name: new Date("${date}")');
// Every shell constructor accepts `new`, so matching the part after `new `
// keeps the other `…d…` constructors alongside `new Date`.
assert.deepEqual(
items1.map((candidate) => candidate.label),
["ISODate", "ObjectId", "BinData", "new Date", "NumberDecimal", "UUID"],
);
// Bad case 2: cursor after `new ` (trailing space)
const text2 = "db.users.find({ name: new ";
const cursor2 = text2.length;
const context2 = getMongoCompletionContext(text2, cursor2);
const items2 = buildMongoCompletionItems(text2, cursor2, { fields });
const item2 = items2.find((candidate) => candidate.label === "new Date");
assert.ok(item2);
assert.equal(context2.from, text2.indexOf("new "));
assert.equal(context2.prefix, "new ");
assert.equal(item2.apply, 'new Date("${date}")');
const inserted2 = text2.slice(0, context2.from) + item2.apply + text2.slice(cursor2);
assert.equal(inserted2, 'db.users.find({ name: new Date("${date}")');
const labels2 = items2.map((candidate) => candidate.label);
assert.ok(labels2.includes("new Date"));
assert.ok(labels2.includes("ObjectId"));
assert.ok(labels2.includes("NumberLong"));
assert.equal(labels2.includes("null"), false, "literals are not constructible");
assert.equal(labels2.includes("true"), false);
assert.equal(labels2.includes("false"), false);
// `new O` finds the other constructible constructors (mongosh BSON classes accept `new`)
const text2b = "db.users.find({ name: new O";
const cursor2b = text2b.length;
const context2b = getMongoCompletionContext(text2b, cursor2b);
const items2b = buildMongoCompletionItems(text2b, cursor2b, { fields });
const item2b = items2b.find((candidate) => candidate.label === "ObjectId");
assert.ok(item2b);
assert.equal(context2b.from, text2b.indexOf("new O"));
assert.equal(item2b.apply, 'ObjectId("${id}")');
const inserted2b = text2b.slice(0, context2b.from) + item2b.apply + text2b.slice(cursor2b);
assert.equal(inserted2b, 'db.users.find({ name: ObjectId("${id}")');
// ValidFor regex allows typing after new in value mode
const pattern = getMongoCompletionResultValidFor(context1);
const isValid = (typed: string) => new RegExp(`^(?:${pattern.source})$`).test(typed);
assert.equal(isValid("new "), true);
assert.equal(isValid("new D"), true);
assert.equal(isValid("new Date"), true);
assert.equal(isValid("new Date("), false);
// Document query completion in filter mode
const docText = "{ name: new D";
const docCursor = docText.length;
const docContext = getMongoDocumentQueryCompletionContext(docText, docCursor, "filter");
assert.equal(docContext.from, docText.indexOf("new D"));
assert.equal(docContext.prefix, "new D");
// `ne` case unchanged
const text3 = "db.users.find({ name: ne";
const cursor3 = text3.length;
const context3 = getMongoCompletionContext(text3, cursor3);
const items3 = buildMongoCompletionItems(text3, cursor3, { fields });
const item3 = items3.find((candidate) => candidate.label === "new Date");
assert.ok(item3);
assert.equal(context3.from, text3.indexOf("ne"));
assert.equal(context3.prefix, "ne");
assert.equal(item3.apply, 'new Date("${date}")');
const inserted3 = text3.slice(0, context3.from) + item3.apply + text3.slice(cursor3);
assert.equal(inserted3, 'db.users.find({ name: new Date("${date}")');
// `{ name: "new D` (inside a string) unchanged
const text4 = 'db.users.find({ name: "new D';
const cursor4 = text4.length;
const context4 = getMongoCompletionContext(text4, cursor4);
const items4 = buildMongoCompletionItems(text4, cursor4, { fields });
assert.equal(context4.mode, "none");
assert.equal(context4.prefix, '"new D');
assert.deepEqual(items4, []);
});
test("offers $comment as a top-level query operator", () => { test("offers $comment as a top-level query operator", () => {
const items = labels("db.users.find({ $c", { fields }); const items = labels("db.users.find({ $c", { fields });
assert.ok(items.includes("$comment"), "db.users.find({ $c should offer $comment"); assert.ok(items.includes("$comment"), "db.users.find({ $c should offer $comment");