sim 2.1.29-dev.171.1 → 2.2.0-preview.173.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +21 -6
- package/THIRD_PARTY_LICENSES +3 -0
- package/dist/commands/search.d.ts +10 -0
- package/dist/config/index.d.ts +1 -1
- package/dist/config/profile.d.ts +6 -0
- package/dist/generated/v2-api.d.ts +9 -17
- package/dist/index.js +1168 -11
- package/dist/program.d.ts +10 -1
- package/dist/runtime.js +1168 -11
- package/package.json +2 -1
package/dist/runtime.js
CHANGED
|
@@ -3550,6 +3550,7 @@ function removeSection(doc, name) {
|
|
|
3550
3550
|
var DEFAULT_PROFILE = "default";
|
|
3551
3551
|
var DEFAULT_ENDPOINT = "https://www.sim.ai";
|
|
3552
3552
|
var OUTPUT_FORMATS = ["table", "json", "yaml", "text"];
|
|
3553
|
+
var DEFAULT_OUTPUT_FORMAT = "json";
|
|
3553
3554
|
var FORBIDDEN_IN_VALUE_GLOBAL = new RegExp(FORBIDDEN_IN_VALUE.source, "g");
|
|
3554
3555
|
function redact(value) {
|
|
3555
3556
|
return value.replace(FORBIDDEN_IN_VALUE_GLOBAL, " ");
|
|
@@ -3900,7 +3901,7 @@ function resolveProfile(overrides = {}) {
|
|
|
3900
3901
|
["flag", overrides.output],
|
|
3901
3902
|
["env", process.env.SIM_OUTPUT],
|
|
3902
3903
|
["config", config.output]
|
|
3903
|
-
],
|
|
3904
|
+
], DEFAULT_OUTPUT_FORMAT, "default");
|
|
3904
3905
|
if (!OUTPUT_FORMATS.includes(output.value)) {
|
|
3905
3906
|
throw new ProfileConfigError(`Unknown output format "${redact(String(output.value))}" from ${output.source}. Use one of: ${OUTPUT_FORMATS.join(", ")}`);
|
|
3906
3907
|
}
|
|
@@ -11967,7 +11968,13 @@ var V2_OPERATIONS = {
|
|
|
11967
11968
|
pathParams: ["runId"],
|
|
11968
11969
|
pathParamDocs: { runId: "Unique workflow run identifier." },
|
|
11969
11970
|
responseMode: "json",
|
|
11970
|
-
summary: "Get Log"
|
|
11971
|
+
summary: "Get Log",
|
|
11972
|
+
query: {
|
|
11973
|
+
includeWorkflowState: {
|
|
11974
|
+
kind: "boolean",
|
|
11975
|
+
describe: "Include the saved workflow snapshot (default: true). Set false to omit block configuration from a log read. Other run fields are unchanged."
|
|
11976
|
+
}
|
|
11977
|
+
}
|
|
11971
11978
|
},
|
|
11972
11979
|
getLogStats: {
|
|
11973
11980
|
method: "GET",
|
|
@@ -17055,7 +17062,7 @@ Waiting for you to approve in the browser…`));
|
|
|
17055
17062
|
}
|
|
17056
17063
|
}
|
|
17057
17064
|
function loginCommand() {
|
|
17058
|
-
return new Command("login").description("
|
|
17065
|
+
return new Command("login").description("Log in through the browser and store the login for the profile").addOption(new Option("--method <method>", "Credential to obtain: oauth requires OAuth support; api-key creates a permanent key through pairing (auto-selects when omitted)").choices(["oauth", "api-key"])).option("--no-browser", "Print the approval URL without opening it (either login method)").option("--read-only", "Ask only for permission to read, never to change anything").option("--callback-port <port>", "Pin the local port the browser returns to").option("-y, --yes", "Overwrite an existing API-key profile without prompting").action(async (options, command) => {
|
|
17059
17066
|
const profile = profileFrom(command, { allowUnknownProfile: true });
|
|
17060
17067
|
const authProfile = resolveAuthenticationProfileName(profile.name);
|
|
17061
17068
|
if (authProfile !== profile.name) {
|
|
@@ -17389,7 +17396,7 @@ function profileListingContext(command) {
|
|
|
17389
17396
|
throw error;
|
|
17390
17397
|
return {
|
|
17391
17398
|
activeName: named || DEFAULT_PROFILE,
|
|
17392
|
-
output: requested ? requested :
|
|
17399
|
+
output: requested ? requested : DEFAULT_OUTPUT_FORMAT
|
|
17393
17400
|
};
|
|
17394
17401
|
}
|
|
17395
17402
|
}
|
|
@@ -17437,7 +17444,7 @@ function quoteProfileArgument(name) {
|
|
|
17437
17444
|
return `'${redacted.replaceAll("'", "'\\''")}'`;
|
|
17438
17445
|
}
|
|
17439
17446
|
function configureCommand() {
|
|
17440
|
-
return new Command("configure").description("
|
|
17447
|
+
return new Command("configure").description("Switch a profile's default workspace, or set its endpoint or output format").option("--set-endpoint <url>", "Sim deployment to talk to").option("--set-workspace <id>", "Default workspace for workspace-scoped commands").option("--set-output <format>", `Default output format (${OUTPUT_FORMATS.join(" | ")})`).option("--unset <key...>", "Remove settings (endpoint, workspace, output)").action(async (options, command) => {
|
|
17441
17448
|
const globals = globalsOf(command);
|
|
17442
17449
|
const selectedProfile = globals.profile || process.env.SIM_PROFILE;
|
|
17443
17450
|
const profileArg = selectedProfile ? ` --profile ${quoteProfileArgument(selectedProfile)}` : "";
|
|
@@ -17593,7 +17600,7 @@ var CLI_CONTRACT = {
|
|
|
17593
17600
|
getBillingStatus: {
|
|
17594
17601
|
command: "billing status",
|
|
17595
17602
|
allWorkspaces: true,
|
|
17596
|
-
describe: "Show billing status
|
|
17603
|
+
describe: "Show billing status, credits spent this period, and storage used (credits and storage require an OAuth login or personal API key)",
|
|
17597
17604
|
fields: [
|
|
17598
17605
|
{ header: "plan" },
|
|
17599
17606
|
{ header: "status" },
|
|
@@ -17716,6 +17723,7 @@ var CLI_CONTRACT = {
|
|
|
17716
17723
|
confirm: "This archives the knowledge base and every document in it; restore with `knowledge restore`."
|
|
17717
17724
|
},
|
|
17718
17725
|
deleteKnowledgeDocument: {
|
|
17726
|
+
describe: "Delete a document from a knowledge base",
|
|
17719
17727
|
pathArgumentNames: KNOWLEDGE_BASE_PATH_ARGUMENT,
|
|
17720
17728
|
confirm: "This deletes the document and its embeddings."
|
|
17721
17729
|
},
|
|
@@ -17754,6 +17762,7 @@ var CLI_CONTRACT = {
|
|
|
17754
17762
|
]
|
|
17755
17763
|
},
|
|
17756
17764
|
listLogs: {
|
|
17765
|
+
describe: "List run logs, such as failed or errored runs, by workflow, trigger or time",
|
|
17757
17766
|
flags: {
|
|
17758
17767
|
...LOG_LIST_FILTER_FLAGS,
|
|
17759
17768
|
details: {
|
|
@@ -17866,6 +17875,7 @@ var CLI_CONTRACT = {
|
|
|
17866
17875
|
},
|
|
17867
17876
|
applyWorkflowOperations: {
|
|
17868
17877
|
command: "workflows operations apply",
|
|
17878
|
+
describe: "Edit a workflow’s blocks, connections and settings with a batch of operations",
|
|
17869
17879
|
confirm: "This edits the draft graph: the batch adds, edits, or deletes blocks and their edges as written.",
|
|
17870
17880
|
flags: {
|
|
17871
17881
|
operations: { json: true, describe: WORKFLOW_OPERATIONS_HELP },
|
|
@@ -17968,6 +17978,7 @@ var CLI_CONTRACT = {
|
|
|
17968
17978
|
},
|
|
17969
17979
|
queryRows: {
|
|
17970
17980
|
command: "tables rows query",
|
|
17981
|
+
describe: "Query rows with a filter and sort",
|
|
17971
17982
|
flags: {
|
|
17972
17983
|
predicate: { name: "filter", json: true, describe: TABLE_READ_FILTER_HELP },
|
|
17973
17984
|
sort: { json: true, describe: TABLE_SORT_HELP }
|
|
@@ -21367,7 +21378,7 @@ async function downloadToOutput(command, operation, pathParams, options) {
|
|
|
21367
21378
|
});
|
|
21368
21379
|
}
|
|
21369
21380
|
function attachFileGet(files) {
|
|
21370
|
-
files.command("get").argument("<fileId>", "File whose content to read").allowExcessArguments(false).description("
|
|
21381
|
+
files.command("get").argument("<fileId>", "File whose content to read").allowExcessArguments(false).description("Download a file’s content to stdout or a local file").option("-o, --output-file <path>", "Write content to a file instead of stdout").option("--force", "Overwrite --output-file if it already exists").action((fileId, options, command) => downloadToOutput(command, V2_OPERATIONS.downloadFile, { fileId }, options));
|
|
21371
21382
|
}
|
|
21372
21383
|
function attachFileVersionDownload(versions) {
|
|
21373
21384
|
versions.command("download").argument("<fileId>", "File identifier.").argument("<version>", "Version number.").allowExcessArguments(false).description("Download the content of one version of a file").option("-o, --output-file <path>", "Write content to a file instead of stdout").option("--force", "Overwrite --output-file if it already exists").action((fileId, version, options, command) => downloadToOutput(command, V2_OPERATIONS.downloadFileVersion, { fileId, version }, options));
|
|
@@ -21914,7 +21925,7 @@ function inSeconds(ms) {
|
|
|
21914
21925
|
return Math.round(ms / 100) / 10;
|
|
21915
21926
|
}
|
|
21916
21927
|
function attachLogsFollow(logs) {
|
|
21917
|
-
logs.command("follow").description("Watch runs as they arrive, printing each new run once").option("--workflow <id>", "Only follow runs of this workflow (repeatable)", collect, []).option("--folder <path>", "Only follow runs of workflows in this folder (repeatable)", collect, []).option("--trigger <type>", "Only follow runs with this trigger type (repeatable)", collect, []).addOption(new Option("--level <level>", "Only follow runs at this severity").choices([
|
|
21928
|
+
logs.command("follow").description("Watch runs live as they arrive, printing each new run once").option("--workflow <id>", "Only follow runs of this workflow (repeatable)", collect, []).option("--folder <path>", "Only follow runs of workflows in this folder (repeatable)", collect, []).option("--trigger <type>", "Only follow runs with this trigger type (repeatable)", collect, []).addOption(new Option("--level <level>", "Only follow runs at this severity").choices([
|
|
21918
21929
|
...V2_OPERATIONS.listLogs.query.level.values
|
|
21919
21930
|
])).addOption(new Option("--details <level>", "Response detail level; full names each run’s workflow").choices([...V2_OPERATIONS.listLogs.query.details.values]).default("full")).option("-n, --lines <count>", "Recent runs to print before watching", String(DEFAULT_BACKLOG)).option("--interval <seconds>", "Seconds between polls", String(DEFAULT_INTERVAL_SECONDS)).addHelpText("after", `
|
|
21920
21931
|
Each run prints once, when it is first seen, so its status is the status it had
|
|
@@ -22809,6 +22820,1140 @@ function attachProtocolCommands(program) {
|
|
|
22809
22820
|
attachChat(program);
|
|
22810
22821
|
}
|
|
22811
22822
|
|
|
22823
|
+
// ../../node_modules/minisearch/dist/es/index.js
|
|
22824
|
+
var ENTRIES = "ENTRIES";
|
|
22825
|
+
var KEYS = "KEYS";
|
|
22826
|
+
var VALUES = "VALUES";
|
|
22827
|
+
var LEAF = "";
|
|
22828
|
+
|
|
22829
|
+
class TreeIterator {
|
|
22830
|
+
constructor(set, type) {
|
|
22831
|
+
const node = set._tree;
|
|
22832
|
+
const keys = Array.from(node.keys());
|
|
22833
|
+
this.set = set;
|
|
22834
|
+
this._type = type;
|
|
22835
|
+
this._path = keys.length > 0 ? [{ node, keys }] : [];
|
|
22836
|
+
}
|
|
22837
|
+
next() {
|
|
22838
|
+
const value = this.dive();
|
|
22839
|
+
this.backtrack();
|
|
22840
|
+
return value;
|
|
22841
|
+
}
|
|
22842
|
+
dive() {
|
|
22843
|
+
if (this._path.length === 0) {
|
|
22844
|
+
return { done: true, value: undefined };
|
|
22845
|
+
}
|
|
22846
|
+
const { node, keys } = last$1(this._path);
|
|
22847
|
+
if (last$1(keys) === LEAF) {
|
|
22848
|
+
return { done: false, value: this.result() };
|
|
22849
|
+
}
|
|
22850
|
+
const child = node.get(last$1(keys));
|
|
22851
|
+
this._path.push({ node: child, keys: Array.from(child.keys()) });
|
|
22852
|
+
return this.dive();
|
|
22853
|
+
}
|
|
22854
|
+
backtrack() {
|
|
22855
|
+
if (this._path.length === 0) {
|
|
22856
|
+
return;
|
|
22857
|
+
}
|
|
22858
|
+
const keys = last$1(this._path).keys;
|
|
22859
|
+
keys.pop();
|
|
22860
|
+
if (keys.length > 0) {
|
|
22861
|
+
return;
|
|
22862
|
+
}
|
|
22863
|
+
this._path.pop();
|
|
22864
|
+
this.backtrack();
|
|
22865
|
+
}
|
|
22866
|
+
key() {
|
|
22867
|
+
return this.set._prefix + this._path.map(({ keys }) => last$1(keys)).filter((key) => key !== LEAF).join("");
|
|
22868
|
+
}
|
|
22869
|
+
value() {
|
|
22870
|
+
return last$1(this._path).node.get(LEAF);
|
|
22871
|
+
}
|
|
22872
|
+
result() {
|
|
22873
|
+
switch (this._type) {
|
|
22874
|
+
case VALUES:
|
|
22875
|
+
return this.value();
|
|
22876
|
+
case KEYS:
|
|
22877
|
+
return this.key();
|
|
22878
|
+
default:
|
|
22879
|
+
return [this.key(), this.value()];
|
|
22880
|
+
}
|
|
22881
|
+
}
|
|
22882
|
+
[Symbol.iterator]() {
|
|
22883
|
+
return this;
|
|
22884
|
+
}
|
|
22885
|
+
}
|
|
22886
|
+
var last$1 = (array) => {
|
|
22887
|
+
return array[array.length - 1];
|
|
22888
|
+
};
|
|
22889
|
+
var fuzzySearch = (node, query, maxDistance) => {
|
|
22890
|
+
const results = new Map;
|
|
22891
|
+
if (query === undefined)
|
|
22892
|
+
return results;
|
|
22893
|
+
const n = query.length + 1;
|
|
22894
|
+
const m = n + maxDistance;
|
|
22895
|
+
const matrix = new Uint8Array(m * n).fill(maxDistance + 1);
|
|
22896
|
+
for (let j = 0;j < n; ++j)
|
|
22897
|
+
matrix[j] = j;
|
|
22898
|
+
for (let i = 1;i < m; ++i)
|
|
22899
|
+
matrix[i * n] = i;
|
|
22900
|
+
recurse(node, query, maxDistance, results, matrix, 1, n, "");
|
|
22901
|
+
return results;
|
|
22902
|
+
};
|
|
22903
|
+
var recurse = (node, query, maxDistance, results, matrix, m, n, prefix) => {
|
|
22904
|
+
const offset = m * n;
|
|
22905
|
+
key:
|
|
22906
|
+
for (const key of node.keys()) {
|
|
22907
|
+
if (key === LEAF) {
|
|
22908
|
+
const distance = matrix[offset - 1];
|
|
22909
|
+
if (distance <= maxDistance) {
|
|
22910
|
+
results.set(prefix, [node.get(key), distance]);
|
|
22911
|
+
}
|
|
22912
|
+
} else {
|
|
22913
|
+
let i = m;
|
|
22914
|
+
for (let pos = 0;pos < key.length; ++pos, ++i) {
|
|
22915
|
+
const char = key[pos];
|
|
22916
|
+
const thisRowOffset = n * i;
|
|
22917
|
+
const prevRowOffset = thisRowOffset - n;
|
|
22918
|
+
let minDistance = matrix[thisRowOffset];
|
|
22919
|
+
const jmin = Math.max(0, i - maxDistance - 1);
|
|
22920
|
+
const jmax = Math.min(n - 1, i + maxDistance);
|
|
22921
|
+
for (let j = jmin;j < jmax; ++j) {
|
|
22922
|
+
const different = char !== query[j];
|
|
22923
|
+
const rpl = matrix[prevRowOffset + j] + +different;
|
|
22924
|
+
const del = matrix[prevRowOffset + j + 1] + 1;
|
|
22925
|
+
const ins = matrix[thisRowOffset + j] + 1;
|
|
22926
|
+
const dist = matrix[thisRowOffset + j + 1] = Math.min(rpl, del, ins);
|
|
22927
|
+
if (dist < minDistance)
|
|
22928
|
+
minDistance = dist;
|
|
22929
|
+
}
|
|
22930
|
+
if (minDistance > maxDistance) {
|
|
22931
|
+
continue key;
|
|
22932
|
+
}
|
|
22933
|
+
}
|
|
22934
|
+
recurse(node.get(key), query, maxDistance, results, matrix, i, n, prefix + key);
|
|
22935
|
+
}
|
|
22936
|
+
}
|
|
22937
|
+
};
|
|
22938
|
+
|
|
22939
|
+
class SearchableMap {
|
|
22940
|
+
constructor(tree = new Map, prefix = "") {
|
|
22941
|
+
this._size = undefined;
|
|
22942
|
+
this._tree = tree;
|
|
22943
|
+
this._prefix = prefix;
|
|
22944
|
+
}
|
|
22945
|
+
atPrefix(prefix) {
|
|
22946
|
+
if (!prefix.startsWith(this._prefix)) {
|
|
22947
|
+
throw new Error("Mismatched prefix");
|
|
22948
|
+
}
|
|
22949
|
+
const [node, path] = trackDown(this._tree, prefix.slice(this._prefix.length));
|
|
22950
|
+
if (node === undefined) {
|
|
22951
|
+
const [parentNode, key] = last(path);
|
|
22952
|
+
for (const k of parentNode.keys()) {
|
|
22953
|
+
if (k !== LEAF && k.startsWith(key)) {
|
|
22954
|
+
const node = new Map;
|
|
22955
|
+
node.set(k.slice(key.length), parentNode.get(k));
|
|
22956
|
+
return new SearchableMap(node, prefix);
|
|
22957
|
+
}
|
|
22958
|
+
}
|
|
22959
|
+
}
|
|
22960
|
+
return new SearchableMap(node, prefix);
|
|
22961
|
+
}
|
|
22962
|
+
clear() {
|
|
22963
|
+
this._size = undefined;
|
|
22964
|
+
this._tree.clear();
|
|
22965
|
+
}
|
|
22966
|
+
delete(key) {
|
|
22967
|
+
this._size = undefined;
|
|
22968
|
+
return remove(this._tree, key);
|
|
22969
|
+
}
|
|
22970
|
+
entries() {
|
|
22971
|
+
return new TreeIterator(this, ENTRIES);
|
|
22972
|
+
}
|
|
22973
|
+
forEach(fn) {
|
|
22974
|
+
for (const [key, value] of this) {
|
|
22975
|
+
fn(key, value, this);
|
|
22976
|
+
}
|
|
22977
|
+
}
|
|
22978
|
+
fuzzyGet(key, maxEditDistance) {
|
|
22979
|
+
return fuzzySearch(this._tree, key, maxEditDistance);
|
|
22980
|
+
}
|
|
22981
|
+
get(key) {
|
|
22982
|
+
const node = lookup(this._tree, key);
|
|
22983
|
+
return node !== undefined ? node.get(LEAF) : undefined;
|
|
22984
|
+
}
|
|
22985
|
+
has(key) {
|
|
22986
|
+
const node = lookup(this._tree, key);
|
|
22987
|
+
return node !== undefined && node.has(LEAF);
|
|
22988
|
+
}
|
|
22989
|
+
keys() {
|
|
22990
|
+
return new TreeIterator(this, KEYS);
|
|
22991
|
+
}
|
|
22992
|
+
set(key, value) {
|
|
22993
|
+
if (typeof key !== "string") {
|
|
22994
|
+
throw new Error("key must be a string");
|
|
22995
|
+
}
|
|
22996
|
+
this._size = undefined;
|
|
22997
|
+
const node = createPath(this._tree, key);
|
|
22998
|
+
node.set(LEAF, value);
|
|
22999
|
+
return this;
|
|
23000
|
+
}
|
|
23001
|
+
get size() {
|
|
23002
|
+
if (this._size) {
|
|
23003
|
+
return this._size;
|
|
23004
|
+
}
|
|
23005
|
+
this._size = 0;
|
|
23006
|
+
const iter = this.entries();
|
|
23007
|
+
while (!iter.next().done)
|
|
23008
|
+
this._size += 1;
|
|
23009
|
+
return this._size;
|
|
23010
|
+
}
|
|
23011
|
+
update(key, fn) {
|
|
23012
|
+
if (typeof key !== "string") {
|
|
23013
|
+
throw new Error("key must be a string");
|
|
23014
|
+
}
|
|
23015
|
+
this._size = undefined;
|
|
23016
|
+
const node = createPath(this._tree, key);
|
|
23017
|
+
node.set(LEAF, fn(node.get(LEAF)));
|
|
23018
|
+
return this;
|
|
23019
|
+
}
|
|
23020
|
+
fetch(key, initial) {
|
|
23021
|
+
if (typeof key !== "string") {
|
|
23022
|
+
throw new Error("key must be a string");
|
|
23023
|
+
}
|
|
23024
|
+
this._size = undefined;
|
|
23025
|
+
const node = createPath(this._tree, key);
|
|
23026
|
+
let value = node.get(LEAF);
|
|
23027
|
+
if (value === undefined) {
|
|
23028
|
+
node.set(LEAF, value = initial());
|
|
23029
|
+
}
|
|
23030
|
+
return value;
|
|
23031
|
+
}
|
|
23032
|
+
values() {
|
|
23033
|
+
return new TreeIterator(this, VALUES);
|
|
23034
|
+
}
|
|
23035
|
+
[Symbol.iterator]() {
|
|
23036
|
+
return this.entries();
|
|
23037
|
+
}
|
|
23038
|
+
static from(entries) {
|
|
23039
|
+
const tree = new SearchableMap;
|
|
23040
|
+
for (const [key, value] of entries) {
|
|
23041
|
+
tree.set(key, value);
|
|
23042
|
+
}
|
|
23043
|
+
return tree;
|
|
23044
|
+
}
|
|
23045
|
+
static fromObject(object) {
|
|
23046
|
+
return SearchableMap.from(Object.entries(object));
|
|
23047
|
+
}
|
|
23048
|
+
}
|
|
23049
|
+
var trackDown = (tree, key, path = []) => {
|
|
23050
|
+
if (key.length === 0 || tree == null) {
|
|
23051
|
+
return [tree, path];
|
|
23052
|
+
}
|
|
23053
|
+
for (const k of tree.keys()) {
|
|
23054
|
+
if (k !== LEAF && key.startsWith(k)) {
|
|
23055
|
+
path.push([tree, k]);
|
|
23056
|
+
return trackDown(tree.get(k), key.slice(k.length), path);
|
|
23057
|
+
}
|
|
23058
|
+
}
|
|
23059
|
+
path.push([tree, key]);
|
|
23060
|
+
return trackDown(undefined, "", path);
|
|
23061
|
+
};
|
|
23062
|
+
var lookup = (tree, key) => {
|
|
23063
|
+
if (key.length === 0 || tree == null) {
|
|
23064
|
+
return tree;
|
|
23065
|
+
}
|
|
23066
|
+
for (const k of tree.keys()) {
|
|
23067
|
+
if (k !== LEAF && key.startsWith(k)) {
|
|
23068
|
+
return lookup(tree.get(k), key.slice(k.length));
|
|
23069
|
+
}
|
|
23070
|
+
}
|
|
23071
|
+
};
|
|
23072
|
+
var createPath = (node, key) => {
|
|
23073
|
+
const keyLength = key.length;
|
|
23074
|
+
outer:
|
|
23075
|
+
for (let pos = 0;node && pos < keyLength; ) {
|
|
23076
|
+
for (const k of node.keys()) {
|
|
23077
|
+
if (k !== LEAF && key[pos] === k[0]) {
|
|
23078
|
+
const len = Math.min(keyLength - pos, k.length);
|
|
23079
|
+
let offset = 1;
|
|
23080
|
+
while (offset < len && key[pos + offset] === k[offset])
|
|
23081
|
+
++offset;
|
|
23082
|
+
const child = node.get(k);
|
|
23083
|
+
if (offset === k.length) {
|
|
23084
|
+
node = child;
|
|
23085
|
+
} else {
|
|
23086
|
+
const intermediate = new Map;
|
|
23087
|
+
intermediate.set(k.slice(offset), child);
|
|
23088
|
+
node.set(key.slice(pos, pos + offset), intermediate);
|
|
23089
|
+
node.delete(k);
|
|
23090
|
+
node = intermediate;
|
|
23091
|
+
}
|
|
23092
|
+
pos += offset;
|
|
23093
|
+
continue outer;
|
|
23094
|
+
}
|
|
23095
|
+
}
|
|
23096
|
+
const child = new Map;
|
|
23097
|
+
node.set(key.slice(pos), child);
|
|
23098
|
+
return child;
|
|
23099
|
+
}
|
|
23100
|
+
return node;
|
|
23101
|
+
};
|
|
23102
|
+
var remove = (tree, key) => {
|
|
23103
|
+
const [node, path] = trackDown(tree, key);
|
|
23104
|
+
if (node === undefined) {
|
|
23105
|
+
return;
|
|
23106
|
+
}
|
|
23107
|
+
node.delete(LEAF);
|
|
23108
|
+
if (node.size === 0) {
|
|
23109
|
+
cleanup(path);
|
|
23110
|
+
} else if (node.size === 1) {
|
|
23111
|
+
const [key, value] = node.entries().next().value;
|
|
23112
|
+
merge2(path, key, value);
|
|
23113
|
+
}
|
|
23114
|
+
};
|
|
23115
|
+
var cleanup = (path) => {
|
|
23116
|
+
if (path.length === 0) {
|
|
23117
|
+
return;
|
|
23118
|
+
}
|
|
23119
|
+
const [node, key] = last(path);
|
|
23120
|
+
node.delete(key);
|
|
23121
|
+
if (node.size === 0) {
|
|
23122
|
+
cleanup(path.slice(0, -1));
|
|
23123
|
+
} else if (node.size === 1) {
|
|
23124
|
+
const [key, value] = node.entries().next().value;
|
|
23125
|
+
if (key !== LEAF) {
|
|
23126
|
+
merge2(path.slice(0, -1), key, value);
|
|
23127
|
+
}
|
|
23128
|
+
}
|
|
23129
|
+
};
|
|
23130
|
+
var merge2 = (path, key, value) => {
|
|
23131
|
+
if (path.length === 0) {
|
|
23132
|
+
return;
|
|
23133
|
+
}
|
|
23134
|
+
const [node, nodeKey] = last(path);
|
|
23135
|
+
node.set(nodeKey + key, value);
|
|
23136
|
+
node.delete(nodeKey);
|
|
23137
|
+
};
|
|
23138
|
+
var last = (array) => {
|
|
23139
|
+
return array[array.length - 1];
|
|
23140
|
+
};
|
|
23141
|
+
var OR = "or";
|
|
23142
|
+
var AND = "and";
|
|
23143
|
+
var AND_NOT = "and_not";
|
|
23144
|
+
|
|
23145
|
+
class MiniSearch {
|
|
23146
|
+
constructor(options) {
|
|
23147
|
+
if ((options === null || options === undefined ? undefined : options.fields) == null) {
|
|
23148
|
+
throw new Error('MiniSearch: option "fields" must be provided');
|
|
23149
|
+
}
|
|
23150
|
+
const autoVacuum = options.autoVacuum == null || options.autoVacuum === true ? defaultAutoVacuumOptions : options.autoVacuum;
|
|
23151
|
+
this._options = {
|
|
23152
|
+
...defaultOptions,
|
|
23153
|
+
...options,
|
|
23154
|
+
autoVacuum,
|
|
23155
|
+
searchOptions: { ...defaultSearchOptions, ...options.searchOptions || {} },
|
|
23156
|
+
autoSuggestOptions: { ...defaultAutoSuggestOptions, ...options.autoSuggestOptions || {} }
|
|
23157
|
+
};
|
|
23158
|
+
this._index = new SearchableMap;
|
|
23159
|
+
this._documentCount = 0;
|
|
23160
|
+
this._documentIds = new Map;
|
|
23161
|
+
this._idToShortId = new Map;
|
|
23162
|
+
this._fieldIds = {};
|
|
23163
|
+
this._fieldLength = new Map;
|
|
23164
|
+
this._avgFieldLength = [];
|
|
23165
|
+
this._nextId = 0;
|
|
23166
|
+
this._storedFields = new Map;
|
|
23167
|
+
this._dirtCount = 0;
|
|
23168
|
+
this._currentVacuum = null;
|
|
23169
|
+
this._enqueuedVacuum = null;
|
|
23170
|
+
this._enqueuedVacuumConditions = defaultVacuumConditions;
|
|
23171
|
+
this.addFields(this._options.fields);
|
|
23172
|
+
}
|
|
23173
|
+
add(document) {
|
|
23174
|
+
const { extractField, stringifyField, tokenize, processTerm, fields, idField } = this._options;
|
|
23175
|
+
const id = extractField(document, idField);
|
|
23176
|
+
if (id == null) {
|
|
23177
|
+
throw new Error(`MiniSearch: document does not have ID field "${idField}"`);
|
|
23178
|
+
}
|
|
23179
|
+
if (this._idToShortId.has(id)) {
|
|
23180
|
+
throw new Error(`MiniSearch: duplicate ID ${id}`);
|
|
23181
|
+
}
|
|
23182
|
+
const shortDocumentId = this.addDocumentId(id);
|
|
23183
|
+
this.saveStoredFields(shortDocumentId, document);
|
|
23184
|
+
for (const field of fields) {
|
|
23185
|
+
const fieldValue = extractField(document, field);
|
|
23186
|
+
if (fieldValue == null)
|
|
23187
|
+
continue;
|
|
23188
|
+
const tokens = tokenize(stringifyField(fieldValue, field), field);
|
|
23189
|
+
const fieldId = this._fieldIds[field];
|
|
23190
|
+
const uniqueTerms = new Set(tokens).size;
|
|
23191
|
+
this.addFieldLength(shortDocumentId, fieldId, this._documentCount - 1, uniqueTerms);
|
|
23192
|
+
for (const term of tokens) {
|
|
23193
|
+
const processedTerm = processTerm(term, field);
|
|
23194
|
+
if (Array.isArray(processedTerm)) {
|
|
23195
|
+
for (const t of processedTerm) {
|
|
23196
|
+
this.addTerm(fieldId, shortDocumentId, t);
|
|
23197
|
+
}
|
|
23198
|
+
} else if (processedTerm) {
|
|
23199
|
+
this.addTerm(fieldId, shortDocumentId, processedTerm);
|
|
23200
|
+
}
|
|
23201
|
+
}
|
|
23202
|
+
}
|
|
23203
|
+
}
|
|
23204
|
+
addAll(documents) {
|
|
23205
|
+
for (const document of documents)
|
|
23206
|
+
this.add(document);
|
|
23207
|
+
}
|
|
23208
|
+
addAllAsync(documents, options = {}) {
|
|
23209
|
+
const { chunkSize = 10 } = options;
|
|
23210
|
+
const acc = { chunk: [], promise: Promise.resolve() };
|
|
23211
|
+
const { chunk, promise } = documents.reduce(({ chunk, promise }, document, i) => {
|
|
23212
|
+
chunk.push(document);
|
|
23213
|
+
if ((i + 1) % chunkSize === 0) {
|
|
23214
|
+
return {
|
|
23215
|
+
chunk: [],
|
|
23216
|
+
promise: promise.then(() => new Promise((resolve) => setTimeout(resolve, 0))).then(() => this.addAll(chunk))
|
|
23217
|
+
};
|
|
23218
|
+
} else {
|
|
23219
|
+
return { chunk, promise };
|
|
23220
|
+
}
|
|
23221
|
+
}, acc);
|
|
23222
|
+
return promise.then(() => this.addAll(chunk));
|
|
23223
|
+
}
|
|
23224
|
+
remove(document) {
|
|
23225
|
+
const { tokenize, processTerm, extractField, stringifyField, fields, idField } = this._options;
|
|
23226
|
+
const id = extractField(document, idField);
|
|
23227
|
+
if (id == null) {
|
|
23228
|
+
throw new Error(`MiniSearch: document does not have ID field "${idField}"`);
|
|
23229
|
+
}
|
|
23230
|
+
const shortId = this._idToShortId.get(id);
|
|
23231
|
+
if (shortId == null) {
|
|
23232
|
+
throw new Error(`MiniSearch: cannot remove document with ID ${id}: it is not in the index`);
|
|
23233
|
+
}
|
|
23234
|
+
for (const field of fields) {
|
|
23235
|
+
const fieldValue = extractField(document, field);
|
|
23236
|
+
if (fieldValue == null)
|
|
23237
|
+
continue;
|
|
23238
|
+
const tokens = tokenize(stringifyField(fieldValue, field), field);
|
|
23239
|
+
const fieldId = this._fieldIds[field];
|
|
23240
|
+
const uniqueTerms = new Set(tokens).size;
|
|
23241
|
+
this.removeFieldLength(shortId, fieldId, this._documentCount, uniqueTerms);
|
|
23242
|
+
for (const term of tokens) {
|
|
23243
|
+
const processedTerm = processTerm(term, field);
|
|
23244
|
+
if (Array.isArray(processedTerm)) {
|
|
23245
|
+
for (const t of processedTerm) {
|
|
23246
|
+
this.removeTerm(fieldId, shortId, t);
|
|
23247
|
+
}
|
|
23248
|
+
} else if (processedTerm) {
|
|
23249
|
+
this.removeTerm(fieldId, shortId, processedTerm);
|
|
23250
|
+
}
|
|
23251
|
+
}
|
|
23252
|
+
}
|
|
23253
|
+
this._storedFields.delete(shortId);
|
|
23254
|
+
this._documentIds.delete(shortId);
|
|
23255
|
+
this._idToShortId.delete(id);
|
|
23256
|
+
this._fieldLength.delete(shortId);
|
|
23257
|
+
this._documentCount -= 1;
|
|
23258
|
+
}
|
|
23259
|
+
removeAll(documents) {
|
|
23260
|
+
if (documents) {
|
|
23261
|
+
for (const document of documents)
|
|
23262
|
+
this.remove(document);
|
|
23263
|
+
} else if (arguments.length > 0) {
|
|
23264
|
+
throw new Error("Expected documents to be present. Omit the argument to remove all documents.");
|
|
23265
|
+
} else {
|
|
23266
|
+
this._index = new SearchableMap;
|
|
23267
|
+
this._documentCount = 0;
|
|
23268
|
+
this._documentIds = new Map;
|
|
23269
|
+
this._idToShortId = new Map;
|
|
23270
|
+
this._fieldLength = new Map;
|
|
23271
|
+
this._avgFieldLength = [];
|
|
23272
|
+
this._storedFields = new Map;
|
|
23273
|
+
this._nextId = 0;
|
|
23274
|
+
}
|
|
23275
|
+
}
|
|
23276
|
+
discard(id) {
|
|
23277
|
+
const shortId = this._idToShortId.get(id);
|
|
23278
|
+
if (shortId == null) {
|
|
23279
|
+
throw new Error(`MiniSearch: cannot discard document with ID ${id}: it is not in the index`);
|
|
23280
|
+
}
|
|
23281
|
+
this._idToShortId.delete(id);
|
|
23282
|
+
this._documentIds.delete(shortId);
|
|
23283
|
+
this._storedFields.delete(shortId);
|
|
23284
|
+
(this._fieldLength.get(shortId) || []).forEach((fieldLength, fieldId) => {
|
|
23285
|
+
this.removeFieldLength(shortId, fieldId, this._documentCount, fieldLength);
|
|
23286
|
+
});
|
|
23287
|
+
this._fieldLength.delete(shortId);
|
|
23288
|
+
this._documentCount -= 1;
|
|
23289
|
+
this._dirtCount += 1;
|
|
23290
|
+
this.maybeAutoVacuum();
|
|
23291
|
+
}
|
|
23292
|
+
maybeAutoVacuum() {
|
|
23293
|
+
if (this._options.autoVacuum === false) {
|
|
23294
|
+
return;
|
|
23295
|
+
}
|
|
23296
|
+
const { minDirtFactor, minDirtCount, batchSize, batchWait } = this._options.autoVacuum;
|
|
23297
|
+
this.conditionalVacuum({ batchSize, batchWait }, { minDirtCount, minDirtFactor });
|
|
23298
|
+
}
|
|
23299
|
+
discardAll(ids) {
|
|
23300
|
+
const autoVacuum = this._options.autoVacuum;
|
|
23301
|
+
try {
|
|
23302
|
+
this._options.autoVacuum = false;
|
|
23303
|
+
for (const id of ids) {
|
|
23304
|
+
this.discard(id);
|
|
23305
|
+
}
|
|
23306
|
+
} finally {
|
|
23307
|
+
this._options.autoVacuum = autoVacuum;
|
|
23308
|
+
}
|
|
23309
|
+
this.maybeAutoVacuum();
|
|
23310
|
+
}
|
|
23311
|
+
replace(updatedDocument) {
|
|
23312
|
+
const { idField, extractField } = this._options;
|
|
23313
|
+
const id = extractField(updatedDocument, idField);
|
|
23314
|
+
this.discard(id);
|
|
23315
|
+
this.add(updatedDocument);
|
|
23316
|
+
}
|
|
23317
|
+
vacuum(options = {}) {
|
|
23318
|
+
return this.conditionalVacuum(options);
|
|
23319
|
+
}
|
|
23320
|
+
conditionalVacuum(options, conditions) {
|
|
23321
|
+
if (this._currentVacuum) {
|
|
23322
|
+
this._enqueuedVacuumConditions = this._enqueuedVacuumConditions && conditions;
|
|
23323
|
+
if (this._enqueuedVacuum != null) {
|
|
23324
|
+
return this._enqueuedVacuum;
|
|
23325
|
+
}
|
|
23326
|
+
this._enqueuedVacuum = this._currentVacuum.then(() => {
|
|
23327
|
+
const conditions = this._enqueuedVacuumConditions;
|
|
23328
|
+
this._enqueuedVacuumConditions = defaultVacuumConditions;
|
|
23329
|
+
return this.performVacuuming(options, conditions);
|
|
23330
|
+
});
|
|
23331
|
+
return this._enqueuedVacuum;
|
|
23332
|
+
}
|
|
23333
|
+
if (this.vacuumConditionsMet(conditions) === false) {
|
|
23334
|
+
return Promise.resolve();
|
|
23335
|
+
}
|
|
23336
|
+
this._currentVacuum = this.performVacuuming(options);
|
|
23337
|
+
return this._currentVacuum;
|
|
23338
|
+
}
|
|
23339
|
+
async performVacuuming(options, conditions) {
|
|
23340
|
+
const initialDirtCount = this._dirtCount;
|
|
23341
|
+
if (this.vacuumConditionsMet(conditions)) {
|
|
23342
|
+
const batchSize = options.batchSize || defaultVacuumOptions.batchSize;
|
|
23343
|
+
const batchWait = options.batchWait || defaultVacuumOptions.batchWait;
|
|
23344
|
+
let i = 1;
|
|
23345
|
+
for (const [term, fieldsData] of this._index) {
|
|
23346
|
+
for (const [fieldId, fieldIndex] of fieldsData) {
|
|
23347
|
+
for (const [shortId] of fieldIndex) {
|
|
23348
|
+
if (this._documentIds.has(shortId)) {
|
|
23349
|
+
continue;
|
|
23350
|
+
}
|
|
23351
|
+
if (fieldIndex.size <= 1) {
|
|
23352
|
+
fieldsData.delete(fieldId);
|
|
23353
|
+
} else {
|
|
23354
|
+
fieldIndex.delete(shortId);
|
|
23355
|
+
}
|
|
23356
|
+
}
|
|
23357
|
+
}
|
|
23358
|
+
if (this._index.get(term).size === 0) {
|
|
23359
|
+
this._index.delete(term);
|
|
23360
|
+
}
|
|
23361
|
+
if (i % batchSize === 0) {
|
|
23362
|
+
await new Promise((resolve) => setTimeout(resolve, batchWait));
|
|
23363
|
+
}
|
|
23364
|
+
i += 1;
|
|
23365
|
+
}
|
|
23366
|
+
this._dirtCount -= initialDirtCount;
|
|
23367
|
+
}
|
|
23368
|
+
await null;
|
|
23369
|
+
this._currentVacuum = this._enqueuedVacuum;
|
|
23370
|
+
this._enqueuedVacuum = null;
|
|
23371
|
+
}
|
|
23372
|
+
vacuumConditionsMet(conditions) {
|
|
23373
|
+
if (conditions == null) {
|
|
23374
|
+
return true;
|
|
23375
|
+
}
|
|
23376
|
+
let { minDirtCount, minDirtFactor } = conditions;
|
|
23377
|
+
minDirtCount = minDirtCount || defaultAutoVacuumOptions.minDirtCount;
|
|
23378
|
+
minDirtFactor = minDirtFactor || defaultAutoVacuumOptions.minDirtFactor;
|
|
23379
|
+
return this.dirtCount >= minDirtCount && this.dirtFactor >= minDirtFactor;
|
|
23380
|
+
}
|
|
23381
|
+
get isVacuuming() {
|
|
23382
|
+
return this._currentVacuum != null;
|
|
23383
|
+
}
|
|
23384
|
+
get dirtCount() {
|
|
23385
|
+
return this._dirtCount;
|
|
23386
|
+
}
|
|
23387
|
+
get dirtFactor() {
|
|
23388
|
+
return this._dirtCount / (1 + this._documentCount + this._dirtCount);
|
|
23389
|
+
}
|
|
23390
|
+
has(id) {
|
|
23391
|
+
return this._idToShortId.has(id);
|
|
23392
|
+
}
|
|
23393
|
+
getStoredFields(id) {
|
|
23394
|
+
const shortId = this._idToShortId.get(id);
|
|
23395
|
+
if (shortId == null) {
|
|
23396
|
+
return;
|
|
23397
|
+
}
|
|
23398
|
+
return this._storedFields.get(shortId);
|
|
23399
|
+
}
|
|
23400
|
+
search(query, searchOptions = {}) {
|
|
23401
|
+
const { searchOptions: globalSearchOptions } = this._options;
|
|
23402
|
+
const searchOptionsWithDefaults = { ...globalSearchOptions, ...searchOptions };
|
|
23403
|
+
const rawResults = this.executeQuery(query, searchOptions);
|
|
23404
|
+
const results = [];
|
|
23405
|
+
for (const [docId, { score, terms, match }] of rawResults) {
|
|
23406
|
+
const quality = terms.length || 1;
|
|
23407
|
+
const result = {
|
|
23408
|
+
id: this._documentIds.get(docId),
|
|
23409
|
+
score: score * quality,
|
|
23410
|
+
terms: Object.keys(match),
|
|
23411
|
+
queryTerms: terms,
|
|
23412
|
+
match
|
|
23413
|
+
};
|
|
23414
|
+
Object.assign(result, this._storedFields.get(docId));
|
|
23415
|
+
if (searchOptionsWithDefaults.filter == null || searchOptionsWithDefaults.filter(result)) {
|
|
23416
|
+
results.push(result);
|
|
23417
|
+
}
|
|
23418
|
+
}
|
|
23419
|
+
if (query === MiniSearch.wildcard && searchOptionsWithDefaults.boostDocument == null) {
|
|
23420
|
+
return results;
|
|
23421
|
+
}
|
|
23422
|
+
results.sort(byScore);
|
|
23423
|
+
return results;
|
|
23424
|
+
}
|
|
23425
|
+
autoSuggest(queryString, options = {}) {
|
|
23426
|
+
options = { ...this._options.autoSuggestOptions, ...options };
|
|
23427
|
+
const suggestions = new Map;
|
|
23428
|
+
for (const { score, terms } of this.search(queryString, options)) {
|
|
23429
|
+
const phrase = terms.join(" ");
|
|
23430
|
+
const suggestion = suggestions.get(phrase);
|
|
23431
|
+
if (suggestion != null) {
|
|
23432
|
+
suggestion.score += score;
|
|
23433
|
+
suggestion.count += 1;
|
|
23434
|
+
} else {
|
|
23435
|
+
suggestions.set(phrase, { score, terms, count: 1 });
|
|
23436
|
+
}
|
|
23437
|
+
}
|
|
23438
|
+
const results = [];
|
|
23439
|
+
for (const [suggestion, { score, terms, count }] of suggestions) {
|
|
23440
|
+
results.push({ suggestion, terms, score: score / count });
|
|
23441
|
+
}
|
|
23442
|
+
results.sort(byScore);
|
|
23443
|
+
return results;
|
|
23444
|
+
}
|
|
23445
|
+
get documentCount() {
|
|
23446
|
+
return this._documentCount;
|
|
23447
|
+
}
|
|
23448
|
+
get termCount() {
|
|
23449
|
+
return this._index.size;
|
|
23450
|
+
}
|
|
23451
|
+
static loadJSON(json, options) {
|
|
23452
|
+
if (options == null) {
|
|
23453
|
+
throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index");
|
|
23454
|
+
}
|
|
23455
|
+
return this.loadJS(JSON.parse(json), options);
|
|
23456
|
+
}
|
|
23457
|
+
static async loadJSONAsync(json, options) {
|
|
23458
|
+
if (options == null) {
|
|
23459
|
+
throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index");
|
|
23460
|
+
}
|
|
23461
|
+
return this.loadJSAsync(JSON.parse(json), options);
|
|
23462
|
+
}
|
|
23463
|
+
static getDefault(optionName) {
|
|
23464
|
+
if (defaultOptions.hasOwnProperty(optionName)) {
|
|
23465
|
+
return getOwnProperty(defaultOptions, optionName);
|
|
23466
|
+
} else {
|
|
23467
|
+
throw new Error(`MiniSearch: unknown option "${optionName}"`);
|
|
23468
|
+
}
|
|
23469
|
+
}
|
|
23470
|
+
static loadJS(js, options) {
|
|
23471
|
+
const { index, documentIds, fieldLength, storedFields, serializationVersion } = js;
|
|
23472
|
+
const miniSearch = this.instantiateMiniSearch(js, options);
|
|
23473
|
+
miniSearch._documentIds = objectToNumericMap(documentIds);
|
|
23474
|
+
miniSearch._fieldLength = objectToNumericMap(fieldLength);
|
|
23475
|
+
miniSearch._storedFields = objectToNumericMap(storedFields);
|
|
23476
|
+
for (const [shortId, id] of miniSearch._documentIds) {
|
|
23477
|
+
miniSearch._idToShortId.set(id, shortId);
|
|
23478
|
+
}
|
|
23479
|
+
for (const [term, data] of index) {
|
|
23480
|
+
const dataMap = new Map;
|
|
23481
|
+
for (const fieldId of Object.keys(data)) {
|
|
23482
|
+
let indexEntry = data[fieldId];
|
|
23483
|
+
if (serializationVersion === 1) {
|
|
23484
|
+
indexEntry = indexEntry.ds;
|
|
23485
|
+
}
|
|
23486
|
+
dataMap.set(parseInt(fieldId, 10), objectToNumericMap(indexEntry));
|
|
23487
|
+
}
|
|
23488
|
+
miniSearch._index.set(term, dataMap);
|
|
23489
|
+
}
|
|
23490
|
+
return miniSearch;
|
|
23491
|
+
}
|
|
23492
|
+
static async loadJSAsync(js, options) {
|
|
23493
|
+
const { index, documentIds, fieldLength, storedFields, serializationVersion } = js;
|
|
23494
|
+
const miniSearch = this.instantiateMiniSearch(js, options);
|
|
23495
|
+
miniSearch._documentIds = await objectToNumericMapAsync(documentIds);
|
|
23496
|
+
miniSearch._fieldLength = await objectToNumericMapAsync(fieldLength);
|
|
23497
|
+
miniSearch._storedFields = await objectToNumericMapAsync(storedFields);
|
|
23498
|
+
for (const [shortId, id] of miniSearch._documentIds) {
|
|
23499
|
+
miniSearch._idToShortId.set(id, shortId);
|
|
23500
|
+
}
|
|
23501
|
+
let count = 0;
|
|
23502
|
+
for (const [term, data] of index) {
|
|
23503
|
+
const dataMap = new Map;
|
|
23504
|
+
for (const fieldId of Object.keys(data)) {
|
|
23505
|
+
let indexEntry = data[fieldId];
|
|
23506
|
+
if (serializationVersion === 1) {
|
|
23507
|
+
indexEntry = indexEntry.ds;
|
|
23508
|
+
}
|
|
23509
|
+
dataMap.set(parseInt(fieldId, 10), await objectToNumericMapAsync(indexEntry));
|
|
23510
|
+
}
|
|
23511
|
+
if (++count % 1000 === 0)
|
|
23512
|
+
await wait(0);
|
|
23513
|
+
miniSearch._index.set(term, dataMap);
|
|
23514
|
+
}
|
|
23515
|
+
return miniSearch;
|
|
23516
|
+
}
|
|
23517
|
+
static instantiateMiniSearch(js, options) {
|
|
23518
|
+
const { documentCount, nextId, fieldIds, averageFieldLength, dirtCount, serializationVersion } = js;
|
|
23519
|
+
if (serializationVersion !== 1 && serializationVersion !== 2) {
|
|
23520
|
+
throw new Error("MiniSearch: cannot deserialize an index created with an incompatible version");
|
|
23521
|
+
}
|
|
23522
|
+
const miniSearch = new MiniSearch(options);
|
|
23523
|
+
miniSearch._documentCount = documentCount;
|
|
23524
|
+
miniSearch._nextId = nextId;
|
|
23525
|
+
miniSearch._idToShortId = new Map;
|
|
23526
|
+
miniSearch._fieldIds = fieldIds;
|
|
23527
|
+
miniSearch._avgFieldLength = averageFieldLength;
|
|
23528
|
+
miniSearch._dirtCount = dirtCount || 0;
|
|
23529
|
+
miniSearch._index = new SearchableMap;
|
|
23530
|
+
return miniSearch;
|
|
23531
|
+
}
|
|
23532
|
+
executeQuery(query, searchOptions = {}) {
|
|
23533
|
+
if (query === MiniSearch.wildcard) {
|
|
23534
|
+
return this.executeWildcardQuery(searchOptions);
|
|
23535
|
+
}
|
|
23536
|
+
if (typeof query !== "string") {
|
|
23537
|
+
const options = { ...searchOptions, ...query, queries: undefined };
|
|
23538
|
+
const results = query.queries.map((subquery) => this.executeQuery(subquery, options));
|
|
23539
|
+
return this.combineResults(results, options.combineWith);
|
|
23540
|
+
}
|
|
23541
|
+
const { tokenize, processTerm, searchOptions: globalSearchOptions } = this._options;
|
|
23542
|
+
const options = { tokenize, processTerm, ...globalSearchOptions, ...searchOptions };
|
|
23543
|
+
const { tokenize: searchTokenize, processTerm: searchProcessTerm } = options;
|
|
23544
|
+
const terms = searchTokenize(query).flatMap((term) => searchProcessTerm(term)).filter((term) => !!term);
|
|
23545
|
+
const queries = terms.map(termToQuerySpec(options));
|
|
23546
|
+
const results = queries.map((query) => this.executeQuerySpec(query, options));
|
|
23547
|
+
return this.combineResults(results, options.combineWith);
|
|
23548
|
+
}
|
|
23549
|
+
executeQuerySpec(query, searchOptions) {
|
|
23550
|
+
const options = { ...this._options.searchOptions, ...searchOptions };
|
|
23551
|
+
const boosts = (options.fields || this._options.fields).reduce((boosts, field) => ({ ...boosts, [field]: getOwnProperty(options.boost, field) || 1 }), {});
|
|
23552
|
+
const { boostDocument, weights, maxFuzzy, bm25: bm25params } = options;
|
|
23553
|
+
const { fuzzy: fuzzyWeight, prefix: prefixWeight } = { ...defaultSearchOptions.weights, ...weights };
|
|
23554
|
+
const data = this._index.get(query.term);
|
|
23555
|
+
const results = this.termResults(query.term, query.term, 1, query.termBoost, data, boosts, boostDocument, bm25params);
|
|
23556
|
+
let prefixMatches;
|
|
23557
|
+
let fuzzyMatches;
|
|
23558
|
+
if (query.prefix) {
|
|
23559
|
+
prefixMatches = this._index.atPrefix(query.term);
|
|
23560
|
+
}
|
|
23561
|
+
if (query.fuzzy) {
|
|
23562
|
+
const fuzzy = query.fuzzy === true ? 0.2 : query.fuzzy;
|
|
23563
|
+
const maxDistance = fuzzy < 1 ? Math.min(maxFuzzy, Math.round(query.term.length * fuzzy)) : fuzzy;
|
|
23564
|
+
if (maxDistance)
|
|
23565
|
+
fuzzyMatches = this._index.fuzzyGet(query.term, maxDistance);
|
|
23566
|
+
}
|
|
23567
|
+
if (prefixMatches) {
|
|
23568
|
+
for (const [term, data] of prefixMatches) {
|
|
23569
|
+
const distance = term.length - query.term.length;
|
|
23570
|
+
if (!distance) {
|
|
23571
|
+
continue;
|
|
23572
|
+
}
|
|
23573
|
+
fuzzyMatches === null || fuzzyMatches === undefined || fuzzyMatches.delete(term);
|
|
23574
|
+
const weight = prefixWeight * term.length / (term.length + 0.3 * distance);
|
|
23575
|
+
this.termResults(query.term, term, weight, query.termBoost, data, boosts, boostDocument, bm25params, results);
|
|
23576
|
+
}
|
|
23577
|
+
}
|
|
23578
|
+
if (fuzzyMatches) {
|
|
23579
|
+
for (const term of fuzzyMatches.keys()) {
|
|
23580
|
+
const [data, distance] = fuzzyMatches.get(term);
|
|
23581
|
+
if (!distance) {
|
|
23582
|
+
continue;
|
|
23583
|
+
}
|
|
23584
|
+
const weight = fuzzyWeight * term.length / (term.length + distance);
|
|
23585
|
+
this.termResults(query.term, term, weight, query.termBoost, data, boosts, boostDocument, bm25params, results);
|
|
23586
|
+
}
|
|
23587
|
+
}
|
|
23588
|
+
return results;
|
|
23589
|
+
}
|
|
23590
|
+
executeWildcardQuery(searchOptions) {
|
|
23591
|
+
const results = new Map;
|
|
23592
|
+
const options = { ...this._options.searchOptions, ...searchOptions };
|
|
23593
|
+
for (const [shortId, id] of this._documentIds) {
|
|
23594
|
+
const score = options.boostDocument ? options.boostDocument(id, "", this._storedFields.get(shortId)) : 1;
|
|
23595
|
+
results.set(shortId, {
|
|
23596
|
+
score,
|
|
23597
|
+
terms: [],
|
|
23598
|
+
match: {}
|
|
23599
|
+
});
|
|
23600
|
+
}
|
|
23601
|
+
return results;
|
|
23602
|
+
}
|
|
23603
|
+
combineResults(results, combineWith = OR) {
|
|
23604
|
+
if (results.length === 0) {
|
|
23605
|
+
return new Map;
|
|
23606
|
+
}
|
|
23607
|
+
const operator = combineWith.toLowerCase();
|
|
23608
|
+
const combinator = combinators[operator];
|
|
23609
|
+
if (!combinator) {
|
|
23610
|
+
throw new Error(`Invalid combination operator: ${combineWith}`);
|
|
23611
|
+
}
|
|
23612
|
+
return results.reduce(combinator) || new Map;
|
|
23613
|
+
}
|
|
23614
|
+
toJSON() {
|
|
23615
|
+
const index = [];
|
|
23616
|
+
for (const [term, fieldIndex] of this._index) {
|
|
23617
|
+
const data = {};
|
|
23618
|
+
for (const [fieldId, freqs] of fieldIndex) {
|
|
23619
|
+
data[fieldId] = Object.fromEntries(freqs);
|
|
23620
|
+
}
|
|
23621
|
+
index.push([term, data]);
|
|
23622
|
+
}
|
|
23623
|
+
return {
|
|
23624
|
+
documentCount: this._documentCount,
|
|
23625
|
+
nextId: this._nextId,
|
|
23626
|
+
documentIds: Object.fromEntries(this._documentIds),
|
|
23627
|
+
fieldIds: this._fieldIds,
|
|
23628
|
+
fieldLength: Object.fromEntries(this._fieldLength),
|
|
23629
|
+
averageFieldLength: this._avgFieldLength,
|
|
23630
|
+
storedFields: Object.fromEntries(this._storedFields),
|
|
23631
|
+
dirtCount: this._dirtCount,
|
|
23632
|
+
index,
|
|
23633
|
+
serializationVersion: 2
|
|
23634
|
+
};
|
|
23635
|
+
}
|
|
23636
|
+
termResults(sourceTerm, derivedTerm, termWeight, termBoost, fieldTermData, fieldBoosts, boostDocumentFn, bm25params, results = new Map) {
|
|
23637
|
+
if (fieldTermData == null)
|
|
23638
|
+
return results;
|
|
23639
|
+
for (const field of Object.keys(fieldBoosts)) {
|
|
23640
|
+
const fieldBoost = fieldBoosts[field];
|
|
23641
|
+
const fieldId = this._fieldIds[field];
|
|
23642
|
+
const fieldTermFreqs = fieldTermData.get(fieldId);
|
|
23643
|
+
if (fieldTermFreqs == null)
|
|
23644
|
+
continue;
|
|
23645
|
+
let matchingFields = fieldTermFreqs.size;
|
|
23646
|
+
const avgFieldLength = this._avgFieldLength[fieldId];
|
|
23647
|
+
for (const docId of fieldTermFreqs.keys()) {
|
|
23648
|
+
if (!this._documentIds.has(docId)) {
|
|
23649
|
+
this.removeTerm(fieldId, docId, derivedTerm);
|
|
23650
|
+
matchingFields -= 1;
|
|
23651
|
+
continue;
|
|
23652
|
+
}
|
|
23653
|
+
const docBoost = boostDocumentFn ? boostDocumentFn(this._documentIds.get(docId), derivedTerm, this._storedFields.get(docId)) : 1;
|
|
23654
|
+
if (!docBoost)
|
|
23655
|
+
continue;
|
|
23656
|
+
const termFreq = fieldTermFreqs.get(docId);
|
|
23657
|
+
const fieldLength = this._fieldLength.get(docId)[fieldId];
|
|
23658
|
+
const rawScore = calcBM25Score(termFreq, matchingFields, this._documentCount, fieldLength, avgFieldLength, bm25params);
|
|
23659
|
+
const weightedScore = termWeight * termBoost * fieldBoost * docBoost * rawScore;
|
|
23660
|
+
const result = results.get(docId);
|
|
23661
|
+
if (result) {
|
|
23662
|
+
result.score += weightedScore;
|
|
23663
|
+
assignUniqueTerm(result.terms, sourceTerm);
|
|
23664
|
+
const match = getOwnProperty(result.match, derivedTerm);
|
|
23665
|
+
if (match) {
|
|
23666
|
+
match.push(field);
|
|
23667
|
+
} else {
|
|
23668
|
+
result.match[derivedTerm] = [field];
|
|
23669
|
+
}
|
|
23670
|
+
} else {
|
|
23671
|
+
results.set(docId, {
|
|
23672
|
+
score: weightedScore,
|
|
23673
|
+
terms: [sourceTerm],
|
|
23674
|
+
match: { [derivedTerm]: [field] }
|
|
23675
|
+
});
|
|
23676
|
+
}
|
|
23677
|
+
}
|
|
23678
|
+
}
|
|
23679
|
+
return results;
|
|
23680
|
+
}
|
|
23681
|
+
addTerm(fieldId, documentId, term) {
|
|
23682
|
+
const indexData = this._index.fetch(term, createMap);
|
|
23683
|
+
let fieldIndex = indexData.get(fieldId);
|
|
23684
|
+
if (fieldIndex == null) {
|
|
23685
|
+
fieldIndex = new Map;
|
|
23686
|
+
fieldIndex.set(documentId, 1);
|
|
23687
|
+
indexData.set(fieldId, fieldIndex);
|
|
23688
|
+
} else {
|
|
23689
|
+
const docs = fieldIndex.get(documentId);
|
|
23690
|
+
fieldIndex.set(documentId, (docs || 0) + 1);
|
|
23691
|
+
}
|
|
23692
|
+
}
|
|
23693
|
+
removeTerm(fieldId, documentId, term) {
|
|
23694
|
+
if (!this._index.has(term)) {
|
|
23695
|
+
this.warnDocumentChanged(documentId, fieldId, term);
|
|
23696
|
+
return;
|
|
23697
|
+
}
|
|
23698
|
+
const indexData = this._index.fetch(term, createMap);
|
|
23699
|
+
const fieldIndex = indexData.get(fieldId);
|
|
23700
|
+
if (fieldIndex == null || fieldIndex.get(documentId) == null) {
|
|
23701
|
+
this.warnDocumentChanged(documentId, fieldId, term);
|
|
23702
|
+
} else if (fieldIndex.get(documentId) <= 1) {
|
|
23703
|
+
if (fieldIndex.size <= 1) {
|
|
23704
|
+
indexData.delete(fieldId);
|
|
23705
|
+
} else {
|
|
23706
|
+
fieldIndex.delete(documentId);
|
|
23707
|
+
}
|
|
23708
|
+
} else {
|
|
23709
|
+
fieldIndex.set(documentId, fieldIndex.get(documentId) - 1);
|
|
23710
|
+
}
|
|
23711
|
+
if (this._index.get(term).size === 0) {
|
|
23712
|
+
this._index.delete(term);
|
|
23713
|
+
}
|
|
23714
|
+
}
|
|
23715
|
+
warnDocumentChanged(shortDocumentId, fieldId, term) {
|
|
23716
|
+
for (const fieldName of Object.keys(this._fieldIds)) {
|
|
23717
|
+
if (this._fieldIds[fieldName] === fieldId) {
|
|
23718
|
+
this._options.logger("warn", `MiniSearch: document with ID ${this._documentIds.get(shortDocumentId)} has changed before removal: term "${term}" was not present in field "${fieldName}". Removing a document after it has changed can corrupt the index!`, "version_conflict");
|
|
23719
|
+
return;
|
|
23720
|
+
}
|
|
23721
|
+
}
|
|
23722
|
+
}
|
|
23723
|
+
addDocumentId(documentId) {
|
|
23724
|
+
const shortDocumentId = this._nextId;
|
|
23725
|
+
this._idToShortId.set(documentId, shortDocumentId);
|
|
23726
|
+
this._documentIds.set(shortDocumentId, documentId);
|
|
23727
|
+
this._documentCount += 1;
|
|
23728
|
+
this._nextId += 1;
|
|
23729
|
+
return shortDocumentId;
|
|
23730
|
+
}
|
|
23731
|
+
addFields(fields) {
|
|
23732
|
+
for (let i = 0;i < fields.length; i++) {
|
|
23733
|
+
this._fieldIds[fields[i]] = i;
|
|
23734
|
+
}
|
|
23735
|
+
}
|
|
23736
|
+
addFieldLength(documentId, fieldId, count, length) {
|
|
23737
|
+
let fieldLengths = this._fieldLength.get(documentId);
|
|
23738
|
+
if (fieldLengths == null)
|
|
23739
|
+
this._fieldLength.set(documentId, fieldLengths = []);
|
|
23740
|
+
fieldLengths[fieldId] = length;
|
|
23741
|
+
const averageFieldLength = this._avgFieldLength[fieldId] || 0;
|
|
23742
|
+
const totalFieldLength = averageFieldLength * count + length;
|
|
23743
|
+
this._avgFieldLength[fieldId] = totalFieldLength / (count + 1);
|
|
23744
|
+
}
|
|
23745
|
+
removeFieldLength(documentId, fieldId, count, length) {
|
|
23746
|
+
if (count === 1) {
|
|
23747
|
+
this._avgFieldLength[fieldId] = 0;
|
|
23748
|
+
return;
|
|
23749
|
+
}
|
|
23750
|
+
const totalFieldLength = this._avgFieldLength[fieldId] * count - length;
|
|
23751
|
+
this._avgFieldLength[fieldId] = totalFieldLength / (count - 1);
|
|
23752
|
+
}
|
|
23753
|
+
saveStoredFields(documentId, doc) {
|
|
23754
|
+
const { storeFields, extractField } = this._options;
|
|
23755
|
+
if (storeFields == null || storeFields.length === 0) {
|
|
23756
|
+
return;
|
|
23757
|
+
}
|
|
23758
|
+
let documentFields = this._storedFields.get(documentId);
|
|
23759
|
+
if (documentFields == null)
|
|
23760
|
+
this._storedFields.set(documentId, documentFields = {});
|
|
23761
|
+
for (const fieldName of storeFields) {
|
|
23762
|
+
const fieldValue = extractField(doc, fieldName);
|
|
23763
|
+
if (fieldValue !== undefined)
|
|
23764
|
+
documentFields[fieldName] = fieldValue;
|
|
23765
|
+
}
|
|
23766
|
+
}
|
|
23767
|
+
}
|
|
23768
|
+
MiniSearch.wildcard = Symbol("*");
|
|
23769
|
+
var getOwnProperty = (object, property) => Object.prototype.hasOwnProperty.call(object, property) ? object[property] : undefined;
|
|
23770
|
+
var combinators = {
|
|
23771
|
+
[OR]: (a, b) => {
|
|
23772
|
+
for (const docId of b.keys()) {
|
|
23773
|
+
const existing = a.get(docId);
|
|
23774
|
+
if (existing == null) {
|
|
23775
|
+
a.set(docId, b.get(docId));
|
|
23776
|
+
} else {
|
|
23777
|
+
const { score, terms, match } = b.get(docId);
|
|
23778
|
+
existing.score = existing.score + score;
|
|
23779
|
+
existing.match = Object.assign(existing.match, match);
|
|
23780
|
+
assignUniqueTerms(existing.terms, terms);
|
|
23781
|
+
}
|
|
23782
|
+
}
|
|
23783
|
+
return a;
|
|
23784
|
+
},
|
|
23785
|
+
[AND]: (a, b) => {
|
|
23786
|
+
const combined = new Map;
|
|
23787
|
+
for (const docId of b.keys()) {
|
|
23788
|
+
const existing = a.get(docId);
|
|
23789
|
+
if (existing == null)
|
|
23790
|
+
continue;
|
|
23791
|
+
const { score, terms, match } = b.get(docId);
|
|
23792
|
+
assignUniqueTerms(existing.terms, terms);
|
|
23793
|
+
combined.set(docId, {
|
|
23794
|
+
score: existing.score + score,
|
|
23795
|
+
terms: existing.terms,
|
|
23796
|
+
match: Object.assign(existing.match, match)
|
|
23797
|
+
});
|
|
23798
|
+
}
|
|
23799
|
+
return combined;
|
|
23800
|
+
},
|
|
23801
|
+
[AND_NOT]: (a, b) => {
|
|
23802
|
+
for (const docId of b.keys())
|
|
23803
|
+
a.delete(docId);
|
|
23804
|
+
return a;
|
|
23805
|
+
}
|
|
23806
|
+
};
|
|
23807
|
+
var defaultBM25params = { k: 1.2, b: 0.7, d: 0.5 };
|
|
23808
|
+
var calcBM25Score = (termFreq, matchingCount, totalCount, fieldLength, avgFieldLength, bm25params) => {
|
|
23809
|
+
const { k, b, d } = bm25params;
|
|
23810
|
+
const invDocFreq = Math.log(1 + (totalCount - matchingCount + 0.5) / (matchingCount + 0.5));
|
|
23811
|
+
return invDocFreq * (d + termFreq * (k + 1) / (termFreq + k * (1 - b + b * fieldLength / avgFieldLength)));
|
|
23812
|
+
};
|
|
23813
|
+
var termToQuerySpec = (options) => (term, i, terms) => {
|
|
23814
|
+
const fuzzy = typeof options.fuzzy === "function" ? options.fuzzy(term, i, terms) : options.fuzzy || false;
|
|
23815
|
+
const prefix = typeof options.prefix === "function" ? options.prefix(term, i, terms) : options.prefix === true;
|
|
23816
|
+
const termBoost = typeof options.boostTerm === "function" ? options.boostTerm(term, i, terms) : 1;
|
|
23817
|
+
return { term, fuzzy, prefix, termBoost };
|
|
23818
|
+
};
|
|
23819
|
+
var defaultOptions = {
|
|
23820
|
+
idField: "id",
|
|
23821
|
+
extractField: (document, fieldName) => document[fieldName],
|
|
23822
|
+
stringifyField: (fieldValue, fieldName) => fieldValue.toString(),
|
|
23823
|
+
tokenize: (text) => text.split(SPACE_OR_PUNCTUATION),
|
|
23824
|
+
processTerm: (term) => term.toLowerCase(),
|
|
23825
|
+
fields: undefined,
|
|
23826
|
+
searchOptions: undefined,
|
|
23827
|
+
storeFields: [],
|
|
23828
|
+
logger: (level, message) => {
|
|
23829
|
+
if (typeof (console === null || console === undefined ? undefined : console[level]) === "function")
|
|
23830
|
+
console[level](message);
|
|
23831
|
+
},
|
|
23832
|
+
autoVacuum: true
|
|
23833
|
+
};
|
|
23834
|
+
var defaultSearchOptions = {
|
|
23835
|
+
combineWith: OR,
|
|
23836
|
+
prefix: false,
|
|
23837
|
+
fuzzy: false,
|
|
23838
|
+
maxFuzzy: 6,
|
|
23839
|
+
boost: {},
|
|
23840
|
+
weights: { fuzzy: 0.45, prefix: 0.375 },
|
|
23841
|
+
bm25: defaultBM25params
|
|
23842
|
+
};
|
|
23843
|
+
var defaultAutoSuggestOptions = {
|
|
23844
|
+
combineWith: AND,
|
|
23845
|
+
prefix: (term, i, terms) => i === terms.length - 1
|
|
23846
|
+
};
|
|
23847
|
+
var defaultVacuumOptions = { batchSize: 1000, batchWait: 10 };
|
|
23848
|
+
var defaultVacuumConditions = { minDirtFactor: 0.1, minDirtCount: 20 };
|
|
23849
|
+
var defaultAutoVacuumOptions = { ...defaultVacuumOptions, ...defaultVacuumConditions };
|
|
23850
|
+
var assignUniqueTerm = (target, term) => {
|
|
23851
|
+
if (!target.includes(term))
|
|
23852
|
+
target.push(term);
|
|
23853
|
+
};
|
|
23854
|
+
var assignUniqueTerms = (target, source) => {
|
|
23855
|
+
for (const term of source) {
|
|
23856
|
+
if (!target.includes(term))
|
|
23857
|
+
target.push(term);
|
|
23858
|
+
}
|
|
23859
|
+
};
|
|
23860
|
+
var byScore = ({ score: a }, { score: b }) => b - a;
|
|
23861
|
+
var createMap = () => new Map;
|
|
23862
|
+
var objectToNumericMap = (object) => {
|
|
23863
|
+
const map = new Map;
|
|
23864
|
+
for (const key of Object.keys(object)) {
|
|
23865
|
+
map.set(parseInt(key, 10), object[key]);
|
|
23866
|
+
}
|
|
23867
|
+
return map;
|
|
23868
|
+
};
|
|
23869
|
+
var objectToNumericMapAsync = async (object) => {
|
|
23870
|
+
const map = new Map;
|
|
23871
|
+
let count = 0;
|
|
23872
|
+
for (const key of Object.keys(object)) {
|
|
23873
|
+
map.set(parseInt(key, 10), object[key]);
|
|
23874
|
+
if (++count % 1000 === 0) {
|
|
23875
|
+
await wait(0);
|
|
23876
|
+
}
|
|
23877
|
+
}
|
|
23878
|
+
return map;
|
|
23879
|
+
};
|
|
23880
|
+
var wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
23881
|
+
var SPACE_OR_PUNCTUATION = /[\n\r\p{Z}\p{P}]+/u;
|
|
23882
|
+
|
|
23883
|
+
// src/commands/search.ts
|
|
23884
|
+
var MAX_RESULTS = 5;
|
|
23885
|
+
var FIELD_BOOST = { command: 8, summary: 5, context: 0.5 };
|
|
23886
|
+
var STOP_WORDS = new Set("a am an and are as at be by can do does for from how i in into is it me my of on or so that the this to what when where which why with you your".split(" "));
|
|
23887
|
+
var MIN_EXPANDED_TERM_LENGTH = 3;
|
|
23888
|
+
var MIN_FUZZY_TERM_LENGTH = 5;
|
|
23889
|
+
var SEARCH_OPTIONS = {
|
|
23890
|
+
boost: FIELD_BOOST,
|
|
23891
|
+
processTerm: (term) => {
|
|
23892
|
+
const lower = term.toLowerCase();
|
|
23893
|
+
return STOP_WORDS.has(lower) ? null : lower;
|
|
23894
|
+
},
|
|
23895
|
+
prefix: (term) => term.length >= MIN_EXPANDED_TERM_LENGTH,
|
|
23896
|
+
fuzzy: (term) => term.length >= MIN_FUZZY_TERM_LENGTH ? 0.2 : false
|
|
23897
|
+
};
|
|
23898
|
+
var TRAILING_PARENTHETICAL = /\s*\([^)]*\)\s*$/;
|
|
23899
|
+
var COLUMNS3 = [
|
|
23900
|
+
{ header: "command", value: (result) => result.command },
|
|
23901
|
+
{ header: "summary", value: (result) => result.summary }
|
|
23902
|
+
];
|
|
23903
|
+
function isHidden(command) {
|
|
23904
|
+
return command._hidden === true;
|
|
23905
|
+
}
|
|
23906
|
+
function visibleSubcommands(command) {
|
|
23907
|
+
return command.commands.filter((child) => child.name() !== "help" && !isHidden(child));
|
|
23908
|
+
}
|
|
23909
|
+
function collectDocuments(command, path, ancestors, exclude) {
|
|
23910
|
+
const children = visibleSubcommands(command);
|
|
23911
|
+
if (children.length === 0) {
|
|
23912
|
+
const display = command.description();
|
|
23913
|
+
return [
|
|
23914
|
+
{
|
|
23915
|
+
command: ["sim", ...path].join(" "),
|
|
23916
|
+
display,
|
|
23917
|
+
summary: display.replace(TRAILING_PARENTHETICAL, ""),
|
|
23918
|
+
context: [
|
|
23919
|
+
...ancestors,
|
|
23920
|
+
...command.registeredArguments.map((argument) => `${argument.name()} ${argument.description}`.trim()),
|
|
23921
|
+
...command.options.filter((option) => !option.hidden).map((option) => `${option.long ?? option.short ?? ""} ${option.description}`.trim())
|
|
23922
|
+
].join(" ")
|
|
23923
|
+
}
|
|
23924
|
+
];
|
|
23925
|
+
}
|
|
23926
|
+
const nextAncestors = path.length > 0 ? [...ancestors, command.description()] : ancestors;
|
|
23927
|
+
return children.filter((child) => child !== exclude).flatMap((child) => collectDocuments(child, [...path, child.name()], nextAncestors, exclude));
|
|
23928
|
+
}
|
|
23929
|
+
function searchCommands(program, query, exclude) {
|
|
23930
|
+
const index = new MiniSearch({
|
|
23931
|
+
fields: ["command", "summary", "context"],
|
|
23932
|
+
storeFields: ["command", "display"],
|
|
23933
|
+
idField: "command"
|
|
23934
|
+
});
|
|
23935
|
+
index.addAll(collectDocuments(program, [], [], exclude));
|
|
23936
|
+
return index.search(query, SEARCH_OPTIONS).slice(0, MAX_RESULTS).map((hit) => ({ command: hit.command, summary: hit.display }));
|
|
23937
|
+
}
|
|
23938
|
+
function searchCommand() {
|
|
23939
|
+
return new Command("search").description("Find the command for a task, described in plain words").argument("<query...>", 'What you want to do, e.g. "cancel a workflow run"').addHelpText("after", `
|
|
23940
|
+
Ranks the commands this CLI ships, locally; your query is never sent anywhere.
|
|
23941
|
+
Returns the ${MAX_RESULTS} best matches. Run \`<command> --help\` on one for its flags.
|
|
23942
|
+
|
|
23943
|
+
Examples:
|
|
23944
|
+
$ sim cli search "cancel a running workflow"
|
|
23945
|
+
$ sim cli search list table rows`).action((words, _options, command) => {
|
|
23946
|
+
let program = command;
|
|
23947
|
+
while (program.parent)
|
|
23948
|
+
program = program.parent;
|
|
23949
|
+
const results = searchCommands(program, words.join(" "), command);
|
|
23950
|
+
printList(profileFrom(command).output, results, COLUMNS3);
|
|
23951
|
+
});
|
|
23952
|
+
}
|
|
23953
|
+
function cliCommand() {
|
|
23954
|
+
return new Command("cli").description("Discover commands in this CLI").addCommand(searchCommand());
|
|
23955
|
+
}
|
|
23956
|
+
|
|
22812
23957
|
// src/terminal/secret-input.ts
|
|
22813
23958
|
import { emitKeypressEvents } from "node:readline";
|
|
22814
23959
|
var MAX_SECRET_LENGTH = 65536;
|
|
@@ -22970,7 +24115,7 @@ function attachSecretCommands(program) {
|
|
|
22970
24115
|
if (!secrets)
|
|
22971
24116
|
throw new Error("The generated secrets command group is missing");
|
|
22972
24117
|
const redactionSpellings = new Set;
|
|
22973
|
-
secrets.command("set").argument("<name>", "Secret name, as referenced in workflows").description(describeOperation(V2_OPERATIONS.setSecret, "Create or replace a named secret")).addOption(new Option("--scope <scope>", "Secret ownership scope (required)").choices([...SECRET_SCOPES]).makeOptionMandatory()).option("--value <value|@file>", "Secret value. Passing it inline exposes it to shell history and process listings; @path reads it from a file and @- from stdin, verbatim — a trailing newline is part of the value, so write the file with printf rather than echo. Prefix a literal leading @ with a second one").option("--description <description>", "What the secret is for, shown to teammates; workspace scope only. Omit to leave an existing description unchanged").option("--unredacted", `${V2_OPERATIONS.setSecret.body.unredacted.describe} Pass --no-unredacted to restore redaction`).option("--no-unredacted", "Send --unredacted as false").on("option:unredacted", () => redactionSpellings.add("--unredacted")).on("option:no-unredacted", () => redactionSpellings.add("--no-unredacted")).action((name, options, command) => setSecret(name, options, command, redactionSpellings));
|
|
24118
|
+
secrets.command("set").argument("<name>", "Secret name, as referenced in workflows").description(describeOperation(V2_OPERATIONS.setSecret, "Create or replace a named secret, such as an API key or environment variable")).addOption(new Option("--scope <scope>", "Secret ownership scope (required)").choices([...SECRET_SCOPES]).makeOptionMandatory()).option("--value <value|@file>", "Secret value. Passing it inline exposes it to shell history and process listings; @path reads it from a file and @- from stdin, verbatim — a trailing newline is part of the value, so write the file with printf rather than echo. Prefix a literal leading @ with a second one").option("--description <description>", "What the secret is for, shown to teammates; workspace scope only. Omit to leave an existing description unchanged").option("--unredacted", `${V2_OPERATIONS.setSecret.body.unredacted.describe} Pass --no-unredacted to restore redaction`).option("--no-unredacted", "Send --unredacted as false").on("option:unredacted", () => redactionSpellings.add("--unredacted")).on("option:no-unredacted", () => redactionSpellings.add("--no-unredacted")).action((name, options, command) => setSecret(name, options, command, redactionSpellings));
|
|
22974
24119
|
}
|
|
22975
24120
|
|
|
22976
24121
|
// src/telemetry/transport.ts
|
|
@@ -23216,19 +24361,28 @@ or custom-tool ID can open with a dash, which reads as a flag; put -- in front
|
|
|
23216
24361
|
of it, as in sim audit-logs get -- -HlDcD1z76nK6R4crsUp0.
|
|
23217
24362
|
|
|
23218
24363
|
Examples:
|
|
24364
|
+
$ sim cli search "cancel a workflow run" Find the command for a task
|
|
23219
24365
|
$ sim login Authorize the default profile
|
|
23220
24366
|
$ sim login --profile dev --endpoint http://localhost:3000
|
|
23221
24367
|
$ sim profile add acme --workspace 7e2d9c14-6b83-4a55-8f01-c4d3e9a76b28
|
|
23222
24368
|
$ sim workflows list
|
|
23223
24369
|
$ sim logs list --level error --limit 20
|
|
23224
|
-
$ sim configure --set-output
|
|
23225
|
-
$ sim --output
|
|
24370
|
+
$ sim configure --set-output table Prefer tables over the JSON default
|
|
24371
|
+
$ sim --output table tables get tbl_9f3c1a05d4b7426e8c2f0917ab35de64
|
|
23226
24372
|
$ sim knowledge search --query "refund policy" --kb 4c1b7f60-2d55-4a3e-9c18-70b6ea2f9d31
|
|
23227
24373
|
$ sim workflows export 3a9e21d8-5f47-4c0b-b2ea-91d7c6034ef8 > wf.json
|
|
23228
24374
|
$ sim workflows import --workflow @wf.json
|
|
23229
24375
|
$ sim knowledge export 4c1b7f60-2d55-4a3e-9c18-70b6ea2f9d31 -o ./kb.simkb.zip
|
|
23230
24376
|
$ sim whoami --profile dev
|
|
23231
24377
|
`;
|
|
24378
|
+
var AGENT_DISCOVERY_NOTE = `=== AGENT COMMAND DISCOVERY ===
|
|
24379
|
+
Do not explore commands by chaining nested --help calls. Instead run:
|
|
24380
|
+
sim cli search "<describe the task you want to accomplish>"
|
|
24381
|
+
It returns the 5 best-matching commands, each with a one-line summary. Pick the
|
|
24382
|
+
best match rather than repeating similar searches, then run
|
|
24383
|
+
\`<command> --help\` for its flags.
|
|
24384
|
+
=== END AGENT COMMAND DISCOVERY ===
|
|
24385
|
+
`;
|
|
23232
24386
|
var ROOT_VALUE_FLAGS = new Set([
|
|
23233
24387
|
"-P",
|
|
23234
24388
|
"--profile",
|
|
@@ -23266,6 +24420,7 @@ function addVersionOption(program) {
|
|
|
23266
24420
|
program.version(cliVersion(), "-V, --version [none]", "output the version number (takes no value)");
|
|
23267
24421
|
}
|
|
23268
24422
|
function buildProgram(options = {}) {
|
|
24423
|
+
const env = options.env ?? process.env;
|
|
23269
24424
|
const program = options.program ?? new Command;
|
|
23270
24425
|
program.name("sim").description(PROGRAM_DESCRIPTION);
|
|
23271
24426
|
if (options.version !== false)
|
|
@@ -23282,6 +24437,7 @@ function buildProgram(options = {}) {
|
|
|
23282
24437
|
const update = updateCommand();
|
|
23283
24438
|
program.addCommand(update);
|
|
23284
24439
|
program.addCommand(telemetryCommand());
|
|
24440
|
+
program.addCommand(cliCommand());
|
|
23285
24441
|
for (const command of buildGeneratedCommands()) {
|
|
23286
24442
|
program.addCommand(command);
|
|
23287
24443
|
}
|
|
@@ -23289,6 +24445,7 @@ function buildProgram(options = {}) {
|
|
|
23289
24445
|
attachProtocolCommands(program);
|
|
23290
24446
|
attachSecretCommands(program);
|
|
23291
24447
|
program.addHelpText("after", options.helpText ?? HELP_EPILOGUE);
|
|
24448
|
+
program.addHelpText("beforeAll", ({ command }) => detectCodingAgent(env) !== undefined && command.commands.length > 0 ? AGENT_DISCOVERY_NOTE : "");
|
|
23292
24449
|
program.hook("preAction", async (_program, command) => {
|
|
23293
24450
|
if (command === update)
|
|
23294
24451
|
return;
|