Files
marqdo/src/host/dispatch.rs
T
cflmyandCursor 88dc6d5a54 feat(core): Artifact Metadata Binding (${env|arg|sys|secret})
Load-time resolve of frontmatter bindings into Module.metadata; Secret
masking; sys.meta / --bind; llm ctor prefers meta over env_get.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-24 19:51:24 +08:00

1549 lines
65 KiB
Rust

//! Host function registry and dispatch.
use std::collections::HashMap;
use crate::host::{
cli, csv, datetime, encoding, fs, hash, html_ops, json, log, math, net, path, re, secrets, stats,
sys, text_ops, time, toml_ops, url_ops, uuid_ops, writeback, HostContext,
};
#[cfg(feature = "exec-host")]
use crate::host::{foreign, subtask};
#[cfg(feature = "plugin-host")]
use crate::host::plugin;
use crate::value::Value;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u16)]
pub enum HostFn {
ReadText = 1,
WriteText = 2,
AppendText = 3,
Exists = 4,
ListDir = 5,
MakeDir = 6,
Remove = 7,
NowUnix = 8,
NowMs = 9,
FormatTime = 10,
SleepMs = 11,
ParseTime = 12,
EnvGet = 13,
EnvSet = 14,
Args = 15,
Cwd = 16,
Exit = 17,
Exec = 18,
JsonParse = 19,
JsonStringify = 20,
JsonGet = 21,
JsonKeys = 22,
HttpGet = 23,
HttpPost = 24,
UrlEncode = 25,
// math
Pi = 26,
EConst = 27,
Num = 28,
MathAdd = 29,
MathSub = 30,
MathMul = 31,
MathDiv = 32,
MathPow = 33,
MathNeg = 34,
MathSin = 35,
MathCos = 36,
MathTan = 37,
MathAsin = 38,
MathAcos = 39,
MathAtan = 40,
MathSqrt = 41,
MathAbs = 42,
MathLn = 43,
MathExp = 44,
MathFloor = 45,
MathCeil = 46,
MathMin = 47,
MathMax = 48,
Random = 49,
RandomInt = 50,
Seed = 51,
Formula = 52,
Simplify = 53,
Expand = 54,
Diff = 55,
Subs = 56,
Eval = 57,
Solve = 58,
Plot = 59,
PlotPoints = 60,
PlotConic = 61,
ForeignSetCmd = 62,
ForeignRun = 63,
ForeignRunLang = 64,
ForeignLangs = 65,
DotenvLoad = 66,
HttpRequest = 67,
JsonQuote = 68,
PluginLoad = 69,
PluginUnload = 70,
PluginList = 71,
ExtNativePath = 72,
MapSet = 76,
ListAppend = 77,
WritebackRecord = 84,
WritebackGet = 85,
WritebackClear = 86,
WritebackList = 87,
SubtaskSpawn = 88,
SubtaskPoll = 89,
SubtaskJoin = 90,
SubtaskKill = 91,
SubtaskWaitAll = 92,
WritebackEnsure = 93,
OuterCallLine = 94,
TextPatch = 95,
ApplyPatchBlocks = 96,
WritebackScanPath = 97,
HttpPostSse = 98,
OpenAiSseParse = 99,
StreamPublish = 100,
CollectionPut = 101,
ListPrepend = 102,
ListConcat = 103,
ListInsert = 104,
ListSetAt = 105,
ListRemoveAt = 106,
ListSlice = 107,
ListContains = 108,
ListIndexOf = 109,
ListReverse = 110,
ListFirst = 111,
ListLast = 112,
MapGet = 113,
MapDelete = 114,
MapHas = 115,
MapKeys = 116,
MapValues = 117,
MapItems = 118,
MapMerge = 119,
MapSize = 120,
CollectionClear = 121,
CookieParse = 122,
MultipartParse = 123,
MarkdownParse = 124,
ReIsMatch = 125,
ReFind = 126,
ReFindAll = 127,
ReReplace = 128,
ReSplit = 129,
EncodingBase64Encode = 130,
EncodingBase64Decode = 131,
EncodingHexEncode = 132,
EncodingHexDecode = 133,
PathJoin = 134,
PathSplit = 135,
PathFileName = 136,
PathParent = 137,
PathExtension = 138,
PathNormalize = 139,
PathIsAbsolute = 140,
FsCopyFile = 141,
FsMove = 142,
FsMakeTemp = 143,
HashSha256 = 144,
HashSha1 = 145,
HashMd5 = 146,
HashHmacSha256 = 147,
SecretsTokenHex = 148,
SecretsTokenUrlsafe = 149,
TextContains = 150,
TextStartsWith = 151,
TextEndsWith = 152,
TextReplace = 153,
TextToUpper = 154,
TextToLower = 155,
TextRepeat = 156,
TextPad = 157,
CsvParse = 158,
CsvStringify = 159,
ListSort = 160,
ListSortBy = 161,
ListUnique = 162,
ListChunk = 163,
ListZip = 164,
ListFlatten = 165,
CliParse = 166,
LogSetLevel = 167,
LogLine = 168,
UuidV4 = 169,
DatetimeNow = 170,
DatetimeFromUnix = 171,
DatetimeToUnix = 172,
DatetimeParse = 173,
DatetimeFormat = 174,
DatetimeAdd = 175,
DatetimeInZone = 176,
UrlParse = 177,
UrlQueryParse = 178,
UrlQueryStringify = 179,
TomlParse = 180,
HtmlEscape = 181,
HtmlUnescape = 182,
EncodingBase32Encode = 183,
EncodingBase32Decode = 184,
FsMakeDirs = 185,
FsRemoveTree = 186,
FsStat = 187,
FsWalk = 188,
StatsMean = 189,
StatsMedian = 190,
StatsStdev = 191,
Meta = 192,
MetaGet = 193,
}
impl HostFn {
pub fn from_u16(id: u16) -> Option<Self> {
Some(match id {
1 => Self::ReadText,
2 => Self::WriteText,
3 => Self::AppendText,
4 => Self::Exists,
5 => Self::ListDir,
6 => Self::MakeDir,
7 => Self::Remove,
8 => Self::NowUnix,
9 => Self::NowMs,
10 => Self::FormatTime,
11 => Self::SleepMs,
12 => Self::ParseTime,
13 => Self::EnvGet,
14 => Self::EnvSet,
15 => Self::Args,
16 => Self::Cwd,
17 => Self::Exit,
18 => Self::Exec,
19 => Self::JsonParse,
20 => Self::JsonStringify,
21 => Self::JsonGet,
22 => Self::JsonKeys,
23 => Self::HttpGet,
24 => Self::HttpPost,
25 => Self::UrlEncode,
26 => Self::Pi,
27 => Self::EConst,
28 => Self::Num,
29 => Self::MathAdd,
30 => Self::MathSub,
31 => Self::MathMul,
32 => Self::MathDiv,
33 => Self::MathPow,
34 => Self::MathNeg,
35 => Self::MathSin,
36 => Self::MathCos,
37 => Self::MathTan,
38 => Self::MathAsin,
39 => Self::MathAcos,
40 => Self::MathAtan,
41 => Self::MathSqrt,
42 => Self::MathAbs,
43 => Self::MathLn,
44 => Self::MathExp,
45 => Self::MathFloor,
46 => Self::MathCeil,
47 => Self::MathMin,
48 => Self::MathMax,
49 => Self::Random,
50 => Self::RandomInt,
51 => Self::Seed,
52 => Self::Formula,
53 => Self::Simplify,
54 => Self::Expand,
55 => Self::Diff,
56 => Self::Subs,
57 => Self::Eval,
58 => Self::Solve,
59 => Self::Plot,
60 => Self::PlotPoints,
61 => Self::PlotConic,
62 => Self::ForeignSetCmd,
63 => Self::ForeignRun,
64 => Self::ForeignRunLang,
65 => Self::ForeignLangs,
66 => Self::DotenvLoad,
67 => Self::HttpRequest,
68 => Self::JsonQuote,
69 => Self::PluginLoad,
70 => Self::PluginUnload,
71 => Self::PluginList,
72 => Self::ExtNativePath,
76 => Self::MapSet,
77 => Self::ListAppend,
84 => Self::WritebackRecord,
85 => Self::WritebackGet,
86 => Self::WritebackClear,
87 => Self::WritebackList,
88 => Self::SubtaskSpawn,
89 => Self::SubtaskPoll,
90 => Self::SubtaskJoin,
91 => Self::SubtaskKill,
92 => Self::SubtaskWaitAll,
93 => Self::WritebackEnsure,
94 => Self::OuterCallLine,
95 => Self::TextPatch,
96 => Self::ApplyPatchBlocks,
97 => Self::WritebackScanPath,
98 => Self::HttpPostSse,
99 => Self::OpenAiSseParse,
100 => Self::StreamPublish,
101 => Self::CollectionPut,
102 => Self::ListPrepend,
103 => Self::ListConcat,
104 => Self::ListInsert,
105 => Self::ListSetAt,
106 => Self::ListRemoveAt,
107 => Self::ListSlice,
108 => Self::ListContains,
109 => Self::ListIndexOf,
110 => Self::ListReverse,
111 => Self::ListFirst,
112 => Self::ListLast,
113 => Self::MapGet,
114 => Self::MapDelete,
115 => Self::MapHas,
116 => Self::MapKeys,
117 => Self::MapValues,
118 => Self::MapItems,
119 => Self::MapMerge,
120 => Self::MapSize,
121 => Self::CollectionClear,
122 => Self::CookieParse,
123 => Self::MultipartParse,
124 => Self::MarkdownParse,
125 => Self::ReIsMatch,
126 => Self::ReFind,
127 => Self::ReFindAll,
128 => Self::ReReplace,
129 => Self::ReSplit,
130 => Self::EncodingBase64Encode,
131 => Self::EncodingBase64Decode,
132 => Self::EncodingHexEncode,
133 => Self::EncodingHexDecode,
134 => Self::PathJoin,
135 => Self::PathSplit,
136 => Self::PathFileName,
137 => Self::PathParent,
138 => Self::PathExtension,
139 => Self::PathNormalize,
140 => Self::PathIsAbsolute,
141 => Self::FsCopyFile,
142 => Self::FsMove,
143 => Self::FsMakeTemp,
144 => Self::HashSha256,
145 => Self::HashSha1,
146 => Self::HashMd5,
147 => Self::HashHmacSha256,
148 => Self::SecretsTokenHex,
149 => Self::SecretsTokenUrlsafe,
150 => Self::TextContains,
151 => Self::TextStartsWith,
152 => Self::TextEndsWith,
153 => Self::TextReplace,
154 => Self::TextToUpper,
155 => Self::TextToLower,
156 => Self::TextRepeat,
157 => Self::TextPad,
158 => Self::CsvParse,
159 => Self::CsvStringify,
160 => Self::ListSort,
161 => Self::ListSortBy,
162 => Self::ListUnique,
163 => Self::ListChunk,
164 => Self::ListZip,
165 => Self::ListFlatten,
166 => Self::CliParse,
167 => Self::LogSetLevel,
168 => Self::LogLine,
169 => Self::UuidV4,
170 => Self::DatetimeNow,
171 => Self::DatetimeFromUnix,
172 => Self::DatetimeToUnix,
173 => Self::DatetimeParse,
174 => Self::DatetimeFormat,
175 => Self::DatetimeAdd,
176 => Self::DatetimeInZone,
177 => Self::UrlParse,
178 => Self::UrlQueryParse,
179 => Self::UrlQueryStringify,
180 => Self::TomlParse,
181 => Self::HtmlEscape,
182 => Self::HtmlUnescape,
183 => Self::EncodingBase32Encode,
184 => Self::EncodingBase32Decode,
185 => Self::FsMakeDirs,
186 => Self::FsRemoveTree,
187 => Self::FsStat,
188 => Self::FsWalk,
189 => Self::StatsMean,
190 => Self::StatsMedian,
191 => Self::StatsStdev,
192 => Self::Meta,
193 => Self::MetaGet,
_ => return None,
})
}
pub fn from_name(name: &str) -> Option<Self> {
Some(match name {
"host_read_text" => Self::ReadText,
"host_write_text" => Self::WriteText,
"host_append_text" => Self::AppendText,
"host_exists" => Self::Exists,
"host_list_dir" => Self::ListDir,
"host_make_dir" => Self::MakeDir,
"host_remove" => Self::Remove,
"host_now_unix" => Self::NowUnix,
"host_now_ms" => Self::NowMs,
"host_format_time" => Self::FormatTime,
"host_sleep_ms" => Self::SleepMs,
"host_parse_time" => Self::ParseTime,
"host_env_get" => Self::EnvGet,
"host_env_set" => Self::EnvSet,
"host_args" => Self::Args,
"host_cwd" => Self::Cwd,
"host_exit" => Self::Exit,
"host_exec" => Self::Exec,
"host_json_parse" => Self::JsonParse,
"host_json_stringify" => Self::JsonStringify,
"host_json_get" => Self::JsonGet,
"host_json_keys" => Self::JsonKeys,
// Aliases so optional `headers` / `content_type` bind like plot.
"host_http_get" | "http_get" => Self::HttpGet,
"host_http_post" | "http_post" => Self::HttpPost,
"host_http_post_sse" | "http_post_sse" => Self::HttpPostSse,
"host_openai_sse_parse" | "openai_sse_parse" => Self::OpenAiSseParse,
"host_stream_publish" | "stream_publish" => Self::StreamPublish,
"host_url_encode" => Self::UrlEncode,
"host_pi" => Self::Pi,
"host_e" => Self::EConst,
"host_num" => Self::Num,
"host_math_add" => Self::MathAdd,
"host_math_sub" => Self::MathSub,
"host_math_mul" => Self::MathMul,
"host_math_div" => Self::MathDiv,
"host_math_pow" => Self::MathPow,
"host_math_neg" => Self::MathNeg,
"host_math_sin" => Self::MathSin,
"host_math_cos" => Self::MathCos,
"host_math_tan" => Self::MathTan,
"host_math_asin" => Self::MathAsin,
"host_math_acos" => Self::MathAcos,
"host_math_atan" => Self::MathAtan,
"host_math_sqrt" => Self::MathSqrt,
"host_math_abs" => Self::MathAbs,
"host_math_ln" => Self::MathLn,
"host_math_exp" => Self::MathExp,
"host_math_floor" => Self::MathFloor,
"host_math_ceil" => Self::MathCeil,
"host_math_min" => Self::MathMin,
"host_math_max" => Self::MathMax,
"host_random" => Self::Random,
"host_random_int" => Self::RandomInt,
"host_seed" => Self::Seed,
"host_formula" => Self::Formula,
"host_simplify" => Self::Simplify,
"host_expand" => Self::Expand,
"host_diff" => Self::Diff,
"host_subs" => Self::Subs,
"host_eval" => Self::Eval,
"host_solve" => Self::Solve,
// Friendly aliases so L1 `plot` / `绘图` get host optionals (`grid`, `path`, …)
// instead of thin wrappers that only forward required params.
"host_plot" | "plot" | "绘图" => Self::Plot,
"host_plot_points" | "plot_points" | "绘点列" => Self::PlotPoints,
"host_plot_conic" | "plot_conic" | "绘圆锥" => Self::PlotConic,
"host_foreign_set_cmd" => Self::ForeignSetCmd,
"host_foreign_run" => Self::ForeignRun,
"host_foreign_run_lang" => Self::ForeignRunLang,
"host_foreign_langs" => Self::ForeignLangs,
"host_dotenv_load" | "load_dotenv" => Self::DotenvLoad,
"host_http_request" | "http_request" => Self::HttpRequest,
"host_json_quote" | "quote" => Self::JsonQuote,
"host_plugin_load" | "plugin_load" => Self::PluginLoad,
"host_plugin_unload" | "plugin_unload" => Self::PluginUnload,
"host_plugin_list" | "plugin_list" => Self::PluginList,
"host_ext_native_path" | "ext_native_path" => Self::ExtNativePath,
"host_map_set" | "map_set" => Self::MapSet,
"host_list_append" | "list_append" => Self::ListAppend,
"host_writeback_record" | "writeback_record" => Self::WritebackRecord,
"host_writeback_get" | "writeback_get" => Self::WritebackGet,
"host_writeback_clear" | "writeback_clear" => Self::WritebackClear,
"host_writeback_list" | "writeback_list" => Self::WritebackList,
"host_writeback_ensure" | "writeback_ensure" => Self::WritebackEnsure,
"host_outer_call_line" | "outer_call_line" => Self::OuterCallLine,
"host_text_patch" | "text_patch" => Self::TextPatch,
"host_apply_patch_blocks" | "apply_patch_blocks" => Self::ApplyPatchBlocks,
"host_writeback_scan_path" | "writeback_scan_path" => Self::WritebackScanPath,
"host_subtask_spawn" | "subtask_spawn" => Self::SubtaskSpawn,
"host_subtask_poll" | "subtask_poll" => Self::SubtaskPoll,
"host_subtask_join" | "subtask_join" => Self::SubtaskJoin,
"host_subtask_kill" | "subtask_kill" => Self::SubtaskKill,
"host_subtask_wait_all" | "subtask_wait_all" => Self::SubtaskWaitAll,
"host_collection_put" | "collection_put" => Self::CollectionPut,
"host_list_prepend" | "list_prepend" => Self::ListPrepend,
"host_list_concat" | "list_concat" => Self::ListConcat,
"host_list_insert" | "list_insert" => Self::ListInsert,
"host_list_set_at" | "list_set_at" => Self::ListSetAt,
"host_list_remove_at" | "list_remove_at" => Self::ListRemoveAt,
"host_list_slice" | "list_slice" => Self::ListSlice,
"host_list_contains" | "list_contains" => Self::ListContains,
"host_list_index_of" | "list_index_of" => Self::ListIndexOf,
"host_list_reverse" | "list_reverse" => Self::ListReverse,
"host_list_first" | "list_first" => Self::ListFirst,
"host_list_last" | "list_last" => Self::ListLast,
"host_map_get" | "map_get" => Self::MapGet,
"host_map_delete" | "map_delete" => Self::MapDelete,
"host_map_has" | "map_has" => Self::MapHas,
"host_map_keys" | "map_keys" => Self::MapKeys,
"host_map_values" | "map_values" => Self::MapValues,
"host_map_items" | "map_items" => Self::MapItems,
"host_map_merge" | "map_merge" => Self::MapMerge,
"host_map_size" | "map_size" => Self::MapSize,
"host_collection_clear" | "collection_clear" => Self::CollectionClear,
"host_cookie_parse" | "cookie_parse" => Self::CookieParse,
"host_multipart_parse" | "multipart_parse" => Self::MultipartParse,
"host_markdown_parse" | "markdown_parse" => Self::MarkdownParse,
"host_re_is_match" | "re_is_match" => Self::ReIsMatch,
"host_re_find" | "re_find" => Self::ReFind,
"host_re_find_all" | "re_find_all" => Self::ReFindAll,
"host_re_replace" | "re_replace" => Self::ReReplace,
"host_re_split" | "re_split" => Self::ReSplit,
"host_encoding_base64_encode" | "encoding_base64_encode" => Self::EncodingBase64Encode,
"host_encoding_base64_decode" | "encoding_base64_decode" => Self::EncodingBase64Decode,
"host_encoding_hex_encode" | "encoding_hex_encode" => Self::EncodingHexEncode,
"host_encoding_hex_decode" | "encoding_hex_decode" => Self::EncodingHexDecode,
"host_path_join" | "path_join" => Self::PathJoin,
"host_path_split" | "path_split" => Self::PathSplit,
"host_path_file_name" | "path_file_name" => Self::PathFileName,
"host_path_parent" | "path_parent" => Self::PathParent,
"host_path_extension" | "path_extension" => Self::PathExtension,
"host_path_normalize" | "path_normalize" => Self::PathNormalize,
"host_path_is_absolute" | "path_is_absolute" => Self::PathIsAbsolute,
"host_copy_file" | "copy_file" => Self::FsCopyFile,
"host_move" | "move_path" => Self::FsMove,
"host_make_temp" | "make_temp" => Self::FsMakeTemp,
"host_hash_sha256" | "hash_sha256" => Self::HashSha256,
"host_hash_sha1" | "hash_sha1" => Self::HashSha1,
"host_hash_md5" | "hash_md5" => Self::HashMd5,
"host_hash_hmac_sha256" | "hash_hmac_sha256" => Self::HashHmacSha256,
"host_secrets_token_hex" | "secrets_token_hex" => Self::SecretsTokenHex,
"host_secrets_token_urlsafe" | "secrets_token_urlsafe" => Self::SecretsTokenUrlsafe,
"host_text_contains" | "text_contains" => Self::TextContains,
"host_text_starts_with" | "text_starts_with" => Self::TextStartsWith,
"host_text_ends_with" | "text_ends_with" => Self::TextEndsWith,
"host_text_replace" | "text_replace" => Self::TextReplace,
"host_text_to_upper" | "text_to_upper" => Self::TextToUpper,
"host_text_to_lower" | "text_to_lower" => Self::TextToLower,
"host_text_repeat" | "text_repeat" => Self::TextRepeat,
"host_text_pad" | "text_pad" => Self::TextPad,
"host_csv_parse" | "csv_parse" => Self::CsvParse,
"host_csv_stringify" | "csv_stringify" => Self::CsvStringify,
"host_list_sort" | "list_sort" => Self::ListSort,
"host_list_sort_by" | "list_sort_by" => Self::ListSortBy,
"host_list_unique" | "list_unique" => Self::ListUnique,
"host_list_chunk" | "list_chunk" => Self::ListChunk,
"host_list_zip" | "list_zip" => Self::ListZip,
"host_list_flatten" | "list_flatten" => Self::ListFlatten,
"host_cli_parse" | "cli_parse" => Self::CliParse,
"host_log_set_level" | "log_set_level" => Self::LogSetLevel,
"host_log_line" | "log_line" => Self::LogLine,
"host_uuid_v4" | "uuid_v4" => Self::UuidV4,
"host_datetime_now" | "datetime_now" => Self::DatetimeNow,
"host_datetime_from_unix" | "datetime_from_unix" => Self::DatetimeFromUnix,
"host_datetime_to_unix" | "datetime_to_unix" => Self::DatetimeToUnix,
"host_datetime_parse" | "datetime_parse" => Self::DatetimeParse,
"host_datetime_format" | "datetime_format" => Self::DatetimeFormat,
"host_datetime_add" | "datetime_add" => Self::DatetimeAdd,
"host_datetime_in_zone" | "datetime_in_zone" => Self::DatetimeInZone,
"host_url_parse" | "url_parse" => Self::UrlParse,
"host_url_query_parse" | "url_query_parse" => Self::UrlQueryParse,
"host_url_query_stringify" | "url_query_stringify" => Self::UrlQueryStringify,
"host_toml_parse" | "toml_parse" => Self::TomlParse,
"host_html_escape" | "html_escape" => Self::HtmlEscape,
"host_html_unescape" | "html_unescape" => Self::HtmlUnescape,
"host_encoding_base32_encode" | "encoding_base32_encode" => Self::EncodingBase32Encode,
"host_encoding_base32_decode" | "encoding_base32_decode" => Self::EncodingBase32Decode,
"host_make_dirs" | "make_dirs" => Self::FsMakeDirs,
"host_remove_tree" | "remove_tree" => Self::FsRemoveTree,
"host_stat" | "stat" => Self::FsStat,
"host_walk" | "walk" => Self::FsWalk,
"host_stats_mean" | "stats_mean" => Self::StatsMean,
"host_stats_median" | "stats_median" => Self::StatsMedian,
"host_stats_stdev" | "stats_stdev" => Self::StatsStdev,
"host_meta" | "meta" => Self::Meta,
"host_meta_get" | "meta_get" => Self::MetaGet,
_ => return None,
})
}
pub fn as_u16(self) -> u16 {
self as u16
}
pub fn name(self) -> &'static str {
match self {
Self::ReadText => "host_read_text",
Self::WriteText => "host_write_text",
Self::AppendText => "host_append_text",
Self::Exists => "host_exists",
Self::ListDir => "host_list_dir",
Self::MakeDir => "host_make_dir",
Self::Remove => "host_remove",
Self::NowUnix => "host_now_unix",
Self::NowMs => "host_now_ms",
Self::FormatTime => "host_format_time",
Self::SleepMs => "host_sleep_ms",
Self::ParseTime => "host_parse_time",
Self::EnvGet => "host_env_get",
Self::EnvSet => "host_env_set",
Self::Args => "host_args",
Self::Cwd => "host_cwd",
Self::Exit => "host_exit",
Self::Exec => "host_exec",
Self::JsonParse => "host_json_parse",
Self::JsonStringify => "host_json_stringify",
Self::JsonGet => "host_json_get",
Self::JsonKeys => "host_json_keys",
Self::HttpGet => "host_http_get",
Self::HttpPost => "host_http_post",
Self::HttpPostSse => "host_http_post_sse",
Self::OpenAiSseParse => "host_openai_sse_parse",
Self::StreamPublish => "host_stream_publish",
Self::UrlEncode => "host_url_encode",
Self::Pi => "host_pi",
Self::EConst => "host_e",
Self::Num => "host_num",
Self::MathAdd => "host_math_add",
Self::MathSub => "host_math_sub",
Self::MathMul => "host_math_mul",
Self::MathDiv => "host_math_div",
Self::MathPow => "host_math_pow",
Self::MathNeg => "host_math_neg",
Self::MathSin => "host_math_sin",
Self::MathCos => "host_math_cos",
Self::MathTan => "host_math_tan",
Self::MathAsin => "host_math_asin",
Self::MathAcos => "host_math_acos",
Self::MathAtan => "host_math_atan",
Self::MathSqrt => "host_math_sqrt",
Self::MathAbs => "host_math_abs",
Self::MathLn => "host_math_ln",
Self::MathExp => "host_math_exp",
Self::MathFloor => "host_math_floor",
Self::MathCeil => "host_math_ceil",
Self::MathMin => "host_math_min",
Self::MathMax => "host_math_max",
Self::Random => "host_random",
Self::RandomInt => "host_random_int",
Self::Seed => "host_seed",
Self::Formula => "host_formula",
Self::Simplify => "host_simplify",
Self::Expand => "host_expand",
Self::Diff => "host_diff",
Self::Subs => "host_subs",
Self::Eval => "host_eval",
Self::Solve => "host_solve",
Self::Plot => "host_plot",
Self::PlotPoints => "host_plot_points",
Self::PlotConic => "host_plot_conic",
Self::ForeignSetCmd => "host_foreign_set_cmd",
Self::ForeignRun => "host_foreign_run",
Self::ForeignRunLang => "host_foreign_run_lang",
Self::ForeignLangs => "host_foreign_langs",
Self::DotenvLoad => "host_dotenv_load",
Self::HttpRequest => "host_http_request",
Self::JsonQuote => "host_json_quote",
Self::PluginLoad => "host_plugin_load",
Self::PluginUnload => "host_plugin_unload",
Self::PluginList => "host_plugin_list",
Self::ExtNativePath => "host_ext_native_path",
Self::MapSet => "host_map_set",
Self::ListAppend => "host_list_append",
Self::CollectionPut => "host_collection_put",
Self::ListPrepend => "host_list_prepend",
Self::ListConcat => "host_list_concat",
Self::ListInsert => "host_list_insert",
Self::ListSetAt => "host_list_set_at",
Self::ListRemoveAt => "host_list_remove_at",
Self::ListSlice => "host_list_slice",
Self::ListContains => "host_list_contains",
Self::ListIndexOf => "host_list_index_of",
Self::ListReverse => "host_list_reverse",
Self::ListFirst => "host_list_first",
Self::ListLast => "host_list_last",
Self::MapGet => "host_map_get",
Self::MapDelete => "host_map_delete",
Self::MapHas => "host_map_has",
Self::MapKeys => "host_map_keys",
Self::MapValues => "host_map_values",
Self::MapItems => "host_map_items",
Self::MapMerge => "host_map_merge",
Self::MapSize => "host_map_size",
Self::CollectionClear => "host_collection_clear",
Self::CookieParse => "host_cookie_parse",
Self::MultipartParse => "host_multipart_parse",
Self::MarkdownParse => "host_markdown_parse",
Self::ReIsMatch => "host_re_is_match",
Self::ReFind => "host_re_find",
Self::ReFindAll => "host_re_find_all",
Self::ReReplace => "host_re_replace",
Self::ReSplit => "host_re_split",
Self::EncodingBase64Encode => "host_encoding_base64_encode",
Self::EncodingBase64Decode => "host_encoding_base64_decode",
Self::EncodingHexEncode => "host_encoding_hex_encode",
Self::EncodingHexDecode => "host_encoding_hex_decode",
Self::PathJoin => "host_path_join",
Self::PathSplit => "host_path_split",
Self::PathFileName => "host_path_file_name",
Self::PathParent => "host_path_parent",
Self::PathExtension => "host_path_extension",
Self::PathNormalize => "host_path_normalize",
Self::PathIsAbsolute => "host_path_is_absolute",
Self::FsCopyFile => "host_copy_file",
Self::FsMove => "host_move",
Self::FsMakeTemp => "host_make_temp",
Self::HashSha256 => "host_hash_sha256",
Self::HashSha1 => "host_hash_sha1",
Self::HashMd5 => "host_hash_md5",
Self::HashHmacSha256 => "host_hash_hmac_sha256",
Self::SecretsTokenHex => "host_secrets_token_hex",
Self::SecretsTokenUrlsafe => "host_secrets_token_urlsafe",
Self::TextContains => "host_text_contains",
Self::TextStartsWith => "host_text_starts_with",
Self::TextEndsWith => "host_text_ends_with",
Self::TextReplace => "host_text_replace",
Self::TextToUpper => "host_text_to_upper",
Self::TextToLower => "host_text_to_lower",
Self::TextRepeat => "host_text_repeat",
Self::TextPad => "host_text_pad",
Self::CsvParse => "host_csv_parse",
Self::CsvStringify => "host_csv_stringify",
Self::ListSort => "host_list_sort",
Self::ListSortBy => "host_list_sort_by",
Self::ListUnique => "host_list_unique",
Self::ListChunk => "host_list_chunk",
Self::ListZip => "host_list_zip",
Self::ListFlatten => "host_list_flatten",
Self::CliParse => "host_cli_parse",
Self::LogSetLevel => "host_log_set_level",
Self::LogLine => "host_log_line",
Self::UuidV4 => "host_uuid_v4",
Self::DatetimeNow => "host_datetime_now",
Self::DatetimeFromUnix => "host_datetime_from_unix",
Self::DatetimeToUnix => "host_datetime_to_unix",
Self::DatetimeParse => "host_datetime_parse",
Self::DatetimeFormat => "host_datetime_format",
Self::DatetimeAdd => "host_datetime_add",
Self::DatetimeInZone => "host_datetime_in_zone",
Self::UrlParse => "host_url_parse",
Self::UrlQueryParse => "host_url_query_parse",
Self::UrlQueryStringify => "host_url_query_stringify",
Self::TomlParse => "host_toml_parse",
Self::HtmlEscape => "host_html_escape",
Self::HtmlUnescape => "host_html_unescape",
Self::EncodingBase32Encode => "host_encoding_base32_encode",
Self::EncodingBase32Decode => "host_encoding_base32_decode",
Self::FsMakeDirs => "host_make_dirs",
Self::FsRemoveTree => "host_remove_tree",
Self::FsStat => "host_stat",
Self::FsWalk => "host_walk",
Self::StatsMean => "host_stats_mean",
Self::StatsMedian => "host_stats_median",
Self::StatsStdev => "host_stats_stdev",
Self::Meta => "host_meta",
Self::MetaGet => "host_meta_get",
Self::WritebackRecord => "host_writeback_record",
Self::WritebackGet => "host_writeback_get",
Self::WritebackClear => "host_writeback_clear",
Self::WritebackList => "host_writeback_list",
Self::WritebackEnsure => "host_writeback_ensure",
Self::OuterCallLine => "host_outer_call_line",
Self::TextPatch => "host_text_patch",
Self::ApplyPatchBlocks => "host_apply_patch_blocks",
Self::WritebackScanPath => "host_writeback_scan_path",
Self::SubtaskSpawn => "host_subtask_spawn",
Self::SubtaskPoll => "host_subtask_poll",
Self::SubtaskJoin => "host_subtask_join",
Self::SubtaskKill => "host_subtask_kill",
Self::SubtaskWaitAll => "host_subtask_wait_all",
}
}
pub fn required_params(self) -> &'static [&'static str] {
match self {
Self::ReadText | Self::Exists | Self::ListDir | Self::MakeDir | Self::Remove => {
&["path"]
}
Self::WriteText | Self::AppendText => &["path", "text"],
Self::NowUnix | Self::NowMs | Self::Args | Self::Cwd | Self::Meta => &[],
Self::FormatTime => &["unix", "pattern"],
Self::ParseTime => &["text", "pattern"],
Self::SleepMs => &["ms"],
Self::EnvGet => &["name"],
Self::MetaGet => &["key"],
Self::EnvSet => &["name", "value"],
Self::Exit => &["code"],
Self::Exec => &["cmd"],
Self::JsonParse | Self::UrlEncode | Self::JsonQuote => &["text"],
Self::JsonStringify | Self::JsonKeys => &["value"],
Self::JsonGet => &["value", "key"],
Self::HttpGet => &["url"],
Self::HttpPost => &["url", "body"],
Self::HttpPostSse => &["url", "body"],
Self::OpenAiSseParse => &["text"],
Self::StreamPublish => &["event"],
Self::HttpRequest => &["method", "url"],
Self::DotenvLoad => &[],
Self::Pi | Self::EConst | Self::Random => &[],
Self::Num | Self::MathNeg | Self::MathSin | Self::MathCos | Self::MathTan
| Self::MathAsin | Self::MathAcos | Self::MathAtan | Self::MathSqrt
| Self::MathAbs | Self::MathLn | Self::MathExp | Self::MathFloor | Self::MathCeil
| Self::Seed | Self::Formula | Self::Simplify | Self::Expand => &["value"],
Self::MathAdd | Self::MathSub | Self::MathMul | Self::MathDiv | Self::MathPow
| Self::MathMin | Self::MathMax => &["a", "b"],
Self::RandomInt => &["min", "max"],
Self::Diff => &["formula", "var"],
Self::Subs | Self::Eval => &["formula", "var", "value"],
Self::Solve => &["formula", "var"],
Self::Plot => &["formula", "var", "min", "max"],
Self::PlotPoints => &["xs", "ys"],
Self::PlotConic => &["kind", "a"],
Self::ForeignSetCmd => &["lang", "cmd"],
Self::ForeignRun => &["code"],
Self::ForeignRunLang => &["lang", "source"],
Self::ForeignLangs => &[],
Self::PluginLoad => &["path"],
Self::PluginUnload | Self::PluginList => &[],
Self::ExtNativePath => &["name"],
Self::OuterCallLine => &[],
Self::TextPatch => &["path", "find", "replace"],
Self::ApplyPatchBlocks => &["path", "text", "soft"],
Self::WritebackScanPath => &["path"],
Self::MapSet => &["map", "key", "value"],
Self::ListAppend => &["list", "item"],
Self::CollectionPut => &["in", "at", "value"],
Self::ListPrepend => &["list", "item"],
Self::ListConcat => &["a", "b"],
Self::ListInsert => &["list", "index", "item"],
Self::ListSetAt => &["list", "index", "item"],
Self::ListRemoveAt => &["list", "index"],
Self::ListSlice => &["list", "start"],
Self::ListContains => &["list", "item"],
Self::ListIndexOf => &["list", "item"],
Self::ListReverse | Self::ListFirst | Self::ListLast => &["list"],
Self::MapGet | Self::MapDelete | Self::MapHas => &["map", "key"],
Self::MapKeys | Self::MapValues | Self::MapItems | Self::MapSize => &["map"],
Self::MapMerge => &["a", "b"],
Self::CollectionClear => &["value"],
Self::CookieParse => &["text", "is_response"],
Self::MultipartParse => &["body", "boundary"],
Self::MarkdownParse => &["text"],
Self::ReIsMatch | Self::ReFind | Self::ReFindAll | Self::ReSplit => {
&["text", "pattern"]
}
Self::ReReplace => &["text", "pattern", "with"],
Self::EncodingBase64Encode
| Self::EncodingBase64Decode
| Self::EncodingHexEncode
| Self::EncodingHexDecode
| Self::EncodingBase32Encode
| Self::EncodingBase32Decode => &["text"],
Self::PathJoin => &["a", "b"],
Self::PathSplit
| Self::PathFileName
| Self::PathParent
| Self::PathExtension
| Self::PathNormalize
| Self::PathIsAbsolute => &["path"],
Self::FsCopyFile | Self::FsMove => &["src", "dest"],
Self::FsMakeTemp => &[],
Self::HashSha256 | Self::HashSha1 | Self::HashMd5 => &["text"],
Self::HashHmacSha256 => &["key", "text"],
Self::SecretsTokenHex | Self::SecretsTokenUrlsafe => &[],
Self::TextContains => &["text", "sub"],
Self::TextStartsWith => &["text", "prefix"],
Self::TextEndsWith => &["text", "suffix"],
Self::TextReplace => &["text", "old", "new"],
Self::TextToUpper | Self::TextToLower => &["text"],
Self::TextRepeat => &["text", "n"],
Self::TextPad => &["text", "width"],
Self::CsvParse => &["text"],
Self::CsvStringify => &["rows"],
Self::ListSort | Self::ListUnique | Self::ListFlatten => &["list"],
Self::ListSortBy => &["list", "key"],
Self::ListChunk => &["list", "size"],
Self::ListZip => &["a", "b"],
Self::CliParse => &[],
Self::LogSetLevel => &["level"],
Self::LogLine => &["level", "text"],
Self::UuidV4 => &[],
Self::StatsMean | Self::StatsMedian | Self::StatsStdev => &["list"],
Self::DatetimeNow => &[],
Self::DatetimeFromUnix => &["unix"],
Self::DatetimeToUnix => &["dt"],
Self::DatetimeParse => &["text"],
Self::DatetimeFormat => &["dt"],
Self::DatetimeAdd => &["dt"],
Self::DatetimeInZone => &["dt", "zone"],
Self::UrlParse | Self::UrlQueryParse => &["text"],
Self::UrlQueryStringify => &["map"],
Self::TomlParse | Self::HtmlEscape | Self::HtmlUnescape => &["text"],
Self::FsMakeDirs | Self::FsRemoveTree | Self::FsStat | Self::FsWalk => &["path"],
Self::WritebackRecord => &["value"],
Self::WritebackGet | Self::WritebackClear => &[],
Self::WritebackList => &[],
Self::WritebackEnsure => &["key"],
Self::SubtaskSpawn => &[],
Self::SubtaskPoll | Self::SubtaskJoin | Self::SubtaskKill => &["id"],
Self::SubtaskWaitAll => &[],
}
}
pub fn optional_params(self) -> &'static [&'static str] {
match self {
Self::JsonStringify => &["indent"],
Self::HttpGet => &["headers"],
Self::HttpPost => &["content_type", "headers"],
Self::HttpPostSse => &["content_type", "headers", "echo"],
Self::OpenAiSseParse => &["echo"],
Self::HttpRequest => &["body", "content_type", "headers"],
Self::DotenvLoad => &["path"],
Self::Exec => &["args", "capture"],
Self::Solve => &["min", "max"],
Self::Plot => &["steps", "path", "derivative", "grid"],
Self::PlotPoints => &["path", "grid"],
Self::PlotConic => &["b", "h", "k", "path", "grid"],
Self::ForeignSetCmd => &["args"],
Self::ForeignRun | Self::ForeignRunLang => &["stdin"],
Self::WritebackRecord | Self::WritebackGet | Self::WritebackClear => {
&["at_end", "key", "line"]
}
Self::WritebackEnsure => &["placeholder", "line"],
Self::SubtaskSpawn => &["path", "fn", "args", "code", "lang", "source", "stdin", "quiet"],
Self::ListSlice => &["end"],
Self::ReReplace => &["count"],
Self::FsMakeTemp => &["prefix"],
Self::SecretsTokenHex | Self::SecretsTokenUrlsafe => &["n"],
Self::TextReplace => &["count"],
Self::TextPad => &["fill", "align"],
Self::CliParse => &["args"],
Self::DatetimeFromUnix => &["zone"],
Self::DatetimeParse => &["pattern"],
Self::DatetimeFormat => &["style"],
Self::DatetimeAdd => &["days", "hours", "minutes", "seconds"],
Self::LogLine => &["fields"],
_ => &[],
}
}
pub fn all_params(self) -> Vec<&'static str> {
let mut v = self.required_params().to_vec();
v.extend_from_slice(self.optional_params());
v
}
}
pub fn call_host(
ctx: &mut HostContext,
fn_id: HostFn,
bound: &HashMap<String, Value>,
) -> Result<Value, String> {
match fn_id {
HostFn::ReadText => fs::read_text(ctx, require(bound, "path")?),
HostFn::WriteText => {
fs::write_text(ctx, require(bound, "path")?, require(bound, "text")?)
}
HostFn::AppendText => {
fs::append_text(ctx, require(bound, "path")?, require(bound, "text")?)
}
HostFn::Exists => fs::exists(ctx, require(bound, "path")?),
HostFn::ListDir => fs::list_dir(ctx, require(bound, "path")?),
HostFn::MakeDir => fs::make_dir(ctx, require(bound, "path")?),
HostFn::Remove => fs::remove(ctx, require(bound, "path")?),
HostFn::FsMakeDirs => fs::make_dirs(ctx, require(bound, "path")?),
HostFn::FsRemoveTree => fs::remove_tree(ctx, require(bound, "path")?),
HostFn::FsStat => fs::stat(ctx, require(bound, "path")?),
HostFn::FsWalk => fs::walk(ctx, require(bound, "path")?),
HostFn::NowUnix => time::now_unix(),
HostFn::NowMs => time::now_ms(),
HostFn::FormatTime => {
time::format_time(require(bound, "unix")?, require(bound, "pattern")?)
}
HostFn::SleepMs => time::sleep_ms(ctx, require(bound, "ms")?),
HostFn::ParseTime => {
time::parse_time(require(bound, "text")?, require(bound, "pattern")?)
}
HostFn::EnvGet => sys::env_get(require(bound, "name")?),
HostFn::EnvSet => sys::env_set(require(bound, "name")?, require(bound, "value")?),
HostFn::DotenvLoad => sys::dotenv_load(ctx, bound.get("path")),
HostFn::Args => sys::args(ctx),
HostFn::Cwd => sys::cwd(ctx),
HostFn::Meta => sys::meta(ctx),
HostFn::MetaGet => sys::meta_get(ctx, require(bound, "key")?),
HostFn::Exit => sys::exit(ctx, require(bound, "code")?),
HostFn::Exec => sys::exec(
ctx,
require(bound, "cmd")?,
bound.get("args"),
bound.get("capture"),
),
HostFn::JsonParse => json::parse(require(bound, "text")?),
HostFn::JsonStringify => {
json::stringify(require(bound, "value")?, bound.get("indent"))
}
HostFn::JsonGet => json::get(require(bound, "value")?, require(bound, "key")?),
HostFn::JsonKeys => json::keys(require(bound, "value")?),
HostFn::JsonQuote => json::quote(require(bound, "text")?),
HostFn::HttpGet => {
#[cfg(feature = "net-host")]
{
net::http_get(ctx, require(bound, "url")?, bound.get("headers"))
}
#[cfg(not(feature = "net-host"))]
{
let _ = (ctx, bound);
Err("http_get unavailable in browser wasm".into())
}
}
HostFn::HttpPost => {
#[cfg(feature = "net-host")]
{
net::http_post(
ctx,
require(bound, "url")?,
require(bound, "body")?,
bound.get("content_type"),
bound.get("headers"),
)
}
#[cfg(not(feature = "net-host"))]
{
let _ = (ctx, bound);
Err("http_post unavailable in browser wasm".into())
}
}
HostFn::HttpPostSse => {
#[cfg(feature = "net-host")]
{
net::http_post_sse(
ctx,
require(bound, "url")?,
require(bound, "body")?,
bound.get("content_type"),
bound.get("headers"),
bound.get("echo"),
)
}
#[cfg(not(feature = "net-host"))]
{
let _ = (ctx, bound);
Err("http_post_sse unavailable in browser wasm".into())
}
}
HostFn::OpenAiSseParse => {
net::openai_sse_parse(require(bound, "text")?, bound.get("echo"))
}
HostFn::StreamPublish => {
crate::host::event_bus::publish(require(bound, "event")?);
Ok(Value::Bool(true))
}
HostFn::HttpRequest => {
#[cfg(feature = "net-host")]
{
net::http_request(
ctx,
require(bound, "method")?,
require(bound, "url")?,
bound.get("body"),
bound.get("content_type"),
bound.get("headers"),
)
}
#[cfg(not(feature = "net-host"))]
{
let _ = (ctx, bound);
Err("http_request unavailable in browser wasm".into())
}
}
HostFn::UrlEncode => net::url_encode(require(bound, "text")?),
HostFn::Pi => math::pi(),
HostFn::EConst => math::e_const(),
HostFn::Num => math::to_num(require(bound, "value")?),
HostFn::MathAdd => math::binary_num("add", require(bound, "a")?, require(bound, "b")?),
HostFn::MathSub => math::binary_num("sub", require(bound, "a")?, require(bound, "b")?),
HostFn::MathMul => math::binary_num("mul", require(bound, "a")?, require(bound, "b")?),
HostFn::MathDiv => math::binary_num("div", require(bound, "a")?, require(bound, "b")?),
HostFn::MathPow => math::binary_num("pow", require(bound, "a")?, require(bound, "b")?),
HostFn::MathMin => math::binary_num("min", require(bound, "a")?, require(bound, "b")?),
HostFn::MathMax => math::binary_num("max", require(bound, "a")?, require(bound, "b")?),
HostFn::MathNeg => math::unary_num("neg", require(bound, "value")?),
HostFn::MathSin => math::unary_num("sin", require(bound, "value")?),
HostFn::MathCos => math::unary_num("cos", require(bound, "value")?),
HostFn::MathTan => math::unary_num("tan", require(bound, "value")?),
HostFn::MathAsin => math::unary_num("asin", require(bound, "value")?),
HostFn::MathAcos => math::unary_num("acos", require(bound, "value")?),
HostFn::MathAtan => math::unary_num("atan", require(bound, "value")?),
HostFn::MathSqrt => math::unary_num("sqrt", require(bound, "value")?),
HostFn::MathAbs => math::unary_num("abs", require(bound, "value")?),
HostFn::MathLn => math::unary_num("ln", require(bound, "value")?),
HostFn::MathExp => math::unary_num("exp", require(bound, "value")?),
HostFn::MathFloor => math::unary_num("floor", require(bound, "value")?),
HostFn::MathCeil => math::unary_num("ceil", require(bound, "value")?),
HostFn::Random => math::random(ctx),
HostFn::RandomInt => {
math::random_int(ctx, require(bound, "min")?, require(bound, "max")?)
}
HostFn::Seed => math::seed(ctx, require(bound, "value")?),
HostFn::Formula => math::formula_parse(require(bound, "value")?),
HostFn::Simplify => math::simplify(require(bound, "value")?),
HostFn::Expand => math::expand(require(bound, "value")?),
HostFn::Diff => math::diff(require(bound, "formula")?, require(bound, "var")?),
HostFn::Subs => math::subs(
require(bound, "formula")?,
require(bound, "var")?,
require(bound, "value")?,
),
HostFn::Eval => math::eval_at(
require(bound, "formula")?,
require(bound, "var")?,
require(bound, "value")?,
),
HostFn::Solve => math::solve(
require(bound, "formula")?,
require(bound, "var")?,
bound.get("min"),
bound.get("max"),
),
HostFn::Plot => math::plot(
ctx,
require(bound, "formula")?,
require(bound, "var")?,
require(bound, "min")?,
require(bound, "max")?,
bound.get("steps"),
bound.get("path"),
bound.get("derivative"),
bound.get("grid"),
),
HostFn::PlotPoints => math::plot_points(
ctx,
require(bound, "xs")?,
require(bound, "ys")?,
bound.get("path"),
bound.get("grid"),
),
HostFn::PlotConic => math::plot_conic(
ctx,
require(bound, "kind")?,
require(bound, "a")?,
bound.get("b"),
bound.get("h"),
bound.get("k"),
bound.get("path"),
bound.get("grid"),
),
HostFn::ForeignSetCmd => {
#[cfg(feature = "exec-host")]
{
foreign::set_cmd(
ctx,
require(bound, "lang")?,
require(bound, "cmd")?,
bound.get("args"),
)
}
#[cfg(not(feature = "exec-host"))]
{
let _ = (ctx, bound);
Err("foreign unavailable in browser wasm".into())
}
}
HostFn::ForeignRun => {
#[cfg(feature = "exec-host")]
{
foreign::run(ctx, require(bound, "code")?, bound.get("stdin"))
}
#[cfg(not(feature = "exec-host"))]
{
let _ = (ctx, bound);
Err("foreign unavailable in browser wasm".into())
}
}
HostFn::ForeignRunLang => {
#[cfg(feature = "exec-host")]
{
foreign::run_lang(
ctx,
require(bound, "lang")?,
require(bound, "source")?,
bound.get("stdin"),
)
}
#[cfg(not(feature = "exec-host"))]
{
let _ = (ctx, bound);
Err("foreign unavailable in browser wasm".into())
}
}
HostFn::ForeignLangs => {
#[cfg(feature = "exec-host")]
{
foreign::langs(ctx)
}
#[cfg(not(feature = "exec-host"))]
{
let _ = ctx;
Ok(Value::List(Vec::new()))
}
}
HostFn::PluginLoad => {
#[cfg(feature = "plugin-host")]
{
plugin::load(ctx, require(bound, "path")?)
}
#[cfg(not(feature = "plugin-host"))]
{
let _ = (ctx, bound);
Err("plugin.load unavailable in browser wasm".into())
}
}
HostFn::PluginUnload => {
#[cfg(feature = "plugin-host")]
{
plugin::unload(ctx)
}
#[cfg(not(feature = "plugin-host"))]
{
let _ = ctx;
Err("plugin.unload unavailable in browser wasm".into())
}
}
HostFn::PluginList => {
#[cfg(feature = "plugin-host")]
{
plugin::list(ctx)
}
#[cfg(not(feature = "plugin-host"))]
{
let _ = ctx;
Ok(Value::List(Vec::new()))
}
}
HostFn::ExtNativePath => {
let name = require(bound, "name")?;
let s = match name {
Value::Text(t) => t.as_str(),
_ => return Err("name must be text".into()),
};
#[cfg(feature = "cli")]
{
Ok(match crate::ext_cli::installed_native_path(s) {
Some(p) => Value::Text(p.to_string_lossy().into_owned()),
None => Value::None,
})
}
#[cfg(not(feature = "cli"))]
{
let _ = s;
Ok(Value::None)
}
}
HostFn::MapSet => {
super::collection::map_set(require(bound, "map")?, require(bound, "key")?, require(bound, "value")?)
}
HostFn::ListAppend => {
super::collection::list_append(require(bound, "list")?, require(bound, "item")?)
}
HostFn::CollectionPut => super::collection::collection_put(
require(bound, "in")?,
require(bound, "at")?,
require(bound, "value")?,
),
HostFn::ListPrepend => {
super::collection::list_prepend(require(bound, "list")?, require(bound, "item")?)
}
HostFn::ListConcat => {
super::collection::list_concat(require(bound, "a")?, require(bound, "b")?)
}
HostFn::ListInsert => {
let idx = match require(bound, "index")? {
Value::Int(n) => *n,
_ => return Err("index must be int".into()),
};
super::collection::list_insert(require(bound, "list")?, idx, require(bound, "item")?)
}
HostFn::ListSetAt => {
let idx = match require(bound, "index")? {
Value::Int(n) => *n,
_ => return Err("index must be int".into()),
};
super::collection::list_set_at(require(bound, "list")?, idx, require(bound, "item")?)
}
HostFn::ListRemoveAt => {
let idx = match require(bound, "index")? {
Value::Int(n) => *n,
_ => return Err("index must be int".into()),
};
super::collection::list_remove_at(require(bound, "list")?, idx)
}
HostFn::ListSlice => super::collection::list_slice_bound(
require(bound, "list")?,
require(bound, "start")?,
bound.get("end"),
),
HostFn::ListContains => {
super::collection::list_contains(require(bound, "list")?, require(bound, "item")?)
}
HostFn::ListIndexOf => {
super::collection::list_index_of(require(bound, "list")?, require(bound, "item")?)
}
HostFn::ListReverse => super::collection::list_reverse(require(bound, "list")?),
HostFn::ListFirst => super::collection::list_first(require(bound, "list")?),
HostFn::ListLast => super::collection::list_last(require(bound, "list")?),
HostFn::MapGet => super::collection::map_get(require(bound, "map")?, require(bound, "key")?),
HostFn::MapDelete => super::collection::map_delete(require(bound, "map")?, require(bound, "key")?),
HostFn::MapHas => super::collection::map_has(require(bound, "map")?, require(bound, "key")?),
HostFn::MapKeys => super::collection::map_keys(require(bound, "map")?),
HostFn::MapValues => super::collection::map_values(require(bound, "map")?),
HostFn::MapItems => super::collection::map_items(require(bound, "map")?),
HostFn::MapMerge => super::collection::map_merge(require(bound, "a")?, require(bound, "b")?),
HostFn::MapSize => super::collection::map_size(require(bound, "map")?),
HostFn::CollectionClear => super::collection::collection_clear(require(bound, "value")?),
HostFn::CookieParse => net::cookie_parse(require(bound, "text")?, bound.get("is_response")),
HostFn::MultipartParse => net::multipart_parse(require(bound, "body")?, require(bound, "boundary")?),
HostFn::MarkdownParse => net::markdown_parse(require(bound, "text")?),
HostFn::ReIsMatch => re::is_match(require(bound, "text")?, require(bound, "pattern")?),
HostFn::ReFind => re::find(require(bound, "text")?, require(bound, "pattern")?),
HostFn::ReFindAll => re::find_all(require(bound, "text")?, require(bound, "pattern")?),
HostFn::ReReplace => re::replace(
require(bound, "text")?,
require(bound, "pattern")?,
require(bound, "with")?,
bound.get("count"),
),
HostFn::ReSplit => re::split(require(bound, "text")?, require(bound, "pattern")?),
HostFn::EncodingBase64Encode => encoding::base64_encode(require(bound, "text")?),
HostFn::EncodingBase64Decode => encoding::base64_decode(require(bound, "text")?),
HostFn::EncodingHexEncode => encoding::hex_encode(require(bound, "text")?),
HostFn::EncodingHexDecode => encoding::hex_decode(require(bound, "text")?),
HostFn::EncodingBase32Encode => encoding::base32_encode(require(bound, "text")?),
HostFn::EncodingBase32Decode => encoding::base32_decode(require(bound, "text")?),
HostFn::TomlParse => toml_ops::parse(require(bound, "text")?),
HostFn::HtmlEscape => html_ops::escape(require(bound, "text")?),
HostFn::HtmlUnescape => html_ops::unescape(require(bound, "text")?),
HostFn::PathJoin => path::join(require(bound, "a")?, require(bound, "b")?),
HostFn::PathSplit => path::split(require(bound, "path")?),
HostFn::PathFileName => path::file_name(require(bound, "path")?),
HostFn::PathParent => path::parent(require(bound, "path")?),
HostFn::PathExtension => path::extension(require(bound, "path")?),
HostFn::PathNormalize => path::normalize(require(bound, "path")?),
HostFn::PathIsAbsolute => path::is_absolute(require(bound, "path")?),
HostFn::FsCopyFile => {
fs::copy_file(ctx, require(bound, "src")?, require(bound, "dest")?)
}
HostFn::FsMove => fs::move_path(ctx, require(bound, "src")?, require(bound, "dest")?),
HostFn::FsMakeTemp => fs::make_temp(ctx, bound.get("prefix")),
HostFn::HashSha256 => hash::sha256(require(bound, "text")?),
HostFn::HashSha1 => hash::sha1(require(bound, "text")?),
HostFn::HashMd5 => hash::md5(require(bound, "text")?),
HostFn::HashHmacSha256 => {
hash::hmac_sha256(require(bound, "key")?, require(bound, "text")?)
}
HostFn::SecretsTokenHex => secrets::token_hex(bound.get("n")),
HostFn::SecretsTokenUrlsafe => secrets::token_urlsafe(bound.get("n")),
HostFn::TextContains => {
text_ops::contains(require(bound, "text")?, require(bound, "sub")?)
}
HostFn::TextStartsWith => {
text_ops::starts_with(require(bound, "text")?, require(bound, "prefix")?)
}
HostFn::TextEndsWith => {
text_ops::ends_with(require(bound, "text")?, require(bound, "suffix")?)
}
HostFn::TextReplace => text_ops::replace(
require(bound, "text")?,
require(bound, "old")?,
require(bound, "new")?,
bound.get("count"),
),
HostFn::TextToUpper => text_ops::to_upper(require(bound, "text")?),
HostFn::TextToLower => text_ops::to_lower(require(bound, "text")?),
HostFn::TextRepeat => text_ops::repeat(require(bound, "text")?, require(bound, "n")?),
HostFn::TextPad => text_ops::pad(
require(bound, "text")?,
require(bound, "width")?,
bound.get("fill"),
bound.get("align"),
),
HostFn::CsvParse => csv::parse(require(bound, "text")?),
HostFn::CsvStringify => csv::stringify(require(bound, "rows")?),
HostFn::ListSort => super::collection::list_sort(require(bound, "list")?),
HostFn::ListSortBy => {
super::collection::list_sort_by(require(bound, "list")?, require(bound, "key")?)
}
HostFn::ListUnique => super::collection::list_unique(require(bound, "list")?),
HostFn::ListChunk => {
super::collection::list_chunk(require(bound, "list")?, require(bound, "size")?)
}
HostFn::ListZip => {
super::collection::list_zip(require(bound, "a")?, require(bound, "b")?)
}
HostFn::ListFlatten => super::collection::list_flatten(require(bound, "list")?),
HostFn::CliParse => cli::parse(ctx, bound.get("args")),
HostFn::LogSetLevel => log::set_level(ctx, require(bound, "level")?),
HostFn::LogLine => log::line(
ctx,
require(bound, "level")?,
require(bound, "text")?,
bound.get("fields"),
),
HostFn::StatsMean => stats::mean(require(bound, "list")?),
HostFn::StatsMedian => stats::median(require(bound, "list")?),
HostFn::StatsStdev => stats::stdev(require(bound, "list")?),
HostFn::UuidV4 => uuid_ops::v4(),
HostFn::DatetimeNow => datetime::now(),
HostFn::DatetimeFromUnix => {
datetime::from_unix(require(bound, "unix")?, bound.get("zone"))
}
HostFn::DatetimeToUnix => datetime::to_unix(require(bound, "dt")?),
HostFn::DatetimeParse => datetime::parse(require(bound, "text")?, bound.get("pattern")),
HostFn::DatetimeFormat => datetime::format(require(bound, "dt")?, bound.get("style")),
HostFn::DatetimeAdd => datetime::add(
require(bound, "dt")?,
bound.get("days"),
bound.get("hours"),
bound.get("minutes"),
bound.get("seconds"),
),
HostFn::DatetimeInZone => {
datetime::in_zone(require(bound, "dt")?, require(bound, "zone")?)
}
HostFn::UrlParse => url_ops::parse(require(bound, "text")?),
HostFn::UrlQueryParse => url_ops::query_parse(require(bound, "text")?),
HostFn::UrlQueryStringify => url_ops::query_stringify(require(bound, "map")?),
HostFn::OuterCallLine => Ok(Value::Int(
ctx.call_site_lines
.first()
.copied()
.unwrap_or(ctx.current_line) as i64,
)),
HostFn::TextPatch => fs::text_patch(
ctx,
require(bound, "path")?,
require(bound, "find")?,
require(bound, "replace")?,
),
HostFn::ApplyPatchBlocks => fs::apply_patch_blocks(
ctx,
require(bound, "path")?,
require(bound, "text")?,
bound.get("soft"),
),
HostFn::WritebackScanPath => writeback::scan_path(ctx, require(bound, "path")?),
HostFn::WritebackRecord => writeback::record(
ctx,
require(bound, "value")?,
bound.get("at_end"),
bound.get("key"),
bound.get("line"),
),
HostFn::WritebackGet => writeback::get(
ctx,
bound.get("at_end"),
bound.get("key"),
bound.get("line"),
),
HostFn::WritebackClear => writeback::clear(
ctx,
bound.get("at_end"),
bound.get("key"),
bound.get("line"),
),
HostFn::WritebackList => writeback::list(ctx),
HostFn::WritebackEnsure => {
let placeholder = bound
.get("placeholder")
.cloned()
.unwrap_or_else(|| Value::Text("pending".into()));
writeback::ensure_slot(
ctx,
require(bound, "key")?,
&placeholder,
bound.get("line"),
)
}
HostFn::SubtaskSpawn => {
#[cfg(feature = "exec-host")]
{
subtask::spawn(ctx, bound)
}
#[cfg(not(feature = "exec-host"))]
{
let _ = (ctx, bound);
Err("subtask unavailable in browser wasm".into())
}
}
HostFn::SubtaskPoll => {
#[cfg(feature = "exec-host")]
{
subtask::poll(ctx, require(bound, "id")?)
}
#[cfg(not(feature = "exec-host"))]
{
let _ = (ctx, bound);
Err("subtask unavailable in browser wasm".into())
}
}
HostFn::SubtaskJoin => {
#[cfg(feature = "exec-host")]
{
subtask::join(ctx, require(bound, "id")?)
}
#[cfg(not(feature = "exec-host"))]
{
let _ = (ctx, bound);
Err("subtask unavailable in browser wasm".into())
}
}
HostFn::SubtaskKill => {
#[cfg(feature = "exec-host")]
{
subtask::kill(ctx, require(bound, "id")?)
}
#[cfg(not(feature = "exec-host"))]
{
let _ = (ctx, bound);
Err("subtask unavailable in browser wasm".into())
}
}
HostFn::SubtaskWaitAll => {
#[cfg(feature = "exec-host")]
{
subtask::wait_all(ctx)
}
#[cfg(not(feature = "exec-host"))]
{
let _ = ctx;
Err("subtask unavailable in browser wasm".into())
}
}
}
}
fn require<'a>(bound: &'a HashMap<String, Value>, key: &str) -> Result<&'a Value, String> {
bound
.get(key)
.ok_or_else(|| format!("host call missing `{key}`"))
}