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/index.js
CHANGED
|
@@ -7736,6 +7736,7 @@ function removeSection(doc, name) {
|
|
|
7736
7736
|
var DEFAULT_PROFILE = "default";
|
|
7737
7737
|
var DEFAULT_ENDPOINT = "https://www.sim.ai";
|
|
7738
7738
|
var OUTPUT_FORMATS = ["table", "json", "yaml", "text"];
|
|
7739
|
+
var DEFAULT_OUTPUT_FORMAT = "json";
|
|
7739
7740
|
var FORBIDDEN_IN_VALUE_GLOBAL = new RegExp(FORBIDDEN_IN_VALUE.source, "g");
|
|
7740
7741
|
function redact(value) {
|
|
7741
7742
|
return value.replace(FORBIDDEN_IN_VALUE_GLOBAL, " ");
|
|
@@ -8086,7 +8087,7 @@ function resolveProfile(overrides = {}) {
|
|
|
8086
8087
|
["flag", overrides.output],
|
|
8087
8088
|
["env", process.env.SIM_OUTPUT],
|
|
8088
8089
|
["config", config.output]
|
|
8089
|
-
],
|
|
8090
|
+
], DEFAULT_OUTPUT_FORMAT, "default");
|
|
8090
8091
|
if (!OUTPUT_FORMATS.includes(output.value)) {
|
|
8091
8092
|
throw new ProfileConfigError(`Unknown output format "${redact(String(output.value))}" from ${output.source}. Use one of: ${OUTPUT_FORMATS.join(", ")}`);
|
|
8092
8093
|
}
|
|
@@ -11916,7 +11917,13 @@ var V2_OPERATIONS = {
|
|
|
11916
11917
|
pathParams: ["runId"],
|
|
11917
11918
|
pathParamDocs: { runId: "Unique workflow run identifier." },
|
|
11918
11919
|
responseMode: "json",
|
|
11919
|
-
summary: "Get Log"
|
|
11920
|
+
summary: "Get Log",
|
|
11921
|
+
query: {
|
|
11922
|
+
includeWorkflowState: {
|
|
11923
|
+
kind: "boolean",
|
|
11924
|
+
describe: "Include the saved workflow snapshot (default: true). Set false to omit block configuration from a log read. Other run fields are unchanged."
|
|
11925
|
+
}
|
|
11926
|
+
}
|
|
11920
11927
|
},
|
|
11921
11928
|
getLogStats: {
|
|
11922
11929
|
method: "GET",
|
|
@@ -17004,7 +17011,7 @@ Waiting for you to approve in the browser…`));
|
|
|
17004
17011
|
}
|
|
17005
17012
|
}
|
|
17006
17013
|
function loginCommand() {
|
|
17007
|
-
return new Command("login").description("
|
|
17014
|
+
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) => {
|
|
17008
17015
|
const profile = profileFrom(command, { allowUnknownProfile: true });
|
|
17009
17016
|
const authProfile = resolveAuthenticationProfileName(profile.name);
|
|
17010
17017
|
if (authProfile !== profile.name) {
|
|
@@ -17338,7 +17345,7 @@ function profileListingContext(command) {
|
|
|
17338
17345
|
throw error;
|
|
17339
17346
|
return {
|
|
17340
17347
|
activeName: named || DEFAULT_PROFILE,
|
|
17341
|
-
output: requested ? requested :
|
|
17348
|
+
output: requested ? requested : DEFAULT_OUTPUT_FORMAT
|
|
17342
17349
|
};
|
|
17343
17350
|
}
|
|
17344
17351
|
}
|
|
@@ -17386,7 +17393,7 @@ function quoteProfileArgument(name) {
|
|
|
17386
17393
|
return `'${redacted.replaceAll("'", "'\\''")}'`;
|
|
17387
17394
|
}
|
|
17388
17395
|
function configureCommand() {
|
|
17389
|
-
return new Command("configure").description("
|
|
17396
|
+
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) => {
|
|
17390
17397
|
const globals = globalsOf(command);
|
|
17391
17398
|
const selectedProfile = globals.profile || process.env.SIM_PROFILE;
|
|
17392
17399
|
const profileArg = selectedProfile ? ` --profile ${quoteProfileArgument(selectedProfile)}` : "";
|
|
@@ -17542,7 +17549,7 @@ var CLI_CONTRACT = {
|
|
|
17542
17549
|
getBillingStatus: {
|
|
17543
17550
|
command: "billing status",
|
|
17544
17551
|
allWorkspaces: true,
|
|
17545
|
-
describe: "Show billing status
|
|
17552
|
+
describe: "Show billing status, credits spent this period, and storage used (credits and storage require an OAuth login or personal API key)",
|
|
17546
17553
|
fields: [
|
|
17547
17554
|
{ header: "plan" },
|
|
17548
17555
|
{ header: "status" },
|
|
@@ -17665,6 +17672,7 @@ var CLI_CONTRACT = {
|
|
|
17665
17672
|
confirm: "This archives the knowledge base and every document in it; restore with `knowledge restore`."
|
|
17666
17673
|
},
|
|
17667
17674
|
deleteKnowledgeDocument: {
|
|
17675
|
+
describe: "Delete a document from a knowledge base",
|
|
17668
17676
|
pathArgumentNames: KNOWLEDGE_BASE_PATH_ARGUMENT,
|
|
17669
17677
|
confirm: "This deletes the document and its embeddings."
|
|
17670
17678
|
},
|
|
@@ -17703,6 +17711,7 @@ var CLI_CONTRACT = {
|
|
|
17703
17711
|
]
|
|
17704
17712
|
},
|
|
17705
17713
|
listLogs: {
|
|
17714
|
+
describe: "List run logs, such as failed or errored runs, by workflow, trigger or time",
|
|
17706
17715
|
flags: {
|
|
17707
17716
|
...LOG_LIST_FILTER_FLAGS,
|
|
17708
17717
|
details: {
|
|
@@ -17815,6 +17824,7 @@ var CLI_CONTRACT = {
|
|
|
17815
17824
|
},
|
|
17816
17825
|
applyWorkflowOperations: {
|
|
17817
17826
|
command: "workflows operations apply",
|
|
17827
|
+
describe: "Edit a workflow’s blocks, connections and settings with a batch of operations",
|
|
17818
17828
|
confirm: "This edits the draft graph: the batch adds, edits, or deletes blocks and their edges as written.",
|
|
17819
17829
|
flags: {
|
|
17820
17830
|
operations: { json: true, describe: WORKFLOW_OPERATIONS_HELP },
|
|
@@ -17917,6 +17927,7 @@ var CLI_CONTRACT = {
|
|
|
17917
17927
|
},
|
|
17918
17928
|
queryRows: {
|
|
17919
17929
|
command: "tables rows query",
|
|
17930
|
+
describe: "Query rows with a filter and sort",
|
|
17920
17931
|
flags: {
|
|
17921
17932
|
predicate: { name: "filter", json: true, describe: TABLE_READ_FILTER_HELP },
|
|
17922
17933
|
sort: { json: true, describe: TABLE_SORT_HELP }
|
|
@@ -21316,7 +21327,7 @@ async function downloadToOutput(command, operation, pathParams, options) {
|
|
|
21316
21327
|
});
|
|
21317
21328
|
}
|
|
21318
21329
|
function attachFileGet(files) {
|
|
21319
|
-
files.command("get").argument("<fileId>", "File whose content to read").allowExcessArguments(false).description("
|
|
21330
|
+
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));
|
|
21320
21331
|
}
|
|
21321
21332
|
function attachFileVersionDownload(versions) {
|
|
21322
21333
|
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));
|
|
@@ -21863,7 +21874,7 @@ function inSeconds(ms) {
|
|
|
21863
21874
|
return Math.round(ms / 100) / 10;
|
|
21864
21875
|
}
|
|
21865
21876
|
function attachLogsFollow(logs) {
|
|
21866
|
-
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([
|
|
21877
|
+
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([
|
|
21867
21878
|
...V2_OPERATIONS.listLogs.query.level.values
|
|
21868
21879
|
])).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", `
|
|
21869
21880
|
Each run prints once, when it is first seen, so its status is the status it had
|
|
@@ -22758,6 +22769,1140 @@ function attachProtocolCommands(program) {
|
|
|
22758
22769
|
attachChat(program);
|
|
22759
22770
|
}
|
|
22760
22771
|
|
|
22772
|
+
// ../../node_modules/minisearch/dist/es/index.js
|
|
22773
|
+
var ENTRIES = "ENTRIES";
|
|
22774
|
+
var KEYS = "KEYS";
|
|
22775
|
+
var VALUES = "VALUES";
|
|
22776
|
+
var LEAF = "";
|
|
22777
|
+
|
|
22778
|
+
class TreeIterator {
|
|
22779
|
+
constructor(set, type) {
|
|
22780
|
+
const node = set._tree;
|
|
22781
|
+
const keys = Array.from(node.keys());
|
|
22782
|
+
this.set = set;
|
|
22783
|
+
this._type = type;
|
|
22784
|
+
this._path = keys.length > 0 ? [{ node, keys }] : [];
|
|
22785
|
+
}
|
|
22786
|
+
next() {
|
|
22787
|
+
const value = this.dive();
|
|
22788
|
+
this.backtrack();
|
|
22789
|
+
return value;
|
|
22790
|
+
}
|
|
22791
|
+
dive() {
|
|
22792
|
+
if (this._path.length === 0) {
|
|
22793
|
+
return { done: true, value: undefined };
|
|
22794
|
+
}
|
|
22795
|
+
const { node, keys } = last$1(this._path);
|
|
22796
|
+
if (last$1(keys) === LEAF) {
|
|
22797
|
+
return { done: false, value: this.result() };
|
|
22798
|
+
}
|
|
22799
|
+
const child = node.get(last$1(keys));
|
|
22800
|
+
this._path.push({ node: child, keys: Array.from(child.keys()) });
|
|
22801
|
+
return this.dive();
|
|
22802
|
+
}
|
|
22803
|
+
backtrack() {
|
|
22804
|
+
if (this._path.length === 0) {
|
|
22805
|
+
return;
|
|
22806
|
+
}
|
|
22807
|
+
const keys = last$1(this._path).keys;
|
|
22808
|
+
keys.pop();
|
|
22809
|
+
if (keys.length > 0) {
|
|
22810
|
+
return;
|
|
22811
|
+
}
|
|
22812
|
+
this._path.pop();
|
|
22813
|
+
this.backtrack();
|
|
22814
|
+
}
|
|
22815
|
+
key() {
|
|
22816
|
+
return this.set._prefix + this._path.map(({ keys }) => last$1(keys)).filter((key) => key !== LEAF).join("");
|
|
22817
|
+
}
|
|
22818
|
+
value() {
|
|
22819
|
+
return last$1(this._path).node.get(LEAF);
|
|
22820
|
+
}
|
|
22821
|
+
result() {
|
|
22822
|
+
switch (this._type) {
|
|
22823
|
+
case VALUES:
|
|
22824
|
+
return this.value();
|
|
22825
|
+
case KEYS:
|
|
22826
|
+
return this.key();
|
|
22827
|
+
default:
|
|
22828
|
+
return [this.key(), this.value()];
|
|
22829
|
+
}
|
|
22830
|
+
}
|
|
22831
|
+
[Symbol.iterator]() {
|
|
22832
|
+
return this;
|
|
22833
|
+
}
|
|
22834
|
+
}
|
|
22835
|
+
var last$1 = (array) => {
|
|
22836
|
+
return array[array.length - 1];
|
|
22837
|
+
};
|
|
22838
|
+
var fuzzySearch = (node, query, maxDistance) => {
|
|
22839
|
+
const results = new Map;
|
|
22840
|
+
if (query === undefined)
|
|
22841
|
+
return results;
|
|
22842
|
+
const n = query.length + 1;
|
|
22843
|
+
const m = n + maxDistance;
|
|
22844
|
+
const matrix = new Uint8Array(m * n).fill(maxDistance + 1);
|
|
22845
|
+
for (let j = 0;j < n; ++j)
|
|
22846
|
+
matrix[j] = j;
|
|
22847
|
+
for (let i = 1;i < m; ++i)
|
|
22848
|
+
matrix[i * n] = i;
|
|
22849
|
+
recurse(node, query, maxDistance, results, matrix, 1, n, "");
|
|
22850
|
+
return results;
|
|
22851
|
+
};
|
|
22852
|
+
var recurse = (node, query, maxDistance, results, matrix, m, n, prefix) => {
|
|
22853
|
+
const offset = m * n;
|
|
22854
|
+
key:
|
|
22855
|
+
for (const key of node.keys()) {
|
|
22856
|
+
if (key === LEAF) {
|
|
22857
|
+
const distance = matrix[offset - 1];
|
|
22858
|
+
if (distance <= maxDistance) {
|
|
22859
|
+
results.set(prefix, [node.get(key), distance]);
|
|
22860
|
+
}
|
|
22861
|
+
} else {
|
|
22862
|
+
let i = m;
|
|
22863
|
+
for (let pos = 0;pos < key.length; ++pos, ++i) {
|
|
22864
|
+
const char = key[pos];
|
|
22865
|
+
const thisRowOffset = n * i;
|
|
22866
|
+
const prevRowOffset = thisRowOffset - n;
|
|
22867
|
+
let minDistance = matrix[thisRowOffset];
|
|
22868
|
+
const jmin = Math.max(0, i - maxDistance - 1);
|
|
22869
|
+
const jmax = Math.min(n - 1, i + maxDistance);
|
|
22870
|
+
for (let j = jmin;j < jmax; ++j) {
|
|
22871
|
+
const different = char !== query[j];
|
|
22872
|
+
const rpl = matrix[prevRowOffset + j] + +different;
|
|
22873
|
+
const del = matrix[prevRowOffset + j + 1] + 1;
|
|
22874
|
+
const ins = matrix[thisRowOffset + j] + 1;
|
|
22875
|
+
const dist = matrix[thisRowOffset + j + 1] = Math.min(rpl, del, ins);
|
|
22876
|
+
if (dist < minDistance)
|
|
22877
|
+
minDistance = dist;
|
|
22878
|
+
}
|
|
22879
|
+
if (minDistance > maxDistance) {
|
|
22880
|
+
continue key;
|
|
22881
|
+
}
|
|
22882
|
+
}
|
|
22883
|
+
recurse(node.get(key), query, maxDistance, results, matrix, i, n, prefix + key);
|
|
22884
|
+
}
|
|
22885
|
+
}
|
|
22886
|
+
};
|
|
22887
|
+
|
|
22888
|
+
class SearchableMap {
|
|
22889
|
+
constructor(tree = new Map, prefix = "") {
|
|
22890
|
+
this._size = undefined;
|
|
22891
|
+
this._tree = tree;
|
|
22892
|
+
this._prefix = prefix;
|
|
22893
|
+
}
|
|
22894
|
+
atPrefix(prefix) {
|
|
22895
|
+
if (!prefix.startsWith(this._prefix)) {
|
|
22896
|
+
throw new Error("Mismatched prefix");
|
|
22897
|
+
}
|
|
22898
|
+
const [node, path] = trackDown(this._tree, prefix.slice(this._prefix.length));
|
|
22899
|
+
if (node === undefined) {
|
|
22900
|
+
const [parentNode, key] = last(path);
|
|
22901
|
+
for (const k of parentNode.keys()) {
|
|
22902
|
+
if (k !== LEAF && k.startsWith(key)) {
|
|
22903
|
+
const node = new Map;
|
|
22904
|
+
node.set(k.slice(key.length), parentNode.get(k));
|
|
22905
|
+
return new SearchableMap(node, prefix);
|
|
22906
|
+
}
|
|
22907
|
+
}
|
|
22908
|
+
}
|
|
22909
|
+
return new SearchableMap(node, prefix);
|
|
22910
|
+
}
|
|
22911
|
+
clear() {
|
|
22912
|
+
this._size = undefined;
|
|
22913
|
+
this._tree.clear();
|
|
22914
|
+
}
|
|
22915
|
+
delete(key) {
|
|
22916
|
+
this._size = undefined;
|
|
22917
|
+
return remove(this._tree, key);
|
|
22918
|
+
}
|
|
22919
|
+
entries() {
|
|
22920
|
+
return new TreeIterator(this, ENTRIES);
|
|
22921
|
+
}
|
|
22922
|
+
forEach(fn) {
|
|
22923
|
+
for (const [key, value] of this) {
|
|
22924
|
+
fn(key, value, this);
|
|
22925
|
+
}
|
|
22926
|
+
}
|
|
22927
|
+
fuzzyGet(key, maxEditDistance) {
|
|
22928
|
+
return fuzzySearch(this._tree, key, maxEditDistance);
|
|
22929
|
+
}
|
|
22930
|
+
get(key) {
|
|
22931
|
+
const node = lookup(this._tree, key);
|
|
22932
|
+
return node !== undefined ? node.get(LEAF) : undefined;
|
|
22933
|
+
}
|
|
22934
|
+
has(key) {
|
|
22935
|
+
const node = lookup(this._tree, key);
|
|
22936
|
+
return node !== undefined && node.has(LEAF);
|
|
22937
|
+
}
|
|
22938
|
+
keys() {
|
|
22939
|
+
return new TreeIterator(this, KEYS);
|
|
22940
|
+
}
|
|
22941
|
+
set(key, value) {
|
|
22942
|
+
if (typeof key !== "string") {
|
|
22943
|
+
throw new Error("key must be a string");
|
|
22944
|
+
}
|
|
22945
|
+
this._size = undefined;
|
|
22946
|
+
const node = createPath(this._tree, key);
|
|
22947
|
+
node.set(LEAF, value);
|
|
22948
|
+
return this;
|
|
22949
|
+
}
|
|
22950
|
+
get size() {
|
|
22951
|
+
if (this._size) {
|
|
22952
|
+
return this._size;
|
|
22953
|
+
}
|
|
22954
|
+
this._size = 0;
|
|
22955
|
+
const iter = this.entries();
|
|
22956
|
+
while (!iter.next().done)
|
|
22957
|
+
this._size += 1;
|
|
22958
|
+
return this._size;
|
|
22959
|
+
}
|
|
22960
|
+
update(key, fn) {
|
|
22961
|
+
if (typeof key !== "string") {
|
|
22962
|
+
throw new Error("key must be a string");
|
|
22963
|
+
}
|
|
22964
|
+
this._size = undefined;
|
|
22965
|
+
const node = createPath(this._tree, key);
|
|
22966
|
+
node.set(LEAF, fn(node.get(LEAF)));
|
|
22967
|
+
return this;
|
|
22968
|
+
}
|
|
22969
|
+
fetch(key, initial) {
|
|
22970
|
+
if (typeof key !== "string") {
|
|
22971
|
+
throw new Error("key must be a string");
|
|
22972
|
+
}
|
|
22973
|
+
this._size = undefined;
|
|
22974
|
+
const node = createPath(this._tree, key);
|
|
22975
|
+
let value = node.get(LEAF);
|
|
22976
|
+
if (value === undefined) {
|
|
22977
|
+
node.set(LEAF, value = initial());
|
|
22978
|
+
}
|
|
22979
|
+
return value;
|
|
22980
|
+
}
|
|
22981
|
+
values() {
|
|
22982
|
+
return new TreeIterator(this, VALUES);
|
|
22983
|
+
}
|
|
22984
|
+
[Symbol.iterator]() {
|
|
22985
|
+
return this.entries();
|
|
22986
|
+
}
|
|
22987
|
+
static from(entries) {
|
|
22988
|
+
const tree = new SearchableMap;
|
|
22989
|
+
for (const [key, value] of entries) {
|
|
22990
|
+
tree.set(key, value);
|
|
22991
|
+
}
|
|
22992
|
+
return tree;
|
|
22993
|
+
}
|
|
22994
|
+
static fromObject(object) {
|
|
22995
|
+
return SearchableMap.from(Object.entries(object));
|
|
22996
|
+
}
|
|
22997
|
+
}
|
|
22998
|
+
var trackDown = (tree, key, path = []) => {
|
|
22999
|
+
if (key.length === 0 || tree == null) {
|
|
23000
|
+
return [tree, path];
|
|
23001
|
+
}
|
|
23002
|
+
for (const k of tree.keys()) {
|
|
23003
|
+
if (k !== LEAF && key.startsWith(k)) {
|
|
23004
|
+
path.push([tree, k]);
|
|
23005
|
+
return trackDown(tree.get(k), key.slice(k.length), path);
|
|
23006
|
+
}
|
|
23007
|
+
}
|
|
23008
|
+
path.push([tree, key]);
|
|
23009
|
+
return trackDown(undefined, "", path);
|
|
23010
|
+
};
|
|
23011
|
+
var lookup = (tree, key) => {
|
|
23012
|
+
if (key.length === 0 || tree == null) {
|
|
23013
|
+
return tree;
|
|
23014
|
+
}
|
|
23015
|
+
for (const k of tree.keys()) {
|
|
23016
|
+
if (k !== LEAF && key.startsWith(k)) {
|
|
23017
|
+
return lookup(tree.get(k), key.slice(k.length));
|
|
23018
|
+
}
|
|
23019
|
+
}
|
|
23020
|
+
};
|
|
23021
|
+
var createPath = (node, key) => {
|
|
23022
|
+
const keyLength = key.length;
|
|
23023
|
+
outer:
|
|
23024
|
+
for (let pos = 0;node && pos < keyLength; ) {
|
|
23025
|
+
for (const k of node.keys()) {
|
|
23026
|
+
if (k !== LEAF && key[pos] === k[0]) {
|
|
23027
|
+
const len = Math.min(keyLength - pos, k.length);
|
|
23028
|
+
let offset = 1;
|
|
23029
|
+
while (offset < len && key[pos + offset] === k[offset])
|
|
23030
|
+
++offset;
|
|
23031
|
+
const child = node.get(k);
|
|
23032
|
+
if (offset === k.length) {
|
|
23033
|
+
node = child;
|
|
23034
|
+
} else {
|
|
23035
|
+
const intermediate = new Map;
|
|
23036
|
+
intermediate.set(k.slice(offset), child);
|
|
23037
|
+
node.set(key.slice(pos, pos + offset), intermediate);
|
|
23038
|
+
node.delete(k);
|
|
23039
|
+
node = intermediate;
|
|
23040
|
+
}
|
|
23041
|
+
pos += offset;
|
|
23042
|
+
continue outer;
|
|
23043
|
+
}
|
|
23044
|
+
}
|
|
23045
|
+
const child = new Map;
|
|
23046
|
+
node.set(key.slice(pos), child);
|
|
23047
|
+
return child;
|
|
23048
|
+
}
|
|
23049
|
+
return node;
|
|
23050
|
+
};
|
|
23051
|
+
var remove = (tree, key) => {
|
|
23052
|
+
const [node, path] = trackDown(tree, key);
|
|
23053
|
+
if (node === undefined) {
|
|
23054
|
+
return;
|
|
23055
|
+
}
|
|
23056
|
+
node.delete(LEAF);
|
|
23057
|
+
if (node.size === 0) {
|
|
23058
|
+
cleanup(path);
|
|
23059
|
+
} else if (node.size === 1) {
|
|
23060
|
+
const [key, value] = node.entries().next().value;
|
|
23061
|
+
merge2(path, key, value);
|
|
23062
|
+
}
|
|
23063
|
+
};
|
|
23064
|
+
var cleanup = (path) => {
|
|
23065
|
+
if (path.length === 0) {
|
|
23066
|
+
return;
|
|
23067
|
+
}
|
|
23068
|
+
const [node, key] = last(path);
|
|
23069
|
+
node.delete(key);
|
|
23070
|
+
if (node.size === 0) {
|
|
23071
|
+
cleanup(path.slice(0, -1));
|
|
23072
|
+
} else if (node.size === 1) {
|
|
23073
|
+
const [key, value] = node.entries().next().value;
|
|
23074
|
+
if (key !== LEAF) {
|
|
23075
|
+
merge2(path.slice(0, -1), key, value);
|
|
23076
|
+
}
|
|
23077
|
+
}
|
|
23078
|
+
};
|
|
23079
|
+
var merge2 = (path, key, value) => {
|
|
23080
|
+
if (path.length === 0) {
|
|
23081
|
+
return;
|
|
23082
|
+
}
|
|
23083
|
+
const [node, nodeKey] = last(path);
|
|
23084
|
+
node.set(nodeKey + key, value);
|
|
23085
|
+
node.delete(nodeKey);
|
|
23086
|
+
};
|
|
23087
|
+
var last = (array) => {
|
|
23088
|
+
return array[array.length - 1];
|
|
23089
|
+
};
|
|
23090
|
+
var OR = "or";
|
|
23091
|
+
var AND = "and";
|
|
23092
|
+
var AND_NOT = "and_not";
|
|
23093
|
+
|
|
23094
|
+
class MiniSearch {
|
|
23095
|
+
constructor(options) {
|
|
23096
|
+
if ((options === null || options === undefined ? undefined : options.fields) == null) {
|
|
23097
|
+
throw new Error('MiniSearch: option "fields" must be provided');
|
|
23098
|
+
}
|
|
23099
|
+
const autoVacuum = options.autoVacuum == null || options.autoVacuum === true ? defaultAutoVacuumOptions : options.autoVacuum;
|
|
23100
|
+
this._options = {
|
|
23101
|
+
...defaultOptions,
|
|
23102
|
+
...options,
|
|
23103
|
+
autoVacuum,
|
|
23104
|
+
searchOptions: { ...defaultSearchOptions, ...options.searchOptions || {} },
|
|
23105
|
+
autoSuggestOptions: { ...defaultAutoSuggestOptions, ...options.autoSuggestOptions || {} }
|
|
23106
|
+
};
|
|
23107
|
+
this._index = new SearchableMap;
|
|
23108
|
+
this._documentCount = 0;
|
|
23109
|
+
this._documentIds = new Map;
|
|
23110
|
+
this._idToShortId = new Map;
|
|
23111
|
+
this._fieldIds = {};
|
|
23112
|
+
this._fieldLength = new Map;
|
|
23113
|
+
this._avgFieldLength = [];
|
|
23114
|
+
this._nextId = 0;
|
|
23115
|
+
this._storedFields = new Map;
|
|
23116
|
+
this._dirtCount = 0;
|
|
23117
|
+
this._currentVacuum = null;
|
|
23118
|
+
this._enqueuedVacuum = null;
|
|
23119
|
+
this._enqueuedVacuumConditions = defaultVacuumConditions;
|
|
23120
|
+
this.addFields(this._options.fields);
|
|
23121
|
+
}
|
|
23122
|
+
add(document) {
|
|
23123
|
+
const { extractField, stringifyField, tokenize, processTerm, fields, idField } = this._options;
|
|
23124
|
+
const id = extractField(document, idField);
|
|
23125
|
+
if (id == null) {
|
|
23126
|
+
throw new Error(`MiniSearch: document does not have ID field "${idField}"`);
|
|
23127
|
+
}
|
|
23128
|
+
if (this._idToShortId.has(id)) {
|
|
23129
|
+
throw new Error(`MiniSearch: duplicate ID ${id}`);
|
|
23130
|
+
}
|
|
23131
|
+
const shortDocumentId = this.addDocumentId(id);
|
|
23132
|
+
this.saveStoredFields(shortDocumentId, document);
|
|
23133
|
+
for (const field of fields) {
|
|
23134
|
+
const fieldValue = extractField(document, field);
|
|
23135
|
+
if (fieldValue == null)
|
|
23136
|
+
continue;
|
|
23137
|
+
const tokens = tokenize(stringifyField(fieldValue, field), field);
|
|
23138
|
+
const fieldId = this._fieldIds[field];
|
|
23139
|
+
const uniqueTerms = new Set(tokens).size;
|
|
23140
|
+
this.addFieldLength(shortDocumentId, fieldId, this._documentCount - 1, uniqueTerms);
|
|
23141
|
+
for (const term of tokens) {
|
|
23142
|
+
const processedTerm = processTerm(term, field);
|
|
23143
|
+
if (Array.isArray(processedTerm)) {
|
|
23144
|
+
for (const t of processedTerm) {
|
|
23145
|
+
this.addTerm(fieldId, shortDocumentId, t);
|
|
23146
|
+
}
|
|
23147
|
+
} else if (processedTerm) {
|
|
23148
|
+
this.addTerm(fieldId, shortDocumentId, processedTerm);
|
|
23149
|
+
}
|
|
23150
|
+
}
|
|
23151
|
+
}
|
|
23152
|
+
}
|
|
23153
|
+
addAll(documents) {
|
|
23154
|
+
for (const document of documents)
|
|
23155
|
+
this.add(document);
|
|
23156
|
+
}
|
|
23157
|
+
addAllAsync(documents, options = {}) {
|
|
23158
|
+
const { chunkSize = 10 } = options;
|
|
23159
|
+
const acc = { chunk: [], promise: Promise.resolve() };
|
|
23160
|
+
const { chunk, promise } = documents.reduce(({ chunk, promise }, document, i) => {
|
|
23161
|
+
chunk.push(document);
|
|
23162
|
+
if ((i + 1) % chunkSize === 0) {
|
|
23163
|
+
return {
|
|
23164
|
+
chunk: [],
|
|
23165
|
+
promise: promise.then(() => new Promise((resolve) => setTimeout(resolve, 0))).then(() => this.addAll(chunk))
|
|
23166
|
+
};
|
|
23167
|
+
} else {
|
|
23168
|
+
return { chunk, promise };
|
|
23169
|
+
}
|
|
23170
|
+
}, acc);
|
|
23171
|
+
return promise.then(() => this.addAll(chunk));
|
|
23172
|
+
}
|
|
23173
|
+
remove(document) {
|
|
23174
|
+
const { tokenize, processTerm, extractField, stringifyField, 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
|
+
const shortId = this._idToShortId.get(id);
|
|
23180
|
+
if (shortId == null) {
|
|
23181
|
+
throw new Error(`MiniSearch: cannot remove document with ID ${id}: it is not in the index`);
|
|
23182
|
+
}
|
|
23183
|
+
for (const field of fields) {
|
|
23184
|
+
const fieldValue = extractField(document, field);
|
|
23185
|
+
if (fieldValue == null)
|
|
23186
|
+
continue;
|
|
23187
|
+
const tokens = tokenize(stringifyField(fieldValue, field), field);
|
|
23188
|
+
const fieldId = this._fieldIds[field];
|
|
23189
|
+
const uniqueTerms = new Set(tokens).size;
|
|
23190
|
+
this.removeFieldLength(shortId, fieldId, this._documentCount, uniqueTerms);
|
|
23191
|
+
for (const term of tokens) {
|
|
23192
|
+
const processedTerm = processTerm(term, field);
|
|
23193
|
+
if (Array.isArray(processedTerm)) {
|
|
23194
|
+
for (const t of processedTerm) {
|
|
23195
|
+
this.removeTerm(fieldId, shortId, t);
|
|
23196
|
+
}
|
|
23197
|
+
} else if (processedTerm) {
|
|
23198
|
+
this.removeTerm(fieldId, shortId, processedTerm);
|
|
23199
|
+
}
|
|
23200
|
+
}
|
|
23201
|
+
}
|
|
23202
|
+
this._storedFields.delete(shortId);
|
|
23203
|
+
this._documentIds.delete(shortId);
|
|
23204
|
+
this._idToShortId.delete(id);
|
|
23205
|
+
this._fieldLength.delete(shortId);
|
|
23206
|
+
this._documentCount -= 1;
|
|
23207
|
+
}
|
|
23208
|
+
removeAll(documents) {
|
|
23209
|
+
if (documents) {
|
|
23210
|
+
for (const document of documents)
|
|
23211
|
+
this.remove(document);
|
|
23212
|
+
} else if (arguments.length > 0) {
|
|
23213
|
+
throw new Error("Expected documents to be present. Omit the argument to remove all documents.");
|
|
23214
|
+
} else {
|
|
23215
|
+
this._index = new SearchableMap;
|
|
23216
|
+
this._documentCount = 0;
|
|
23217
|
+
this._documentIds = new Map;
|
|
23218
|
+
this._idToShortId = new Map;
|
|
23219
|
+
this._fieldLength = new Map;
|
|
23220
|
+
this._avgFieldLength = [];
|
|
23221
|
+
this._storedFields = new Map;
|
|
23222
|
+
this._nextId = 0;
|
|
23223
|
+
}
|
|
23224
|
+
}
|
|
23225
|
+
discard(id) {
|
|
23226
|
+
const shortId = this._idToShortId.get(id);
|
|
23227
|
+
if (shortId == null) {
|
|
23228
|
+
throw new Error(`MiniSearch: cannot discard document with ID ${id}: it is not in the index`);
|
|
23229
|
+
}
|
|
23230
|
+
this._idToShortId.delete(id);
|
|
23231
|
+
this._documentIds.delete(shortId);
|
|
23232
|
+
this._storedFields.delete(shortId);
|
|
23233
|
+
(this._fieldLength.get(shortId) || []).forEach((fieldLength, fieldId) => {
|
|
23234
|
+
this.removeFieldLength(shortId, fieldId, this._documentCount, fieldLength);
|
|
23235
|
+
});
|
|
23236
|
+
this._fieldLength.delete(shortId);
|
|
23237
|
+
this._documentCount -= 1;
|
|
23238
|
+
this._dirtCount += 1;
|
|
23239
|
+
this.maybeAutoVacuum();
|
|
23240
|
+
}
|
|
23241
|
+
maybeAutoVacuum() {
|
|
23242
|
+
if (this._options.autoVacuum === false) {
|
|
23243
|
+
return;
|
|
23244
|
+
}
|
|
23245
|
+
const { minDirtFactor, minDirtCount, batchSize, batchWait } = this._options.autoVacuum;
|
|
23246
|
+
this.conditionalVacuum({ batchSize, batchWait }, { minDirtCount, minDirtFactor });
|
|
23247
|
+
}
|
|
23248
|
+
discardAll(ids) {
|
|
23249
|
+
const autoVacuum = this._options.autoVacuum;
|
|
23250
|
+
try {
|
|
23251
|
+
this._options.autoVacuum = false;
|
|
23252
|
+
for (const id of ids) {
|
|
23253
|
+
this.discard(id);
|
|
23254
|
+
}
|
|
23255
|
+
} finally {
|
|
23256
|
+
this._options.autoVacuum = autoVacuum;
|
|
23257
|
+
}
|
|
23258
|
+
this.maybeAutoVacuum();
|
|
23259
|
+
}
|
|
23260
|
+
replace(updatedDocument) {
|
|
23261
|
+
const { idField, extractField } = this._options;
|
|
23262
|
+
const id = extractField(updatedDocument, idField);
|
|
23263
|
+
this.discard(id);
|
|
23264
|
+
this.add(updatedDocument);
|
|
23265
|
+
}
|
|
23266
|
+
vacuum(options = {}) {
|
|
23267
|
+
return this.conditionalVacuum(options);
|
|
23268
|
+
}
|
|
23269
|
+
conditionalVacuum(options, conditions) {
|
|
23270
|
+
if (this._currentVacuum) {
|
|
23271
|
+
this._enqueuedVacuumConditions = this._enqueuedVacuumConditions && conditions;
|
|
23272
|
+
if (this._enqueuedVacuum != null) {
|
|
23273
|
+
return this._enqueuedVacuum;
|
|
23274
|
+
}
|
|
23275
|
+
this._enqueuedVacuum = this._currentVacuum.then(() => {
|
|
23276
|
+
const conditions = this._enqueuedVacuumConditions;
|
|
23277
|
+
this._enqueuedVacuumConditions = defaultVacuumConditions;
|
|
23278
|
+
return this.performVacuuming(options, conditions);
|
|
23279
|
+
});
|
|
23280
|
+
return this._enqueuedVacuum;
|
|
23281
|
+
}
|
|
23282
|
+
if (this.vacuumConditionsMet(conditions) === false) {
|
|
23283
|
+
return Promise.resolve();
|
|
23284
|
+
}
|
|
23285
|
+
this._currentVacuum = this.performVacuuming(options);
|
|
23286
|
+
return this._currentVacuum;
|
|
23287
|
+
}
|
|
23288
|
+
async performVacuuming(options, conditions) {
|
|
23289
|
+
const initialDirtCount = this._dirtCount;
|
|
23290
|
+
if (this.vacuumConditionsMet(conditions)) {
|
|
23291
|
+
const batchSize = options.batchSize || defaultVacuumOptions.batchSize;
|
|
23292
|
+
const batchWait = options.batchWait || defaultVacuumOptions.batchWait;
|
|
23293
|
+
let i = 1;
|
|
23294
|
+
for (const [term, fieldsData] of this._index) {
|
|
23295
|
+
for (const [fieldId, fieldIndex] of fieldsData) {
|
|
23296
|
+
for (const [shortId] of fieldIndex) {
|
|
23297
|
+
if (this._documentIds.has(shortId)) {
|
|
23298
|
+
continue;
|
|
23299
|
+
}
|
|
23300
|
+
if (fieldIndex.size <= 1) {
|
|
23301
|
+
fieldsData.delete(fieldId);
|
|
23302
|
+
} else {
|
|
23303
|
+
fieldIndex.delete(shortId);
|
|
23304
|
+
}
|
|
23305
|
+
}
|
|
23306
|
+
}
|
|
23307
|
+
if (this._index.get(term).size === 0) {
|
|
23308
|
+
this._index.delete(term);
|
|
23309
|
+
}
|
|
23310
|
+
if (i % batchSize === 0) {
|
|
23311
|
+
await new Promise((resolve) => setTimeout(resolve, batchWait));
|
|
23312
|
+
}
|
|
23313
|
+
i += 1;
|
|
23314
|
+
}
|
|
23315
|
+
this._dirtCount -= initialDirtCount;
|
|
23316
|
+
}
|
|
23317
|
+
await null;
|
|
23318
|
+
this._currentVacuum = this._enqueuedVacuum;
|
|
23319
|
+
this._enqueuedVacuum = null;
|
|
23320
|
+
}
|
|
23321
|
+
vacuumConditionsMet(conditions) {
|
|
23322
|
+
if (conditions == null) {
|
|
23323
|
+
return true;
|
|
23324
|
+
}
|
|
23325
|
+
let { minDirtCount, minDirtFactor } = conditions;
|
|
23326
|
+
minDirtCount = minDirtCount || defaultAutoVacuumOptions.minDirtCount;
|
|
23327
|
+
minDirtFactor = minDirtFactor || defaultAutoVacuumOptions.minDirtFactor;
|
|
23328
|
+
return this.dirtCount >= minDirtCount && this.dirtFactor >= minDirtFactor;
|
|
23329
|
+
}
|
|
23330
|
+
get isVacuuming() {
|
|
23331
|
+
return this._currentVacuum != null;
|
|
23332
|
+
}
|
|
23333
|
+
get dirtCount() {
|
|
23334
|
+
return this._dirtCount;
|
|
23335
|
+
}
|
|
23336
|
+
get dirtFactor() {
|
|
23337
|
+
return this._dirtCount / (1 + this._documentCount + this._dirtCount);
|
|
23338
|
+
}
|
|
23339
|
+
has(id) {
|
|
23340
|
+
return this._idToShortId.has(id);
|
|
23341
|
+
}
|
|
23342
|
+
getStoredFields(id) {
|
|
23343
|
+
const shortId = this._idToShortId.get(id);
|
|
23344
|
+
if (shortId == null) {
|
|
23345
|
+
return;
|
|
23346
|
+
}
|
|
23347
|
+
return this._storedFields.get(shortId);
|
|
23348
|
+
}
|
|
23349
|
+
search(query, searchOptions = {}) {
|
|
23350
|
+
const { searchOptions: globalSearchOptions } = this._options;
|
|
23351
|
+
const searchOptionsWithDefaults = { ...globalSearchOptions, ...searchOptions };
|
|
23352
|
+
const rawResults = this.executeQuery(query, searchOptions);
|
|
23353
|
+
const results = [];
|
|
23354
|
+
for (const [docId, { score, terms, match }] of rawResults) {
|
|
23355
|
+
const quality = terms.length || 1;
|
|
23356
|
+
const result = {
|
|
23357
|
+
id: this._documentIds.get(docId),
|
|
23358
|
+
score: score * quality,
|
|
23359
|
+
terms: Object.keys(match),
|
|
23360
|
+
queryTerms: terms,
|
|
23361
|
+
match
|
|
23362
|
+
};
|
|
23363
|
+
Object.assign(result, this._storedFields.get(docId));
|
|
23364
|
+
if (searchOptionsWithDefaults.filter == null || searchOptionsWithDefaults.filter(result)) {
|
|
23365
|
+
results.push(result);
|
|
23366
|
+
}
|
|
23367
|
+
}
|
|
23368
|
+
if (query === MiniSearch.wildcard && searchOptionsWithDefaults.boostDocument == null) {
|
|
23369
|
+
return results;
|
|
23370
|
+
}
|
|
23371
|
+
results.sort(byScore);
|
|
23372
|
+
return results;
|
|
23373
|
+
}
|
|
23374
|
+
autoSuggest(queryString, options = {}) {
|
|
23375
|
+
options = { ...this._options.autoSuggestOptions, ...options };
|
|
23376
|
+
const suggestions = new Map;
|
|
23377
|
+
for (const { score, terms } of this.search(queryString, options)) {
|
|
23378
|
+
const phrase = terms.join(" ");
|
|
23379
|
+
const suggestion = suggestions.get(phrase);
|
|
23380
|
+
if (suggestion != null) {
|
|
23381
|
+
suggestion.score += score;
|
|
23382
|
+
suggestion.count += 1;
|
|
23383
|
+
} else {
|
|
23384
|
+
suggestions.set(phrase, { score, terms, count: 1 });
|
|
23385
|
+
}
|
|
23386
|
+
}
|
|
23387
|
+
const results = [];
|
|
23388
|
+
for (const [suggestion, { score, terms, count }] of suggestions) {
|
|
23389
|
+
results.push({ suggestion, terms, score: score / count });
|
|
23390
|
+
}
|
|
23391
|
+
results.sort(byScore);
|
|
23392
|
+
return results;
|
|
23393
|
+
}
|
|
23394
|
+
get documentCount() {
|
|
23395
|
+
return this._documentCount;
|
|
23396
|
+
}
|
|
23397
|
+
get termCount() {
|
|
23398
|
+
return this._index.size;
|
|
23399
|
+
}
|
|
23400
|
+
static loadJSON(json, options) {
|
|
23401
|
+
if (options == null) {
|
|
23402
|
+
throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index");
|
|
23403
|
+
}
|
|
23404
|
+
return this.loadJS(JSON.parse(json), options);
|
|
23405
|
+
}
|
|
23406
|
+
static async loadJSONAsync(json, options) {
|
|
23407
|
+
if (options == null) {
|
|
23408
|
+
throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index");
|
|
23409
|
+
}
|
|
23410
|
+
return this.loadJSAsync(JSON.parse(json), options);
|
|
23411
|
+
}
|
|
23412
|
+
static getDefault(optionName) {
|
|
23413
|
+
if (defaultOptions.hasOwnProperty(optionName)) {
|
|
23414
|
+
return getOwnProperty(defaultOptions, optionName);
|
|
23415
|
+
} else {
|
|
23416
|
+
throw new Error(`MiniSearch: unknown option "${optionName}"`);
|
|
23417
|
+
}
|
|
23418
|
+
}
|
|
23419
|
+
static loadJS(js, options) {
|
|
23420
|
+
const { index, documentIds, fieldLength, storedFields, serializationVersion } = js;
|
|
23421
|
+
const miniSearch = this.instantiateMiniSearch(js, options);
|
|
23422
|
+
miniSearch._documentIds = objectToNumericMap(documentIds);
|
|
23423
|
+
miniSearch._fieldLength = objectToNumericMap(fieldLength);
|
|
23424
|
+
miniSearch._storedFields = objectToNumericMap(storedFields);
|
|
23425
|
+
for (const [shortId, id] of miniSearch._documentIds) {
|
|
23426
|
+
miniSearch._idToShortId.set(id, shortId);
|
|
23427
|
+
}
|
|
23428
|
+
for (const [term, data] of index) {
|
|
23429
|
+
const dataMap = new Map;
|
|
23430
|
+
for (const fieldId of Object.keys(data)) {
|
|
23431
|
+
let indexEntry = data[fieldId];
|
|
23432
|
+
if (serializationVersion === 1) {
|
|
23433
|
+
indexEntry = indexEntry.ds;
|
|
23434
|
+
}
|
|
23435
|
+
dataMap.set(parseInt(fieldId, 10), objectToNumericMap(indexEntry));
|
|
23436
|
+
}
|
|
23437
|
+
miniSearch._index.set(term, dataMap);
|
|
23438
|
+
}
|
|
23439
|
+
return miniSearch;
|
|
23440
|
+
}
|
|
23441
|
+
static async loadJSAsync(js, options) {
|
|
23442
|
+
const { index, documentIds, fieldLength, storedFields, serializationVersion } = js;
|
|
23443
|
+
const miniSearch = this.instantiateMiniSearch(js, options);
|
|
23444
|
+
miniSearch._documentIds = await objectToNumericMapAsync(documentIds);
|
|
23445
|
+
miniSearch._fieldLength = await objectToNumericMapAsync(fieldLength);
|
|
23446
|
+
miniSearch._storedFields = await objectToNumericMapAsync(storedFields);
|
|
23447
|
+
for (const [shortId, id] of miniSearch._documentIds) {
|
|
23448
|
+
miniSearch._idToShortId.set(id, shortId);
|
|
23449
|
+
}
|
|
23450
|
+
let count = 0;
|
|
23451
|
+
for (const [term, data] of index) {
|
|
23452
|
+
const dataMap = new Map;
|
|
23453
|
+
for (const fieldId of Object.keys(data)) {
|
|
23454
|
+
let indexEntry = data[fieldId];
|
|
23455
|
+
if (serializationVersion === 1) {
|
|
23456
|
+
indexEntry = indexEntry.ds;
|
|
23457
|
+
}
|
|
23458
|
+
dataMap.set(parseInt(fieldId, 10), await objectToNumericMapAsync(indexEntry));
|
|
23459
|
+
}
|
|
23460
|
+
if (++count % 1000 === 0)
|
|
23461
|
+
await wait(0);
|
|
23462
|
+
miniSearch._index.set(term, dataMap);
|
|
23463
|
+
}
|
|
23464
|
+
return miniSearch;
|
|
23465
|
+
}
|
|
23466
|
+
static instantiateMiniSearch(js, options) {
|
|
23467
|
+
const { documentCount, nextId, fieldIds, averageFieldLength, dirtCount, serializationVersion } = js;
|
|
23468
|
+
if (serializationVersion !== 1 && serializationVersion !== 2) {
|
|
23469
|
+
throw new Error("MiniSearch: cannot deserialize an index created with an incompatible version");
|
|
23470
|
+
}
|
|
23471
|
+
const miniSearch = new MiniSearch(options);
|
|
23472
|
+
miniSearch._documentCount = documentCount;
|
|
23473
|
+
miniSearch._nextId = nextId;
|
|
23474
|
+
miniSearch._idToShortId = new Map;
|
|
23475
|
+
miniSearch._fieldIds = fieldIds;
|
|
23476
|
+
miniSearch._avgFieldLength = averageFieldLength;
|
|
23477
|
+
miniSearch._dirtCount = dirtCount || 0;
|
|
23478
|
+
miniSearch._index = new SearchableMap;
|
|
23479
|
+
return miniSearch;
|
|
23480
|
+
}
|
|
23481
|
+
executeQuery(query, searchOptions = {}) {
|
|
23482
|
+
if (query === MiniSearch.wildcard) {
|
|
23483
|
+
return this.executeWildcardQuery(searchOptions);
|
|
23484
|
+
}
|
|
23485
|
+
if (typeof query !== "string") {
|
|
23486
|
+
const options = { ...searchOptions, ...query, queries: undefined };
|
|
23487
|
+
const results = query.queries.map((subquery) => this.executeQuery(subquery, options));
|
|
23488
|
+
return this.combineResults(results, options.combineWith);
|
|
23489
|
+
}
|
|
23490
|
+
const { tokenize, processTerm, searchOptions: globalSearchOptions } = this._options;
|
|
23491
|
+
const options = { tokenize, processTerm, ...globalSearchOptions, ...searchOptions };
|
|
23492
|
+
const { tokenize: searchTokenize, processTerm: searchProcessTerm } = options;
|
|
23493
|
+
const terms = searchTokenize(query).flatMap((term) => searchProcessTerm(term)).filter((term) => !!term);
|
|
23494
|
+
const queries = terms.map(termToQuerySpec(options));
|
|
23495
|
+
const results = queries.map((query) => this.executeQuerySpec(query, options));
|
|
23496
|
+
return this.combineResults(results, options.combineWith);
|
|
23497
|
+
}
|
|
23498
|
+
executeQuerySpec(query, searchOptions) {
|
|
23499
|
+
const options = { ...this._options.searchOptions, ...searchOptions };
|
|
23500
|
+
const boosts = (options.fields || this._options.fields).reduce((boosts, field) => ({ ...boosts, [field]: getOwnProperty(options.boost, field) || 1 }), {});
|
|
23501
|
+
const { boostDocument, weights, maxFuzzy, bm25: bm25params } = options;
|
|
23502
|
+
const { fuzzy: fuzzyWeight, prefix: prefixWeight } = { ...defaultSearchOptions.weights, ...weights };
|
|
23503
|
+
const data = this._index.get(query.term);
|
|
23504
|
+
const results = this.termResults(query.term, query.term, 1, query.termBoost, data, boosts, boostDocument, bm25params);
|
|
23505
|
+
let prefixMatches;
|
|
23506
|
+
let fuzzyMatches;
|
|
23507
|
+
if (query.prefix) {
|
|
23508
|
+
prefixMatches = this._index.atPrefix(query.term);
|
|
23509
|
+
}
|
|
23510
|
+
if (query.fuzzy) {
|
|
23511
|
+
const fuzzy = query.fuzzy === true ? 0.2 : query.fuzzy;
|
|
23512
|
+
const maxDistance = fuzzy < 1 ? Math.min(maxFuzzy, Math.round(query.term.length * fuzzy)) : fuzzy;
|
|
23513
|
+
if (maxDistance)
|
|
23514
|
+
fuzzyMatches = this._index.fuzzyGet(query.term, maxDistance);
|
|
23515
|
+
}
|
|
23516
|
+
if (prefixMatches) {
|
|
23517
|
+
for (const [term, data] of prefixMatches) {
|
|
23518
|
+
const distance = term.length - query.term.length;
|
|
23519
|
+
if (!distance) {
|
|
23520
|
+
continue;
|
|
23521
|
+
}
|
|
23522
|
+
fuzzyMatches === null || fuzzyMatches === undefined || fuzzyMatches.delete(term);
|
|
23523
|
+
const weight = prefixWeight * term.length / (term.length + 0.3 * distance);
|
|
23524
|
+
this.termResults(query.term, term, weight, query.termBoost, data, boosts, boostDocument, bm25params, results);
|
|
23525
|
+
}
|
|
23526
|
+
}
|
|
23527
|
+
if (fuzzyMatches) {
|
|
23528
|
+
for (const term of fuzzyMatches.keys()) {
|
|
23529
|
+
const [data, distance] = fuzzyMatches.get(term);
|
|
23530
|
+
if (!distance) {
|
|
23531
|
+
continue;
|
|
23532
|
+
}
|
|
23533
|
+
const weight = fuzzyWeight * term.length / (term.length + distance);
|
|
23534
|
+
this.termResults(query.term, term, weight, query.termBoost, data, boosts, boostDocument, bm25params, results);
|
|
23535
|
+
}
|
|
23536
|
+
}
|
|
23537
|
+
return results;
|
|
23538
|
+
}
|
|
23539
|
+
executeWildcardQuery(searchOptions) {
|
|
23540
|
+
const results = new Map;
|
|
23541
|
+
const options = { ...this._options.searchOptions, ...searchOptions };
|
|
23542
|
+
for (const [shortId, id] of this._documentIds) {
|
|
23543
|
+
const score = options.boostDocument ? options.boostDocument(id, "", this._storedFields.get(shortId)) : 1;
|
|
23544
|
+
results.set(shortId, {
|
|
23545
|
+
score,
|
|
23546
|
+
terms: [],
|
|
23547
|
+
match: {}
|
|
23548
|
+
});
|
|
23549
|
+
}
|
|
23550
|
+
return results;
|
|
23551
|
+
}
|
|
23552
|
+
combineResults(results, combineWith = OR) {
|
|
23553
|
+
if (results.length === 0) {
|
|
23554
|
+
return new Map;
|
|
23555
|
+
}
|
|
23556
|
+
const operator = combineWith.toLowerCase();
|
|
23557
|
+
const combinator = combinators[operator];
|
|
23558
|
+
if (!combinator) {
|
|
23559
|
+
throw new Error(`Invalid combination operator: ${combineWith}`);
|
|
23560
|
+
}
|
|
23561
|
+
return results.reduce(combinator) || new Map;
|
|
23562
|
+
}
|
|
23563
|
+
toJSON() {
|
|
23564
|
+
const index = [];
|
|
23565
|
+
for (const [term, fieldIndex] of this._index) {
|
|
23566
|
+
const data = {};
|
|
23567
|
+
for (const [fieldId, freqs] of fieldIndex) {
|
|
23568
|
+
data[fieldId] = Object.fromEntries(freqs);
|
|
23569
|
+
}
|
|
23570
|
+
index.push([term, data]);
|
|
23571
|
+
}
|
|
23572
|
+
return {
|
|
23573
|
+
documentCount: this._documentCount,
|
|
23574
|
+
nextId: this._nextId,
|
|
23575
|
+
documentIds: Object.fromEntries(this._documentIds),
|
|
23576
|
+
fieldIds: this._fieldIds,
|
|
23577
|
+
fieldLength: Object.fromEntries(this._fieldLength),
|
|
23578
|
+
averageFieldLength: this._avgFieldLength,
|
|
23579
|
+
storedFields: Object.fromEntries(this._storedFields),
|
|
23580
|
+
dirtCount: this._dirtCount,
|
|
23581
|
+
index,
|
|
23582
|
+
serializationVersion: 2
|
|
23583
|
+
};
|
|
23584
|
+
}
|
|
23585
|
+
termResults(sourceTerm, derivedTerm, termWeight, termBoost, fieldTermData, fieldBoosts, boostDocumentFn, bm25params, results = new Map) {
|
|
23586
|
+
if (fieldTermData == null)
|
|
23587
|
+
return results;
|
|
23588
|
+
for (const field of Object.keys(fieldBoosts)) {
|
|
23589
|
+
const fieldBoost = fieldBoosts[field];
|
|
23590
|
+
const fieldId = this._fieldIds[field];
|
|
23591
|
+
const fieldTermFreqs = fieldTermData.get(fieldId);
|
|
23592
|
+
if (fieldTermFreqs == null)
|
|
23593
|
+
continue;
|
|
23594
|
+
let matchingFields = fieldTermFreqs.size;
|
|
23595
|
+
const avgFieldLength = this._avgFieldLength[fieldId];
|
|
23596
|
+
for (const docId of fieldTermFreqs.keys()) {
|
|
23597
|
+
if (!this._documentIds.has(docId)) {
|
|
23598
|
+
this.removeTerm(fieldId, docId, derivedTerm);
|
|
23599
|
+
matchingFields -= 1;
|
|
23600
|
+
continue;
|
|
23601
|
+
}
|
|
23602
|
+
const docBoost = boostDocumentFn ? boostDocumentFn(this._documentIds.get(docId), derivedTerm, this._storedFields.get(docId)) : 1;
|
|
23603
|
+
if (!docBoost)
|
|
23604
|
+
continue;
|
|
23605
|
+
const termFreq = fieldTermFreqs.get(docId);
|
|
23606
|
+
const fieldLength = this._fieldLength.get(docId)[fieldId];
|
|
23607
|
+
const rawScore = calcBM25Score(termFreq, matchingFields, this._documentCount, fieldLength, avgFieldLength, bm25params);
|
|
23608
|
+
const weightedScore = termWeight * termBoost * fieldBoost * docBoost * rawScore;
|
|
23609
|
+
const result = results.get(docId);
|
|
23610
|
+
if (result) {
|
|
23611
|
+
result.score += weightedScore;
|
|
23612
|
+
assignUniqueTerm(result.terms, sourceTerm);
|
|
23613
|
+
const match = getOwnProperty(result.match, derivedTerm);
|
|
23614
|
+
if (match) {
|
|
23615
|
+
match.push(field);
|
|
23616
|
+
} else {
|
|
23617
|
+
result.match[derivedTerm] = [field];
|
|
23618
|
+
}
|
|
23619
|
+
} else {
|
|
23620
|
+
results.set(docId, {
|
|
23621
|
+
score: weightedScore,
|
|
23622
|
+
terms: [sourceTerm],
|
|
23623
|
+
match: { [derivedTerm]: [field] }
|
|
23624
|
+
});
|
|
23625
|
+
}
|
|
23626
|
+
}
|
|
23627
|
+
}
|
|
23628
|
+
return results;
|
|
23629
|
+
}
|
|
23630
|
+
addTerm(fieldId, documentId, term) {
|
|
23631
|
+
const indexData = this._index.fetch(term, createMap);
|
|
23632
|
+
let fieldIndex = indexData.get(fieldId);
|
|
23633
|
+
if (fieldIndex == null) {
|
|
23634
|
+
fieldIndex = new Map;
|
|
23635
|
+
fieldIndex.set(documentId, 1);
|
|
23636
|
+
indexData.set(fieldId, fieldIndex);
|
|
23637
|
+
} else {
|
|
23638
|
+
const docs = fieldIndex.get(documentId);
|
|
23639
|
+
fieldIndex.set(documentId, (docs || 0) + 1);
|
|
23640
|
+
}
|
|
23641
|
+
}
|
|
23642
|
+
removeTerm(fieldId, documentId, term) {
|
|
23643
|
+
if (!this._index.has(term)) {
|
|
23644
|
+
this.warnDocumentChanged(documentId, fieldId, term);
|
|
23645
|
+
return;
|
|
23646
|
+
}
|
|
23647
|
+
const indexData = this._index.fetch(term, createMap);
|
|
23648
|
+
const fieldIndex = indexData.get(fieldId);
|
|
23649
|
+
if (fieldIndex == null || fieldIndex.get(documentId) == null) {
|
|
23650
|
+
this.warnDocumentChanged(documentId, fieldId, term);
|
|
23651
|
+
} else if (fieldIndex.get(documentId) <= 1) {
|
|
23652
|
+
if (fieldIndex.size <= 1) {
|
|
23653
|
+
indexData.delete(fieldId);
|
|
23654
|
+
} else {
|
|
23655
|
+
fieldIndex.delete(documentId);
|
|
23656
|
+
}
|
|
23657
|
+
} else {
|
|
23658
|
+
fieldIndex.set(documentId, fieldIndex.get(documentId) - 1);
|
|
23659
|
+
}
|
|
23660
|
+
if (this._index.get(term).size === 0) {
|
|
23661
|
+
this._index.delete(term);
|
|
23662
|
+
}
|
|
23663
|
+
}
|
|
23664
|
+
warnDocumentChanged(shortDocumentId, fieldId, term) {
|
|
23665
|
+
for (const fieldName of Object.keys(this._fieldIds)) {
|
|
23666
|
+
if (this._fieldIds[fieldName] === fieldId) {
|
|
23667
|
+
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");
|
|
23668
|
+
return;
|
|
23669
|
+
}
|
|
23670
|
+
}
|
|
23671
|
+
}
|
|
23672
|
+
addDocumentId(documentId) {
|
|
23673
|
+
const shortDocumentId = this._nextId;
|
|
23674
|
+
this._idToShortId.set(documentId, shortDocumentId);
|
|
23675
|
+
this._documentIds.set(shortDocumentId, documentId);
|
|
23676
|
+
this._documentCount += 1;
|
|
23677
|
+
this._nextId += 1;
|
|
23678
|
+
return shortDocumentId;
|
|
23679
|
+
}
|
|
23680
|
+
addFields(fields) {
|
|
23681
|
+
for (let i = 0;i < fields.length; i++) {
|
|
23682
|
+
this._fieldIds[fields[i]] = i;
|
|
23683
|
+
}
|
|
23684
|
+
}
|
|
23685
|
+
addFieldLength(documentId, fieldId, count, length) {
|
|
23686
|
+
let fieldLengths = this._fieldLength.get(documentId);
|
|
23687
|
+
if (fieldLengths == null)
|
|
23688
|
+
this._fieldLength.set(documentId, fieldLengths = []);
|
|
23689
|
+
fieldLengths[fieldId] = length;
|
|
23690
|
+
const averageFieldLength = this._avgFieldLength[fieldId] || 0;
|
|
23691
|
+
const totalFieldLength = averageFieldLength * count + length;
|
|
23692
|
+
this._avgFieldLength[fieldId] = totalFieldLength / (count + 1);
|
|
23693
|
+
}
|
|
23694
|
+
removeFieldLength(documentId, fieldId, count, length) {
|
|
23695
|
+
if (count === 1) {
|
|
23696
|
+
this._avgFieldLength[fieldId] = 0;
|
|
23697
|
+
return;
|
|
23698
|
+
}
|
|
23699
|
+
const totalFieldLength = this._avgFieldLength[fieldId] * count - length;
|
|
23700
|
+
this._avgFieldLength[fieldId] = totalFieldLength / (count - 1);
|
|
23701
|
+
}
|
|
23702
|
+
saveStoredFields(documentId, doc) {
|
|
23703
|
+
const { storeFields, extractField } = this._options;
|
|
23704
|
+
if (storeFields == null || storeFields.length === 0) {
|
|
23705
|
+
return;
|
|
23706
|
+
}
|
|
23707
|
+
let documentFields = this._storedFields.get(documentId);
|
|
23708
|
+
if (documentFields == null)
|
|
23709
|
+
this._storedFields.set(documentId, documentFields = {});
|
|
23710
|
+
for (const fieldName of storeFields) {
|
|
23711
|
+
const fieldValue = extractField(doc, fieldName);
|
|
23712
|
+
if (fieldValue !== undefined)
|
|
23713
|
+
documentFields[fieldName] = fieldValue;
|
|
23714
|
+
}
|
|
23715
|
+
}
|
|
23716
|
+
}
|
|
23717
|
+
MiniSearch.wildcard = Symbol("*");
|
|
23718
|
+
var getOwnProperty = (object, property) => Object.prototype.hasOwnProperty.call(object, property) ? object[property] : undefined;
|
|
23719
|
+
var combinators = {
|
|
23720
|
+
[OR]: (a, b) => {
|
|
23721
|
+
for (const docId of b.keys()) {
|
|
23722
|
+
const existing = a.get(docId);
|
|
23723
|
+
if (existing == null) {
|
|
23724
|
+
a.set(docId, b.get(docId));
|
|
23725
|
+
} else {
|
|
23726
|
+
const { score, terms, match } = b.get(docId);
|
|
23727
|
+
existing.score = existing.score + score;
|
|
23728
|
+
existing.match = Object.assign(existing.match, match);
|
|
23729
|
+
assignUniqueTerms(existing.terms, terms);
|
|
23730
|
+
}
|
|
23731
|
+
}
|
|
23732
|
+
return a;
|
|
23733
|
+
},
|
|
23734
|
+
[AND]: (a, b) => {
|
|
23735
|
+
const combined = new Map;
|
|
23736
|
+
for (const docId of b.keys()) {
|
|
23737
|
+
const existing = a.get(docId);
|
|
23738
|
+
if (existing == null)
|
|
23739
|
+
continue;
|
|
23740
|
+
const { score, terms, match } = b.get(docId);
|
|
23741
|
+
assignUniqueTerms(existing.terms, terms);
|
|
23742
|
+
combined.set(docId, {
|
|
23743
|
+
score: existing.score + score,
|
|
23744
|
+
terms: existing.terms,
|
|
23745
|
+
match: Object.assign(existing.match, match)
|
|
23746
|
+
});
|
|
23747
|
+
}
|
|
23748
|
+
return combined;
|
|
23749
|
+
},
|
|
23750
|
+
[AND_NOT]: (a, b) => {
|
|
23751
|
+
for (const docId of b.keys())
|
|
23752
|
+
a.delete(docId);
|
|
23753
|
+
return a;
|
|
23754
|
+
}
|
|
23755
|
+
};
|
|
23756
|
+
var defaultBM25params = { k: 1.2, b: 0.7, d: 0.5 };
|
|
23757
|
+
var calcBM25Score = (termFreq, matchingCount, totalCount, fieldLength, avgFieldLength, bm25params) => {
|
|
23758
|
+
const { k, b, d } = bm25params;
|
|
23759
|
+
const invDocFreq = Math.log(1 + (totalCount - matchingCount + 0.5) / (matchingCount + 0.5));
|
|
23760
|
+
return invDocFreq * (d + termFreq * (k + 1) / (termFreq + k * (1 - b + b * fieldLength / avgFieldLength)));
|
|
23761
|
+
};
|
|
23762
|
+
var termToQuerySpec = (options) => (term, i, terms) => {
|
|
23763
|
+
const fuzzy = typeof options.fuzzy === "function" ? options.fuzzy(term, i, terms) : options.fuzzy || false;
|
|
23764
|
+
const prefix = typeof options.prefix === "function" ? options.prefix(term, i, terms) : options.prefix === true;
|
|
23765
|
+
const termBoost = typeof options.boostTerm === "function" ? options.boostTerm(term, i, terms) : 1;
|
|
23766
|
+
return { term, fuzzy, prefix, termBoost };
|
|
23767
|
+
};
|
|
23768
|
+
var defaultOptions = {
|
|
23769
|
+
idField: "id",
|
|
23770
|
+
extractField: (document, fieldName) => document[fieldName],
|
|
23771
|
+
stringifyField: (fieldValue, fieldName) => fieldValue.toString(),
|
|
23772
|
+
tokenize: (text) => text.split(SPACE_OR_PUNCTUATION),
|
|
23773
|
+
processTerm: (term) => term.toLowerCase(),
|
|
23774
|
+
fields: undefined,
|
|
23775
|
+
searchOptions: undefined,
|
|
23776
|
+
storeFields: [],
|
|
23777
|
+
logger: (level, message) => {
|
|
23778
|
+
if (typeof (console === null || console === undefined ? undefined : console[level]) === "function")
|
|
23779
|
+
console[level](message);
|
|
23780
|
+
},
|
|
23781
|
+
autoVacuum: true
|
|
23782
|
+
};
|
|
23783
|
+
var defaultSearchOptions = {
|
|
23784
|
+
combineWith: OR,
|
|
23785
|
+
prefix: false,
|
|
23786
|
+
fuzzy: false,
|
|
23787
|
+
maxFuzzy: 6,
|
|
23788
|
+
boost: {},
|
|
23789
|
+
weights: { fuzzy: 0.45, prefix: 0.375 },
|
|
23790
|
+
bm25: defaultBM25params
|
|
23791
|
+
};
|
|
23792
|
+
var defaultAutoSuggestOptions = {
|
|
23793
|
+
combineWith: AND,
|
|
23794
|
+
prefix: (term, i, terms) => i === terms.length - 1
|
|
23795
|
+
};
|
|
23796
|
+
var defaultVacuumOptions = { batchSize: 1000, batchWait: 10 };
|
|
23797
|
+
var defaultVacuumConditions = { minDirtFactor: 0.1, minDirtCount: 20 };
|
|
23798
|
+
var defaultAutoVacuumOptions = { ...defaultVacuumOptions, ...defaultVacuumConditions };
|
|
23799
|
+
var assignUniqueTerm = (target, term) => {
|
|
23800
|
+
if (!target.includes(term))
|
|
23801
|
+
target.push(term);
|
|
23802
|
+
};
|
|
23803
|
+
var assignUniqueTerms = (target, source) => {
|
|
23804
|
+
for (const term of source) {
|
|
23805
|
+
if (!target.includes(term))
|
|
23806
|
+
target.push(term);
|
|
23807
|
+
}
|
|
23808
|
+
};
|
|
23809
|
+
var byScore = ({ score: a }, { score: b }) => b - a;
|
|
23810
|
+
var createMap = () => new Map;
|
|
23811
|
+
var objectToNumericMap = (object) => {
|
|
23812
|
+
const map = new Map;
|
|
23813
|
+
for (const key of Object.keys(object)) {
|
|
23814
|
+
map.set(parseInt(key, 10), object[key]);
|
|
23815
|
+
}
|
|
23816
|
+
return map;
|
|
23817
|
+
};
|
|
23818
|
+
var objectToNumericMapAsync = async (object) => {
|
|
23819
|
+
const map = new Map;
|
|
23820
|
+
let count = 0;
|
|
23821
|
+
for (const key of Object.keys(object)) {
|
|
23822
|
+
map.set(parseInt(key, 10), object[key]);
|
|
23823
|
+
if (++count % 1000 === 0) {
|
|
23824
|
+
await wait(0);
|
|
23825
|
+
}
|
|
23826
|
+
}
|
|
23827
|
+
return map;
|
|
23828
|
+
};
|
|
23829
|
+
var wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
23830
|
+
var SPACE_OR_PUNCTUATION = /[\n\r\p{Z}\p{P}]+/u;
|
|
23831
|
+
|
|
23832
|
+
// src/commands/search.ts
|
|
23833
|
+
var MAX_RESULTS = 5;
|
|
23834
|
+
var FIELD_BOOST = { command: 8, summary: 5, context: 0.5 };
|
|
23835
|
+
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(" "));
|
|
23836
|
+
var MIN_EXPANDED_TERM_LENGTH = 3;
|
|
23837
|
+
var MIN_FUZZY_TERM_LENGTH = 5;
|
|
23838
|
+
var SEARCH_OPTIONS = {
|
|
23839
|
+
boost: FIELD_BOOST,
|
|
23840
|
+
processTerm: (term) => {
|
|
23841
|
+
const lower = term.toLowerCase();
|
|
23842
|
+
return STOP_WORDS.has(lower) ? null : lower;
|
|
23843
|
+
},
|
|
23844
|
+
prefix: (term) => term.length >= MIN_EXPANDED_TERM_LENGTH,
|
|
23845
|
+
fuzzy: (term) => term.length >= MIN_FUZZY_TERM_LENGTH ? 0.2 : false
|
|
23846
|
+
};
|
|
23847
|
+
var TRAILING_PARENTHETICAL = /\s*\([^)]*\)\s*$/;
|
|
23848
|
+
var COLUMNS3 = [
|
|
23849
|
+
{ header: "command", value: (result) => result.command },
|
|
23850
|
+
{ header: "summary", value: (result) => result.summary }
|
|
23851
|
+
];
|
|
23852
|
+
function isHidden(command) {
|
|
23853
|
+
return command._hidden === true;
|
|
23854
|
+
}
|
|
23855
|
+
function visibleSubcommands(command) {
|
|
23856
|
+
return command.commands.filter((child) => child.name() !== "help" && !isHidden(child));
|
|
23857
|
+
}
|
|
23858
|
+
function collectDocuments(command, path, ancestors, exclude) {
|
|
23859
|
+
const children = visibleSubcommands(command);
|
|
23860
|
+
if (children.length === 0) {
|
|
23861
|
+
const display = command.description();
|
|
23862
|
+
return [
|
|
23863
|
+
{
|
|
23864
|
+
command: ["sim", ...path].join(" "),
|
|
23865
|
+
display,
|
|
23866
|
+
summary: display.replace(TRAILING_PARENTHETICAL, ""),
|
|
23867
|
+
context: [
|
|
23868
|
+
...ancestors,
|
|
23869
|
+
...command.registeredArguments.map((argument) => `${argument.name()} ${argument.description}`.trim()),
|
|
23870
|
+
...command.options.filter((option) => !option.hidden).map((option) => `${option.long ?? option.short ?? ""} ${option.description}`.trim())
|
|
23871
|
+
].join(" ")
|
|
23872
|
+
}
|
|
23873
|
+
];
|
|
23874
|
+
}
|
|
23875
|
+
const nextAncestors = path.length > 0 ? [...ancestors, command.description()] : ancestors;
|
|
23876
|
+
return children.filter((child) => child !== exclude).flatMap((child) => collectDocuments(child, [...path, child.name()], nextAncestors, exclude));
|
|
23877
|
+
}
|
|
23878
|
+
function searchCommands(program, query, exclude) {
|
|
23879
|
+
const index = new MiniSearch({
|
|
23880
|
+
fields: ["command", "summary", "context"],
|
|
23881
|
+
storeFields: ["command", "display"],
|
|
23882
|
+
idField: "command"
|
|
23883
|
+
});
|
|
23884
|
+
index.addAll(collectDocuments(program, [], [], exclude));
|
|
23885
|
+
return index.search(query, SEARCH_OPTIONS).slice(0, MAX_RESULTS).map((hit) => ({ command: hit.command, summary: hit.display }));
|
|
23886
|
+
}
|
|
23887
|
+
function searchCommand() {
|
|
23888
|
+
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", `
|
|
23889
|
+
Ranks the commands this CLI ships, locally; your query is never sent anywhere.
|
|
23890
|
+
Returns the ${MAX_RESULTS} best matches. Run \`<command> --help\` on one for its flags.
|
|
23891
|
+
|
|
23892
|
+
Examples:
|
|
23893
|
+
$ sim cli search "cancel a running workflow"
|
|
23894
|
+
$ sim cli search list table rows`).action((words, _options, command) => {
|
|
23895
|
+
let program = command;
|
|
23896
|
+
while (program.parent)
|
|
23897
|
+
program = program.parent;
|
|
23898
|
+
const results = searchCommands(program, words.join(" "), command);
|
|
23899
|
+
printList(profileFrom(command).output, results, COLUMNS3);
|
|
23900
|
+
});
|
|
23901
|
+
}
|
|
23902
|
+
function cliCommand() {
|
|
23903
|
+
return new Command("cli").description("Discover commands in this CLI").addCommand(searchCommand());
|
|
23904
|
+
}
|
|
23905
|
+
|
|
22761
23906
|
// src/terminal/secret-input.ts
|
|
22762
23907
|
import { emitKeypressEvents } from "node:readline";
|
|
22763
23908
|
var MAX_SECRET_LENGTH = 65536;
|
|
@@ -22919,7 +24064,7 @@ function attachSecretCommands(program) {
|
|
|
22919
24064
|
if (!secrets)
|
|
22920
24065
|
throw new Error("The generated secrets command group is missing");
|
|
22921
24066
|
const redactionSpellings = new Set;
|
|
22922
|
-
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));
|
|
24067
|
+
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));
|
|
22923
24068
|
}
|
|
22924
24069
|
|
|
22925
24070
|
// src/telemetry/transport.ts
|
|
@@ -23165,19 +24310,28 @@ or custom-tool ID can open with a dash, which reads as a flag; put -- in front
|
|
|
23165
24310
|
of it, as in sim audit-logs get -- -HlDcD1z76nK6R4crsUp0.
|
|
23166
24311
|
|
|
23167
24312
|
Examples:
|
|
24313
|
+
$ sim cli search "cancel a workflow run" Find the command for a task
|
|
23168
24314
|
$ sim login Authorize the default profile
|
|
23169
24315
|
$ sim login --profile dev --endpoint http://localhost:3000
|
|
23170
24316
|
$ sim profile add acme --workspace 7e2d9c14-6b83-4a55-8f01-c4d3e9a76b28
|
|
23171
24317
|
$ sim workflows list
|
|
23172
24318
|
$ sim logs list --level error --limit 20
|
|
23173
|
-
$ sim configure --set-output
|
|
23174
|
-
$ sim --output
|
|
24319
|
+
$ sim configure --set-output table Prefer tables over the JSON default
|
|
24320
|
+
$ sim --output table tables get tbl_9f3c1a05d4b7426e8c2f0917ab35de64
|
|
23175
24321
|
$ sim knowledge search --query "refund policy" --kb 4c1b7f60-2d55-4a3e-9c18-70b6ea2f9d31
|
|
23176
24322
|
$ sim workflows export 3a9e21d8-5f47-4c0b-b2ea-91d7c6034ef8 > wf.json
|
|
23177
24323
|
$ sim workflows import --workflow @wf.json
|
|
23178
24324
|
$ sim knowledge export 4c1b7f60-2d55-4a3e-9c18-70b6ea2f9d31 -o ./kb.simkb.zip
|
|
23179
24325
|
$ sim whoami --profile dev
|
|
23180
24326
|
`;
|
|
24327
|
+
var AGENT_DISCOVERY_NOTE = `=== AGENT COMMAND DISCOVERY ===
|
|
24328
|
+
Do not explore commands by chaining nested --help calls. Instead run:
|
|
24329
|
+
sim cli search "<describe the task you want to accomplish>"
|
|
24330
|
+
It returns the 5 best-matching commands, each with a one-line summary. Pick the
|
|
24331
|
+
best match rather than repeating similar searches, then run
|
|
24332
|
+
\`<command> --help\` for its flags.
|
|
24333
|
+
=== END AGENT COMMAND DISCOVERY ===
|
|
24334
|
+
`;
|
|
23181
24335
|
var ROOT_VALUE_FLAGS = new Set([
|
|
23182
24336
|
"-P",
|
|
23183
24337
|
"--profile",
|
|
@@ -23215,6 +24369,7 @@ function addVersionOption(program) {
|
|
|
23215
24369
|
program.version(cliVersion(), "-V, --version [none]", "output the version number (takes no value)");
|
|
23216
24370
|
}
|
|
23217
24371
|
function buildProgram(options = {}) {
|
|
24372
|
+
const env = options.env ?? process.env;
|
|
23218
24373
|
const program = options.program ?? new Command;
|
|
23219
24374
|
program.name("sim").description(PROGRAM_DESCRIPTION);
|
|
23220
24375
|
if (options.version !== false)
|
|
@@ -23231,6 +24386,7 @@ function buildProgram(options = {}) {
|
|
|
23231
24386
|
const update = updateCommand();
|
|
23232
24387
|
program.addCommand(update);
|
|
23233
24388
|
program.addCommand(telemetryCommand());
|
|
24389
|
+
program.addCommand(cliCommand());
|
|
23234
24390
|
for (const command of buildGeneratedCommands()) {
|
|
23235
24391
|
program.addCommand(command);
|
|
23236
24392
|
}
|
|
@@ -23238,6 +24394,7 @@ function buildProgram(options = {}) {
|
|
|
23238
24394
|
attachProtocolCommands(program);
|
|
23239
24395
|
attachSecretCommands(program);
|
|
23240
24396
|
program.addHelpText("after", options.helpText ?? HELP_EPILOGUE);
|
|
24397
|
+
program.addHelpText("beforeAll", ({ command }) => detectCodingAgent(env) !== undefined && command.commands.length > 0 ? AGENT_DISCOVERY_NOTE : "");
|
|
23241
24398
|
program.hook("preAction", async (_program, command) => {
|
|
23242
24399
|
if (command === update)
|
|
23243
24400
|
return;
|