@tocca-systems/twp-cli 0.115.0 → 0.116.0
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/CHANGELOG.public.md +4 -0
- package/dist/THIRD-PARTY-NOTICES.md +1 -1
- package/dist/{agent-loop-5IBBUKPF.js → agent-loop-5SMJG7CB.js} +15 -12
- package/dist/{api-command-XHXLX45I.js → api-command-RXXCI72A.js} +1 -1
- package/dist/{app-H6WJRVDR.js → app-MRG7YVO7.js} +1 -1
- package/dist/{capacity-list-command-W3HOC5YB.js → capacity-list-command-EUU3H5ZE.js} +1 -1
- package/dist/{chunk-BBV5NLQZ.js → chunk-46OWZRTJ.js} +3 -3
- package/dist/chunk-56LNKTKM.js +4 -0
- package/dist/{chunk-GFLGXGWE.js → chunk-F5QDUPQO.js} +1 -1
- package/dist/{chunk-5R5Z6KHV.js → chunk-F7LPERJA.js} +1 -1
- package/dist/{chunk-VVOPXTGC.js → chunk-FFRQGBMA.js} +1 -1
- package/dist/cli.js +7 -7
- package/dist/{commands-CIMVQEMO.js → commands-74PDZH6C.js} +5 -5
- package/dist/{commands-WNPM6734.js → commands-P77EIMBU.js} +1 -1
- package/dist/dist-B4FAEXU4.js +120 -0
- package/dist/{media-JDLTK23Z.js → media-RI32UZY5.js} +1 -1
- package/dist/{query-XEOVFI4D.js → query-J76QIXWR.js} +1 -1
- package/dist/{registry-TAPAIGQV.js → registry-7LKI5A35.js} +1 -1
- package/dist/{run-ISFJYA2U.js → run-EYQI5JLL.js} +1 -1
- package/dist/{runner-command-POVZMRJ5.js → runner-command-YVY25WNU.js} +1 -1
- package/dist/{skill-manage-command-QEZ5SI3A.js → skill-manage-command-HGLXVSJB.js} +2 -2
- package/dist/{status-command-LBTN3UWE.js → status-command-XGAFTFTW.js} +2 -2
- package/dist/{task-FLIYESKS.js → task-OHQ7BTOP.js} +21 -23
- package/dist/{trigger-command-TQCKGHGL.js → trigger-command-QUWGCSXO.js} +1 -1
- package/package.json +1 -1
- package/dist/dist-HZIZTJ4O.js +0 -93
package/CHANGELOG.public.md
CHANGED
|
@@ -11,6 +11,10 @@
|
|
|
11
11
|
`CHANGELOG.md` に残してあります。顧客向けの履歴は public 公開以降を対象とします。
|
|
12
12
|
-->
|
|
13
13
|
|
|
14
|
+
## 0.116.0
|
|
15
|
+
|
|
16
|
+
`twp task-loop item create` で、アイテムを実行できる機体のプラットフォームを `--required-platforms` で指定できるようになりました。
|
|
17
|
+
|
|
14
18
|
## 0.115.0
|
|
15
19
|
|
|
16
20
|
承認待ちのコンテンツを CLI から削除しようとしたとき、「権限がありません」ではなく「承認待ちのため削除できません」と正しい理由を表示するようにしました。コンテンツやカテゴリの操作が断られたときの案内も、原因に合った内容に直しました。
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
2
|
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
-
import{stepToItem}from"./chunk-2UTJI3BT.js";import"./chunk-VEEZJNOB.js";import{loadLocalConfig}from"./chunk-LEZ576RA.js";import{parseOperations}from"./chunk-S5MDCZEF.js";import"./chunk-VYDPW2YO.js";import"./chunk-TTST7UDR.js";import{loadAiConfig}from"./chunk-ZFSWQQH3.js";import{SKILL_PREFIX_RE,setSkillPrefix}from"./chunk-6CS5L24D.js";import"./chunk-N2UVRM3Z.js";import"./chunk-UZUV5FYG.js";
|
|
4
|
-
isPrivateProjectRef,privateProjectId}from"./chunk-RMFLTSOV.js";import"./chunk-BD7O73GK.js";import"./chunk-SBRTBKEZ.js";import{LIST_FLAGS,LIST_PAGING_HELP,envelopePaging,nonEmpty,positiveInteger}from"./chunk-MI6HVYR2.js";import{requireResolved,singleRef,withResolved}from"./chunk-PS5QFKHB.js";import{acknowledgement,isRecord,pick}from"./chunk-3ZRMMBP5.js";import{ApiResponseError,UsageError}from"./chunk-VFPY2A23.js";
|
|
5
|
-
import"./chunk-5WGOHFAS.js";import"./chunk-RZVI6PMW.js";import"./chunk-NHYMHCAT.js";import"./chunk-VSJBJXZO.js";var LABEL="\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u30EB\u30FC\u30D7\u306E\u30A2\u30A4\u30C6\u30E0";var STATUSES=["pending","processing","completed","failed"];var AI_TYPES=["claude","gemini","codex","copilot"];var EFFORTS=["low","medium","high","xhigh","max"];var PRIORITIES=["P0","P1","P2","P3"];var LIST_COLUMNS=["item_id","status","task_key","label","ai_type","ai_effort","runner_id","created_at"];var GET_COLUMNS=["item_id","status","task_key","label","prompt","ai_type","ai_model","ai_effort","runn\
|
|
3
|
+
import{stepToItem}from"./chunk-2UTJI3BT.js";import"./chunk-VEEZJNOB.js";import{loadLocalConfig}from"./chunk-LEZ576RA.js";import{parseOperations}from"./chunk-S5MDCZEF.js";import"./chunk-VYDPW2YO.js";import"./chunk-TTST7UDR.js";import{loadAiConfig}from"./chunk-ZFSWQQH3.js";import{SKILL_PREFIX_RE,setSkillPrefix}from"./chunk-6CS5L24D.js";import"./chunk-N2UVRM3Z.js";import{parseRequiredPlatforms}from"./chunk-56LNKTKM.js";import"./chunk-UZUV5FYG.js";
|
|
4
|
+
import{PRIVATE_PROJECT_PREFIX,PRIVATE_PROJECT_REF,isPrivateProjectRef,privateProjectId}from"./chunk-RMFLTSOV.js";import"./chunk-BD7O73GK.js";import"./chunk-VGT2EGH6.js";import"./chunk-SBRTBKEZ.js";import{LIST_FLAGS,LIST_PAGING_HELP,envelopePaging,nonEmpty,positiveInteger}from"./chunk-MI6HVYR2.js";import{requireResolved,singleRef,withResolved}from"./chunk-PS5QFKHB.js";import{acknowledgement,isRecord,pick}from"./chunk-3ZRMMBP5.js";import{ApiResponseError,UsageError}from"./chunk-VFPY2A23.js";
|
|
5
|
+
import"./chunk-PMOUHEJQ.js";import"./chunk-J7QYPKVK.js";import"./chunk-5WGOHFAS.js";import"./chunk-RZVI6PMW.js";import"./chunk-OKATZ4SN.js";import"./chunk-NHYMHCAT.js";import"./chunk-VSJBJXZO.js";var LABEL="\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u30EB\u30FC\u30D7\u306E\u30A2\u30A4\u30C6\u30E0";var STATUSES=["pending","processing","completed","failed"];var AI_TYPES=["claude","gemini","codex","copilot"];var EFFORTS=["low","medium","high","xhigh","max"];var PRIORITIES=["P0","P1","P2","P3"];var LIST_COLUMNS=["item_id","status","task_key","label","ai_type","ai_effort","runner_id","created_at"];var GET_COLUMNS=["item_id","status","task_key","label","prompt","ai_type","ai_model","ai_effort","runn\
|
|
6
6
|
er_id","attempt_count","reclaim_count","error_message","created_by_name","created_at","started_at","completed_at"];var HISTORY_COLUMNS=["item_id","status","task_key","skill","ai_type","runner_id","duration_ms","cost_usd","created_at"];var PLAN_RESULTS=["enqueued","empty","json_not_found","ai_failed","error","skipped","gated","locked","abandoned"];var PLAN_HISTORY_COLUMNS=["plan_run_id","result","runner_id","ai_type","duration_ms","cost_usd","step_count","started_at"];var PROJECT_FLAG={name:"--pr\
|
|
7
7
|
oject",summary:`\u30AD\u30E5\u30FC\u306E\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\uFF08\u30B3\u30FC\u30C9\u307E\u305F\u306F ID\u3002\u7701\u7565\u6642\u306F TWP_PROJECT / .twp/config.json / ~/.twp/config.json\uFF09\u3002\u500B\u4EBA\u30AD\u30E5\u30FC\u306F ${PRIVATE_PROJECT_REF}`,takesValue:true,placeholder:`<\u30B3\u30FC\u30C9|ID|${PRIVATE_PROJECT_REF}>`};var ITEM_FLAG={name:"--item",summary:"\u30A2\u30A4\u30C6\u30E0\u306E ID\uFF08item_id\uFF09\u3002\u4F4D\u7F6E\u5F15\u6570\u3068\u540C\u3058\u610F\u5473\uFF08\u4E21\u65B9\u6307\u5B9A\u306F\u30A8\u30E9\u30FC\uFF09",
|
|
8
8
|
takesValue:true,placeholder:"<\u30A2\u30A4\u30C6\u30E0ID>"};var FORBIDDEN_CORE="\u30C6\u30CA\u30F3\u30C8\u306E\u7BA1\u7406\u8005\uFF08admin \u30ED\u30FC\u30EB\uFF09\u306E\u6A29\u9650\u304C\u5FC5\u8981\u3067\u3059\uFF08\u500B\u4EBA\u30AD\u30E5\u30FC\u3092\u9664\u304F\uFF09";var CREATE_HINT="\u30A2\u30A4\u30C6\u30E0\u306E\u6295\u5165\uFF08twp task-loop item create\uFF09\u306F\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u306E\u30E1\u30F3\u30D0\u30FC\u306A\u3089\u7BA1\u7406\u8005\u3067\u306A\u304F\u3066\u3082\u884C\u3048\u307E\u3059";
|
|
@@ -19,26 +19,29 @@ slice(prefix.length),args:(m[2]??"").trim()}}function skillPrefixFromLocalConfig
|
|
|
19
19
|
function assignFromLocalConfig(projectId,step,prefix){const local=loadLocalConfig(projectId);const configured=local.ai!==void 0||(local.ai_config_file??"").trim()!=="";const{config,warnings}=loadAiConfig(local.ai,local.ai_config_file,local.workspace??process.cwd());const category=config.categoryForSkill(step.skill);const item=stepToItem(step,{categoryForSkill:()=>category,selectPrimary:(c,s,p,display)=>config.selectPrimary(c,s,p,display)},prefix);return{category,primary:item?.ai_type??"",configured,
|
|
20
20
|
warnings}}function createStep(input,prefix=resolvedPrefix(input)){const prompt=nonEmpty(input.flags,"--prompt");if(prompt===void 0){throw new UsageError("--prompt \u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044",'twp task-loop item create --prompt "/<\u30B9\u30AD\u30EB\u540D> <\u5F15\u6570>"')}const{skill,args}=parseSkillPrompt(prompt,prefix);return{skill,args,priority:oneOf(input.flags,"--priority",PRIORITIES)??"P2",label:nonEmpty(input.flags,"--label")??""}}function createBody(input){const step=createStep(
|
|
21
21
|
input);const category=requireResolved(input,"category");const primary=input.resolved?.["primary"]??"";const item=stepToItem(step,fixedAssignment(category,primary),resolvedPrefix(input));if(item===null)throw new Error("\u5185\u90E8\u30A8\u30E9\u30FC: \u30B9\u30AD\u30EB\u540D\u304C\u7A7A\u306E\u307E\u307E stepToItem \u306B\u6E21\u308A\u307E\u3057\u305F");const body={label:item.label,prompt:item.prompt};if(item.task_key!=="")body["task_key"]=item.task_key;if(item.ai_type!==void 0)body["ai_type"]=item.
|
|
22
|
-
ai_type;const effort=oneOf(input.flags,"--ai-effort",EFFORTS);if(effort!==void 0)body["ai_effort"]=effort;return body}var createOperation={name:"create",summary:"\u30AD\u30E5\u30FC\u306B\u30A2\u30A4\u30C6\u30E0\u3092\u6295\u5165\u3059\u308B",usage:'twp task-loop item create --prompt "/<\u63A5\u982D\u8F9E><\u30B9\u30AD\u30EB\u540D> <\u5F15\u6570>" [--priority P2] [--label <\u30E9\u30D9\u30EB>] [--ai-effort <effort>] [--
|
|
23
|
-
\u4F5C\u308A\u307E\u3059\uFF08\u30E9\u30D9\u30EB\u66F8\u5F0F\u30FBtask_key \u306E\u62BD\u51FA\u306F\u8A08\u753B\u6295\u5165\u3068\u5171\u901A\uFF09:
|
|
22
|
+
ai_type;const effort=oneOf(input.flags,"--ai-effort",EFFORTS);if(effort!==void 0)body["ai_effort"]=effort;const platforms=parseRequiredPlatforms(input);if(platforms!==void 0)body["required_platforms"]=platforms;return body}var createOperation={name:"create",summary:"\u30AD\u30E5\u30FC\u306B\u30A2\u30A4\u30C6\u30E0\u3092\u6295\u5165\u3059\u308B",usage:'twp task-loop item create --prompt "/<\u63A5\u982D\u8F9E><\u30B9\u30AD\u30EB\u540D> <\u5F15\u6570>" [--priority P2] [--label <\u30E9\u30D9\u30EB>] [--ai-effort <effort>] [--required-platforms <mac|windows|l\
|
|
23
|
+
inux>] [--project <\u30B3\u30FC\u30C9|ID|__private__>]',description:`\u30EB\u30FC\u30D7\u306E\u8A08\u753B\u6295\u5165\u3068\u540C\u3058\u898F\u5247\u3067\u30A2\u30A4\u30C6\u30E0\u3092\u4F5C\u308A\u307E\u3059\uFF08\u30E9\u30D9\u30EB\u66F8\u5F0F\u30FBtask_key \u306E\u62BD\u51FA\u306F\u8A08\u753B\u6295\u5165\u3068\u5171\u901A\uFF09:
|
|
24
24
|
\u30E9\u30D9\u30EB [<\u512A\u5148\u5EA6>] <\u30BF\u30B9\u30AF\u30AD\u30FC> <\u30E9\u30D9\u30EB> #ai:<\u30AB\u30C6\u30B4\u30EA>\uFF08200\u5B57\u3067\u5207\u308B\u3002--label \u7701\u7565\u6642\u306F\u30D7\u30ED\u30F3\u30D7\u30C8\uFF09
|
|
25
25
|
task_key \u30D7\u30ED\u30F3\u30D7\u30C8\u306E\u5F15\u6570\u306E\u5148\u982D\u306B\u3042\u308B\u30BF\u30B9\u30AF\u30AD\u30FC\uFF08\u4F8B ABC-123\uFF09\u3002\u5148\u982D\u304C\u30AD\u30FC\u3067\u306A\u3044\u30FB[\u691C\u8A3C\u7528] \u306E\u3088\u3046\u306A\u62EC\u5F27\u4ED8\u304D\u306E\u6CE8\u8A18\u3067\u59CB\u307E\u308B\u3068\u304D\u306F\u9001\u308A\u307E\u305B\u3093
|
|
26
26
|
1\u756A\u624B \u3053\u306E\u6A5F\u4F53\u306E\u30EB\u30FC\u30D7\u8A2D\u5B9A\uFF08~/.twp/loops/<\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8ID>.json\uFF09\u306E\u30AB\u30C6\u30B4\u30EA\u8868\u3068 primary_rotation \u3067\u6C7A\u3081\u308B
|
|
27
27
|
\uFF08\u30B3\u30DE\u30F3\u30C91\u56DE\u3054\u3068\u306B\u8A2D\u5B9A\u3092\u8AAD\u307F\u76F4\u3059\u306E\u3067\u3001\u91CD\u307F\u4ED8\u304D\u30ED\u30FC\u30C6\u30FC\u30B7\u30E7\u30F3\u306F\u56DE\u3089\u305A\u6BCE\u56DE\u305D\u306E\u5148\u982D\u306E\u4F7F\u3048\u308B AI \u306B\u306A\u308A\u307E\u3059\uFF09
|
|
28
28
|
ai_model \u9001\u308A\u307E\u305B\u3093\uFF08claim \u3057\u305F\u5B9F\u884C\u6A5F\u304C\u81EA\u5206\u306E\u8A2D\u5B9A\u3067\u89E3\u6C7A\u3057\u307E\u3059\uFF09
|
|
29
29
|
\u63A5\u982D\u8F9E \u3053\u306E\u6A5F\u4F53\u306E\u30EB\u30FC\u30D7\u8A2D\u5B9A\u306E operations.skill_prefix\uFF08\u65E2\u5B9A twp-\uFF09\u3002\u904B\u7528\u8A2D\u5B9A\u304C\u7121\u3051\u308C\u3070 /<\u540D\u524D> \u3092\u305D\u306E\u307E\u307E\u7A4D\u307F\u307E\u3059
|
|
30
|
+
\u5B9F\u884C\u6A5F --required-platforms \u3092\u7701\u7565\u3059\u308B\u3068\u30B5\u30FC\u30D0\u304C task_key \u306E\u30BF\u30B9\u30AF\u306E\u5FC5\u8981\u30D7\u30E9\u30C3\u30C8\u30D5\u30A9\u30FC\u30E0\u3092\u5199\u3057\u307E\u3059\u3002
|
|
31
|
+
\u6307\u5B9A\u3059\u308B\u3068\u30BF\u30B9\u30AF\u306E\u5024\u3088\u308A\u512A\u5148\u3057\u307E\u3059\uFF08\u30BF\u30B9\u30AF\u306E\u5236\u7D04\u3092\u5916\u3059\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093\uFF09
|
|
30
32
|
|
|
31
33
|
\u540C\u3058\u30BF\u30B9\u30AF\u306E\u30A2\u30A4\u30C6\u30E0\u304C\u65E2\u306B\u4E26\u3093\u3067\u3044\u3066\u3082\u5F3E\u304D\u307E\u305B\u3093\u3002\u78BA\u304B\u3081\u308B\u306B\u306F:
|
|
32
34
|
twp task-loop item list --status pending --query "[?task_key=='ABC-123']"
|
|
33
35
|
|
|
34
36
|
${PROJECT_HELP}`,flags:[{name:"--prompt",summary:"\u5B9F\u884C\u3059\u308B\u30B9\u30AD\u30EB\u3068\u5F15\u6570\uFF08/<\u63A5\u982D\u8F9E><\u30B9\u30AD\u30EB\u540D> \u3067\u59CB\u3081\u308B\uFF09",takesValue:true,placeholder:'"/<\u63A5\u982D\u8F9E><\u30B9\u30AD\u30EB\u540D> <\u5F15\u6570>"'},{name:"--priority",summary:`\u512A\u5148\u5EA6\uFF08${PRIORITIES.join(" / ")}\u3002\u65E2\u5B9A P2\uFF09\u3002\u30E9\u30D9\u30EB\u306E\u5148\u982D\u306B\u5165\u308B`,takesValue:true,placeholder:"<P0-P3>"},{name:"\
|
|
35
|
-
--label",summary:"\u30E9\u30D9\u30EB\u306E\u672C\u6587\uFF08\u7701\u7565\u6642\u306F\u30D7\u30ED\u30F3\u30D7\u30C8\uFF09",takesValue:true,placeholder:"<\u30E9\u30D9\u30EB>"},{name:"--ai-effort",summary:`\u3053\u306E\u30A2\u30A4\u30C6\u30E0\u306E effort\uFF08${EFFORTS.join(" / ")}\uFF09\u3002\u30AB\u30C6\u30B4\u30EA\u65E2\u5B9A\u3088\u308A\u512A\u5148\u3059\u308B`,takesValue:true,placeholder:"<effort>"},
|
|
36
|
-
input,ctx);const projectId=isPrivateQueue(queue)?privateProjectId((await ctx.resolver.currentUser()).id):requireResolved(queue,"projectId");const skillPrefix=skillPrefixFromLocalConfig(projectId);const step=createStep(input,skillPrefix);const assign=assignFromLocalConfig(
|
|
37
|
-
POST",path:basePath(input),body:createBody(input)}),plannedNotes(input){const notes=[];const warnings=input.resolved?.["aiWarnings"]??"";if(warnings!=="")notes.push(`\u30EB\u30FC\u30D7\u8A2D\u5B9A\u306E\u8AAD\u307F\u8FBC\u307F\u3067\u554F\u984C\u304C\u3042\u308A\u307E\u3057\u305F: ${warnings}`);
|
|
38
|
-
resolved?.["category"]??"?"}\uFF09\u3067\u6C7A\u3081\u307E\u3057\u305F\u3002\u5B9F\u884C\u6A5F\u306F claim \u6642\u306B\u81EA\u5206\u306E\u8A2D\u5B9A\u3067\u30AB\u30C6\u30B4\u30EA\u3092\u5F15\u304D\u76F4\u3057\u307E\u3059\u304C\u3001\u30E9\u30D9\u30EB\u306E #ai: \u30BF\u30B0\u306F\u6295\u5165\u6642\u306E\u5024\u306E\u307E\u307E\u3067\u3059\u3002`)}
|
|
39
|
-
"--label");if(label!==void 0)body["label"]=label;const prompt=nonEmpty(input.flags,"--prompt");if(prompt!==void 0){parseSkillPrompt(prompt);body["prompt"]=prompt.trim()}const taskKey=input.flags.get("--task-key");if(taskKey!==void 0)body["task_key"]=taskKey.trim()==="none"?null:nonEmpty(input.flags,"--task-key");const aiType=oneOfOrNone(input.
|
|
40
|
-
ai_effort"]=effort;if(Object.keys(body).length===0){throw new UsageError("\u66F4\u65B0\u3059\u308B\u9805\u76EE\u304C\u3042\u308A\u307E\u305B\u3093\uFF08--label / --prompt / --task-key / --ai-type / --ai-effort \u306E\u3044\u305A\u308C\u304B\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF09","twp task-loop item update help")}return body}
|
|
41
|
-
usage:"twp task-loop item update <\u30A2\u30A4\u30C6\u30E0ID> [--label <\u30E9\u30D9\u30EB>] [--prompt <\u30D7\u30ED\u30F3\u30D7\u30C8>] [--task-key <\u30AD\u30FC|none>] [--ai-type <AI|none>] [--ai-effort <effort|none>] [--project <\u30B3\u30FC\u30C9|ID|__private__>]",description:`\
|
|
37
|
+
--label",summary:"\u30E9\u30D9\u30EB\u306E\u672C\u6587\uFF08\u7701\u7565\u6642\u306F\u30D7\u30ED\u30F3\u30D7\u30C8\uFF09",takesValue:true,placeholder:"<\u30E9\u30D9\u30EB>"},{name:"--ai-effort",summary:`\u3053\u306E\u30A2\u30A4\u30C6\u30E0\u306E effort\uFF08${EFFORTS.join(" / ")}\uFF09\u3002\u30AB\u30C6\u30B4\u30EA\u65E2\u5B9A\u3088\u308A\u512A\u5148\u3059\u308B`,takesValue:true,placeholder:"<effort>"},{name:"--required-platforms",summary:"\u5B9F\u884C\u3067\u304D\u308B\u6A5F\u4F53\u306E\u30D7\u30E9\u30C3\u30C8\u30D5\u30A9\u30FC\u30E0\uFF08mac / windows / linux\uFF09\u3002\u8907\u6570\u6307\u5B9A\u30FB\u30AB\u30F3\u30DE\u533A\u5207\u308A\u53EF\u3002\u7701\u7565\u6642\
|
|
38
|
+
\u306F\u30BF\u30B9\u30AF\u306E\u5024",takesValue:true,placeholder:"<mac|windows|linux>",repeatable:true},PROJECT_FLAG],async prepare(input,ctx){rejectArgs(input,"create");createStep(input,"");parseRequiredPlatforms(input);const queue=await prepareQueue(input,ctx);const projectId=isPrivateQueue(queue)?privateProjectId((await ctx.resolver.currentUser()).id):requireResolved(queue,"projectId");const skillPrefix=skillPrefixFromLocalConfig(projectId);const step=createStep(input,skillPrefix);const assign=assignFromLocalConfig(
|
|
39
|
+
projectId,step,skillPrefix);return withResolved(queue,{projectId,skillPrefix,category:assign.category,primary:assign.primary,aiConfigured:assign.configured?"yes":"no",aiWarnings:assign.warnings.join("\n")})},plan:input=>({method:"POST",path:basePath(input),body:createBody(input)}),plannedNotes(input){const notes=[];const warnings=input.resolved?.["aiWarnings"]??"";if(warnings!=="")notes.push(`\u30EB\u30FC\u30D7\u8A2D\u5B9A\u306E\u8AAD\u307F\u8FBC\u307F\u3067\u554F\u984C\u304C\u3042\u308A\u307E\u3057\u305F: ${warnings}`);
|
|
40
|
+
if(input.resolved?.["aiConfigured"]==="no"){notes.push(`\u3053\u306E\u6A5F\u4F53\u306B\u30EB\u30FC\u30D7\u8A2D\u5B9A\uFF08ai / ai_config_file\uFF09\u304C\u7121\u3044\u305F\u3081\u3001\u30AB\u30C6\u30B4\u30EA\u306F\u7D44\u307F\u8FBC\u307F\u65E2\u5B9A\uFF08${input.resolved?.["category"]??"?"}\uFF09\u3067\u6C7A\u3081\u307E\u3057\u305F\u3002\u5B9F\u884C\u6A5F\u306F claim \u6642\u306B\u81EA\u5206\u306E\u8A2D\u5B9A\u3067\u30AB\u30C6\u30B4\u30EA\u3092\u5F15\u304D\u76F4\u3057\u307E\u3059\u304C\u3001\u30E9\u30D9\u30EB\u306E #ai: \u30BF\u30B0\u306F\u6295\u5165\u6642\u306E\u5024\u306E\u307E\u307E\u3067\u3059\u3002`)}
|
|
41
|
+
return notes},summarize:body=>pick(itemObject(body),GET_COLUMNS),raw:itemObject};function updateBody(input){const body={};const label=nonEmpty(input.flags,"--label");if(label!==void 0)body["label"]=label;const prompt=nonEmpty(input.flags,"--prompt");if(prompt!==void 0){parseSkillPrompt(prompt);body["prompt"]=prompt.trim()}const taskKey=input.flags.get("--task-key");if(taskKey!==void 0)body["task_key"]=taskKey.trim()==="none"?null:nonEmpty(input.flags,"--task-key");const aiType=oneOfOrNone(input.
|
|
42
|
+
flags,"--ai-type",AI_TYPES);if(aiType!==void 0)body["ai_type"]=aiType;const effort=oneOfOrNone(input.flags,"--ai-effort",EFFORTS);if(effort!==void 0)body["ai_effort"]=effort;if(Object.keys(body).length===0){throw new UsageError("\u66F4\u65B0\u3059\u308B\u9805\u76EE\u304C\u3042\u308A\u307E\u305B\u3093\uFF08--label / --prompt / --task-key / --ai-type / --ai-effort \u306E\u3044\u305A\u308C\u304B\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF09","twp task-loop item update help")}return body}
|
|
43
|
+
var updateOperation={name:"update",summary:"\u30A2\u30A4\u30C6\u30E0\u306E\u30E9\u30D9\u30EB\u30FB\u30D7\u30ED\u30F3\u30D7\u30C8\u30FBAI \u6307\u5B9A\u3092\u66F4\u65B0\u3059\u308B\uFF08\u7BA1\u7406\u8005\u306E\u307F\uFF09",usage:"twp task-loop item update <\u30A2\u30A4\u30C6\u30E0ID> [--label <\u30E9\u30D9\u30EB>] [--prompt <\u30D7\u30ED\u30F3\u30D7\u30C8>] [--task-key <\u30AD\u30FC|none>] [--ai-type <AI|none>] [--ai-effort <effort|none>] [--project <\u30B3\u30FC\u30C9|ID|__private__>]",description:`\
|
|
44
|
+
\u6307\u5B9A\u3057\u305F\u9805\u76EE\u3060\u3051\u3092\u9001\u308A\u307E\u3059\u3002none \u3092\u6E21\u3059\u3068\u305D\u306E\u9805\u76EE\u3092\u6D88\u3057\u307E\u3059\uFF08--task-key / --ai-type / --ai-effort\uFF09\u3002
|
|
42
45
|
--label \u306F\u66F8\u5F0F\u3092\u7D44\u307F\u7ACB\u3066\u76F4\u3055\u305A\u3001\u6E21\u3057\u305F\u6587\u5B57\u5217\u3092\u305D\u306E\u307E\u307E\u4FDD\u5B58\u3057\u307E\u3059\uFF08#ai: \u30BF\u30B0\u3082\u81EA\u5206\u3067\u66F8\u3044\u3066\u304F\u3060\u3055\u3044\uFF09\u3002
|
|
43
46
|
|
|
44
47
|
\u66F4\u65B0\u306B\u306F\u66F8\u304D\u8FBC\u307F\u30B2\u30FC\u30C8\u304C\u639B\u304B\u308A\u307E\u3059: ${FORBIDDEN_UPDATE}\u3002
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
2
|
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
-
import{CommandModelMissingError,MAX_REPORTED_VIOLATIONS,loadCommandModelDomain,loadCommandModelRoutes,validateBody,validateQuery}from"./chunk-CDAU3M7F.js";import{exitCodeFor,fetchAllPages,reportError}from"./chunk-
|
|
3
|
+
import{CommandModelMissingError,MAX_REPORTED_VIOLATIONS,loadCommandModelDomain,loadCommandModelRoutes,validateBody,validateQuery}from"./chunk-CDAU3M7F.js";import{exitCodeFor,fetchAllPages,reportError}from"./chunk-F7LPERJA.js";import"./chunk-46OWZRTJ.js";import{evaluateQuery}from"./chunk-F5QDUPQO.js";import{renderOutput}from"./chunk-P4QSPSOQ.js";import"./chunk-Q3B65OFC.js";import{describeWaitResult,parseWaitOptions,waitUntilTerminal}from"./chunk-WVCEKC7V.js";
|
|
4
4
|
import{readBody}from"./chunk-HEH3PUW2.js";import{ALLOW_REDACTED_FLAG,NO_REDACT_FLAG,NO_REDACT_NOTICE}from"./chunk-W4NLJ2YK.js";import{redactSecretValues,redactSecrets,withDebug}from"./chunk-BD7O73GK.js";import{parseOperationArgs,repeatedValues}from"./chunk-VGT2EGH6.js";import"./chunk-A7MM5WSC.js";import"./chunk-HVZUXLQ4.js";import{ApiError,TwpApiClient,appendQuery}from"./chunk-JA5A6UJ2.js";import"./chunk-MMVXE2CJ.js";import"./chunk-SBRTBKEZ.js";
|
|
5
5
|
import{DEFAULT_MAX_ITEMS,DEFAULT_MAX_PAGES,envelopePaging,isPageNumberEnvelope,pageRangeNotes,positiveInteger,readEnvelopeCursor,readPageNumberCursor,shellQuote}from"./chunk-MI6HVYR2.js";import"./chunk-3ZRMMBP5.js";import{ApiResponseError,EXIT_OK,EXIT_WAIT_TIMEOUT,NetworkError,UsageError}from"./chunk-VFPY2A23.js";import{GLOBAL_OPTIONS_HELP}from"./chunk-KIZIRVW6.js";import{AuthSession,NotLoggedInError,SessionExpiredError,loadCredentials}from"./chunk-XNLIEUAW.js";import{
|
|
6
6
|
httpFetch}from"./chunk-J7QYPKVK.js";import{effectiveApiUrl,resolveConfiguredOutput,resolveProfile}from"./chunk-EDF4U5BT.js";import"./chunk-RZVI6PMW.js";import{HELP_TOKEN}from"./chunk-AAABT3AX.js";import"./chunk-OKATZ4SN.js";import{OUTPUT_FORMATS,resolveOutputFormat}from"./chunk-RKBUJKI5.js";import"./chunk-UREA4ZIG.js";import{stripTerminalControls}from"./chunk-NHYMHCAT.js";import"./chunk-VSJBJXZO.js";var MIN_SEGMENT_CHARS=3;var parsedCache=new WeakMap;function splitSegments(path){return path.split("/").filter(segment=>segment!=="")}function parseRoutes(routes){const cached=parsedCache.get(routes);if(cached!==void 0)return cached;const parsed=[];for(const[key,domain]of Object.entries(routes.routes)){const space=key.indexOf(" ");if(space<=0)continue;const template=key.slice(space+1);parsed.push({method:key.slice(0,space),template,domain,segments:splitSegments(template).map(segment=>/^\{[^/{}]+\}$/.
|
|
@@ -1212,7 +1212,7 @@ cwd()){const listed=await gitListFiles(cwd2);const raw=listed??await walkFiles(c
|
|
|
1212
1212
|
1;const after=/^[^\s]*/.exec(text.slice(cursor))?.[0]??"";return{query,start,end:cursor+after.length}}var TWP_SLASH_ROUTES={"/tasks":{domain:"task",operation:"list"},"/task":{domain:"task",operation:"get"},"/projects":{domain:"project",operation:"list"}};function isTwpSlashCommand(name){return Object.hasOwn(TWP_SLASH_ROUTES,name)}async function runTwpSlashCommand(name,args,deps){const route=TWP_SLASH_ROUTES[name];if(!Object.hasOwn(TWP_SLASH_ROUTES,name)||route===void 0){return{code:2,out:"",err:`\u4E0D\u660E\u306A\u30B3\u30DE\u30F3\u30C9: ${name}
|
|
1213
1213
|
`}}const parsed=parseArgv([route.domain,route.operation,...args]);if(parsed.command!=="domain"||parsed.domain!==route.domain){return{code:2,out:"",err:`${name}: \u3053\u306E\u5F15\u6570\u306F\u4F7F\u3048\u307E\u305B\u3093\uFF08${args.join(" ")}\uFF09
|
|
1214
1214
|
`}}if(parsed.unknown.length>0){return{code:2,out:"",err:`\u4E0D\u660E\u306A\u5F15\u6570: ${formatUnknownArgs(parsed.unknown)}
|
|
1215
|
-
`}}let out="";let err="";const io={out:text=>void(out+=text),err:text=>void(err+=text),isTty:true};const globals={profile:parsed.profile??deps.profile,...parsed.output!==void 0?{output:parsed.output}:{},...parsed.query!==void 0?{query:parsed.query}:{},dryRun:parsed.dryRun,debug:parsed.debug,yes:parsed.yes,refresh:parsed.refresh};const{runDomain}=await import("./run-
|
|
1215
|
+
`}}let out="";let err="";const io={out:text=>void(out+=text),err:text=>void(err+=text),isTty:true};const globals={profile:parsed.profile??deps.profile,...parsed.output!==void 0?{output:parsed.output}:{},...parsed.query!==void 0?{query:parsed.query}:{},dryRun:parsed.dryRun,debug:parsed.debug,yes:parsed.yes,refresh:parsed.refresh};const{runDomain}=await import("./run-EYQI5JLL.js");try{const code=await runDomain({domain:route.domain,...parsed.operation!==void 0?{operation:parsed.operation}:
|
|
1216
1216
|
{},argv:parsed.domainArgv,help:parsed.domainHelp,globals,version:deps.version,io,...deps.fetchImpl!==void 0?{fetchImpl:deps.fetchImpl}:{}});return{code,out,err}}catch(e){return{code:1,out,err:`${err}${e.message}
|
|
1217
1217
|
`}}}var GIT_LOG_OUTPUT=["9f3c1a2 feat(ui): \u4E00\u89A7\u306E\u30D5\u30A3\u30EB\u30BF\u3092 URL \u30AF\u30A8\u30EA\u3068\u540C\u671F\u3059\u308B","4b8e0d7 fix(ui): \u4EEE\u60F3\u30B9\u30AF\u30ED\u30FC\u30EB\u306E\u884C\u9AD8\u3055\u3092\u5B9F\u6E2C\u5024\u306B\u5408\u308F\u305B\u308B","c15a99e refactor(api): \u4E00\u89A7\u53D6\u5F97\u306E\u30DA\u30FC\u30B8\u30F3\u30B0\u51E6\u7406\u3092\u5171\u901A\u5316\u3059\u308B","2d70f4b test: \u4E00\u89A7\u30D5\u30A3\u30EB\u30BF\u306E\u56DE\u5E30\u30C6\u30B9\u30C8\u3092\u8FFD\u52A0\u3059\u308B",
|
|
1218
1218
|
"a6e2b38 fix(api): \u7A7A\u306E\u691C\u7D22\u6761\u4EF6\u3067\u5168\u4EF6\u8FD4\u3089\u306A\u3044\u3088\u3046\u306B\u3059\u308B","7c40d51 chore(deps): \u958B\u767A\u4F9D\u5B58\u3092\u6700\u65B0\u3078\u66F4\u65B0\u3059\u308B","e83b1c6 docs: \u30BB\u30C3\u30C8\u30A2\u30C3\u30D7\u624B\u9806\u306B Node 22 \u306E\u524D\u63D0\u3092\u8FFD\u8A18\u3059\u308B","b91f7a4 fix(ui): \u30E2\u30FC\u30C0\u30EB\u306E\u91CD\u306A\u308A\u9806\u3092\u6307\u5B9A\u3059\u308B","5a2c8e0 perf(api): \u4E00\u89A7\u306E N+1 \u3092\u89E3\u6D88\u3059\u308B",
|
|
@@ -16,7 +16,7 @@ includes(format)){const e=new UsageError(`capacity list \u306E --output \u306B\u
|
|
|
16
16
|
${e.hint?`${e.hint}
|
|
17
17
|
`:""}`);return EXIT_USAGE}const res=await deps.get();if(!res.ok){err(`\u26D4 \u5B9F\u884C\u6A5F\u306E\u72B6\u614B\u3092\u53D6\u5F97\u3067\u304D\u307E\u305B\u3093\uFF08${errorDetail(res)}\uFF09
|
|
18
18
|
`);return apiExit(res)}const overview=parseOverview(res,opts,(deps.now??Date.now)());if(overview===null){err(`\u26D4 \u5B9F\u884C\u6A5F\u306E\u72B6\u614B\u3092\u89E3\u91C8\u3067\u304D\u307E\u305B\u3093\uFF08\u5FDC\u7B54\u306E\u5148\u982D: ${res.raw.slice(0,120)}\uFF09
|
|
19
|
-
`);return EXIT_API_SERVER}const{evaluateQuery}=await import("./query-
|
|
19
|
+
`);return EXIT_API_SERVER}const{evaluateQuery}=await import("./query-J76QIXWR.js");const{renderOutput}=await import("./render-I6U5PEYR.js");if(format==="json"){const selected2=opts.query===void 0?overview:await evaluateQuery(opts.query,overview);const text2=renderOutput(selected2,"json");out(text2.endsWith("\n")?text2:`${text2}
|
|
20
20
|
`);return EXIT_OK}const runnerCount=overview.projects.reduce((n,p)=>n+p.runners.length,0);const hiddenNote=overview.hidden_stopped>0?`\u30FB\u505C\u6B62\u4E2D ${overview.hidden_stopped}\u53F0\u306F\u975E\u8868\u793A\uFF08--include-stopped \u3067\u8868\u793A\uFF09`:"";const serverHidden=overview.projects.filter(p=>(p.hidden_count??0)>0).map(p=>`${projectLabel(p)}: ${p.hide_after_days??"?"}\u65E5\u4EE5\u4E0A\u5FDC\u7B54\u306E\u306A\u3044${p.hidden_count}\u53F0`).join("\u3001");err(`\u5B9F\u884C\u6A5F ${runnerCount}\
|
|
21
21
|
\u53F0\uFF08${overview.projects.length}\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\uFF09${hiddenNote}\u30FB\u53D6\u5F97 ${overview.generated_at||"\u4E0D\u660E"}
|
|
22
22
|
`);if(serverHidden!=="")err(`\u30B5\u30FC\u30D0\u5074\u3067\u4E00\u89A7\u304B\u3089\u5916\u308C\u3066\u3044\u308B\u6A5F: ${serverHidden}
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
2
|
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
-
var LOADERS={agent:async()=>(await import("./agent-2BNIUX2U.js")).agentDomain,"agent-loop":async()=>(await import("./agent-loop-
|
|
3
|
+
var LOADERS={agent:async()=>(await import("./agent-2BNIUX2U.js")).agentDomain,"agent-loop":async()=>(await import("./agent-loop-5SMJG7CB.js")).agentLoopDomain,"ai-review-reason":async()=>(await import("./sales-ai-review-2RBOUUYJ.js")).aiReviewReasonDomain,analysis:async()=>(await import("./analysis-IZJ7OGBS.js")).analysisDomain,announcement:async()=>(await import("./announcement-6FE7ZS4Z.js")).announcementDomain,"api-key":async()=>(await import("./api-key-TRRJUKYE.js")).apiKeyDomain,attendance:async()=>(await import("./attendance-correct-2KTCXVJX.js")).
|
|
4
4
|
attendanceDomainWithRecords,"audit-log":async()=>(await import("./audit-log-ZGK7IVLD.js")).auditLogDomain,backlog:async()=>(await import("./backlog-3WLFVEBA.js")).backlogDomain,budget:async()=>(await import("./budget-NA2SD5YD.js")).budgetDomain,"business-hours":async()=>(await import("./business-hours-37MRL53C.js")).businessHoursDomain,"business-place":async()=>(await import("./sales-master-SGT73CHC.js")).businessPlaceDomain,company:async()=>(await import("./company-GYE4NSYY.js")).companyDomain,
|
|
5
5
|
content:async()=>(await import("./content-JB6P46IF.js")).contentDomain,contract:async()=>(await import("./contract-J7IPD2IT.js")).contractDomain,corporate:async()=>(await import("./corporate-2QRAGFZ4.js")).corporateDomain,customer:async()=>(await import("./company-GYE4NSYY.js")).customerDomain,department:async()=>(await import("./department-PJOH2MXZ.js")).departmentDomain,deposit:async()=>(await import("./deposit-BBDYJVOG.js")).depositDomain,estimate:async()=>(await import("./estimate-MDCQUAIA.js")).
|
|
6
6
|
estimateDomain,evaluation:async()=>(await import("./evaluation-BVIVVRAX.js")).evaluationDomain,expense:async()=>(await import("./expense-MQPJVLVB.js")).expenseDomain,faq:async()=>(await import("./faq-MBW7SLC6.js")).faqDomain,"fiscal-year":async()=>(await import("./fiscal-year-4GC3CLDB.js")).fiscalYearDomain,holiday:async()=>(await import("./holiday-GTYFPTAI.js")).holidayDomain,"goal-sheet":async()=>(await import("./evaluation-BVIVVRAX.js")).goalSheetDomain,inquiry:async()=>(await import("./inquiry-QECSQJWD.js")).
|
|
7
|
-
inquiryDomain,invoice:async()=>(await import("./invoice-7PVEO7WG.js")).invoiceDomain,"job-title":async()=>(await import("./job-title-T3EVIB5D.js")).jobTitleDomain,knowledge:async()=>(await import("./domain-knowledge-G4NBJGWD.js")).knowledgeDomain,leave:async()=>(await import("./leave-WBZRI7ZO.js")).leaveDomain,license:async()=>(await import("./license-AMXSVUUX.js")).licenseDomain,"login-history":async()=>(await import("./login-history-ZF2QVJ4S.js")).loginHistoryDomain,media:async()=>(await import("./media-
|
|
7
|
+
inquiryDomain,invoice:async()=>(await import("./invoice-7PVEO7WG.js")).invoiceDomain,"job-title":async()=>(await import("./job-title-T3EVIB5D.js")).jobTitleDomain,knowledge:async()=>(await import("./domain-knowledge-G4NBJGWD.js")).knowledgeDomain,leave:async()=>(await import("./leave-WBZRI7ZO.js")).leaveDomain,license:async()=>(await import("./license-AMXSVUUX.js")).licenseDomain,"login-history":async()=>(await import("./login-history-ZF2QVJ4S.js")).loginHistoryDomain,media:async()=>(await import("./media-RI32UZY5.js")).
|
|
8
8
|
mediaDomain,meeting:async()=>(await import("./knowledge-5ZKO6N5X.js")).meetingDomain,note:async()=>(await import("./knowledge-5ZKO6N5X.js")).noteDomain,notification:async()=>(await import("./notification-WVJ6V2UN.js")).notificationDomain,onedrive:async()=>(await import("./onedrive-Z43D26SJ.js")).onedriveDomain,outlook:async()=>(await import("./outlook-U4XXFMC3.js")).outlookDomain,payee:async()=>(await import("./sales-master-SGT73CHC.js")).payeeDomain,position:async()=>(await import("./position-U56E7GX6.js")).
|
|
9
9
|
positionDomain,project:async()=>(await import("./project-YAFIKH4Z.js")).projectDomain,prospect:async()=>(await import("./prospect-ROAE2JQ6.js")).prospectDomain,purchase:async()=>(await import("./purchase-T3QS3EPW.js")).purchaseDomain,qualification:async()=>(await import("./skill-HA3DBVJ3.js")).qualificationDomain,receivable:async()=>(await import("./receivable-QGNV2FT7.js")).receivableDomain,redmine:async()=>(await import("./redmine-GTHXTKKD.js")).redmineDomain,report:async()=>(await import("./report-TCFRJYL6.js")).
|
|
10
10
|
reportDomain,"role-template":async()=>(await import("./evaluation-BVIVVRAX.js")).roleTemplateDomain,"rounding-setting":async()=>(await import("./sales-numbering-GLWL3NOI.js")).roundingSettingDomain,"seal-impression":async()=>(await import("./sales-master-SGT73CHC.js")).sealImpressionDomain,search:async()=>(await import("./search-JP77X4JS.js")).searchDomain,secret:async()=>(await import("./secret-P42JCOI4.js")).secretDomain,segment:async()=>(await import("./segment-ZTWVP32K.js")).segmentDomain,
|
|
11
|
-
shift:async()=>(await import("./attendance-lists-OIF5KYDQ.js")).shiftDomain,skill:async()=>(await import("./skill-HA3DBVJ3.js")).skillDomain,"staffing-board":async()=>(await import("./staffing-board-PORZDQBF.js")).staffingBoardDomain,storage:async()=>(await import("./storage-AQDCEBDJ.js")).storageDomain,"supplier-payment":async()=>(await import("./supplier-payment-FCIATDMY.js")).supplierPaymentDomain,support:async()=>(await import("./support-ZSYBBO52.js")).supportDomain,task:async()=>(await import("./task-
|
|
11
|
+
shift:async()=>(await import("./attendance-lists-OIF5KYDQ.js")).shiftDomain,skill:async()=>(await import("./skill-HA3DBVJ3.js")).skillDomain,"staffing-board":async()=>(await import("./staffing-board-PORZDQBF.js")).staffingBoardDomain,storage:async()=>(await import("./storage-AQDCEBDJ.js")).storageDomain,"supplier-payment":async()=>(await import("./supplier-payment-FCIATDMY.js")).supplierPaymentDomain,support:async()=>(await import("./support-ZSYBBO52.js")).supportDomain,task:async()=>(await import("./task-OHQ7BTOP.js")).
|
|
12
12
|
taskDomain,teams:async()=>(await import("./teams-HGOGRVEL.js")).teamsDomain,user:async()=>(await import("./user-6ACQM4GJ.js")).userDomain,"user-contract-type":async()=>(await import("./user-contract-type-I4KTAIZ3.js")).userContractTypeDomain,"user-group":async()=>(await import("./user-group-44DPCXVC.js")).userGroupDomain,wiki:async()=>(await import("./knowledge-5ZKO6N5X.js")).wikiDomain,workchange:async()=>(await import("./attendance-lists-OIF5KYDQ.js")).workchangeDomain,"worker-agent":async()=>(await import("./worker-agent-56PJ6YTR.js")).
|
|
13
13
|
workerAgentDomain,workflow:async()=>(await import("./workflow-ZWRPMTBR.js")).workflowDomain};async function loadDomain(name){return LOADERS[name]()}export{loadDomain};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
|
+
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
+
import{RUNNER_PLATFORMS}from"./chunk-UZUV5FYG.js";import{repeatedValues}from"./chunk-VGT2EGH6.js";import{UsageError}from"./chunk-VFPY2A23.js";function parseRequiredPlatforms(input,emptyHint=`\u6307\u5B9A\u3067\u304D\u308B\u5024: ${RUNNER_PLATFORMS.join(" / ")}`){const raw=repeatedValues(input,"--required-platforms");if(raw.length===0)return void 0;const given=new Set;for(const entry of raw){for(const part of entry.split(",")){const value=part.trim().toLowerCase();if(value===""){throw new UsageError(`--required-platforms \u306B\u7A7A\u306E\u5024\u304C\u3042\u308A\u307E\u3059: ${entry===""?"(\u7A7A)":entry}`,emptyHint)}if(!RUNNER_PLATFORMS.
|
|
4
|
+
includes(value)){throw new UsageError(`--required-platforms \u306B\u6307\u5B9A\u3067\u304D\u306A\u3044\u5024\u3067\u3059: ${part.trim()}`,`\u6307\u5B9A\u3067\u304D\u308B\u5024: ${RUNNER_PLATFORMS.join(" / ")}`)}given.add(value)}}return RUNNER_PLATFORMS.filter(platform=>given.has(platform))}export{parseRequiredPlatforms};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
2
|
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
-
import{UsageError}from"./chunk-VFPY2A23.js";async function evaluateQuery(expression,value){if(expression.trim()===""){throw new UsageError("--query \u306B\u7A7A\u306E\u5F0F\u306F\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093")}const{search}=await import("./dist-
|
|
3
|
+
import{UsageError}from"./chunk-VFPY2A23.js";async function evaluateQuery(expression,value){if(expression.trim()===""){throw new UsageError("--query \u306B\u7A7A\u306E\u5F0F\u306F\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093")}const{search}=await import("./dist-B4FAEXU4.js");try{return search(value??null,expression)}catch(err){throw new UsageError(`--query \u306E\u5F0F\u3092\u8A55\u4FA1\u3067\u304D\u307E\u305B\u3093: ${err.message}`)}}export{evaluateQuery};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
2
|
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
-
import{loadDomain}from"./chunk-
|
|
3
|
+
import{loadDomain}from"./chunk-46OWZRTJ.js";import{evaluateQuery}from"./chunk-F5QDUPQO.js";import{renderDocument,renderOutput}from"./chunk-P4QSPSOQ.js";import{JsonBodyWithView}from"./chunk-Q3B65OFC.js";import{NO_REDACT_NOTICE,withCommonFlags}from"./chunk-W4NLJ2YK.js";import{redactSecretValues,redactSecrets,withDebug}from"./chunk-BD7O73GK.js";import{parseOperationArgs}from"./chunk-VGT2EGH6.js";import{Resolver,requireDefaultProject}from"./chunk-A7MM5WSC.js";
|
|
4
4
|
import{ResolveError}from"./chunk-HVZUXLQ4.js";import{ApiError,MultipartBody,TwpApiClient,appendQuery}from"./chunk-JA5A6UJ2.js";import{DEFAULT_MAX_ITEMS,DEFAULT_MAX_PAGES,nextPageNotes,positiveInteger,shellQuote}from"./chunk-MI6HVYR2.js";import{isRecord}from"./chunk-3ZRMMBP5.js";import{ApiRejectedError,ApiResponseError,EXIT_API_CLIENT,EXIT_API_SERVER,EXIT_AUTH,EXIT_FAILURE,EXIT_OK,EXIT_USAGE,EXIT_WAIT_TIMEOUT,NetworkError,UsageError,WaitTimeoutError}from"./chunk-VFPY2A23.js";
|
|
5
5
|
import{GLOBAL_OPTIONS_HELP}from"./chunk-KIZIRVW6.js";import{AuthSession,NotLoggedInError,SessionExpiredError,loadCredentials}from"./chunk-XNLIEUAW.js";import{httpFetch}from"./chunk-J7QYPKVK.js";import{effectiveApiUrl,loadUserConfig,resolveConfiguredBacklogSpace,resolveConfiguredOutput,resolveProfile}from"./chunk-EDF4U5BT.js";import{HELP_TOKEN}from"./chunk-AAABT3AX.js";import{OUTPUT_FORMATS,resolveOutputFormat}from"./chunk-RKBUJKI5.js";import{stringWidth}from"./chunk-UREA4ZIG.js";
|
|
6
6
|
import{stripTerminalControls}from"./chunk-NHYMHCAT.js";import fs from"fs";import path from"path";function alignedList(entries,indent=" "){const width=entries.reduce((max,[left])=>Math.max(max,stringWidth(left)),0);return entries.map(([left,right])=>`${indent}${left}${" ".repeat(Math.max(0,width-stringWidth(left)))} ${right}`).join("\n")}function subresourcesOf(resource){return resource.subresources??[]}function renderResourceHelp(resource,path2){const subresources=subresourcesOf(resource);const operationSection=resource.operations.length===0?"":`
|
|
@@ -7,7 +7,7 @@ body,"hidden_count"),removed_count:pickNumber(body,"removed_count"),hide_after_d
|
|
|
7
7
|
r["version"])}}async function listRunners(api,opts,io){const{resolveOutputFormat}=await import("./format-X65HXAAU.js");const format=resolveOutputFormat({...opts.output!==void 0?{flag:opts.output}:{},isTty:io.isTty});if(format===null||!LIST_FORMATS.includes(format)){throw new UsageError(`runner list \u306E --output \u306B\u300C${opts.output??""}\u300D\u306F\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093`,`\u6307\u5B9A\u3067\u304D\u308B\u306E\u306F ${LIST_FORMATS.join(" / ")} \u3067\u3059`)}const res=await api.
|
|
8
8
|
request("GET","/runners");if(!res.ok){io.err(`\u26D4 \u30E9\u30F3\u30CA\u30FC\u4E00\u89A7\u3092\u53D6\u5F97\u3067\u304D\u307E\u305B\u3093\uFF08${errorDetail(res)}\uFF09
|
|
9
9
|
`);return apiExit(res)}const parsed=parseRunners(res);if(parsed===null){io.err(`\u26D4 \u30E9\u30F3\u30CA\u30FC\u4E00\u89A7\u3092\u89E3\u91C8\u3067\u304D\u307E\u305B\u3093\uFF08\u5FDC\u7B54\u306E\u5148\u982D: ${res.raw.slice(0,120)}\uFF09
|
|
10
|
-
`);return EXIT_API_SERVER}const{entries,summary}=parsed;const{evaluateQuery}=await import("./query-
|
|
10
|
+
`);return EXIT_API_SERVER}const{entries,summary}=parsed;const{evaluateQuery}=await import("./query-J76QIXWR.js");const{renderOutput}=await import("./render-I6U5PEYR.js");if(format==="json"){const value={...summary,runners:entries};const selected2=opts.query===void 0?value:await evaluateQuery(opts.query,value);const text2=renderOutput(selected2,"json");io.out(text2.endsWith("\n")?text2:`${text2}
|
|
11
11
|
`);return EXIT_OK}io.err(summaryLine(summary));const selected=opts.query===void 0?entries:await evaluateQuery(opts.query,entries);if(opts.query===void 0&&entries.length===0){io.err("\u4E00\u89A7\u306B\u8868\u793A\u3055\u308C\u308B\u767B\u9332\u306F\u3042\u308A\u307E\u305B\u3093\n");return EXIT_OK}const text=renderOutput(selected,format);io.out(text.endsWith("\n")?text:`${text}
|
|
12
12
|
`);if(opts.query===void 0&&entries.some(e=>e.state==="stale")){io.err(`${removeHint(opts)}
|
|
13
13
|
`)}return EXIT_OK}function summaryLine(s){const n=v=>v===null?"?":String(v);const parts=[`\u7A3C\u50CD ${n(s.live_count)} / ${n(s.max_runners)}\uFF08\u6B7B\u6D3B\u3057\u304D\u3044\u5024 ${n(s.heartbeat_timeout)}\u79D2\uFF09`];parts.push(`${n(s.hide_after_days)}\u65E5\u4EE5\u4E0A\u5FDC\u7B54\u306A\u3057\u3067\u975E\u8868\u793A ${n(s.hidden_count)}\u53F0`);if(s.removed_count!==null)parts.push(`\u624B\u52D5\u3067\u5916\u3057\u305F\u767B\u9332 ${s.removed_count}\u53F0`);return`\u30E9\u30F3\u30CA\u30FC: ${parts.
|
package/dist/cli.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
3
3
|
const require = __twpCreateRequire(import.meta.url);
|
|
4
|
-
import{GLOBAL_OPTIONS_HELP}from"./chunk-KIZIRVW6.js";import{parseArgv,quietFromEnv}from"./chunk-YNZZRPI3.js";import"./chunk-2LOT54OO.js";import"./chunk-NJL3H2BB.js";import"./chunk-AAABT3AX.js";import"./chunk-AH4KHEAC.js";import{formatUnknownArgs}from"./chunk-OKATZ4SN.js";import"./chunk-VSJBJXZO.js";var VERSION=true?"0.
|
|
4
|
+
import{GLOBAL_OPTIONS_HELP}from"./chunk-KIZIRVW6.js";import{parseArgv,quietFromEnv}from"./chunk-YNZZRPI3.js";import"./chunk-2LOT54OO.js";import"./chunk-NJL3H2BB.js";import"./chunk-AAABT3AX.js";import"./chunk-AH4KHEAC.js";import{formatUnknownArgs}from"./chunk-OKATZ4SN.js";import"./chunk-VSJBJXZO.js";var VERSION=true?"0.116.0":"0.0.0-dev";var HELP=`twp ${VERSION} \u2014 TWP CLI
|
|
5
5
|
|
|
6
6
|
\u4F7F\u3044\u65B9:
|
|
7
7
|
twp \u5BFE\u8A71 TUI \u3092\u8D77\u52D5
|
|
@@ -1707,16 +1707,16 @@ TUI \u5185:
|
|
|
1707
1707
|
\u4F1A\u8A71\u30FB\u30ED\u30FC\u30AB\u30EB\u30C4\u30FC\u30EB\uFF08\u30D5\u30A1\u30A4\u30EB\u30FB\u30B3\u30DE\u30F3\u30C9\u30FBgit\uFF09\u306F\u30C6\u30CA\u30F3\u30C8\u306E\u30AF\u30EC\u30B8\u30C3\u30C8\u3067\u5B9F\u969B\u306B\u52D5\u304D\u307E\u3059\u3002
|
|
1708
1708
|
`;function ignoreEpipe(stream){stream.on("error",err=>{if(err.code==="EPIPE")process.exit(0);throw err})}async function main(){const nodeMajor=Number(process.versions.node.split(".")[0]);if(nodeMajor<22){process.stderr.write(`twp-cli \u306B\u306F Node.js 22 \u4EE5\u4E0A\u304C\u5FC5\u8981\u3067\u3059\uFF08\u73FE\u5728: ${process.versions.node}\uFF09
|
|
1709
1709
|
`);process.exit(1)}ignoreEpipe(process.stdout);ignoreEpipe(process.stderr);if(process.env["TWP_AUTO_UPDATE_WORKER"]==="1"){const{runAutoUpdateWorker}=await import("./auto-update-worker-26OZDLQ7.js");await runAutoUpdateWorker().catch(()=>void 0);return}const[first,...rest]=process.argv.slice(2);if(first==="__complete"||first==="completion"){const completion=await import("./completion-RLEEOJMU.js");if(first==="completion"){process.exitCode=completion.runCompletion(rest,process.stdout,process.stderr);return}
|
|
1710
|
-
const[{loadDomain},{loadUserConfig}]=await Promise.all([import("./registry-
|
|
1710
|
+
const[{loadDomain},{loadUserConfig}]=await Promise.all([import("./registry-7LKI5A35.js"),import("./config-XYWRBIC6.js")]);process.exitCode=await completion.runComplete(rest,process.stdout,{loadDomain,profileNames:()=>Object.keys(loadUserConfig().profiles??{})});return}if(first==="configure"){const autoUpdate2=await import("./auto-update-FXXQHBV5.js");autoUpdate2.registerRunning();autoUpdate2.onStartup(VERSION);const{runConfigure}=await import("./configure-BJGPASNG.js");process.exitCode=
|
|
1711
1711
|
await runConfigure(rest);return}const args=parseArgv(process.argv.slice(2));if(args.command==="version"){process.stdout.write(`${VERSION}
|
|
1712
1712
|
`);return}if(args.command==="help"){process.stdout.write(HELP);return}if(args.movedCommand!==void 0){const{MOVED_QUEUE_COMMAND_MESSAGE}=await import("./dispatch-ZWCEVLKZ.js");process.stderr.write(MOVED_QUEUE_COMMAND_MESSAGE);process.exitCode=2;return}if(args.unknown.length>0){process.stderr.write(`\u4E0D\u660E\u306A\u5F15\u6570: ${formatUnknownArgs(args.unknown)}
|
|
1713
1713
|
|
|
1714
|
-
${HELP}`);process.exitCode=2;return}const autoUpdate=await import("./auto-update-FXXQHBV5.js");autoUpdate.registerRunning();if(args.command==="task-loop"&&args.taskLoopAction!=="capacity"){process.env[autoUpdate.DISABLE_ENV]="1"}else if(args.command!=="update"){autoUpdate.onStartup(VERSION)}if(args.command==="domain"&&args.domain!==void 0){const{runDomain}=await import("./run-
|
|
1715
|
-
{},argv:args.domainArgv,help:args.domainHelp,globals:{...args.profile!==void 0?{profile:args.profile}:{},...args.output!==void 0?{output:args.output}:{},...args.query!==void 0?{query:args.query}:{},dryRun:args.dryRun,debug:args.debug,yes:args.yes,refresh:args.refresh,quiet:args.quiet||quietFromEnv(process.env)},version:VERSION});return}if(args.command==="api"){const{runApiCommand}=await import("./api-command-
|
|
1714
|
+
${HELP}`);process.exitCode=2;return}const autoUpdate=await import("./auto-update-FXXQHBV5.js");autoUpdate.registerRunning();if(args.command==="task-loop"&&args.taskLoopAction!=="capacity"){process.env[autoUpdate.DISABLE_ENV]="1"}else if(args.command!=="update"){autoUpdate.onStartup(VERSION)}if(args.command==="domain"&&args.domain!==void 0){const{runDomain}=await import("./run-EYQI5JLL.js");process.exitCode=await runDomain({domain:args.domain,...args.operation!==void 0?{operation:args.operation}:
|
|
1715
|
+
{},argv:args.domainArgv,help:args.domainHelp,globals:{...args.profile!==void 0?{profile:args.profile}:{},...args.output!==void 0?{output:args.output}:{},...args.query!==void 0?{query:args.query}:{},dryRun:args.dryRun,debug:args.debug,yes:args.yes,refresh:args.refresh,quiet:args.quiet||quietFromEnv(process.env)},version:VERSION});return}if(args.command==="api"){const{runApiCommand}=await import("./api-command-RXXCI72A.js");process.exitCode=await runApiCommand({argv:args.domainArgv,help:args.domainHelp,
|
|
1716
1716
|
globals:{...args.profile!==void 0?{profile:args.profile}:{},...args.output!==void 0?{output:args.output}:{},...args.query!==void 0?{query:args.query}:{},dryRun:args.dryRun,debug:args.debug,yes:args.yes,quiet:args.quiet||quietFromEnv(process.env)},version:VERSION});return}if(args.command==="update"){const{runUpdate}=await import("./update-QGM225Q7.js");process.exitCode=await runUpdate({...args.profile!==void 0?{profile:args.profile}:{},version:VERSION});return}if(args.command==="login"||args.
|
|
1717
|
-
command==="logout"||args.command==="whoami"){const{runLogin,runLogout,runWhoami}=await import("./commands-
|
|
1718
|
-
if(args.command==="task-loop"){const{runTaskLoop}=await import("./commands-
|
|
1717
|
+
command==="logout"||args.command==="whoami"){const{runLogin,runLogout,runWhoami}=await import("./commands-P77EIMBU.js");const options={profile:args.profile,method:args.loginMethod,tenant:args.tenant,noBrowser:args.loginNoBrowser,cliVersion:VERSION,force:args.logoutForce,...args.output!==void 0?{output:args.output}:{},...args.query!==void 0?{query:args.query}:{}};const runner=args.command==="login"?runLogin:args.command==="logout"?runLogout:runWhoami;process.exitCode=await runner(options);return}
|
|
1718
|
+
if(args.command==="task-loop"){const{runTaskLoop}=await import("./commands-74PDZH6C.js");process.exitCode=await runTaskLoop({action:args.taskLoopAction??"run",project:args.project,profile:args.profile,safe:args.safe,daemon:args.daemon,interval:args.interval,maxCycles:args.maxCycles,forceRunner:args.forceRunner,force:args.stopForce,drain:args.stopDrain,engine:args.engine,version:VERSION,verbose:args.verbose,scheduleNow:args.scheduleNow,scheduleCounts:args.scheduleCounts,scheduleGate:args.scheduleGate,
|
|
1719
1719
|
scheduleOp:args.scheduleOp,scheduleConfigOp:args.scheduleConfigOp,scheduleId:args.scheduleId,charterOp:args.charterOp,charterInput:args.charterFile,charterOutput:args.charterOut,charterRevision:args.charterRevision,settingsOp:args.settingsOp,orientationOp:args.orientationOp,orientationArgs:args.orientationArgs,skillOp:args.skillOp,skillName:args.skillName,skillAll:args.skillAll,skillDir:args.skillDir,skillConfig:args.skillConfig,output:args.output,query:args.query,revisionFrom:args.revisionFrom,
|
|
1720
1720
|
revisionTo:args.revisionTo,planOp:args.planOp,capacityOp:args.capacityOp,includeStopped:args.includeStopped,runnerOp:args.runnerOp,runnerId:args.runnerTargetId,triggerOp:args.triggerOp,triggerId:args.triggerId,triggerKey:args.triggerKey,triggerLimit:args.triggerLimit,planEmpty:args.planEmpty,planCheck:args.planCheck,yes:args.yes,ais:args.ais,workspace:args.workspace,aiConfigFile:args.aiConfigFile,noAiConfigFile:args.noAiConfigFile});return}if(args.command==="print"){const{runOneShot}=await import("./oneshot-BDKA2IGL.js");
|
|
1721
|
-
process.exitCode=await runOneShot({prompt:args.prompt??"",fromStdin:args.promptFromStdin,mode:args.mode??"dev",...args.permissionMode!==void 0?{permissionMode:args.permissionMode}:{},allowedTools:args.allowedTools,disallowedTools:args.disallowedTools,...args.model!==void 0?{model:args.model}:{},...args.profile!==void 0?{profile:args.profile}:{},version:VERSION});return}const{startTui}=await import("./app-
|
|
1721
|
+
process.exitCode=await runOneShot({prompt:args.prompt??"",fromStdin:args.promptFromStdin,mode:args.mode??"dev",...args.permissionMode!==void 0?{permissionMode:args.permissionMode}:{},allowedTools:args.allowedTools,disallowedTools:args.disallowedTools,...args.model!==void 0?{model:args.model}:{},...args.profile!==void 0?{profile:args.profile}:{},version:VERSION});return}const{startTui}=await import("./app-MRG7YVO7.js");await startTui({mode:args.mode,permissionMode:args.permissionMode,allowedTools:args.
|
|
1722
1722
|
allowedTools,disallowedTools:args.disallowedTools,model:args.model,profile:args.profile,noTui:args.noTui||!process.stdout.isTTY,doctor:args.doctor,version:VERSION})}await main();
|
|
@@ -308,20 +308,20 @@ claudeLauncher,...extraHosts.length>0?{preflightHosts:[...DEFAULT_PREFLIGHT_HOST
|
|
|
308
308
|
action==="stop")return await stopLoop(opts);if(opts.action==="plan"){if(opts.planOp!=="submit"){process.stderr.write("plan \u306B\u306F submit \u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\n");return 2}const{runPlanSubmit}=await import("./plan-submit-QQPKYJ3M.js");return runPlanSubmit({file:opts.charterInput,empty:opts.planEmpty===true,check:opts.planCheck===true},{env:process.env,readStdin:()=>fs9.readFileSync(0,"utf8"),stdout:s=>process.stdout.write(s),stderr:s=>process.stderr.write(s)})}
|
|
309
309
|
const profile=resolveProfile(opts.profile);let creds;try{creds=new AuthSession(profile.name,profile.apiUrl).loadOrThrow()}catch(err){process.stderr.write(`${err.message}
|
|
310
310
|
`);return 1}const apiUrl=effectiveApiUrl(profile,creds.api_url);const session=new AuthSession(profile.name,apiUrl);if(opts.action==="capacity"&&opts.capacityOp==="list"){let filterId;if(opts.project!==void 0&&opts.project!==""){try{filterId=(await new ProjectApi(apiUrl,session).resolve(opts.project)).id}catch(err){process.stderr.write(`${err.message}
|
|
311
|
-
`);return 1}}const api2=new AgentLoopApi({apiUrl,projectId:filterId??"",session});const{runCapacityList}=await import("./capacity-list-command-
|
|
311
|
+
`);return 1}}const api2=new AgentLoopApi({apiUrl,projectId:filterId??"",session});const{runCapacityList}=await import("./capacity-list-command-EUU3H5ZE.js");return runCapacityList({get:()=>api2.runnersOverview()},{output:opts.output,query:opts.query,includeStopped:opts.includeStopped===true,projectId:filterId})}const projectRef=opts.project??process.env.TWP_PROJECT??"";if(projectRef===""){process.stderr.write("--project <\u30AD\u30FC|UUID> \u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF08TWP_PROJECT \u3067\u3082\u53EF\uFF09\n");
|
|
312
312
|
return 2}const projectApi=new ProjectApi(apiUrl,session);let project;try{project=await projectApi.resolve(projectRef)}catch(err){process.stderr.write(`${err.message}
|
|
313
313
|
`);return 1}const projectId=project.id;if(opts.action==="setup"){const{runSetup,parseAiList}=await import("./setup-3NYVAJKI.js");let ais;if(opts.ais!==void 0&&opts.ais.length>0){const parsed=parseAiList(opts.ais.join(","));if(parsed.unknown.length>0){process.stderr.write(`--ai \u306B\u672A\u77E5\u306E\u5024\u304C\u3042\u308A\u307E\u3059: ${parsed.unknown.join(" / ")}
|
|
314
314
|
`);return 2}ais=parsed.ais}return runSetup({projectId,projectRef,projectName:project.name===project.id?projectRef:`${project.code} / ${project.name}`,apiUrl,yes:opts.yes===true,...ais!==void 0?{ais}:{},...opts.workspace!==void 0?{workspace:opts.workspace}:{},...opts.aiConfigFile!==void 0?{aiConfigFile:opts.aiConfigFile}:{},...opts.noAiConfigFile===true?{noAiConfigFile:true}:{},...opts.profile!==void 0?{profile:opts.profile}:{}})}if(opts.action==="charter"){if(opts.charterOp===void 0){process.stderr.
|
|
315
315
|
write("charter \u306B\u306F push / pull / history / diff / revert \u306E\u3044\u305A\u308C\u304B\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\n");return 2}if(isPrivateProjectId(projectId)){process.stderr.write("\u500B\u4EBA\u30BF\u30B9\u30AF\u306E\u30AD\u30E5\u30FC\uFF08--project __private__\uFF09\u306B\u306F\u61B2\u7AE0\u306E\u8A2D\u5B9A\u304C\u3042\u308A\u307E\u305B\u3093\n");return 2}if(opts.charterOp!=="push"&&opts.charterOp!=="pull"){const{runRevisionCommand}=await import("./revision-command-KT7NMRES.js");
|
|
316
316
|
return runRevisionCommand({api:new AgentLoopApi({apiUrl,projectId,session})},{target:"charter",op:opts.charterOp,from:opts.revisionFrom,to:opts.revisionTo,revision:opts.charterRevision,yes:opts.yes===true,projectRef,profile:opts.profile})}const{runCharterCommand}=await import("./charter-command-A4MFFBGE.js");return runCharterCommand({api:new AgentLoopApi({apiUrl,projectId,session})},{op:opts.charterOp,file:opts.charterInput,out:opts.charterOutput,revision:opts.charterRevision,yes:opts.yes===true,projectRef,
|
|
317
|
-
profile:opts.profile})}if(opts.action==="runner"){if(opts.runnerOp===void 0){process.stderr.write("runner \u306B\u306F list / remove \u306E\u3044\u305A\u308C\u304B\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\n");return 2}const{runRunnerCommand}=await import("./runner-command-
|
|
318
|
-
if(opts.action==="trigger"){if(opts.triggerOp===void 0){process.stderr.write("trigger \u306B\u306F list / show / push / delete / history / release \u306E\u3044\u305A\u308C\u304B\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\n");return 2}const{runTriggerCommand}=await import("./trigger-command-
|
|
317
|
+
profile:opts.profile})}if(opts.action==="runner"){if(opts.runnerOp===void 0){process.stderr.write("runner \u306B\u306F list / remove \u306E\u3044\u305A\u308C\u304B\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\n");return 2}const{runRunnerCommand}=await import("./runner-command-YVY25WNU.js");return runRunnerCommand({api:new AgentLoopApi({apiUrl,projectId,session})},{op:opts.runnerOp,runnerId:opts.runnerId,output:opts.output,query:opts.query,yes:opts.yes===true,projectRef,profile:opts.profile})}
|
|
318
|
+
if(opts.action==="trigger"){if(opts.triggerOp===void 0){process.stderr.write("trigger \u306B\u306F list / show / push / delete / history / release \u306E\u3044\u305A\u308C\u304B\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\n");return 2}const{runTriggerCommand}=await import("./trigger-command-QUWGCSXO.js");return runTriggerCommand({api:new AgentLoopApi({apiUrl,projectId,session})},{op:opts.triggerOp,id:opts.triggerId,file:opts.charterInput,taskKey:opts.triggerKey,limit:opts.triggerLimit,revision:opts.
|
|
319
319
|
charterRevision,output:opts.output,query:opts.query,yes:opts.yes===true,projectRef,profile:opts.profile})}if(opts.action==="schedule"&&opts.scheduleOp!==void 0){const{runScheduleDefCommand}=await import("./schedule-def-command-QZB4FGWV.js");return runScheduleDefCommand({api:new AgentLoopApi({apiUrl,projectId,session})},{op:opts.scheduleOp,configOp:opts.scheduleConfigOp,id:opts.scheduleId,file:opts.charterInput,out:opts.charterOutput,revision:opts.charterRevision,yes:opts.yes===true,projectRef,profile:opts.
|
|
320
320
|
profile})}if(opts.action==="settings"){if(opts.settingsOp===void 0){process.stderr.write("settings \u306B\u306F push / pull \u306E\u3044\u305A\u308C\u304B\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\n");return 2}if(isPrivateProjectId(projectId)){process.stderr.write("\u500B\u4EBA\u30BF\u30B9\u30AF\u306E\u30AD\u30E5\u30FC\uFF08--project __private__\uFF09\u306B\u306F\u30EB\u30FC\u30D7\u8A2D\u5B9A\u304C\u3042\u308A\u307E\u305B\u3093\n");return 2}const{runSettingsCommand}=await import("./settings-command-3SLINN5N.js");
|
|
321
321
|
return runSettingsCommand({api:new AgentLoopApi({apiUrl,projectId,session})},{op:opts.settingsOp,file:opts.charterInput,out:opts.charterOutput,revision:opts.charterRevision,yes:opts.yes===true,projectRef,profile:opts.profile})}if(opts.action==="orientation"){if(opts.orientationOp===void 0){process.stderr.write("orientation \u306B\u306F show / set / on / off / add / remove \u306E\u3044\u305A\u308C\u304B\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\n");return 2}const{runOrientationCommand}=await import("./orientation-command-PQ3QXDPE.js");
|
|
322
322
|
return runOrientationCommand({api:new AgentLoopApi({apiUrl,projectId,session})},{op:opts.orientationOp,args:opts.orientationArgs??[],revision:opts.charterRevision,yes:opts.yes===true,projectRef,profile:opts.profile})}if(opts.action==="skill"){if(opts.skillOp===void 0){process.stderr.write("skill \u306B\u306F push / pull / list / show / delete / history / diff / revert / check \u306E\u3044\u305A\u308C\u304B\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\n");return 2}if(isPrivateProjectId(projectId)){
|
|
323
323
|
process.stderr.write("\u500B\u4EBA\u30BF\u30B9\u30AF\u306E\u30AD\u30E5\u30FC\uFF08--project __private__\uFF09\u306B\u306F\u30B9\u30AD\u30EB\u5B9A\u7FA9\u306E\u8A2D\u5B9A\u304C\u3042\u308A\u307E\u305B\u3093\n");return 2}if(opts.skillOp==="check"){const{runSkillCheck}=await import("./skill-check-2XYES4X3.js");return runSkillCheck({api:new AgentLoopApi({apiUrl,projectId,session})},{configPath:opts.skillConfig,defaultConfigPath:localConfigPath(projectId),output:opts.output})}if(opts.skillOp==="list"||
|
|
324
|
-
opts.skillOp==="show"||opts.skillOp==="delete"){const{runSkillManageCommand}=await import("./skill-manage-command-
|
|
324
|
+
opts.skillOp==="show"||opts.skillOp==="delete"){const{runSkillManageCommand}=await import("./skill-manage-command-HGLXVSJB.js");return runSkillManageCommand({api:new AgentLoopApi({apiUrl,projectId,session})},{op:opts.skillOp,name:opts.skillName,output:opts.output,query:opts.query,revision:opts.charterRevision,yes:opts.yes===true,projectRef,profile:opts.profile})}if(opts.skillOp!=="push"&&opts.skillOp!=="pull"){const{runRevisionCommand}=await import("./revision-command-KT7NMRES.js");return runRevisionCommand({
|
|
325
325
|
api:new AgentLoopApi({apiUrl,projectId,session})},{target:"skill",op:opts.skillOp,name:opts.skillName,from:opts.revisionFrom,to:opts.revisionTo,revision:opts.charterRevision,yes:opts.yes===true,projectRef,profile:opts.profile})}const{runSkillCommand}=await import("./skill-command-4VMZ2H6A.js");return runSkillCommand({api:new AgentLoopApi({apiUrl,projectId,session})},{op:opts.skillOp,name:opts.skillName,all:opts.skillAll===true,dir:opts.skillDir,revision:opts.charterRevision,yes:opts.yes===true,projectRef,
|
|
326
326
|
profile:opts.profile})}const config=buildLoopConfig({projectId,projectRef,apiUrl,safeMode:opts.safe,daemon:opts.daemon,...opts.maxCycles!==void 0?{maxCycles:opts.maxCycles}:{},...opts.interval!==void 0?{intervalSec:opts.interval}:{},forceRunner:opts.forceRunner,...opts.engine!==void 0?{engine:opts.engine}:{},version:opts.version});const api=new AgentLoopApi({apiUrl,projectId,session});if(opts.action==="capacity"){if(opts.capacityOp!=="report"){process.stderr.write("capacity \u306B\u306F report / list \u306E\u3044\u305A\u308C\
|
|
327
327
|
\u304B\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\n");return 2}for(const warning of config.warnings)process.stderr.write(`\u26A0\uFE0F ${warning}
|
|
@@ -346,7 +346,7 @@ void shutdown().catch(()=>void 0).then(()=>process.exit(130))};process.once("SIG
|
|
|
346
346
|
\uFF09\u3002\u518D\u8D77\u52D5\u306F systemd\uFF08Restart=always\uFF09\u304C\u884C\u3044\u307E\u3059`);const reason=`\u7248\u30C9\u30EA\u30D5\u30C8 ${from} \u2192 ${to} \u306B\u3088\u308B\u81EA\u52D5\u518D\u8D77\u52D5`;if(loop===null)pendingDrain.value={reason,exitCode:EXIT_VERSION_DRIFT};else loop.requestDrain(reason,EXIT_VERSION_DRIFT)}});driftWatcher=watch.stop}try{const{LoopSettingsApplier:LoopSettingsApplier2}=await import("./server-settings-DOWTEZGC.js");const settings=new LoopSettingsApplier2(
|
|
347
347
|
{api,config,log:m=>log.log(m)});await settings.apply();const{ServerSkillCatalog:ServerSkillCatalog2}=await import("./server-skills-5JESWOTH.js");const skills=new ServerSkillCatalog2({api,config,log:m=>log.log(m)});await skills.refresh();await runner.checkHeartbeatInterval();await runner.registerOrThrow();runner.startHeartbeatWorker();log.log(` heartbeat: ${config.heartbeatIntervalSec}\u79D2\u3054\u3068\u306B\u9001\u4FE1${runner.heartbeatTimeoutServer?`\uFF08\u30B5\u30FC\u30D0\u306E\u6B7B\u6D3B\u3057\u304D\u3044\u5024 ${runner.
|
|
348
348
|
heartbeatTimeoutServer}\u79D2\uFF09`:""}`);loop=new TaskLoop({api,projectApi,config,log,runner,engine:await buildEngine(config,m=>log.log(m)),settings,skills});if(pendingDrain.value!==null){loop.requestDrain(pendingDrain.value.reason,pendingDrain.value.exitCode)}exitCode=await loop.run()}catch(err){if(err instanceof RunnerRegistrationError){exitCode=1}else{log.log(`\u26D4 \u4E88\u671F\u3057\u306A\u3044\u30A8\u30E9\u30FC\u3067\u7D42\u4E86\u3057\u307E\u3059: ${err.message}`);exitCode=1}}finally{await shutdown(
|
|
349
|
-
nextRunInOnExit({exitCode,loopStarted:loop!==null,drainRequested:(loop?.drainRequested??false)||pendingDrain.value!==null,endedAbnormally:loop?.endedAbnormallyWithZero??false,nextRunInSec:config.nextRunInSec}))}return exitCode}async function showStatus(api,config,opts){const{runStatusCommand}=await import("./status-command-
|
|
349
|
+
nextRunInOnExit({exitCode,loopStarted:loop!==null,drainRequested:(loop?.drainRequested??false)||pendingDrain.value!==null,endedAbnormally:loop?.endedAbnormallyWithZero??false,nextRunInSec:config.nextRunInSec}))}return exitCode}async function showStatus(api,config,opts){const{runStatusCommand}=await import("./status-command-XGAFTFTW.js");const lock=lockDir(config);return runStatusCommand(api,{projectRef:config.projectRef,projectId:config.projectId,apiUrl:config.apiUrl,lockPath:lock,lockHeld:fs9.existsSync(
|
|
350
350
|
lock),profile:opts.profile},{output:opts.output,query:opts.query},{out:s=>process.stdout.write(s),err:s=>process.stderr.write(s)})}var STOP_WAIT_MS=18e4;var STOP_POLL_MS=250;function defaultIsAlive(pid){try{process.kill(pid,0);return true}catch(err){return err.code==="EPERM"}}async function stopLoop(opts,deps={}){const platform=deps.platform??process.platform;const isLoopProcess=deps.isLoopProcess??defaultIsLoopProcess;const isAlive=deps.isAlive??defaultIsAlive;const waitMs=deps.waitMs??STOP_WAIT_MS;
|
|
351
351
|
const pollMs=deps.pollMs??STOP_POLL_MS;const now=deps.now??Date.now;const nap=deps.sleep??(ms=>new Promise(r=>setTimeout(r,ms)));const request=deps.requestMarkerFn??requestMarker;const out=m=>void process.stdout.write(m);const err=m=>void process.stderr.write(m);if(opts.force&&opts.drain){err("\u26A0\uFE0F --force \u3068 --drain \u306F\u540C\u6642\u306B\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093\uFF08\u8981\u6C42\u304C\u6B63\u53CD\u5BFE\u3067\u3059\uFF09\u3002\u3069\u3061\u3089\u3082\u5B9F\u884C\u3057\u307E\u305B\u3093\n");
|
|
352
352
|
return 2}const stateDir=deps.stateDir??loopStateDir();let dirs;try{dirs=fs9.readdirSync(stateDir).filter(d=>/^task-loop-.*\.lock\.d$/.test(d))}catch{dirs=[]}if(opts.project){if(/^[0-9a-f-]{36}$/i.test(opts.project)||ULID_RE.test(opts.project)){dirs=dirs.filter(d=>d===`task-loop-${opts.project}.lock.d`)}else if(isPrivateProjectRef(opts.project)){dirs=dirs.filter(d=>d.startsWith("task-loop-private-"))}else{err(`\u26A0\uFE0F --project \u306F ID\uFF08UUID / ULID\uFF09\u6307\u5B9A\u306E\u3068\u304D\u3060\u3051\u7D5E\u308A\u8FBC\u3081\u307E\u3059\uFF08${safe(
|
|
@@ -55,7 +55,7 @@ ation/json",Authorization:`Bearer ${creds.token}`}}).then(res=>res.ok,()=>false)
|
|
|
55
55
|
`);if(!revoked){writeOut("\u26A0 \u30B5\u30FC\u30D0\u5074\u306E\u30C8\u30FC\u30AF\u30F3\u5931\u52B9\u306B\u5931\u6557\u3057\u307E\u3057\u305F\uFF08\u30AA\u30D5\u30E9\u30A4\u30F3\u7B49\uFF09\u3002TWP \u306E\u300C\u8A2D\u5B9A > CLI\u7AEF\u672B\u300D\u304B\u3089\u3082\u5931\u52B9\u3067\u304D\u307E\u3059\u3002\n")}})}async function runWhoami(options){return run(async()=>{const profile=resolveProfile(options.profile);const structured=options.output!==void 0||options.query!==void 0;let format=null;if(structured){
|
|
56
56
|
const{resolveOutputFormat,OUTPUT_FORMATS}=await import("./format-X65HXAAU.js");format=resolveOutputFormat({...options.output!==void 0?{flag:options.output}:{},isTty:process.stdout.isTTY===true});if(format===null){throw new UsageError(`--output \u306B\u300C${options.output??""}\u300D\u306F\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093`,`\u6307\u5B9A\u3067\u304D\u308B\u306E\u306F ${OUTPUT_FORMATS.join(" / ")} \u3067\u3059`)}}const stored=loadCredentials(profile.name);const apiUrl=effectiveApiUrl(
|
|
57
57
|
profile,stored?.api_url);const session=new AuthSession(profile.name,apiUrl);const client=new TwpApiClient(apiUrl,session,httpFetch,options.cliVersion);const me=await client.get("/api/v2/user");const user=me.user;const creds=loadCredentials(profile.name);if(format!==null){const value={id:user?.id??null,name:user?.name??null,email:user?.email??null,tenant_code:user?.tenant_code??null,role:user?.role??null,is_admin:user?.is_admin??null,profile:profile.name,api_url:apiUrl,expires_at:creds?.token_expires_at??
|
|
58
|
-
null};const{evaluateQuery}=await import("./query-
|
|
58
|
+
null};const{evaluateQuery}=await import("./query-J76QIXWR.js");const{renderOutput}=await import("./render-I6U5PEYR.js");const selected=options.query===void 0?value:await evaluateQuery(options.query,value);const text=renderOutput(selected,format);process.stdout.write(text.endsWith("\n")?text:`${text}
|
|
59
59
|
`);return}writeOut(`\u30E6\u30FC\u30B6\u30FC: ${user?.name??"?"}\uFF08${user?.email??"?"}\uFF09
|
|
60
60
|
`);writeOut(`ID: ${user?.id??"?"}
|
|
61
61
|
`);writeOut(`\u30C6\u30CA\u30F3\u30C8: ${user?.tenant_code??"?"}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
|
+
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
+
import"./chunk-VSJBJXZO.js";var CHILD_PROPS=["left","right","condition","child","operand","trueExpr","falseExpr","expression"];function pushChildren(node,stack){const n=node;for(const prop of CHILD_PROPS){const val=n[prop];if(val&&typeof val==="object"&&"type"in val){stack.push(val)}}if(Array.isArray(n.children)){for(const item of n.children){if(!item){continue}stack.push(item);if(item.type==="KeyValuePair"&&item.value){stack.push(item.value)}}}if(Array.isArray(n.bindings)){for(const item of n.bindings){if(!item){continue}
|
|
4
|
+
stack.push(item);if(item.reference){stack.push(item.reference)}}}}function forEachNode(root,visitor){const stack=[root];while(stack.length>0){const current=stack.pop();if(!current){break}if(visitor(current)===false){return}pushChildren(current,stack)}}function countNodes(root){let count=0;forEachNode(root,()=>{count+=1;return true});return count}function findDisallowedFunction(root,options){const{allowedFunctions,disallowedFunctions}=options;if(!allowedFunctions&&!disallowedFunctions){return null}
|
|
5
|
+
let violation=null;forEachNode(root,node=>{if(node.type!=="Function"){return true}const name=node.name;if(allowedFunctions&&!allowedFunctions.includes(name)){violation=`Function '${name}' is not allowed`;return false}if(disallowedFunctions&&disallowedFunctions.includes(name)){violation=`Function '${name}' is disallowed`;return false}return true});return violation}var isObject=obj=>{return obj!==null&&Object.prototype.toString.call(obj)==="[object Object]"};var strictDeepEqual=(first,second)=>{if(first===
|
|
6
|
+
second){return true}if(typeof first!==typeof second){return false}if(Array.isArray(first)&&Array.isArray(second)){if(first.length!==second.length){return false}for(let i=0;i<first.length;i+=1){if(!strictDeepEqual(first[i],second[i])){return false}}return true}if(isObject(first)&&isObject(second)){const firstEntries=Object.entries(first);const secondKeys=new Set(Object.keys(second));if(firstEntries.length!==secondKeys.size){return false}for(const[key,value]of firstEntries){if(!strictDeepEqual(value,
|
|
7
|
+
second[key])){return false}secondKeys.delete(key)}return secondKeys.size===0}return false};var isFalse=obj=>{if(obj===null||obj===void 0||obj===false){return true}if(typeof obj==="string"){return obj===""}if(typeof obj==="object"){if(Array.isArray(obj)){return obj.length===0}return Object.keys(obj).length===0}return false};var isAlpha=ch=>{return ch>="a"&&ch<="z"||ch>="A"&&ch<="Z"||ch==="_"};var isNum=ch=>{return ch>="0"&&ch<="9"||ch==="-"};var isAlphaNum=ch=>{return ch>="a"&&ch<="z"||ch>="A"&&ch<=
|
|
8
|
+
"Z"||ch>="0"&&ch<="9"||ch==="_"};var ensureInteger=value=>{if(!(typeof value==="number")||Math.floor(value)!==value){throw new Error("invalid-value: expecting an integer.")}return value};var ensurePositiveInteger=value=>{if(!(typeof value==="number")||value<0||Math.floor(value)!==value){throw new Error("invalid-value: expecting a non-negative integer.")}return value};var ensureNumbers=(...operands)=>{for(let i=0;i<operands.length;i++){if(operands[i]===null||operands[i]===void 0){throw new Error(
|
|
9
|
+
"not-a-number: undefined")}if(typeof operands[i]!=="number"){throw new Error("not-a-number")}}};var notZero=n=>{n=+n;if(!n){throw new Error("not-a-number: divide by zero")}return n};var add=(left,right)=>{ensureNumbers(left,right);return left+right};var sub=(left,right)=>{ensureNumbers(left,right);return left-right};var mul=(left,right)=>{ensureNumbers(left,right);return left*right};var divide=(left,right)=>{ensureNumbers(left,right);return left/notZero(right)};var div=(left,right)=>{ensureNumbers(
|
|
10
|
+
left,right);return Math.floor(left/notZero(right))};var mod=(left,right)=>{ensureNumbers(left,right);return left%right};var basicTokens={"(":"Lparen",")":"Rparen","*":"Star",",":"Comma",".":"Dot",":":"Colon","@":"Current","]":"Rbracket","{":"Lbrace","}":"Rbrace","+":"Plus","%":"Modulo","?":"Question","\u2212":"Minus","\xD7":"Multiply","\xF7":"Divide"};var operatorStartToken={"!":true,"<":true,"=":true,">":true,"&":true,"|":true,"/":true};var skipChars={" ":true,"\n":true,"\r":true," ":true};var StreamLexer=class{_current=0;_enable_legacy_literals=false;tokenize(stream,options){
|
|
11
|
+
const tokens=[];this._current=0;this._enable_legacy_literals=options?.enable_legacy_literals||false;let start;let identifier;let token;while(this._current<stream.length){if(isAlpha(stream[this._current])){start=this._current;identifier=this.consumeUnquotedIdentifier(stream);tokens.push({start,type:"UnquotedIdentifier",value:identifier})}else if(basicTokens[stream[this._current]]!==void 0){tokens.push({start:this._current,type:basicTokens[stream[this._current]],value:stream[this._current]});this.
|
|
12
|
+
_current+=1}else if(stream[this._current]==="$"){start=this._current;if(this._current+1<stream.length&&isAlpha(stream[this._current+1])){this._current+=1;identifier=this.consumeUnquotedIdentifier(stream);tokens.push({start,type:"Variable",value:identifier})}else{tokens.push({start,type:"Root",value:stream[this._current]});this._current+=1}}else if(stream[this._current]==="-"){if(this._current+1<stream.length&&isNum(stream[this._current+1])){const token2=this.consumeNumber(stream);token2&&tokens.
|
|
13
|
+
push(token2)}else{const token2={start:this._current,type:"Minus",value:"-"};tokens.push(token2);this._current+=1}}else if(isNum(stream[this._current])){token=this.consumeNumber(stream);tokens.push(token)}else if(stream[this._current]==="["){token=this.consumeLBracket(stream);tokens.push(token)}else if(stream[this._current]==='"'){start=this._current;identifier=this.consumeQuotedIdentifier(stream);tokens.push({start,type:"QuotedIdentifier",value:identifier})}else if(stream[this._current]===`'`){start=
|
|
14
|
+
this._current;identifier=this.consumeRawStringLiteral(stream);tokens.push({start,type:"Literal",value:identifier})}else if(stream[this._current]==="`"){start=this._current;const literal=this.consumeLiteral(stream);tokens.push({start,type:"Literal",value:literal})}else if(operatorStartToken[stream[this._current]]!==void 0){token=this.consumeOperator(stream);token&&tokens.push(token)}else if(skipChars[stream[this._current]]!==void 0){this._current+=1}else{const error=new Error(`Syntax error: unkno\
|
|
15
|
+
wn character: ${stream[this._current]}`);error.name="LexerError";throw error}}return tokens}consumeUnquotedIdentifier(stream){const start=this._current;this._current+=1;while(this._current<stream.length&&isAlphaNum(stream[this._current])){this._current+=1}return stream.slice(start,this._current)}consumeQuotedIdentifier(stream){const start=this._current;this._current+=1;const maxLength=stream.length;while(stream[this._current]!=='"'&&this._current<maxLength){let current=this._current;if(stream[current]===
|
|
16
|
+
"\\"&&(stream[current+1]==="\\"||stream[current+1]==='"')){current+=2}else{current+=1}this._current=current}this._current+=1;const[value,ok]=this.parseJSON(stream.slice(start,this._current));if(!ok){const error=new Error(`syntax: unexpected end of JSON input`);error.name="LexerError";throw error}return value}consumeRawStringLiteral(stream){const start=this._current;this._current+=1;const maxLength=stream.length;while(stream[this._current]!==`'`&&this._current<maxLength){let current=this._current;
|
|
17
|
+
if(stream[current]==="\\"&&(stream[current+1]==="\\"||stream[current+1]===`'`)){current+=2}else{current+=1}this._current=current}this._current+=1;const literal=stream.slice(start+1,this._current-1);return literal.replace(/\\(['\\])/g,"$1")}consumeNumber(stream){const start=this._current;this._current+=1;const maxLength=stream.length;while(isNum(stream[this._current])&&this._current<maxLength){this._current+=1}const value=parseInt(stream.slice(start,this._current),10);return{start,value,type:"Num\
|
|
18
|
+
ber"}}consumeLBracket(stream){const start=this._current;this._current+=1;if(stream[this._current]==="?"){this._current+=1;return{start,type:"Filter",value:"[?"}}if(stream[this._current]==="]"){this._current+=1;return{start,type:"Flatten",value:"[]"}}return{start,type:"Lbracket",value:"["}}consumeOrElse(stream,peek,token,orElse){const start=this._current;this._current+=1;if(this._current<stream.length&&stream[this._current]===peek){this._current+=1;return{start,type:orElse,value:stream.slice(start,
|
|
19
|
+
this._current)}}return{start,type:token,value:stream[start]}}consumeOperator(stream){const start=this._current;const startingChar=stream[start];switch(startingChar){case"!":return this.consumeOrElse(stream,"=","Not","NE");case"<":return this.consumeOrElse(stream,"=","LT","LTE");case">":return this.consumeOrElse(stream,"=","GT","GTE");case"=":return this.consumeOrElse(stream,"=","Assign","EQ");case"&":return this.consumeOrElse(stream,"&","Expref","And");case"|":return this.consumeOrElse(stream,"|",
|
|
20
|
+
"Pipe","Or");case"/":return this.consumeOrElse(stream,"/","Divide","Div")}}consumeLiteral(stream){this._current+=1;const start=this._current;const maxLength=stream.length;while(stream[this._current]!=="`"&&this._current<maxLength){let current=this._current;if(stream[current]==="\\"&&(stream[current+1]==="\\"||stream[current+1]==="`")){current+=2}else{current+=1}this._current=current}let literalString=stream.slice(start,this._current).trimStart();literalString=literalString.replace("\\`","`");let literal=null;
|
|
21
|
+
let ok=false;if(this.looksLikeJSON(literalString)){[literal,ok]=this.parseJSON(literalString)}if(!ok&&this._enable_legacy_literals){[literal,ok]=this.parseJSON(`"${literalString}"`)}if(!ok){const error=new Error(`Syntax error: unexpected end of JSON input or invalid format for a JSON literal: ${stream[this._current]}`);error.name="LexerError";throw error}this._current+=1;return literal}looksLikeJSON(literalString){const startingChars='[{"';const jsonLiterals=["true","false","null"];const numberLooking="\
|
|
22
|
+
-0123456789";if(literalString===""){return false}if(startingChars.includes(literalString[0])){return true}if(jsonLiterals.includes(literalString)){return true}if(numberLooking.includes(literalString[0])){const[_,ok]=this.parseJSON(literalString);return ok}return false}parseJSON(text){try{const json=JSON.parse(text);return[json,true]}catch{return[null,false]}}};var Lexer=new StreamLexer;var Lexer_default=Lexer;var bindingPower={["EOF"]:0,["Variable"]:0,["UnquotedIdentifier"]:0,["QuotedIdentifier"]:0,
|
|
23
|
+
["Rbracket"]:0,["Rparen"]:0,["Comma"]:0,["Rbrace"]:0,["Number"]:0,["Current"]:0,["Expref"]:0,["Root"]:0,["Assign"]:1,["Pipe"]:1,["Question"]:2,["Or"]:3,["And"]:4,["EQ"]:5,["GT"]:5,["LT"]:5,["GTE"]:5,["LTE"]:5,["NE"]:5,["Minus"]:6,["Plus"]:6,["Div"]:7,["Divide"]:7,["Modulo"]:7,["Multiply"]:7,["Flatten"]:9,["Star"]:20,["Filter"]:21,["Dot"]:40,["Not"]:45,["Lbrace"]:50,["Lbracket"]:55,["Lparen"]:60};var TokenParser=class _TokenParser{index=0;tokens=[];depth=0;maxDepth;nodeCount=0;maxNodes;parse(expression,options){
|
|
24
|
+
this.loadTokens(expression,options||{enable_legacy_literals:false});this.index=0;this.depth=0;this.nodeCount=0;this.maxDepth=options?.maxDepth;this.maxNodes=options?.maxNodes;const ast=this.expression(0);if(this.lookahead(0)!=="EOF"){const token=this.lookaheadToken(0);this.errorToken(token,`Syntax error: unexpected token type: ${token.type}, value: ${token.value}`)}if(this.maxNodes!==void 0&&countNodes(ast)>this.maxNodes){throw new Error(`Expression exceeds maximum allowed node count of ${this.maxNodes}`)}
|
|
25
|
+
return ast}loadTokens(expression,options){this.tokens=Lexer_default.tokenize(expression,options);this.tokens.push({type:"EOF",value:"",start:expression.length})}expression(rbp){if(this.maxDepth!==void 0&&this.depth>=this.maxDepth){throw new Error(`Expression exceeds maximum allowed depth of ${this.maxDepth}`)}this.depth+=1;this.trackNode();try{const leftToken=this.lookaheadToken(0);this.advance();let left=this.nud(leftToken);let currentTokenType=this.lookahead(0);while(rbp<bindingPower[currentTokenType]){
|
|
26
|
+
this.trackNode();this.advance();left=this.led(currentTokenType,left);currentTokenType=this.lookahead(0)}return left}finally{this.depth-=1}}trackNode(){this.nodeCount+=1;if(this.maxNodes!==void 0&&this.nodeCount>this.maxNodes){throw new Error(`Expression exceeds maximum allowed node count of ${this.maxNodes}`)}}lookahead(offset){return this.tokens[this.index+offset].type}lookaheadToken(offset){return this.tokens[this.index+offset]}advance(){this.index+=1}nud(token){switch(token.type){case"Variabl\
|
|
27
|
+
e":return{type:"Variable",name:token.value};case"Literal":return{type:"Literal",value:token.value};case"UnquotedIdentifier":{if(_TokenParser.isKeyword(token,"let")&&this.lookahead(0)==="Variable"){return this.parseLetExpression()}else{return{type:"Field",name:token.value}}}case"QuotedIdentifier":if(this.lookahead(0)==="Lparen"){throw new Error("Syntax error: quoted identifier not allowed for function names.")}else{return{type:"Field",name:token.value}}case"Not":{const child=this.expression(bindingPower.
|
|
28
|
+
Not);return{type:"NotExpression",child}}case"Minus":{const child=this.expression(bindingPower.Minus);return{type:"Unary",operator:token.type,operand:child}}case"Plus":{const child=this.expression(bindingPower.Plus);return{type:"Unary",operator:token.type,operand:child}}case"Star":{const left={type:"Identity"};return{type:"ValueProjection",left,right:this.parseProjectionRHS(bindingPower.Star)}}case"Filter":return this.led(token.type,{type:"Identity"});case"Lbrace":return this.parseMultiselectHash();case"\
|
|
29
|
+
Flatten":{const left={type:"Flatten",child:{type:"Identity"}};const right=this.parseProjectionRHS(bindingPower.Flatten);return{type:"Projection",left,right}}case"Lbracket":{if(this.lookahead(0)==="Number"||this.lookahead(0)==="Colon"){const right=this.parseIndexExpression();return this.projectIfSlice({type:"Identity"},right)}if(this.lookahead(0)==="Star"&&this.lookahead(1)==="Rbracket"){this.advance();this.advance();const right=this.parseProjectionRHS(bindingPower.Star);return{left:{type:"Identi\
|
|
30
|
+
ty"},right,type:"Projection"}}return this.parseMultiselectList()}case"Current":return{type:"Current"};case"Root":return{type:"Root"};case"Expref":{const child=this.expression(bindingPower.Expref);return{type:"ExpressionReference",child}}case"Lparen":{const expression=this.expression(0);this.match("Rparen");return expression}default:this.errorToken(token)}}led(tokenName,left){switch(tokenName){case"Question":{const trueExpr=this.expression(0);this.match("Colon");const falseExpr=this.expression(0);
|
|
31
|
+
return{type:"Ternary",condition:left,trueExpr,falseExpr}}case"Dot":{const rbp=bindingPower.Dot;if(this.lookahead(0)!=="Star"){const right2=this.parseDotRHS(rbp);return{type:"Subexpression",left,right:right2}}this.advance();const right=this.parseProjectionRHS(rbp);return{type:"ValueProjection",left,right}}case"Pipe":{const right=this.expression(bindingPower.Pipe);return{type:"Pipe",left,right}}case"Or":{const right=this.expression(bindingPower.Or);return{type:"OrExpression",left,right}}case"And":{
|
|
32
|
+
const right=this.expression(bindingPower.And);return{type:"AndExpression",left,right}}case"Lparen":{if(left.type!=="Field"){throw new Error("Syntax error: expected a Field node")}const name=left.name;const args=this.parseCommaSeparatedExpressionsUntilToken("Rparen");const node={name,type:"Function",children:args};return node}case"Filter":{const condition=this.expression(0);this.match("Rbracket");const right=this.lookahead(0)==="Flatten"?{type:"Identity"}:this.parseProjectionRHS(bindingPower.Filter);
|
|
33
|
+
return{type:"FilterProjection",left,right,condition}}case"Flatten":{const leftNode={type:"Flatten",child:left};const right=this.parseProjectionRHS(bindingPower.Flatten);return{type:"Projection",left:leftNode,right}}case"Assign":{const leftNode=left;const right=this.expression(0);return{type:"Binding",variable:leftNode.name,reference:right}}case"EQ":case"NE":case"GT":case"GTE":case"LT":case"LTE":return this.parseComparator(left,tokenName);case"Plus":case"Minus":case"Multiply":case"Star":case"Divi\
|
|
34
|
+
de":case"Modulo":case"Div":return this.parseArithmetic(left,tokenName);case"Lbracket":{const token=this.lookaheadToken(0);if(token.type==="Number"||token.type==="Colon"){const right2=this.parseIndexExpression();return this.projectIfSlice(left,right2)}this.match("Star");this.match("Rbracket");const right=this.parseProjectionRHS(bindingPower.Star);return{type:"Projection",left,right}}default:return this.errorToken(this.lookaheadToken(0))}}static isKeyword(token,keyword){return token.type==="Unquot\
|
|
35
|
+
edIdentifier"&&token.value===keyword}match(tokenType){if(this.lookahead(0)===tokenType){this.advance();return}else{const token=this.lookaheadToken(0);this.errorToken(token,`Syntax error: expected ${tokenType}, got: ${token.type}`)}}errorToken(token,message=""){const error=new Error(message||`Syntax error: invalid token (${token.type}): "${token.value}"`);error.name="ParserError";throw error}parseIndexExpression(){if(this.lookahead(0)==="Colon"||this.lookahead(1)==="Colon"){return this.parseSliceExpression()}
|
|
36
|
+
const value=Number(this.lookaheadToken(0).value);this.advance();this.match("Rbracket");return{type:"Index",value}}projectIfSlice(left,right){const indexExpr={type:"IndexExpression",left,right};if(right.type==="Slice"){const rhs=this.parseProjectionRHS(bindingPower.Star);if(rhs.type==="Identity"){return indexExpr}return{left:indexExpr,right:rhs,type:"Projection"}}return indexExpr}parseSliceExpression(){const parts=[null,null,null];let index=0;let current=this.lookaheadToken(0);while(current.type!=
|
|
37
|
+
"Rbracket"&&index<3){if(current.type==="Colon"){index++;if(index===3){this.errorToken(this.lookaheadToken(0),"Syntax error, too many colons in slice expression")}this.advance()}else if(current.type==="Number"&&parts[index]===null){const part=this.lookaheadToken(0).value;parts[index]=part;this.advance()}else{const next=this.lookaheadToken(0);this.errorToken(next,`Syntax error, unexpected token: ${next.value}(${next.type})`)}current=this.lookaheadToken(0)}this.match("Rbracket");const[start,stop,step]=parts;
|
|
38
|
+
return{type:"Slice",start,stop,step}}parseLetExpression(){const separated=this.parseCommaSeparatedExpressionsUntilKeyword("in");const expression=this.expression(0);const bindings=separated.map(binding=>binding);return{type:"LetExpression",bindings,expression}}parseCommaSeparatedExpressionsUntilKeyword(keyword){return this.parseCommaSeparatedExpressionsUntil(()=>{return _TokenParser.isKeyword(this.lookaheadToken(0),keyword)},()=>{this.advance()})}parseCommaSeparatedExpressionsUntilToken(token){return this.
|
|
39
|
+
parseCommaSeparatedExpressionsUntil(()=>{return this.lookahead(0)===token},()=>{return this.match(token)})}parseCommaSeparatedExpressionsUntil(isEndToken,matchEndToken){const args=[];let expression;while(!isEndToken()){expression=this.expression(0);if(this.lookahead(0)==="Comma"){this.match("Comma")}args.push(expression)}matchEndToken();return args}parseComparator(left,comparator){const right=this.expression(bindingPower[comparator]);return{type:"Comparator",name:comparator,left,right}}parseArithmetic(left,operator){
|
|
40
|
+
const right=this.expression(bindingPower[operator]);return{type:"Arithmetic",operator,left,right}}parseDotRHS(rbp){const lookahead=this.lookahead(0);const exprTokens=["UnquotedIdentifier","QuotedIdentifier","Star"];if(exprTokens.includes(lookahead)){return this.expression(rbp)}if(lookahead==="Lbracket"){this.match("Lbracket");return this.parseMultiselectList()}if(lookahead==="Lbrace"){this.match("Lbrace");return this.parseMultiselectHash()}const token=this.lookaheadToken(0);this.errorToken(token,
|
|
41
|
+
`Syntax error, unexpected token: ${token.value}(${token.type})`)}parseProjectionRHS(rbp){if(bindingPower[this.lookahead(0)]<10){return{type:"Identity"}}if(this.lookahead(0)==="Lbracket"){return this.expression(rbp)}if(this.lookahead(0)==="Filter"){return this.expression(rbp)}if(this.lookahead(0)==="Dot"){this.match("Dot");return this.parseDotRHS(rbp)}const token=this.lookaheadToken(0);this.errorToken(token,`Syntax error, unexpected token: ${token.value}(${token.type})`)}parseMultiselectList(){const expressions=[];
|
|
42
|
+
while(this.lookahead(0)!=="Rbracket"){const expression=this.expression(0);expressions.push(expression);if(this.lookahead(0)==="Comma"){this.match("Comma");if(this.lookahead(0)==="Rbracket"){throw new Error("Syntax error: unexpected token Rbracket")}}}this.match("Rbracket");return{type:"MultiSelectList",children:expressions}}parseMultiselectHash(){const pairs=[];const identifierTypes=["UnquotedIdentifier","QuotedIdentifier"];let keyToken;let keyName;let value;for(;;){keyToken=this.lookaheadToken(
|
|
43
|
+
0);if(!identifierTypes.includes(keyToken.type)){throw new Error(`Syntax error: expecting an identifier token, got: ${keyToken.type}`)}keyName=keyToken.value;this.advance();this.match("Colon");value=this.expression(0);pairs.push({value,type:"KeyValuePair",name:keyName});if(this.lookahead(0)==="Comma"){this.match("Comma")}else if(this.lookahead(0)==="Rbrace"){this.match("Rbrace");break}}return{type:"MultiSelectHash",children:pairs}}};var Parser=new TokenParser;var Parser_default=Parser;var findFirst=(subject,sub2,start,end)=>{
|
|
44
|
+
if(!subject||!sub2){return null}const s=Math.max(ensureInteger(start??0),0);const e=Math.min(ensureInteger(end??subject.length),subject.length);const offset=subject.slice(s,e).indexOf(sub2);return offset===-1?null:offset+s};var findLast=(subject,sub2,start,end)=>{if(!subject||!sub2){return null}const s=Math.max(ensureInteger(start??0),0);const e=Math.min(ensureInteger(end??subject.length),subject.length);const offset=subject.slice(s,e).lastIndexOf(sub2);return offset===-1?null:offset+s};var lower=subject=>subject.
|
|
45
|
+
toLowerCase();var ensurePadFuncParams=(name,width,padding=" ")=>{if(padding.length>1){throw new Error(`invalid value, ${name} expects its 'pad' parameter to be a valid string with a single codepoint`)}ensurePositiveInteger(width);return padding};var padLeft=(subject,width,padding)=>{padding=ensurePadFuncParams("pad_left",width,padding);return subject&&subject.padStart(width,padding)||""};var padRight=(subject,width,padding)=>{padding=ensurePadFuncParams("pad_right",width,padding);return subject&&
|
|
46
|
+
subject.padEnd(width,padding)||""};var replace=(subject,string,by,count)=>{if(count===0){return subject}if(!count){return subject.split(string).join(by)}ensurePositiveInteger(count);while(count-- >0&&subject.includes(string)){subject=subject.replace(string,by)}return subject};var split=(subject,search2,count)=>{if(subject.length==0&&search2.length===0){return[]}if(count===null||count===void 0){return subject.split(search2)}ensurePositiveInteger(count);if(count===0){return[subject]}const split2=subject.
|
|
47
|
+
split(search2);return[...split2.slice(0,count),split2.slice(count).join(search2)]};var trim=(subject,chars)=>{return trimLeft(trimRight(subject,chars),chars)};var trimLeft=(subject,chars)=>{return trimImpl(subject,list=>new RegExp(`^[${list}]*(.*?)`),chars)};var trimRight=(subject,chars)=>{return trimImpl(subject,list=>new RegExp(`(.*?)[${list}]*$`),chars)};var trimImpl=(subject,regExper,chars)=>{const pattern=chars?chars.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&"):"\\s\x85";return subject.replace(regExper(
|
|
48
|
+
pattern),"$1")};var upper=subject=>subject.toUpperCase();var Text=class _Text{_text;constructor(text){this._text=text}get string(){return this._text}get length(){let count=0;for(const _ of this._text){count+=1}return count}compareTo(other){return _Text.compare(this,new _Text(other))}static get comparer(){const stringComparer=(left,right)=>{return new _Text(left).compareTo(right)};return stringComparer}static compare(left,right){const leftCp=left.codePoints;const rightCp=right.codePoints;for(let index=0;index<
|
|
49
|
+
Math.min(leftCp.length,rightCp.length);index++){if(leftCp[index]===rightCp[index]){continue}return leftCp[index]-rightCp[index]>0?1:-1}return leftCp.length-rightCp.length>0?1:-1}reverse(){return String.fromCodePoint(...this.codePoints.reverse())}get codePoints(){const array=[...this._text].map(s=>s.codePointAt(0));return array}};var createMathFunction=mathFn=>([value])=>mathFn(value);var createStringFunction=stringFn=>([subject])=>stringFn(subject);var createObjectFunction=objFn=>([obj])=>objFn(
|
|
50
|
+
obj);var ARRAY_SUBTYPES={[8]:0,[10]:4,[9]:2,[11]:3};var Runtime=class{_interpreter;_functionTable;_customFunctions=new Set;TYPE_NAME_TABLE=Object.freeze({[0]:"number",[1]:"any",[2]:"string",[3]:"array",[4]:"object",[5]:"boolean",[6]:"expression",[7]:"null",[8]:"Array<number>",[10]:"Array<object>",[9]:"Array<string>",[11]:"Array<Array<any>>"});constructor(interpreter){this._interpreter=interpreter;this._functionTable=this.buildFunctionTable()}buildFunctionTable(){return{abs:{_func:createMathFunction(
|
|
51
|
+
Math.abs),_signature:[{types:[0]}]},ceil:{_func:createMathFunction(Math.ceil),_signature:[{types:[0]}]},floor:{_func:createMathFunction(Math.floor),_signature:[{types:[0]}]},lower:{_func:createStringFunction(lower),_signature:[{types:[2]}]},upper:{_func:createStringFunction(upper),_signature:[{types:[2]}]},keys:{_func:createObjectFunction(Object.keys),_signature:[{types:[4]}]},values:{_func:createObjectFunction(Object.values),_signature:[{types:[4]}]},avg:{_func:this.functionAvg,_signature:[{types:[
|
|
52
|
+
8]}]},contains:{_func:this.functionContains,_signature:[{types:[2,3]},{types:[1]}]},ends_with:{_func:this.functionEndsWith,_signature:[{types:[2]},{types:[2]}]},find_first:{_func:this.functionFindFirst,_signature:[{types:[2]},{types:[2]},{types:[0],optional:true},{types:[0],optional:true}]},find_last:{_func:this.functionFindLast,_signature:[{types:[2]},{types:[2]},{types:[0],optional:true},{types:[0],optional:true}]},from_items:{_func:this.functionFromItems,_signature:[{types:[11]}]},group_by:{_func:this.
|
|
53
|
+
functionGroupBy,_signature:[{types:[3]},{types:[6]}]},items:{_func:this.functionItems,_signature:[{types:[4]}]},join:{_func:this.functionJoin,_signature:[{types:[2]},{types:[9]}]},length:{_func:this.functionLength,_signature:[{types:[2,3,4]}]},map:{_func:this.functionMap,_signature:[{types:[6]},{types:[3]}]},max:{_func:this.functionMax,_signature:[{types:[8,9]}]},max_by:{_func:this.functionMaxBy,_signature:[{types:[3]},{types:[6]}]},merge:{_func:this.functionMerge,_signature:[{types:[4],variadic:true}]},
|
|
54
|
+
min:{_func:this.functionMin,_signature:[{types:[8,9]}]},min_by:{_func:this.functionMinBy,_signature:[{types:[3]},{types:[6]}]},not_null:{_func:this.functionNotNull,_signature:[{types:[1],variadic:true}]},pad_left:{_func:this.functionPadLeft,_signature:[{types:[2]},{types:[0]},{types:[2],optional:true}]},pad_right:{_func:this.functionPadRight,_signature:[{types:[2]},{types:[0]},{types:[2],optional:true}]},replace:{_func:this.functionReplace,_signature:[{types:[2]},{types:[2]},{types:[2]},{types:[
|
|
55
|
+
0],optional:true}]},reverse:{_func:this.functionReverse,_signature:[{types:[2,3]}]},sort:{_func:this.functionSort,_signature:[{types:[9,8]}]},sort_by:{_func:this.functionSortBy,_signature:[{types:[3]},{types:[6]}]},split:{_func:this.functionSplit,_signature:[{types:[2]},{types:[2]},{types:[0],optional:true}]},starts_with:{_func:this.functionStartsWith,_signature:[{types:[2]},{types:[2]}]},sum:{_func:this.functionSum,_signature:[{types:[8]}]},to_array:{_func:this.functionToArray,_signature:[{types:[
|
|
56
|
+
1]}]},to_number:{_func:this.functionToNumber,_signature:[{types:[1]}]},to_string:{_func:this.functionToString,_signature:[{types:[1]}]},trim:{_func:this.functionTrim,_signature:[{types:[2]},{types:[2],optional:true}]},trim_left:{_func:this.functionTrimLeft,_signature:[{types:[2]},{types:[2],optional:true}]},trim_right:{_func:this.functionTrimRight,_signature:[{types:[2]},{types:[2],optional:true}]},type:{_func:this.functionType,_signature:[{types:[1]}]},zip:{_func:this.functionZip,_signature:[{types:[
|
|
57
|
+
3],variadic:true}]}}}registerFunction(name,customFunction,signature,options){const result=this._registerInternal(name,customFunction,signature,options);if(!result.success){throw new Error(result.message)}}_registerInternal(name,customFunction,signature,options={}){if(!name||typeof name!=="string"||name.trim()===""){return{success:false,reason:"invalid-name",message:"Function name must be a non-empty string"}}try{this.validateInputSignatures(name,signature)}catch(error){return{success:false,reason:"\
|
|
58
|
+
invalid-signature",message:error instanceof Error?error.message:"Invalid function signature"}}const{override=false,warn=false}=options;const exists=name in this._functionTable;if(exists&&!override){return{success:false,reason:"already-exists",message:`Function already defined: ${name}(). Use { override: true } to replace it.`}}if(exists&&override&&warn){console.warn(`Warning: Overriding existing function: ${name}()`)}this._functionTable[name]={_func:customFunction.bind(this),_signature:signature};
|
|
59
|
+
this._customFunctions.add(name);const message=exists?`Function ${name}() overridden successfully`:`Function ${name}() registered successfully`;return{success:true,message}}register(name,customFunction,signature,options={}){return this._registerInternal(name,customFunction,signature,options)}unregister(name){if(!this._customFunctions.has(name)){return false}delete this._functionTable[name];this._customFunctions.delete(name);return true}isRegistered(name){return name in this._functionTable}getRegistered(){
|
|
60
|
+
return Object.keys(this._functionTable)}getCustomFunctions(){return Array.from(this._customFunctions)}clearCustomFunctions(){for(const name of this._customFunctions){delete this._functionTable[name]}this._customFunctions.clear()}callFunction(name,resolvedArgs){const functionEntry=this._functionTable[name];if(functionEntry===void 0){throw new Error(`Unknown function: ${name}()`)}this.validateArgs(name,resolvedArgs,functionEntry._signature);return functionEntry._func.call(this,resolvedArgs)}validateInputSignatures(name,signature){
|
|
61
|
+
for(let i=0;i<signature.length;i+=1){if("variadic"in signature[i]&&i!==signature.length-1){throw new Error(`Invalid arity: ${name}() 'variadic' argument ${i+1} must occur last`)}}}validateArgs(name,args,signature){this.validateInputSignatures(name,signature);this.validateArity(name,args,signature);this.validateTypes(name,args,signature)}validateArity(name,args,signature){const numberOfRequiredArgs=signature.filter(argSignature=>!(argSignature.optional??false)).length;const lastArgIsVariadic=signature[signature.
|
|
62
|
+
length-1]?.variadic??false;const tooFewArgs=args.length<numberOfRequiredArgs;const tooManyArgs=args.length>signature.length;if(lastArgIsVariadic&&tooFewArgs||!lastArgIsVariadic&&(tooFewArgs||tooManyArgs)){const tooFewModifier=tooFewArgs&&(!lastArgIsVariadic&&numberOfRequiredArgs>1||lastArgIsVariadic)?"at least ":"";const pluralized=signature.length>1;throw new Error(`Invalid arity: ${name}() takes ${tooFewModifier}${numberOfRequiredArgs} argument${pluralized&&"s"||""} but received ${args.length}`)}}validateTypes(name,args,signature){
|
|
63
|
+
for(let i=0;i<signature.length;i+=1){const currentSpec=signature[i].types;const actualType=this.getTypeName(args[i]);if(actualType===void 0){continue}const typeMatched=currentSpec.some(expectedType=>this.typeMatches(actualType,expectedType,args[i]));if(!typeMatched){const expected=currentSpec.map(typeId=>this.TYPE_NAME_TABLE[typeId]).join(" | ");throw new Error(`Invalid type: ${name}() expected argument ${i+1} to be type (${expected}) but received type ${this.TYPE_NAME_TABLE[actualType]} instead\
|
|
64
|
+
.`)}}}typeMatches(actual,expected,argValue){if(expected===1){return true}const subtype=ARRAY_SUBTYPES[expected];if(subtype!==void 0){if(actual!==3){return false}const array=argValue;return array.every(item=>{const typeName=this.getTypeName(item);return typeName===void 0||this.typeMatches(typeName,subtype,item)})}return actual===expected}getTypeName(obj){if(obj===null){return 7}if(typeof obj==="string"){return 2}if(typeof obj==="number"){return 0}if(typeof obj==="boolean"){return 5}if(Array.isArray(
|
|
65
|
+
obj)){return 3}if(typeof obj==="object"){if(obj.expref){return 6}return 4}return}createKeyFunction(exprefNode,allowedTypes){const interpreter=this._interpreter;const keyFunc=x=>{const current=interpreter.visit(exprefNode,x);if(!allowedTypes.includes(this.getTypeName(current))){const msg=`Invalid type: expected one of (${allowedTypes.map(t=>this.TYPE_NAME_TABLE[t]).join(" | ")}), received ${this.TYPE_NAME_TABLE[this.getTypeName(current)]}`;throw new Error(msg)}return current};return keyFunc}functionAvg=([
|
|
66
|
+
inputArray])=>{if(!inputArray||inputArray.length==0){return null}let sum=0;for(let i=0;i<inputArray.length;i+=1){sum+=inputArray[i]}return sum/inputArray.length};functionContains=([searchable,searchValue])=>{if(Array.isArray(searchable)){const array=searchable;return array.includes(searchValue)}if(typeof searchable==="string"){const text=searchable;if(typeof searchValue==="string"){return text.includes(searchValue)}}return null};functionEndsWith=([searchStr,suffix])=>{return searchStr.endsWith(suffix)};functionFindFirst=this.
|
|
67
|
+
createFindFunction(findFirst);functionFindLast=this.createFindFunction(findLast);createFindFunction(findFn){return resolvedArgs=>{const subject=resolvedArgs[0];const search2=resolvedArgs[1];const start=resolvedArgs.length>2?resolvedArgs[2]:void 0;const end=resolvedArgs.length>3?resolvedArgs[3]:void 0;return findFn(subject,search2,start,end)}}functionFromItems=([array])=>{for(const pair of array){if(pair.length!==2||typeof pair[0]!=="string"){throw new Error("invalid value, each array must contai\
|
|
68
|
+
n two elements, a pair of string and value")}}return Object.fromEntries(array)};functionGroupBy=([array,exprefNode])=>{const keyFunction=this.createKeyFunction(exprefNode,[2]);const groups={};for(const item of array){const key=keyFunction(item);if(!groups[key]){groups[key]=[]}groups[key].push(item)}return groups};functionItems=([inputValue])=>{return Object.entries(inputValue)};functionJoin=resolvedArgs=>{const[joinChar,listJoin]=resolvedArgs;return listJoin.join(joinChar)};functionLength=([inputValue])=>{
|
|
69
|
+
if(typeof inputValue==="string"){return new Text(inputValue).length}if(Array.isArray(inputValue)){return inputValue.length}return Object.keys(inputValue).length};functionMap=([exprefNode,elements])=>{if(!this._interpreter){return[]}const mapped=[];const interpreter=this._interpreter;for(let i=0;i<elements.length;i+=1){mapped.push(interpreter.visit(exprefNode,elements[i]))}return mapped};functionMax=([inputValue])=>{if(!inputValue.length){return null}const typeName=this.getTypeName(inputValue[0]);
|
|
70
|
+
if(typeName===0){return Math.max(...inputValue)}const elements=inputValue;let maxElement=elements[0];for(let i=1;i<elements.length;i+=1){if(maxElement.localeCompare(elements[i])<0){maxElement=elements[i]}}return maxElement};functionMaxBy=resolvedArgs=>{const exprefNode=resolvedArgs[1];const resolvedArray=resolvedArgs[0];const keyFunction=this.createKeyFunction(exprefNode,[0,2]);let maxNumber=-Infinity;let maxRecord;let current;for(let i=0;i<resolvedArray.length;i+=1){current=keyFunction&&keyFunction(
|
|
71
|
+
resolvedArray[i]);if(current!==void 0&¤t>maxNumber){maxNumber=current;maxRecord=resolvedArray[i]}}return maxRecord||null};functionMerge=resolvedArgs=>{return Object.assign({},...resolvedArgs)};functionMin=([inputValue])=>{if(!inputValue.length){return null}const typeName=this.getTypeName(inputValue[0]);if(typeName===0){return Math.min(...inputValue)}const elements=inputValue;let minElement=elements[0];for(let i=1;i<elements.length;i+=1){if(elements[i].localeCompare(minElement)<0){minElement=
|
|
72
|
+
elements[i]}}return minElement};functionMinBy=resolvedArgs=>{const exprefNode=resolvedArgs[1];const resolvedArray=resolvedArgs[0];const keyFunction=this.createKeyFunction(exprefNode,[0,2]);let minNumber=Infinity;let minRecord;let current;for(let i=0;i<resolvedArray.length;i+=1){current=keyFunction&&keyFunction(resolvedArray[i]);if(current!==void 0&¤t<minNumber){minNumber=current;minRecord=resolvedArray[i]}}return minRecord||null};functionNotNull=resolvedArgs=>{return resolvedArgs.find(arg=>arg!==
|
|
73
|
+
null)??null};functionPadLeft=this.createPadFunction(padLeft);functionPadRight=this.createPadFunction(padRight);createPadFunction(padFn){return resolvedArgs=>{const subject=resolvedArgs[0];const width=resolvedArgs[1];const padding=resolvedArgs.length>2?resolvedArgs[2]:void 0;return padFn(subject,width,padding)}}functionReplace=resolvedArgs=>{const subject=resolvedArgs[0];const string=resolvedArgs[1];const by=resolvedArgs[2];return replace(subject,string,by,resolvedArgs.length>3?resolvedArgs[3]:void 0)};functionSplit=resolvedArgs=>{
|
|
74
|
+
const subject=resolvedArgs[0];const search2=resolvedArgs[1];return split(subject,search2,resolvedArgs.length>2?resolvedArgs[2]:void 0)};functionReverse=([inputValue])=>{const typeName=this.getTypeName(inputValue);if(typeName===2){return new Text(inputValue).reverse()}const reversedArray=[...inputValue];reversedArray.reverse();return reversedArray};functionSort=([inputValue])=>{if(inputValue.length<=1){return inputValue}if(typeof inputValue[0]==="string"){return[...inputValue].sort(Text.comparer)}
|
|
75
|
+
return[...inputValue].sort()};functionSortBy=resolvedArgs=>{const sortedArray=[...resolvedArgs[0]];if(sortedArray.length<=1){return sortedArray}const interpreter=this._interpreter;const exprefNode=resolvedArgs[1];const requiredType=this.getTypeName(interpreter.visit(exprefNode,sortedArray[0]));if(requiredType!==void 0&&![0,2].includes(requiredType)){throw new Error(`Invalid type: unexpected type (${this.TYPE_NAME_TABLE[requiredType]})`)}function throwInvalidTypeError(rt,item){throw new Error(`In\
|
|
76
|
+
valid type: expected (${rt.TYPE_NAME_TABLE[requiredType]}), received ${rt.TYPE_NAME_TABLE[rt.getTypeName(item)]}`)}return sortedArray.sort((a,b)=>{const exprA=interpreter.visit(exprefNode,a);const exprB=interpreter.visit(exprefNode,b);if(this.getTypeName(exprA)!==requiredType){throwInvalidTypeError(this,exprA)}else if(this.getTypeName(exprB)!==requiredType){throwInvalidTypeError(this,exprB)}if(requiredType===2){return Text.comparer(exprA,exprB)}return exprA-exprB})};functionStartsWith=([searchable,
|
|
77
|
+
searchStr])=>{return searchable.startsWith(searchStr)};functionSum=([inputValue])=>{return inputValue.reduce((x,y)=>x+y,0)};functionToArray=([inputValue])=>{return Array.isArray(inputValue)?inputValue:[inputValue]};functionToNumber=([inputValue])=>{const typeName=this.getTypeName(inputValue);let convertedValue;if(typeName===0){return inputValue}if(typeName===2){convertedValue=+inputValue;if(!isNaN(convertedValue)){return convertedValue}}return null};functionToString=([inputValue])=>{return typeof inputValue===
|
|
78
|
+
"string"?inputValue:JSON.stringify(inputValue)};functionTrim=this.createTrimFunction(trim);functionTrimLeft=this.createTrimFunction(trimLeft);functionTrimRight=this.createTrimFunction(trimRight);createTrimFunction(trimFn){return resolvedArgs=>{const subject=resolvedArgs[0];const chars=resolvedArgs.length>1?resolvedArgs[1]:void 0;return trimFn(subject,chars)}}functionType=([inputValue])=>{const type=this.getTypeName(inputValue);const name=type!==void 0?this.TYPE_NAME_TABLE[type]:void 0;if(!name){
|
|
79
|
+
throw new Error("invalid-type")}return name};functionZip=array=>{const length=Math.min(...array.map(arr=>arr.length));return Array.from({length},(_,index)=>array.map(arr=>arr[index]))}};var ScopeChain=class _ScopeChain{inner=void 0;data={};get currentScopeData(){return this.data}withScope(data){const outer=new _ScopeChain;outer.inner=this;outer.data=data;return outer}getValue(identifier){if(Object.prototype.hasOwnProperty.call(this.data,identifier)){return this.data[identifier]}if(this.inner){return this.
|
|
80
|
+
inner.getValue(identifier)}return null}};var emptyScopeChain=new ScopeChain;var TreeInterpreter=class _TreeInterpreter{runtime;_rootValue=null;_scope;_options;_depth=0;_deadline=0;constructor(options){this.runtime=new Runtime(this);this._scope=new ScopeChain;if(options){this._options=options;this._deadline=options.timeoutMs!==void 0?Date.now()+options.timeoutMs:0}}withScope(scope){const interpreter=new _TreeInterpreter(this._options);interpreter.runtime._functionTable=this.runtime._functionTable;
|
|
81
|
+
interpreter._rootValue=this._rootValue;interpreter._scope=this._scope.withScope(scope);interpreter._depth=this._depth;interpreter._deadline=this._deadline;return interpreter}search(node,value,options){if(options?.maxNodes!==void 0&&countNodes(node)>options.maxNodes){throw new Error(`Expression exceeds maximum allowed node count of ${options.maxNodes}`)}this._rootValue=value;this._scope=emptyScopeChain;this._options=options;this._depth=0;this._deadline=options?.timeoutMs!==void 0?Date.now()+options.
|
|
82
|
+
timeoutMs:0;const result=this.visit(node,value);this.checkOutputSize(result);return result}checkOutputSize(val){const max=this._options?.maxOutputSize;if(max===void 0||val==null){return}const size=Array.isArray(val)||typeof val==="string"?val.length:typeof val==="object"?Object.keys(val).length:0;if(size>max){throw new Error(`Output size exceeds maximum allowed size of ${max}`)}}collect(target,item){target.push(item);if(this._options?.maxOutputSize!==void 0&&target.length>this._options.maxOutputSize){
|
|
83
|
+
throw new Error(`Output size exceeds maximum allowed size of ${this._options.maxOutputSize}`)}}evaluateProjectionItems(items,right){const collected=[];if(right.type==="Field"){const key=right.name;for(let i=0;i<items.length;i++){if(this._deadline>0&&Date.now()>=this._deadline){throw new Error(`Query execution timed out after ${this._options?.timeoutMs}ms`)}const elem=items[i];if(!elem||typeof elem!=="object"||Array.isArray(elem)){continue}const val=elem[key];if(val!==void 0&&val!==null){this.collect(
|
|
84
|
+
collected,val)}}return collected}if(right.type==="Identity"){for(let i=0;i<items.length;i++){const elem=items[i];if(elem!==null){this.collect(collected,elem)}}return collected}for(const elem of items){const current=this.visit(right,elem);if(current!==null){this.collect(collected,current)}}return collected}visit(node,value){if(this._options){if(this._options.maxDepth!==void 0&&this._depth>=this._options.maxDepth){throw new Error(`Evaluation exceeds maximum allowed depth of ${this._options.maxDepth}`)}
|
|
85
|
+
if(this._deadline>0&&Date.now()>=this._deadline){throw new Error(`Query execution timed out after ${this._options.timeoutMs}ms`)}}this._depth+=1;try{return this.evaluateNode(node,value)}finally{this._depth-=1}}evaluateNode(node,value){switch(node.type){case"Ternary":{const condition=this.visit(node.condition,value);if(!isFalse(condition)){return this.visit(node.trueExpr,value)}return this.visit(node.falseExpr,value)}case"Field":const identifier=node.name;if(value===null||typeof value!=="object"||
|
|
86
|
+
Array.isArray(value)){return null}return value[identifier]??null;case"LetExpression":{const scope={};for(const binding of node.bindings){Object.assign(scope,this.visit(binding,value))}return this.withScope(scope).visit(node.expression,value)}case"Binding":{const{variable,reference}=node;const result=this.visit(reference,value);return{[variable]:result}}case"Variable":{const variable=node.name;if(!this._scope.getValue(variable)&&!Object.prototype.hasOwnProperty.call(this._scope.currentScopeData,variable)){
|
|
87
|
+
throw new Error(`Error referencing undefined variable ${variable}`)}return this._scope.getValue(variable)}case"IndexExpression":return this.visit(node.right,this.visit(node.left,value));case"Subexpression":{const result=this.visit(node.left,value);return result!=null?this.visit(node.right,result)??null:null}case"Index":{if(!Array.isArray(value)){return null}const index=node.value<0?value.length+node.value:node.value;return value[index]??null}case"Slice":{if(!Array.isArray(value)&&typeof value!==
|
|
88
|
+
"string"){return null}const{start,stop,step}=this.computeSliceParams(value.length,node);const target=typeof value==="string"?[...value]:value;const sliced=this.slice(target,start,stop,step);const res=typeof value==="string"?sliced.join(""):sliced;this.checkOutputSize(res);return res}case"Projection":{const{left,right}=node;const allowString=left.type==="IndexExpression"&&left.right.type==="Slice";const base=this.visit(left,value);if(allowString&&typeof base==="string"){return this.visit(right,base)}
|
|
89
|
+
return Array.isArray(base)?this.evaluateProjectionItems(base,right):null}case"ValueProjection":{const base=this.visit(node.left,value);if(base===null||typeof base!=="object"||Array.isArray(base)){return null}return this.evaluateProjectionItems(Object.values(base),node.right)}case"FilterProjection":{const{left,right,condition}=node;const base=this.visit(left,value);if(!Array.isArray(base)){return null}const results=[];if(right.type==="Field"){const key=right.name;for(let i=0;i<base.length;i++){const elem=base[i];
|
|
90
|
+
if(isFalse(this.visit(condition,elem))){continue}if(!elem||typeof elem!=="object"||Array.isArray(elem)){continue}const val=elem[key];if(val!==void 0&&val!==null){this.collect(results,val)}}return results}if(right.type==="Identity"){for(let i=0;i<base.length;i++){const elem=base[i];if(isFalse(this.visit(condition,elem))){continue}if(elem!==null){this.collect(results,elem)}}return results}for(const elem of base){if(isFalse(this.visit(condition,elem))){continue}const result=this.visit(right,elem);if(result!==
|
|
91
|
+
null){this.collect(results,result)}}return results}case"Arithmetic":{const first=this.visit(node.left,value);const second=this.visit(node.right,value);switch(node.operator){case"Plus":return add(first,second);case"Minus":return sub(first,second);case"Multiply":case"Star":return mul(first,second);case"Divide":return divide(first,second);case"Modulo":return mod(first,second);case"Div":return div(first,second);default:throw new Error(`Syntax error: unknown arithmetic operator: ${node.operator}`)}}case"\
|
|
92
|
+
Unary":{const operand=this.visit(node.operand,value);switch(node.operator){case"Plus":ensureNumbers(operand);return operand;case"Minus":ensureNumbers(operand);return-operand;default:throw new Error(`Syntax error: unknown arithmetic operator: ${node.operator}`)}}case"Comparator":{const first=this.visit(node.left,value);const second=this.visit(node.right,value);switch(node.name){case"EQ":return strictDeepEqual(first,second);case"NE":return!strictDeepEqual(first,second)}if(typeof first!=="number"||
|
|
93
|
+
typeof second!=="number"){return null}switch(node.name){case"GT":return first>second;case"GTE":return first>=second;case"LT":return first<second;case"LTE":return first<=second}}case"Flatten":{const original=this.visit(node.child,value);const res=Array.isArray(original)?original.flat():null;this.checkOutputSize(res);return res}case"Root":return this._rootValue;case"MultiSelectList":{const collected=[];for(const child of node.children){collected.push(this.visit(child,value))}this.checkOutputSize(collected);
|
|
94
|
+
return collected}case"MultiSelectHash":{const collected={};for(const child of node.children){collected[child.name]=this.visit(child.value,value)}this.checkOutputSize(collected);return collected}case"OrExpression":{const result=this.visit(node.left,value);if(isFalse(result)){return this.visit(node.right,value)}return result}case"AndExpression":{const result=this.visit(node.left,value);if(isFalse(result)){return result}return this.visit(node.right,value)}case"NotExpression":return isFalse(this.visit(
|
|
95
|
+
node.child,value));case"Literal":return node.value;case"Pipe":return this.visit(node.right,this.visit(node.left,value));case"Function":{if(this._options?.allowedFunctions&&!this._options.allowedFunctions.includes(node.name)){throw new Error(`Function '${node.name}' is not allowed`)}if(this._options?.disallowedFunctions&&this._options.disallowedFunctions.includes(node.name)){throw new Error(`Function '${node.name}' is disallowed`)}const args=[];for(const child of node.children){args.push(this.visit(
|
|
96
|
+
child,value))}const res=this.runtime.callFunction(node.name,args);this.checkOutputSize(res);return res}case"ExpressionReference":return{expref:true,...node.child};case"Current":case"Identity":return value}}computeSliceParams(arrayLength,sliceNode){let{start,stop,step}=sliceNode;if(step===null){step=1}else if(step===0){const error=new Error("Invalid value: slice step cannot be 0");error.name="RuntimeError";throw error}start=start===null?step<0?arrayLength-1:0:this.capSliceRange(arrayLength,start,
|
|
97
|
+
step);stop=stop===null?step<0?-1:arrayLength:this.capSliceRange(arrayLength,stop,step);return{start,stop,step}}capSliceRange(arrayLength,actualValue,step){let nextActualValue=actualValue;if(nextActualValue<0){nextActualValue+=arrayLength;if(nextActualValue<0){nextActualValue=step<0?-1:0}}else if(nextActualValue>=arrayLength){nextActualValue=step<0?arrayLength-1:arrayLength}return nextActualValue}slice(collection,start,end,step){if(step===1){return collection.slice(start,end)}const len=Math.max(0,
|
|
98
|
+
Math.ceil((end-start)/step));const result=new Array(len);let idx=0;if(step>0){for(let i=start;i<end;i+=step){result[idx++]=collection[i]}}else{for(let i=start;i>end;i+=step){result[idx++]=collection[i]}}return result}};var TreeInterpreterInstance=new TreeInterpreter;var TreeInterpreter_default=TreeInterpreterInstance;async function*toAsyncIterable(source){if(source==null){return}if(typeof source!=="object"&&typeof source!=="function"){throw new TypeError("Invalid stream source: expected AsyncIte\
|
|
99
|
+
rable, Iterable, or ReadableStream")}if(Symbol.asyncIterator in source){for await(const chunk of source){yield chunk}return}if(typeof source.getReader==="function"){const reader=source.getReader();try{while(true){const{done,value}=await reader.read();if(done){break}yield value}}finally{reader.releaseLock()}return}if(Symbol.iterator in source){for(const chunk of source){yield chunk}return}throw new TypeError("Invalid stream source: expected AsyncIterable, Iterable, or ReadableStream")}function parseItem(str,parseJson){
|
|
100
|
+
if(parseJson===true){return JSON.parse(str)}if(parseJson==="auto"){try{return JSON.parse(str)}catch{return str}}return str}async function*normalizeSource(source,options){const parseJson=options?.parseJson??"auto";const flatten=options?.flattenChunks??true;let buffer="";const textDecoder=typeof TextDecoder!=="undefined"?new TextDecoder:null;for await(const chunk of toAsyncIterable(source)){if(chunk instanceof Uint8Array&&textDecoder){buffer+=textDecoder.decode(chunk,{stream:true});if(buffer.includes(
|
|
101
|
+
"\n")){const lines=buffer.split("\n");buffer=lines.pop()??"";for(const line of lines){const trimmed=line.trim();if(trimmed){yield parseItem(trimmed,parseJson)}}}}else if(typeof chunk==="string"){if(parseJson===false){yield chunk}else{buffer+=chunk;if(buffer.includes("\n")){const lines=buffer.split("\n");buffer=lines.pop()??"";for(const line of lines){const trimmed=line.trim();if(trimmed){yield parseItem(trimmed,parseJson)}}}}}else if(flatten&&Array.isArray(chunk)){if(buffer.trim()){yield parseItem(
|
|
102
|
+
buffer.trim(),parseJson);buffer=""}for(let i=0;i<chunk.length;i++){yield chunk[i]}}else{if(buffer.trim()){yield parseItem(buffer.trim(),parseJson);buffer=""}yield chunk}}if(textDecoder&&buffer){buffer+=textDecoder.decode()}if(buffer.trim()){yield parseItem(buffer.trim(),parseJson)}}function isStreamableNode(node){switch(node.type){case"Projection":if(node.left.type==="Identity"||node.left.type==="Current"){return true}if(node.left.type==="IndexExpression"&&node.left.right.type==="Slice"){const slice=node.
|
|
103
|
+
left.right;return(slice.start===null||slice.start>=0)&&(slice.stop===null||slice.stop>=0)&&(slice.step===null||slice.step>0)}return false;case"FilterProjection":return node.left.type==="Identity"||node.left.type==="Current";case"IndexExpression":if(node.right.type==="Slice"&&(node.left.type==="Identity"||node.left.type==="Current")){const slice=node.right;return(slice.start===null||slice.start>=0)&&(slice.stop===null||slice.stop>=0)&&(slice.step===null||slice.step>0)}return true;case"Field":case"\
|
|
104
|
+
Identity":case"Current":case"Subexpression":case"MultiSelectHash":case"MultiSelectList":case"Ternary":case"Comparator":case"Arithmetic":case"NotExpression":return true;case"Pipe":return isStreamableNode(node.left)&&isStreamableNode(node.right);default:return false}}async function*evaluateStreamNode(source,node,interpreter,options){const deadline=options?.timeoutMs!==void 0?Date.now()+options.timeoutMs:0;function checkDeadline(){if(deadline>0&&Date.now()>=deadline){throw new Error(`Query executio\
|
|
105
|
+
n timed out after ${options?.timeoutMs}ms`)}}switch(node.type){case"Projection":{const{left,right}=node;let streamSource=source;if(left.type==="IndexExpression"&&left.right.type==="Slice"){streamSource=evaluateStreamNode(source,left,interpreter,options)}if(right.type==="Identity"||right.type==="Current"){for await(const item of streamSource){checkDeadline();if(item!==null&&item!==void 0){yield item}}return}if(right.type==="Field"){const key=right.name;for await(const item of streamSource){checkDeadline();
|
|
106
|
+
if(item&&typeof item==="object"&&!Array.isArray(item)){const val=item[key];if(val!==void 0&&val!==null){yield val}}}return}for await(const item of streamSource){checkDeadline();const res=interpreter.visit(right,item);if(res!==null&&res!==void 0){yield res}}return}case"IndexExpression":{if(node.right.type==="Slice"&&(node.left.type==="Identity"||node.left.type==="Current")){const slice=node.right;const start=slice.start??0;const stop=slice.stop??Infinity;const step=slice.step??1;if(start>=0&&stop>=
|
|
107
|
+
0&&step>0){let index=0;for await(const item of source){checkDeadline();if(index>=stop){break}if(index>=start&&(index-start)%step===0){yield item}index++;if(index>=stop){break}}return}const collected=[];for await(const item of source){checkDeadline();collected.push(item);if(options?.maxOutputSize!==void 0&&collected.length>options.maxOutputSize){throw new Error(`Output size exceeds maximum allowed size of ${options.maxOutputSize}`)}}const result=interpreter.search(node,collected,options);if(Array.
|
|
108
|
+
isArray(result)){for(const item of result){yield item}}return}for await(const item of source){checkDeadline();const res=interpreter.visit(node,item);if(res!==null&&res!==void 0){yield res}}return}case"FilterProjection":{const{condition,right}=node;if(right.type==="Identity"||right.type==="Current"){for await(const item of source){checkDeadline();if(!isFalse(interpreter.visit(condition,item))){yield item}}return}if(right.type==="Field"){const key=right.name;for await(const item of source){checkDeadline();
|
|
109
|
+
if(!isFalse(interpreter.visit(condition,item))){if(item&&typeof item==="object"&&!Array.isArray(item)){const val=item[key];if(val!==void 0&&val!==null){yield val}}}}return}for await(const item of source){checkDeadline();if(!isFalse(interpreter.visit(condition,item))){const res=interpreter.visit(right,item);if(res!==null&&res!==void 0){yield res}}}return}case"Pipe":{const leftStream=evaluateStreamNode(source,node.left,interpreter,options);if(isStreamableNode(node.right)){for await(const res of evaluateStreamNode(
|
|
110
|
+
leftStream,node.right,interpreter,options)){yield res}}else{const collected=[];for await(const item of leftStream){checkDeadline();collected.push(item);if(options?.maxOutputSize!==void 0&&collected.length>options.maxOutputSize){throw new Error(`Output size exceeds maximum allowed size of ${options.maxOutputSize}`)}}const result=interpreter.search(node.right,collected,options);if(result!==null&&result!==void 0){yield result}}return}case"Identity":case"Current":{for await(const item of source){checkDeadline();
|
|
111
|
+
yield item}return}case"Field":{const key=node.name;for await(const item of source){checkDeadline();if(item&&typeof item==="object"&&!Array.isArray(item)){const val=item[key];if(val!==void 0&&val!==null){yield val}}}return}default:{if(isStreamableNode(node)){for await(const item of source){checkDeadline();const res=interpreter.visit(node,item);if(res!==null&&res!==void 0){yield res}}return}const collected=[];for await(const item of source){checkDeadline();collected.push(item);if(options?.maxOutputSize!==
|
|
112
|
+
void 0&&collected.length>options.maxOutputSize){throw new Error(`Output size exceeds maximum allowed size of ${options.maxOutputSize}`)}}const result=interpreter.search(node,collected,options);if(result!==null&&result!==void 0){yield result}return}}}function isExpressionNode(val){return typeof val==="object"&&val!==null&&"type"in val&&typeof val.type==="string"&&!(Symbol.iterator in val)&&!(Symbol.asyncIterator in val)}async function*searchStream(sourceOrExpression,expressionOrSource,options){let expression;
|
|
113
|
+
let source;if(typeof sourceOrExpression==="string"||isExpressionNode(sourceOrExpression)){expression=sourceOrExpression;source=expressionOrSource}else{source=sourceOrExpression;expression=expressionOrSource}if(typeof expression!=="string"&&!isExpressionNode(expression)){throw new TypeError("Expression must be a string or AST ExpressionNode")}const ast=typeof expression==="string"?Parser_default.parse(expression,options):expression;if(options){const fnError=findDisallowedFunction(ast,options);if(fnError){
|
|
114
|
+
throw new Error(fnError)}}const interpreter=new TreeInterpreter(options);interpreter.runtime._functionTable=TreeInterpreterInstance.runtime._functionTable;const items=normalizeSource(source,options);const results=evaluateStreamNode(items,ast,interpreter,options);const limit=options?.limit;const maxOutputSize=options?.maxOutputSize;let count=0;for await(const result of results){yield result;count++;if(limit!==void 0&&count>=limit){break}if(maxOutputSize!==void 0&&count>maxOutputSize){throw new Error(
|
|
115
|
+
`Output size exceeds maximum allowed size of ${maxOutputSize}`)}}}var TYPE_ANY=1;var TYPE_ARRAY=3;var TYPE_ARRAY_ARRAY=11;var TYPE_ARRAY_NUMBER=8;var TYPE_ARRAY_OBJECT=10;var TYPE_ARRAY_STRING=9;var TYPE_BOOLEAN=5;var TYPE_EXPREF=6;var TYPE_NULL=7;var TYPE_NUMBER=0;var TYPE_OBJECT=4;var TYPE_STRING=2;function compile(expression,options){return Parser_default.parse(expression,options)}function compileQuery(expression,options){const nodeTree=Parser_default.parse(expression,options);const fn=function(data){
|
|
116
|
+
return TreeInterpreter_default.search(nodeTree,data,options)};fn.search=data=>TreeInterpreter_default.search(nodeTree,data,options);fn.searchStream=(source,streamOptions)=>searchStream(source,nodeTree,{...options,...streamOptions});fn.ast=nodeTree;return fn}function validate(expression,options){if(typeof expression!=="string"){return{valid:false,error:"Expression must be a string"}}try{const ast=Parser_default.parse(expression,options);if(options){const fnError=findDisallowedFunction(ast,options);
|
|
117
|
+
if(fnError){return{valid:false,error:fnError}}}return{valid:true,ast}}catch(err){return{valid:false,error:err instanceof Error?err.message:String(err)}}}function tokenize(expression,options){return Lexer_default.tokenize(expression,options)}var registerFunction=(functionName,customFunction,signature,options)=>{TreeInterpreter_default.runtime.registerFunction(functionName,customFunction,signature,options)};var register=(name,customFunction,signature,options)=>{return TreeInterpreter_default.runtime.
|
|
118
|
+
register(name,customFunction,signature,options)};var unregisterFunction=name=>{return TreeInterpreter_default.runtime.unregister(name)};var isRegistered=name=>{return TreeInterpreter_default.runtime.isRegistered(name)};var getRegisteredFunctions=()=>{return TreeInterpreter_default.runtime.getRegistered()};var getCustomFunctions=()=>{return TreeInterpreter_default.runtime.getCustomFunctions()};var clearCustomFunctions=()=>{TreeInterpreter_default.runtime.clearCustomFunctions()};var MAX_CACHE_SIZE=1e3;
|
|
119
|
+
var astCache=new Map;function search(data,expression,options){let nodeTree;if(!options){nodeTree=astCache.get(expression);if(!nodeTree){nodeTree=Parser_default.parse(expression);if(astCache.size>=MAX_CACHE_SIZE){const firstKey=astCache.keys().next().value;if(firstKey!==void 0){astCache.delete(firstKey)}}astCache.set(expression,nodeTree)}}else{nodeTree=Parser_default.parse(expression,options)}return TreeInterpreter_default.search(nodeTree,data,options)}function Scope(){return new ScopeChain}var TreeInterpreter2=TreeInterpreter_default;
|
|
120
|
+
var jmespath={compile,compileQuery,searchStream,validate,registerFunction,register,unregisterFunction,isRegistered,getRegisteredFunctions,getCustomFunctions,clearCustomFunctions,search,tokenize,TreeInterpreter:TreeInterpreter2,TYPE_ANY,TYPE_ARRAY_NUMBER,TYPE_ARRAY_STRING,TYPE_ARRAY,TYPE_BOOLEAN,TYPE_EXPREF,TYPE_NULL,TYPE_NUMBER,TYPE_OBJECT,TYPE_STRING,TYPE_ARRAY_ARRAY,TYPE_ARRAY_OBJECT,Scope};var index_default=jmespath;export{Scope,TYPE_ANY,TYPE_ARRAY,TYPE_ARRAY_ARRAY,TYPE_ARRAY_NUMBER,TYPE_ARRAY_OBJECT,TYPE_ARRAY_STRING,TYPE_BOOLEAN,TYPE_EXPREF,TYPE_NULL,TYPE_NUMBER,TYPE_OBJECT,TYPE_STRING,TreeInterpreter2 as TreeInterpreter,clearCustomFunctions,compile,compileQuery,index_default as default,getCustomFunctions,getRegisteredFunctions,isRegistered,jmespath,register,registerFunction,search,searchStream,tokenize,unregisterFunction,validate};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
2
|
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
-
import{checkOutTarget}from"./chunk-
|
|
3
|
+
import{checkOutTarget}from"./chunk-F7LPERJA.js";import"./chunk-46OWZRTJ.js";import"./chunk-F5QDUPQO.js";import"./chunk-P4QSPSOQ.js";import"./chunk-Q3B65OFC.js";import{contentTypeFor,inspectLocalFile}from"./chunk-6H5TPSXU.js";import{checkUploadQuota}from"./chunk-V64CGX7V.js";import{parseWaitOptions,waitUntilTerminal}from"./chunk-WVCEKC7V.js";import"./chunk-RMFLTSOV.js";import{readBody}from"./chunk-HEH3PUW2.js";import"./chunk-W4NLJ2YK.js";
|
|
4
4
|
import"./chunk-BD7O73GK.js";import{repeatedValues}from"./chunk-VGT2EGH6.js";import"./chunk-A7MM5WSC.js";import{collapsesInUrlPath,isSafePathSegment}from"./chunk-HVZUXLQ4.js";import{ApiError}from"./chunk-JA5A6UJ2.js";import"./chunk-MMVXE2CJ.js";import"./chunk-SBRTBKEZ.js";import{LIST_FLAGS,LIST_PAGING_HELP,envelopePaging,nonEmpty,positiveInteger,readEnvelopeCursor,shellQuote}from"./chunk-MI6HVYR2.js";import{requireResolved,singleRef,withResolved}from"./chunk-PS5QFKHB.js";
|
|
5
5
|
import{acknowledgement,isRecord,pick}from"./chunk-3ZRMMBP5.js";import{ApiRejectedError,ApiResponseError,NetworkError,UsageError,WaitTimeoutError}from"./chunk-VFPY2A23.js";import"./chunk-KIZIRVW6.js";import"./chunk-XNLIEUAW.js";import"./chunk-J7QYPKVK.js";import"./chunk-EDF4U5BT.js";import"./chunk-RZVI6PMW.js";import"./chunk-AAABT3AX.js";import"./chunk-OKATZ4SN.js";import"./chunk-RKBUJKI5.js";import"./chunk-UREA4ZIG.js";import"./chunk-NHYMHCAT.js";
|
|
6
6
|
import"./chunk-VSJBJXZO.js";import crypto2 from"crypto";import fs2 from"fs";import path from"path";var SCOPE_PERSONAL="personal";var SCOPE_PROJECT="project";var UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;var FORBIDDEN_NAME=/[/\\:*?"<>|]/;var NAME_MAX=255;var ROW_COLUMNS=["id","path","name","file_count","subfolder_count","parent_id","updated_at"];var TRASH_COLUMNS=["id","path","name","file_count","subfolder_count","parent_id","deleted_at"];function folderRows(raw){return raw.map(row=>{const id=row["id"];const name=row["name"];const parentId=row["parent_id"];if(typeof id!==
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
2
|
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
-
import{evaluateQuery}from"./chunk-
|
|
3
|
+
import{evaluateQuery}from"./chunk-F5QDUPQO.js";import"./chunk-VFPY2A23.js";import"./chunk-VSJBJXZO.js";export{evaluateQuery};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
2
|
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
-
import{loadDomain}from"./chunk-
|
|
3
|
+
import{loadDomain}from"./chunk-46OWZRTJ.js";import"./chunk-VSJBJXZO.js";export{loadDomain};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
2
|
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
-
import{CURATED_PAGING_VOCABULARY,buildPrepareContext,checkOutTarget,exitCodeFor,fetchAllPages,outputValue,reportError,requiresYes,resolvePaging,runDomain}from"./chunk-
|
|
3
|
+
import{CURATED_PAGING_VOCABULARY,buildPrepareContext,checkOutTarget,exitCodeFor,fetchAllPages,outputValue,reportError,requiresYes,resolvePaging,runDomain}from"./chunk-F7LPERJA.js";import"./chunk-46OWZRTJ.js";import"./chunk-F5QDUPQO.js";import"./chunk-P4QSPSOQ.js";import"./chunk-Q3B65OFC.js";import"./chunk-W4NLJ2YK.js";import"./chunk-BD7O73GK.js";import"./chunk-VGT2EGH6.js";import"./chunk-A7MM5WSC.js";import"./chunk-HVZUXLQ4.js";import"./chunk-JA5A6UJ2.js";
|
|
4
4
|
import"./chunk-MMVXE2CJ.js";import"./chunk-SBRTBKEZ.js";import"./chunk-MI6HVYR2.js";import"./chunk-3ZRMMBP5.js";import"./chunk-VFPY2A23.js";import"./chunk-KIZIRVW6.js";import"./chunk-XNLIEUAW.js";import"./chunk-J7QYPKVK.js";import"./chunk-EDF4U5BT.js";import"./chunk-RZVI6PMW.js";import"./chunk-AAABT3AX.js";import"./chunk-OKATZ4SN.js";import"./chunk-RKBUJKI5.js";import"./chunk-UREA4ZIG.js";import"./chunk-NHYMHCAT.js";
|
|
5
5
|
import"./chunk-VSJBJXZO.js";export{CURATED_PAGING_VOCABULARY,buildPrepareContext,checkOutTarget,exitCodeFor,fetchAllPages,outputValue,reportError,requiresYes,resolvePaging,runDomain};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
2
|
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
-
import{hasRemovableRunner,parseRunners,removeHint,runRunnerCommand}from"./chunk-
|
|
3
|
+
import{hasRemovableRunner,parseRunners,removeHint,runRunnerCommand}from"./chunk-FFRQGBMA.js";import"./chunk-MYBIPHZ7.js";import"./chunk-A4LFG7MW.js";import"./chunk-VRBI2NPI.js";import"./chunk-VFPY2A23.js";import"./chunk-NHYMHCAT.js";import"./chunk-VSJBJXZO.js";export{hasRemovableRunner,parseRunners,removeHint,runRunnerCommand};
|
|
@@ -8,11 +8,11 @@ ${e.hint?`${e.hint}
|
|
|
8
8
|
const res=await api.request("GET","/settings/skills");if(!res.ok){io.err(`\u26D4 \u30B9\u30AD\u30EB\u5B9A\u7FA9\u306E\u4E00\u89A7\u3092\u53D6\u5F97\u3067\u304D\u307E\u305B\u3093\uFF08${errorDetail(res)}\uFF09
|
|
9
9
|
`);return apiExit(res)}const raw=unwrap(res,"skills")["skills"];if(!Array.isArray(raw)){io.err(`\u26D4 \u30B9\u30AD\u30EB\u5B9A\u7FA9\u306E\u4E00\u89A7\u3092\u89E3\u91C8\u3067\u304D\u307E\u305B\u3093\uFF08\u5FDC\u7B54\u306E\u5148\u982D: ${res.raw.slice(0,120)}\uFF09
|
|
10
10
|
`);return EXIT_API_SERVER}const entries=[];for(const item of raw){const r=item&&typeof item==="object"?item:{};const name=str(r["name"]);const revision=pickNumber(r,"revision");const digest=str(r["digest"]);if(!isValidSkillName(name)||revision===null||!/^sha256:[0-9a-f]{64}$/.test(digest)){io.err(`\u26D4 \u30B9\u30AD\u30EB\u5B9A\u7FA9\u306E\u4E00\u89A7\u306B\u5951\u7D04\u5916\u306E\u8981\u7D20\u304C\u3042\u308A\u307E\u3059\uFF08${JSON.stringify(item).slice(0,160)}\uFF09
|
|
11
|
-
`);return EXIT_API_SERVER}entries.push({name,revision,updated_by_name:str(r["updated_by_name"]),updated_at:str(r["updated_at"]),bytes:pickNumber(r,"bytes"),digest})}entries.sort((a,b)=>a.name<b.name?-1:a.name>b.name?1:0);const{evaluateQuery}=await import("./query-
|
|
11
|
+
`);return EXIT_API_SERVER}entries.push({name,revision,updated_by_name:str(r["updated_by_name"]),updated_at:str(r["updated_at"]),bytes:pickNumber(r,"bytes"),digest})}entries.sort((a,b)=>a.name<b.name?-1:a.name>b.name?1:0);const{evaluateQuery}=await import("./query-J76QIXWR.js");const{renderOutput}=await import("./render-I6U5PEYR.js");const selected=opts.query===void 0?entries:await evaluateQuery(opts.query,entries);if(format!=="json"&&opts.query===void 0&&entries.length===0){io.err("\u30B5\u30FC\
|
|
12
12
|
\u30D0\u306B\u30B9\u30AD\u30EB\u304C\u767B\u9332\u3055\u308C\u3066\u3044\u307E\u305B\u3093\uFF08\u30EB\u30FC\u30D7\u306F\u3059\u3079\u3066\u4F5C\u696D\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u306E\u30D5\u30A1\u30A4\u30EB\u7248\u3092\u4F7F\u3044\u307E\u3059\uFF09\n");return EXIT_OK}const text=renderOutput(selected,format);io.out(text.endsWith("\n")?text:`${text}
|
|
13
13
|
`);return EXIT_OK}async function showSkill(api,opts,name,io){if(opts.output!==void 0&&opts.output!=="json"){throw new UsageError(`skill show \u306E --output \u306B\u300C${opts.output}\u300D\u306F\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093`,"\u6307\u5B9A\u3067\u304D\u308B\u306E\u306F json \u3060\u3051\u3067\u3059\uFF08\u7701\u7565\u3059\u308B\u3068\u672C\u6587\u3092\u305D\u306E\u307E\u307E\u51FA\u3057\u307E\u3059\uFF09")}const structured=opts.output==="json"||opts.query!==void 0;const current=await fetchSkill(
|
|
14
14
|
api,name,io.err);if(typeof current==="number")return current;if(current===null){io.err(`\u30B5\u30FC\u30D0\u306B\u30B9\u30AD\u30EB ${name} \u304C\u767B\u9332\u3055\u308C\u3066\u3044\u307E\u305B\u3093\uFF08\u30EB\u30FC\u30D7\u306F\u4F5C\u696D\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u306E\u30D5\u30A1\u30A4\u30EB\u7248\u3092\u4F7F\u3044\u307E\u3059\uFF09
|
|
15
|
-
`);return EXIT_FAILURE}if(structured){const value={name:current.name,revision:current.revision,updated_by_name:current.updatedByName,updated_at:current.updatedAt,bytes:Buffer.byteLength(current.body,"utf8"),digest:skillDigest(current.body),body:current.body};const{evaluateQuery}=await import("./query-
|
|
15
|
+
`);return EXIT_FAILURE}if(structured){const value={name:current.name,revision:current.revision,updated_by_name:current.updatedByName,updated_at:current.updatedAt,bytes:Buffer.byteLength(current.body,"utf8"),digest:skillDigest(current.body),body:current.body};const{evaluateQuery}=await import("./query-J76QIXWR.js");const{renderOutput}=await import("./render-I6U5PEYR.js");const selected=opts.query===void 0?value:await evaluateQuery(opts.query,value);const text=renderOutput(selected,"jso\
|
|
16
16
|
n",true);io.out(text.endsWith("\n")?text:`${text}
|
|
17
17
|
`);return EXIT_OK}if(io.isTty){warnHiddenChars(io.err,current.body,name);io.out(current.body);if(!current.body.endsWith("\n"))io.out("\n");return EXIT_OK}io.rawOut(current.body);return EXIT_OK}async function deleteSkill(api,opts,name,io){let expected;if(opts.revision!==void 0){if(!/^\d{1,15}$/.test(opts.revision)){io.err(`--revision \u306F0\u4EE5\u4E0A\u306E\u6574\u6570\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044: ${opts.revision}
|
|
18
18
|
`);return EXIT_USAGE}if(!opts.yes){io.err("--revision \u306F --yes \u3068\u4E00\u7DD2\u306B\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF08--yes \u306A\u3057\u3067\u306F\u524A\u9664\u3057\u307E\u305B\u3093\uFF09\n");return EXIT_USAGE}expected=opts.revision}else if(opts.yes){io.err("skill delete \u306E\u78BA\u5B9A\u306B\u306F --yes \u3068 --revision <N> \u306E\u4E21\u65B9\u304C\u5FC5\u8981\u3067\u3059\uFF08--yes \u3092\u5916\u3057\u3066\u5B9F\u884C\u3059\u308B\u3068\u3001\u6D88\u3059\u5185\u5BB9\u3068 revision \u3092\u8868\u793A\u3057\u307E\u3059\uFF09\n");
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
2
|
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
-
import{hasRemovableRunner,removeHint}from"./chunk-
|
|
3
|
+
import{hasRemovableRunner,removeHint}from"./chunk-FFRQGBMA.js";import"./chunk-MYBIPHZ7.js";import"./chunk-A4LFG7MW.js";import"./chunk-VRBI2NPI.js";import{describeError,filterByStatus,pick}from"./chunk-UZUV5FYG.js";import"./chunk-RMFLTSOV.js";import{EXIT_OK,EXIT_USAGE,UsageError}from"./chunk-VFPY2A23.js";import"./chunk-J7QYPKVK.js";import{stripTerminalControls}from"./chunk-NHYMHCAT.js";import"./chunk-VSJBJXZO.js";function str(v){return typeof v==="string"&&v!==""?v:null}function num(v){return typeof v==="number"&&Number.isFinite(v)?v:null}function secondsSince(iso,now){if(iso===null)return null;const at=Date.parse(iso);if(Number.isNaN(at))return null;return Math.max(0,Math.floor((now.getTime()-at)/1e3))}async function collectStatus(api,ctx){const now=ctx.now??new Date;const runnersRes=await api.runners();let runners;if(!runnersRes.ok){runners={ok:false,error:describeError(runnersRes)}}else{const raw=pick(
|
|
4
4
|
runnersRes.json,"runners");const list=Array.isArray(raw)?raw:[];runners={ok:true,live_count:num(pick(runnersRes.json,"live_count")),max_runners:num(pick(runnersRes.json,"max_runners")),heartbeat_timeout:num(pick(runnersRes.json,"heartbeat_timeout")),items:list.map(r=>{const lastSeen=str(r?.["last_seen_at"]);return{runner_id:str(r?.["runner_id"]),is_live:r?.["is_live"]===true,is_reporting:r?.["is_reporting"]===true,is_waiting:r?.["is_waiting"]===true,next_run_at:str(r?.["next_run_at"]),kind:str(r?.["\
|
|
5
5
|
kind"]),phase:str(r?.["phase"]),current_item_id:str(r?.["current_item_id"]),hostname:str(r?.["hostname"]),last_seen_at:lastSeen,seconds_since_last_seen:secondsSince(lastSeen,now)}})}}const queue={};for(const status of["pending","processing"]){const res=await api.list({status,limit:100});if(!res.ok){queue[status]={ok:false,error:describeError(res)};continue}const items=pick(res.json,"items");const more=pick(res.json,"has_more")===true||pick(res.json,"pagination.has_more")===true;const counted=Array.
|
|
6
6
|
isArray(items)?filterByStatus(items,status).length:null;queue[status]={ok:true,count:counted,has_more:more}}const state=await api.request("GET","/state");const plan_lock=state.ok?{held:pick(state.json,"state.planning")===true,owner_runner_id:str(pick(state.json,"state.plan_owner_runner_id")),expires_at:str(pick(state.json,"state.plan_lock_expires_at"))}:null;return{project:{ref:ctx.projectRef,id:ctx.projectId},api_url:ctx.apiUrl,runners,queue,plan_lock,local_lock:{held:ctx.lockHeld,path:ctx.lockPath}}}
|
|
@@ -11,7 +11,7 @@ live_count??"?"} / ${r.max_runners??"?"} \u7A3C\u50CD\uFF08\u6B7B\u6D3B\u3057\u3
|
|
|
11
11
|
/ \u671F\u9650 ${pl.expires_at??"?"}\uFF09`:"\u7A7A\u304D"}`)}lines.push("",`\u30ED\u30FC\u30AB\u30EB\u30ED\u30C3\u30AF: ${report.local_lock.held?`\u4FDD\u6301\u4E2D\uFF08${report.local_lock.path}\uFF09`:"\u7121\u3057"}`);return`${lines.join("\n")}
|
|
12
12
|
`}async function runStatusCommand(api,ctx,opts,io){if(opts.output!==void 0&&opts.output!=="json"){io.err(`task-loop status \u306E --output \u306B\u300C${opts.output}\u300D\u306F\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093
|
|
13
13
|
\u6307\u5B9A\u3067\u304D\u308B\u306E\u306F json \u3060\u3051\u3067\u3059\uFF08\u7701\u7565\u3059\u308B\u3068\u4EBA\u5411\u3051\u306E\u6587\u9762\u3092\u51FA\u3057\u307E\u3059\uFF09
|
|
14
|
-
`);return EXIT_USAGE}if(opts.query!==void 0&&opts.query.trim()===""){io.err("--query \u306B\u7A7A\u306E\u5F0F\u306F\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093\n");return EXIT_USAGE}const report=await collectStatus(api,ctx);if(opts.output===void 0&&opts.query===void 0){io.out(stripTerminalControls(renderStatusText(report,{profile:ctx.profile})));return EXIT_OK}const{evaluateQuery}=await import("./query-
|
|
14
|
+
`);return EXIT_USAGE}if(opts.query!==void 0&&opts.query.trim()===""){io.err("--query \u306B\u7A7A\u306E\u5F0F\u306F\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093\n");return EXIT_USAGE}const report=await collectStatus(api,ctx);if(opts.output===void 0&&opts.query===void 0){io.out(stripTerminalControls(renderStatusText(report,{profile:ctx.profile})));return EXIT_OK}const{evaluateQuery}=await import("./query-J76QIXWR.js");const{renderOutput}=await import("./render-I6U5PEYR.js");let selected=report;
|
|
15
15
|
if(opts.query!==void 0){try{selected=await evaluateQuery(opts.query,report)}catch(e){if(e instanceof UsageError){io.err(`${e.message}
|
|
16
16
|
`);return EXIT_USAGE}throw e}}const text=renderOutput(selected,"json");io.out(text.endsWith("\n")?text:`${text}
|
|
17
17
|
`);return EXIT_OK}function runnerStateLabel(x){if(x.is_live)return"live";if(x.is_waiting)return x.next_run_at===null?"waiting":`waiting \u6B21\u56DE ${formatLocalTime(x.next_run_at)}`;return"stale"}export{collectStatus,formatElapsed,formatLocalTime,renderStatusText,runStatusCommand};
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
2
|
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
-
import{infoNote}from"./chunk-TYO6THPW.js";import{PROJECT_FLAG,TASK_REF_FLAG,TASK_REF_HELP,classifyTaskRef,rejectPrivateSurface,rejectRedundantProject,resolveTaskLocation,taskAttachmentResource,taskSurface,wantsPrivateSurface}from"./chunk-6H5TPSXU.js";import"./chunk-V64CGX7V.js";import{RUNNER_PLATFORMS}from"./chunk-UZUV5FYG.js";import{PRIVATE_PROJECT_PREFIX,PRIVATE_PROJECT_REF,isPrivateProjectId}from"./chunk-RMFLTSOV.js";
|
|
4
|
-
manhourNotes,manhourQuery,manhourRows}from"./chunk-L4THNX4M.js";import"./chunk-KPLC3UP7.js";import"./chunk-UVCJXHWN.js";import{createFlags,fieldBody,hasAnyField,updateFlags}from"./chunk-IOVZDBAD.js";import"./chunk-EXT4AIDF.js";import{boundedText,decimal,integerInRange,isoDate,priority}from"./chunk-JJSBBWJ5.js";import{charCount,readBody}from"./chunk-HEH3PUW2.js";import"./chunk-W4NLJ2YK.js";
|
|
5
|
-
import{PRIVATE_TASKS_PATH,TASK_MASTERS}from"./chunk-A7MM5WSC.js";import{UUID_RE,isSafePathSegment}from"./chunk-HVZUXLQ4.js";import"./chunk-JA5A6UJ2.js";import"./chunk-MMVXE2CJ.js";import"./chunk-SBRTBKEZ.js";import{LIST_FLAGS,LIST_PAGING_HELP,envelopePaging,nonEmpty,positiveInteger}from"./chunk-MI6HVYR2.js";import{requireResolved,singleRef,withResolved}from"./chunk-PS5QFKHB.js";
|
|
6
|
-
UsageError}from"./chunk-VFPY2A23.js";import"./chunk-J7QYPKVK.js";import"./chunk-EDF4U5BT.js";import"./chunk-RZVI6PMW.js";import"./chunk-OKATZ4SN.js";import"./chunk-NHYMHCAT.js";import"./chunk-VSJBJXZO.js";var PRIVATE_UNSUPPORTED=[{flag:"--assignee",clearToken:"assignee",reason:"\u500B\u4EBA\u30BF\u30B9\u30AF\u306F\u5E38\u306B\u81EA\u5206\u306E\u3082\u306E\u306A\u306E\u3067\u3001\u30B5\u30FC\u30D0\u5074\u306B\u62C5\u5F53\u8005\u3092\u6307\u5B9A\u30FB\u7D5E\u308A\u8FBC\u307F\u3059\u308B\u9805\u76EE\u304C\u3042\u308A\u307E\u305B\u3093\u3002"},{flag:"--milestone",clearToken:"milestone",reason:"\u500B\u4EBA\u30BF\u30B9\u30AF\u306B\u30DE\u30A4\u30EB\u30B9\u30C8\u30FC\u30F3\u306E\u9805\u76EE\u304C\u30B5\u30FC\u30D0\u5074\u306B\u3042\u308A\u307E\u305B\u3093\u3002"},
|
|
3
|
+
import{infoNote}from"./chunk-TYO6THPW.js";import{PROJECT_FLAG,TASK_REF_FLAG,TASK_REF_HELP,classifyTaskRef,rejectPrivateSurface,rejectRedundantProject,resolveTaskLocation,taskAttachmentResource,taskSurface,wantsPrivateSurface}from"./chunk-6H5TPSXU.js";import"./chunk-V64CGX7V.js";import{parseRequiredPlatforms}from"./chunk-56LNKTKM.js";import{RUNNER_PLATFORMS}from"./chunk-UZUV5FYG.js";import{PRIVATE_PROJECT_PREFIX,PRIVATE_PROJECT_REF,isPrivateProjectId}from"./chunk-RMFLTSOV.js";
|
|
4
|
+
import{MANHOUR_DESCRIPTION,MANHOUR_FROM_FLAG,MANHOUR_TO_FLAG,manhourNotes,manhourQuery,manhourRows}from"./chunk-L4THNX4M.js";import"./chunk-KPLC3UP7.js";import"./chunk-UVCJXHWN.js";import{createFlags,fieldBody,hasAnyField,updateFlags}from"./chunk-IOVZDBAD.js";import"./chunk-EXT4AIDF.js";import{boundedText,decimal,integerInRange,isoDate,priority}from"./chunk-JJSBBWJ5.js";import{charCount,readBody}from"./chunk-HEH3PUW2.js";import"./chunk-W4NLJ2YK.js";
|
|
5
|
+
import"./chunk-BD7O73GK.js";import{repeatedValues}from"./chunk-VGT2EGH6.js";import{PRIVATE_TASKS_PATH,TASK_MASTERS}from"./chunk-A7MM5WSC.js";import{UUID_RE,isSafePathSegment}from"./chunk-HVZUXLQ4.js";import"./chunk-JA5A6UJ2.js";import"./chunk-MMVXE2CJ.js";import"./chunk-SBRTBKEZ.js";import{LIST_FLAGS,LIST_PAGING_HELP,envelopePaging,nonEmpty,positiveInteger}from"./chunk-MI6HVYR2.js";import{requireResolved,singleRef,withResolved}from"./chunk-PS5QFKHB.js";
|
|
6
|
+
import{acknowledgement,isRecord,pick}from"./chunk-3ZRMMBP5.js";import{ApiResponseError,UsageError}from"./chunk-VFPY2A23.js";import"./chunk-J7QYPKVK.js";import"./chunk-EDF4U5BT.js";import"./chunk-RZVI6PMW.js";import"./chunk-OKATZ4SN.js";import"./chunk-NHYMHCAT.js";import"./chunk-VSJBJXZO.js";var PRIVATE_UNSUPPORTED=[{flag:"--assignee",clearToken:"assignee",reason:"\u500B\u4EBA\u30BF\u30B9\u30AF\u306F\u5E38\u306B\u81EA\u5206\u306E\u3082\u306E\u306A\u306E\u3067\u3001\u30B5\u30FC\u30D0\u5074\u306B\u62C5\u5F53\u8005\u3092\u6307\u5B9A\u30FB\u7D5E\u308A\u8FBC\u307F\u3059\u308B\u9805\u76EE\u304C\u3042\u308A\u307E\u305B\u3093\u3002"},{flag:"--milestone",clearToken:"milestone",reason:"\u500B\u4EBA\u30BF\u30B9\u30AF\u306B\u30DE\u30A4\u30EB\u30B9\u30C8\u30FC\u30F3\u306E\u9805\u76EE\u304C\u30B5\u30FC\u30D0\u5074\u306B\u3042\u308A\u307E\u305B\u3093\u3002"},
|
|
7
7
|
{flag:"--group",clearToken:"group",reason:"\u500B\u4EBA\u30BF\u30B9\u30AF\u306B\u30BF\u30B9\u30AF\u30B0\u30EB\u30FC\u30D7\u306E\u9805\u76EE\u304C\u30B5\u30FC\u30D0\u5074\u306B\u3042\u308A\u307E\u305B\u3093\u3002"},{flag:"--required-platforms",clearToken:"required-platforms",reason:"\u5FC5\u8981\u30D7\u30E9\u30C3\u30C8\u30D5\u30A9\u30FC\u30E0\u306F\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u30EB\u30FC\u30D7\u304C\u62FE\u3046\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u30BF\u30B9\u30AF\u3060\u3051\u306E\u9805\u76EE\u3067\u3001\u500B\u4EBA\u30BF\u30B9\u30AF\u306E\u30B5\u30FC\u30D0\u5074\u306B\u3042\u308A\u307E\u305B\u3093\u3002"}];
|
|
8
8
|
function rejectPrivateUnsupportedFlags(input){const clearTokens=new Set(repeatedValues(input,"--clear").map(token=>token.trim()));for(const entry of PRIVATE_UNSUPPORTED){if(input.flags.has(entry.flag)||repeatedValues(input,entry.flag).length>0){throw new UsageError(`--project ${PRIVATE_PROJECT_REF}\uFF08\u500B\u4EBA\u30BF\u30B9\u30AF\uFF09\u3067\u306F ${entry.flag} \u3092\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093`,`${entry.reason}${entry.flag} \u3092\u5916\u3057\u3066\u304F\u3060\u3055\u3044\u3002`)}
|
|
9
9
|
if(clearTokens.has(entry.clearToken)){throw new UsageError(`--project ${PRIVATE_PROJECT_REF}\uFF08\u500B\u4EBA\u30BF\u30B9\u30AF\uFF09\u3067\u306F --clear ${entry.clearToken} \u3092\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093`,`${entry.reason}\u9001\u3063\u3066\u3082\u4F55\u3082\u8D77\u304D\u306A\u3044\u305F\u3081\u3001--clear ${entry.clearToken} \u3092\u5916\u3057\u3066\u304F\u3060\u3055\u3044\u3002`)}}}function privateTaskRef(ref){const{kind,value}=classifyTaskRef(ref);if(kind==="unknown"){throw new UsageError(
|
|
@@ -227,25 +227,23 @@ stone_id"},{token:"group",flags:["--group"],key:"task_group_id"},{token:"label",
|
|
|
227
227
|
\u4EF6\u540D\u30FB\u30B9\u30C6\u30FC\u30BF\u30B9\u30FB\u7A2E\u5225\u306F\u30B5\u30FC\u30D0\u5074\u3067\u5FC5\u9808\u306E\u305F\u3081\u7A7A\u306B\u3067\u304D\u307E\u305B\u3093\u3002
|
|
228
228
|
\u540C\u3058\u9805\u76EE\u3092\u5024\u3068 --clear \u306E\u4E21\u65B9\u3067\u6307\u5B9A\u3059\u308B\u3068\u30A8\u30E9\u30FC\u306B\u306A\u308A\u307E\u3059\uFF08\u3069\u3061\u3089\u304C\u52B9\u3044\u305F\u306E\u304B\u5206\u304B\u3089\u306A\u3044\u305F\u3081\uFF09\u3002`;function clearTargets(input){const tokens=repeatedValues(input,CLEAR_FLAG.name).map(token=>token.trim());const out=[];for(const token of tokens){const entry=CLEARABLE.find(candidate=>candidate.token===token);if(entry===void 0){throw new UsageError(
|
|
229
229
|
`--clear \u306B\u6307\u5B9A\u3067\u304D\u306A\u3044\u9805\u76EE\u3067\u3059: ${token===""?"(\u7A7A)":token}`,`\u6307\u5B9A\u3067\u304D\u308B\u9805\u76EE: ${CLEARABLE.map(candidate=>candidate.token).join(" / ")}`)}if(out.includes(entry))throw new UsageError(`--clear \u306E\u9805\u76EE\u304C\u91CD\u8907\u3057\u3066\u3044\u307E\u3059: ${token}`);const conflict=entry.flags.find(flag=>input.flags.has(flag)||repeatedValues(input,flag).length>0);if(conflict!==void 0){throw new UsageError(`${conflict} \u3068\
|
|
230
|
-
--clear ${token} \u306E\u4E21\u65B9\u304C\u6307\u5B9A\u3055\u308C\u3066\u3044\u307E\u3059`,"\u5024\u3092\u5165\u308C\u308B\u304B\u7A7A\u306B\u3059\u308B\u304B\u306E\u3069\u3061\u3089\u304B\u4E00\u65B9\u3060\u3051\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\u3002")}out.push(entry)}return out}function requiredPlatforms(input){
|
|
231
|
-
const
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
"
|
|
242
|
-
const
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
\
|
|
246
|
-
|
|
247
|
-
ctx,parent)}}var taskDomain={name:"task",summary:"\u30BF\u30B9\u30AF\u306E\u4E00\u89A7\u30FB\u8A73\u7D30\u30FB\u30B5\u30D6\u30BF\u30B9\u30AF\u30FB\u4F5C\u6210\u30FB\u66F4\u65B0\u30FB\u524A\u9664",operations:[{name:"list",summary:"\u30BF\u30B9\u30AF\u3092\u4E00\u89A7\u3059\u308B",usage:"twp task list [--project <\u30B3\u30FC\u30C9|ID|__private__>] [--status <\u540D\u524D>] [--type <\u540D\u524D>] [--assignee <me|\u540D\u524D>] [--keyword <\u8A9E>] [--all] [--summary]",description:`--output json \u306F\
|
|
248
|
-
API \u304C\u8FD4\u3059\u5168\u30D5\u30A3\u30FC\u30EB\u30C9\u3092\u51FA\u3057\u307E\u3059\u3002
|
|
230
|
+
--clear ${token} \u306E\u4E21\u65B9\u304C\u6307\u5B9A\u3055\u308C\u3066\u3044\u307E\u3059`,"\u5024\u3092\u5165\u308C\u308B\u304B\u7A7A\u306B\u3059\u308B\u304B\u306E\u3069\u3061\u3089\u304B\u4E00\u65B9\u3060\u3051\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\u3002")}out.push(entry)}return out}function requiredPlatforms(input){return parseRequiredPlatforms(input,`\u6307\u5B9A\u3067\u304D\u308B\u5024: ${RUNNER_PLATFORMS.join(" / ")}\uFF08\u5236\u7D04\u3092\u5916\u3059\u3068\u304D\u306F --clear required-platforms\uFF09`)}
|
|
231
|
+
function customFields(input){const entries=repeatedValues(input,"--custom-field");if(entries.length===0)return void 0;const out={};for(const entry of entries){const at=entry.indexOf("=");if(at<=0){throw new UsageError(`--custom-field \u306F <\u30D5\u30A3\u30FC\u30EB\u30C9\u540D>=<\u5024> \u306E\u5F62\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044: ${entry}`,"\u4F8B: --custom-field \u9867\u5BA2\u540D=\u30C8\u30C3\u30AB\uFF08\u5024\u304C\u7A7A\u306E\u3068\u304D\u306F --custom-field \u9867\u5BA2\u540D= \u3068\u66F8\u304D\u307E\u3059\uFF09")}
|
|
232
|
+
const name=entry.slice(0,at).trim();if(name==="")throw new UsageError(`--custom-field \u306E\u30D5\u30A3\u30FC\u30EB\u30C9\u540D\u304C\u7A7A\u3067\u3059: ${entry}`);if(name in out)throw new UsageError(`--custom-field \u306E\u30D5\u30A3\u30FC\u30EB\u30C9\u540D\u304C\u91CD\u8907\u3057\u3066\u3044\u307E\u3059: ${name}`);out[name]=entry.slice(at+1)}return out}var FIELD_HELP="--status / --type / --assignee \u306F\u540D\u524D\u30FB\u30B3\u30FC\u30C9\u30FBID \u306E\u3044\u305A\u308C\u3067\u3082\u6307\u5B9A\u3067\u304D\u307E\u3059\u3002\n\u5B8C\u5168\u4E00\u81F4\u3060\u3051\u3067\u89E3\u6C7A\u3057\u3001\u8907\u6570\u306B\u5F53\u305F\u308B\u30FB1\u4EF6\u3082\u5F53\u305F\u3089\u306A\u3044\u5834\u5408\u306F\u5019\u88DC\u3092\u51FA\u3057\u3066\u7D42\u4E86\u30B3\u30FC\u30C9 2 \u3067\u6B62\u307E\u308A\u307E\u3059\u3002\n--assignee me \u306F\u300C\u3044\u307E\u30ED\
|
|
233
|
+
\u30B0\u30A4\u30F3\u3057\u3066\u3044\u308B\u30E6\u30FC\u30B6\u30FC\u300D\u3067\u3059\u3002\n\n\u672C\u6587\u306F --description-file \u3092\u4E3B\u7D4C\u8DEF\u306B\u3057\u3066\u304F\u3060\u3055\u3044\uFF08\u30B7\u30A7\u30EB\u306E\u5F15\u6570\u306B\u8F09\u305B\u308B\u3068\u6539\u884C\u30FBMarkdown \u306E\n\u898B\u51FA\u3057\uFF08#\uFF09\u30FB\u5F15\u7528\u7B26\u3067\u58CA\u308C\u307E\u3059\uFF09\u3002--description-file - \u3067\u6A19\u6E96\u5165\u529B\u304B\u3089\u8AAD\u3081\u307E\u3059\u3002\u672C\u6587\u306F\u52A0\u5DE5\u3057\u307E\u305B\u3093\n\uFF08\u6539\u884C\u30FBCRLF \u306F\u305D\u306E\u307E\u307E\u9001\u308A\u307E\u3059\u3002\u843D\u3068\u3059\u306E\u306F\u5148\u982D\u306E UTF-8 BOM \u3060\u3051\u3067\u3059\uFF09\u3002\n\u672C\u6587\u3092\u66F8\u304D\u623B\u3059\u3068\u304D\u306F --no-redact \u3067\u8AAD\u3093\u3067\u304F\u3060\u3055\u3044\u3002\u65E2\u5B9A\u306E\u51FA\u529B\u306F\u4F0F\u5B57\u5316\u3055\u308C\u3066\u304A\u308A\u3001\u305D\u306E\u51FA\u529B\u304B\u3089\u4F5C\u3063\u305F\u672C\u6587\u306B\n\u4F0F\u5B57\u30DE\u30FC\u30AB\u30FC\uFF08***\uFF08\u4F0F\u5B57\uFF09\uFF09\u304C\u6B8B\u3063\u3066\u3044\u308B\u3068\u9001\u4FE1\u524D\u306B\u6B62\u3081\u307E\u3059\uFF08\u7D42\u4E86\u30B3\u30FC\u30C9 2\u3002\u610F\u56F3\u3057\u3066\u542B\u3081\u308B\u306A\u3089 --allow-redacted\uFF09\u3002\n\n--category / --milestone / --label / --group \u3082\u540C\u3058\u898F\u7D04\u3067\u540D\u524D\u304B\u3089\u5F15\u3051\u307E\u3059\uFF08--label \u306F\u8907\u6570\u6307\u5B9A\u3067\u304D\u307E\u3059\uFF09\u3002\n--group \u3092\u4ED8\u3051\u305F\u30BF\u30B9\u30AF\u306F\u3001\u30B0\u30EB\u30FC\u30D7\u306E\u95B2\u89A7\u30E1\u30F3\u30D0\u30FC\u30FB\u4F5C\u6210\u8005\u30FB\u62C5\u5F53\u8005\u30FB\u7BA1\u7406\u8005\u3060\u3051\u304C\u898B\u3089\u308C\u307E\u3059\uFF08\u5019\u88DC\u306F twp task group list\uFF09\u3002\n\u62C5\u5F53\u8005\u306F\u30B0\u30EB\u30FC\u30D7\u306E\u95B2\u89A7\u30E1\u30F3\u30D0\u30FC\u304B\u4F5C\u6210\u8005\u3067\u306A\u3051\u308C\u3070\u306A\u3089\u305A\u3001\u5916\u308C\u3066\u3044\u308B\u3068\
|
|
234
|
+
\u30B5\u30FC\u30D0\u304C\u65AD\u308A\u307E\u3059\u3002\u30B0\u30EB\u30FC\u30D7\u304B\u3089\u5916\u3059\u3068\u304D\u306F\ntwp task update \u306E --clear group \u3092\u4F7F\u3044\u307E\u3059\u3002\n--label \u306F\u300C\u6307\u5B9A\u3057\u305F\u3082\u306E\u304C\u5168\u4F53\u300D\u3067\u3059\uFF08\u3044\u307E\u4ED8\u3044\u3066\u3044\u308B\u30E9\u30D9\u30EB\u306B\u8DB3\u3059\u306E\u3067\u306F\u306A\u304F\u3001\u7F6E\u304D\u63DB\u3048\u307E\u3059\uFF09\u3002\n--parent \u3092\u6307\u5B9A\u3059\u308B\u3068\u3001\u305D\u306E\u30BF\u30B9\u30AF\u306E\u30B5\u30D6\u30BF\u30B9\u30AF\u3068\u3057\u3066\u6271\u308F\u308C\u307E\u3059\uFF08\u30B5\u30FC\u30D0\u5074\u3067\u968E\u5C64\u306E\u691C\u8A3C\u304C\u8D70\u308A\u307E\u3059\uFF09\u3002\n--required-platforms \u306F\u30BF\u30B9\u30AF\u3092\u5B9F\u884C\u3067\u304D\u308B\u6A5F\u4F53\u3092 mac / windows / linux \u306B\u9650\u308A\u307E\u3059\uFF08\u8907\u6570\u6307\u5B9A\u30FB\u30AB\u30F3\u30DE\u533A\u5207\u308A\u53EF\u3002\n\u6307\u5B9A\u3057\u305F\u3082\u306E\u304C\u5168\u4F53\u3067\u3059\uFF09\u3002\u5236\u7D04\u3092\u5916\u3059\u3068\u304D\u306F twp task update \u306E --clear required-platforms \u3092\u4F7F\u3044\u307E\u3059\u3002\n--custom-field \u306F\u30AB\u30B9\u30BF\u30E0\u30D5\u30A3\u30FC\u30EB\u30C9\u306E\u300C\u540D\u524D\u300D\u3092\u9375\u306B\u3057\u307E\u3059\uFF08\u7DE8\u96C6\u306B\u306F\u7BA1\u7406\u8005\u307E\u305F\u306F\u30DE\u30CD\u30FC\u30B8\u30E3\u30FC\u6A29\u9650\u304C\u8981\u308A\u307E\u3059\uFF09\u3002";
|
|
235
|
+
function readDescription(input,usage){return readBody(input,{flag:"--description",fileFlag:"--description-file",label:"\u672C\u6587",maxChars:DESCRIPTION_MAX_CHARS,usage})}function checkPureFields(input){boundedText(input,"--subject",{maxChars:SUBJECT_MAX_CHARS,label:"\u4EF6\u540D"});isoDate(input,"--due-date");isoDate(input,"--start-date");priority(input);decimal(input,"--estimated-hours",{min:0,max:ESTIMATED_HOURS_MAX});integerInRange(input,"--progress",PROGRESS_RANGE);customFields(input);requiredPlatforms(
|
|
236
|
+
input);clearTargets(input)}function taskBody(input){const body={};const put=(key,value)=>{if(value!==void 0)body[key]=value};put("subject",boundedText(input,"--subject",{maxChars:SUBJECT_MAX_CHARS,label:"\u4EF6\u540D"}));const description=input.resolved?.["description"];put("description",description);if(description!==void 0)body["description_html"]=null;put("status_id",input.resolved?.["status_id"]);put("type_id",input.resolved?.["type_id"]);put("assignee_id",input.resolved?.["assignee_id"]);put(
|
|
237
|
+
"due_date",isoDate(input,"--due-date"));put("start_date",isoDate(input,"--start-date"));put("priority",priority(input));put("category_id",input.resolved?.["category_id"]);put("milestone_id",input.resolved?.["milestone_id"]);put("task_group_id",input.resolved?.["task_group_id"]);put("label_ids",takeList2(input,"label_ids"));put("estimated_hours",decimal(input,"--estimated-hours",{min:0,max:ESTIMATED_HOURS_MAX}));put("progress",integerInRange(input,"--progress",PROGRESS_RANGE));put("custom_fields",
|
|
238
|
+
customFields(input));put("parent_task_id",input.resolved?.["parent_task_id"]);put("required_platforms",requiredPlatforms(input));for(const entry of clearTargets(input)){body[entry.key]="empty"in entry?entry.empty:null;if(entry.key==="description")body["description_html"]=null}return body}function takeList2(input,key){const raw=input.resolved?.[key];if(raw===void 0||raw==="")return void 0;const parsed=JSON.parse(raw);if(!Array.isArray(parsed))throw new Error(`\u5185\u90E8\u30A8\u30E9\u30FC: ${key}\
|
|
239
|
+
\u306E\u53D7\u3051\u6E21\u3057\u304C\u58CA\u308C\u3066\u3044\u307E\u3059`);return parsed}async function resolveStatusAndType(input,ctx,projectId,options){const out={};const status=nonEmpty(input.flags,"--status");if(status!==void 0){out["status_id"]=(await ctx.resolver.status(projectId,status)).id}else if(options.useDefaults){const ref=await ctx.resolver.defaultStatus(projectId);out["status_id"]=ref.id;out["status_defaulted"]=ref.name}const type=nonEmpty(input.flags,"--type");if(type!==void 0){
|
|
240
|
+
out["type_id"]=(await ctx.resolver.taskType(projectId,type)).id}else if(options.useDefaults){const ref=await ctx.resolver.defaultTaskType(projectId);out["type_id"]=ref.id;out["type_defaulted"]=ref.name}const assignee=nonEmpty(input.flags,"--assignee");if(assignee!==void 0)out["assignee_id"]=(await ctx.resolver.assignee(projectId,assignee)).id;return out}async function resolveExtras(input,ctx,projectId){const out={};const category=nonEmpty(input.flags,"--category");if(category!==void 0)out["categ\
|
|
241
|
+
ory_id"]=(await ctx.resolver.taskMaster("category",projectId,category,"--category")).id;const milestone=nonEmpty(input.flags,"--milestone");if(milestone!==void 0)out["milestone_id"]=(await ctx.resolver.taskMaster("milestone",projectId,milestone,"--milestone")).id;const group=nonEmpty(input.flags,"--group");if(group!==void 0)out["task_group_id"]=(await ctx.resolver.taskMaster("group",projectId,group,"--group")).id;const labels=repeatedValues(input,"--label");if(labels.length>0){const ids=[];for(const ref of labels){
|
|
242
|
+
const label=await ctx.resolver.taskMaster("label",projectId,ref,"--label");if(!ids.includes(label.id))ids.push(label.id)}out["label_ids"]=JSON.stringify(ids)}const parent=nonEmpty(input.flags,"--parent");if(parent!==void 0)out["parent_task_id"]=await resolveParentTaskId(ctx,projectId,parent);return out}async function resolveParentTaskId(ctx,projectId,ref){const classified=classifyTaskRef(ref);if(classified.kind==="id")return classified.value;if(classified.kind==="unknown"){throw new UsageError(`\
|
|
243
|
+
--parent \u304C\u300C\u30BF\u30B9\u30AF\u30AD\u30FC\uFF08\u4F8B ABC-123\uFF09\u300D\u306B\u3082\u300CID\uFF08UUID / ULID\uFF09\u300D\u306B\u3082\u898B\u3048\u307E\u305B\u3093: ${ref}`,"\u89AA\u30BF\u30B9\u30AF\u306F\u30AD\u30FC\u304B ID \u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\u3002")}const resolved=await ctx.resolver.taskByKey(classified.value);if(resolved.projectId!==projectId){throw new UsageError(`--parent ${classified.value} \u306F\u5225\u306E\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u306E\u30BF\u30B9\u30AF\u3067\u3059`,
|
|
244
|
+
"\u89AA\u30BF\u30B9\u30AF\u306F\u540C\u3058\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u306E\u30BF\u30B9\u30AF\u3060\u3051\u3092\u6307\u5B9A\u3067\u304D\u307E\u3059\uFF08\u30B5\u30FC\u30D0\u5074\u304C\u540C\u4E00\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u5185\u3067\u3057\u304B\u968E\u5C64\u3092\u4F5C\u308C\u307E\u305B\u3093\uFF09\u3002")}const id=resolved.task["id"];if(typeof id!=="string"||id===""){throw new ApiResponseError(`\u30BF\u30B9\u30AF\u30AD\u30FC\u89E3\u6C7A\u306E\u5FDC\u7B54\u306B task.id \u304C\u3042\u308A\u307E\u305B\u3093\uFF08--parent ${classified.
|
|
245
|
+
value}\uFF09\u3002\u63A5\u7D9A\u5148\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002`)}return id}async function resolvePrivateParent(input,ctx){const parent=nonEmpty(input.flags,"--parent");if(parent===void 0)return{};return{parent_task_id:await resolvePrivateTaskId(ctx,parent)}}var taskDomain={name:"task",summary:"\u30BF\u30B9\u30AF\u306E\u4E00\u89A7\u30FB\u8A73\u7D30\u30FB\u30B5\u30D6\u30BF\u30B9\u30AF\u30FB\u4F5C\u6210\u30FB\u66F4\u65B0\u30FB\u524A\u9664",operations:[{name:"list",
|
|
246
|
+
summary:"\u30BF\u30B9\u30AF\u3092\u4E00\u89A7\u3059\u308B",usage:"twp task list [--project <\u30B3\u30FC\u30C9|ID|__private__>] [--status <\u540D\u524D>] [--type <\u540D\u524D>] [--assignee <me|\u540D\u524D>] [--keyword <\u8A9E>] [--all] [--summary]",description:`--output json \u306F API \u304C\u8FD4\u3059\u5168\u30D5\u30A3\u30FC\u30EB\u30C9\u3092\u51FA\u3057\u307E\u3059\u3002
|
|
249
247
|
--output table / text / tsv \u306F\u8981\u7D04\u5217\uFF08key / subject / status_id / assignee_id / priority / due_date / updated_at\uFF09\u3067\u3059\u3002
|
|
250
248
|
\u6B32\u3057\u3044\u5217\u3060\u3051\u3092\u6A5F\u68B0\u51E6\u7406\u3057\u305F\u3044\u3068\u304D\u306F --query \u3067\u9078\u3093\u3067\u304F\u3060\u3055\u3044\uFF08--query \u306F\u751F\u30C7\u30FC\u30BF\u306B\u5BFE\u3057\u3066\u8A55\u4FA1\u3055\u308C\u307E\u3059\uFF09\u3002
|
|
251
249
|
--summary \u3092\u4ED8\u3051\u308B\u3068\u5404\u30BF\u30B9\u30AF\u306E\u672C\u6587\uFF08description / description_html\uFF09\u3092\u7701\u304D\u307E\u3059\u3002\u4EF6\u6570\u30FB\u30DA\u30FC\u30B8\u30F3\u30B0\u60C5\u5831\u306F\u5909\u308F\u3089\u305A\u3001
|
|
@@ -4,7 +4,7 @@ import{stableJson}from"./chunk-76WVQ45F.js";import{reasonOf,unwrap}from"./chunk-
|
|
|
4
4
|
deps.api,opts,io);case"show":return await show(deps.api,opts,io);case"push":return await push(deps.api,opts,io);case"delete":return await remove(deps.api,opts,io);case"history":return await history(deps.api,opts,io);case"release":return await release(deps.api,opts,io)}}catch(e){if(e instanceof UsageError){io.err(`${e.message}
|
|
5
5
|
${e.hint?`${e.hint}
|
|
6
6
|
`:""}`);return EXIT_USAGE}throw e}}async function formatOf(opts,io){const{resolveOutputFormat}=await import("./format-X65HXAAU.js");const format=resolveOutputFormat({...opts.output!==void 0?{flag:opts.output}:{},isTty:io.isTty});if(format===null||!FORMATS.includes(format)){throw new UsageError(`trigger ${opts.op} \u306E --output \u306B\u300C${opts.output??""}\u300D\u306F\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093`,`\u6307\u5B9A\u3067\u304D\u308B\u306E\u306F ${FORMATS.join(" / ")} \u3067\u3059`)}
|
|
7
|
-
return format}async function emit(value,opts,format,io){const{evaluateQuery}=await import("./query-
|
|
7
|
+
return format}async function emit(value,opts,format,io){const{evaluateQuery}=await import("./query-J76QIXWR.js");const{renderOutput}=await import("./render-I6U5PEYR.js");const selected=opts.query===void 0?value:await evaluateQuery(opts.query,value);const text2=renderOutput(selected,format);io.out(text2.endsWith("\n")?text2:`${text2}
|
|
8
8
|
`)}async function list(api,opts,io){const format=await formatOf(opts,io);const triggers=await fetchTriggers(api,io.err);if(typeof triggers==="number")return triggers;const sorted=[...triggers].sort((a,b)=>str(a["id"]).localeCompare(str(b["id"])));if(format==="json"){await emit(sorted,opts,format,io);return EXIT_OK}io.err(`\u6761\u4EF6\u30C8\u30EA\u30AC\u30FC ${sorted.length} \u4EF6
|
|
9
9
|
`);if(opts.query===void 0&&sorted.length===0)return EXIT_OK;await emit(sorted.map(summaryRow),opts,format,io);return EXIT_OK}function summaryRow(t){const match=obj(t["match"]);const threshold=obj(t["threshold"]);const action=obj(t["action"]);const skills=Array.isArray(match["skills"])?match["skills"].map(String).join(","):"";const codes=Array.isArray(match["outcome_codes"])?match["outcome_codes"].map(String).join(","):"";return{id:str(t["id"]),enabled:t["enabled"]===false?"\u7121\u52B9":"\u6709\u52B9",
|
|
10
10
|
name:str(t["name"]),skills,outcome_codes:codes,condition:`${text(threshold["count"])}\u56DE/${text(threshold["window_hours"])}h${match["require_state_unchanged"]===false?"":"\u30FB\u72B6\u614B\u4E0D\u5909"}`,action:`${str(action["skill"])}${str(action["args"])!==""?` ${str(action["args"])}`:""}\uFF08${str(action["priority"])}\uFF09`,block_source:action["block_source"]===true?"\u3042\u308A":"\u306A\u3057",revision:t["revision"]??""}}async function show(api,opts,io){const id=requireId(opts);const format=await formatOf(
|
package/package.json
CHANGED
package/dist/dist-HZIZTJ4O.js
DELETED
|
@@ -1,93 +0,0 @@
|
|
|
1
|
-
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
|
-
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
-
import"./chunk-VSJBJXZO.js";var isObject=obj=>{return obj!==null&&Object.prototype.toString.call(obj)==="[object Object]"};var strictDeepEqual=(first,second)=>{if(first===second){return true}if(typeof first!==typeof second){return false}if(Array.isArray(first)&&Array.isArray(second)){if(first.length!==second.length){return false}for(let i=0;i<first.length;i+=1){if(!strictDeepEqual(first[i],second[i])){return false}}return true}if(isObject(first)&&isObject(second)){const firstEntries=Object.entries(first);const secondKeys=new Set(
|
|
4
|
-
Object.keys(second));if(firstEntries.length!==secondKeys.size){return false}for(const[key,value]of firstEntries){if(!strictDeepEqual(value,second[key])){return false}secondKeys.delete(key)}return secondKeys.size===0}return false};var isFalse=obj=>{if(obj===null||obj===void 0||obj===false){return true}if(typeof obj==="string"){return obj===""}if(typeof obj==="object"){if(Array.isArray(obj)){return obj.length===0}if(obj===null){return true}return Object.keys(obj).length===0}return false};var isAlpha=ch=>{
|
|
5
|
-
return ch>="a"&&ch<="z"||ch>="A"&&ch<="Z"||ch==="_"};var isNum=ch=>{return ch>="0"&&ch<="9"||ch==="-"};var isAlphaNum=ch=>{return ch>="a"&&ch<="z"||ch>="A"&&ch<="Z"||ch>="0"&&ch<="9"||ch==="_"};var ensureInteger=value=>{if(!(typeof value==="number")||Math.floor(value)!==value){throw new Error("invalid-value: expecting an integer.")}return value};var ensurePositiveInteger=value=>{if(!(typeof value==="number")||value<0||Math.floor(value)!==value){throw new Error("invalid-value: expecting a non-neg\
|
|
6
|
-
ative integer.")}return value};var ensureNumbers=(...operands)=>{for(let i=0;i<operands.length;i++){if(operands[i]===null||operands[i]===void 0){throw new Error("not-a-number: undefined")}if(typeof operands[i]!=="number"){throw new Error("not-a-number")}}};var notZero=n=>{n=+n;if(!n){throw new Error("not-a-number: divide by zero")}return n};var add=(left,right)=>{ensureNumbers(left,right);const result=left+right;return result};var sub=(left,right)=>{ensureNumbers(left,right);const result=left-right;
|
|
7
|
-
return result};var mul=(left,right)=>{ensureNumbers(left,right);const result=left*right;return result};var divide=(left,right)=>{ensureNumbers(left,right);const result=left/notZero(right);return result};var div=(left,right)=>{ensureNumbers(left,right);const result=Math.floor(left/notZero(right));return result};var mod=(left,right)=>{ensureNumbers(left,right);const result=left%right;return result};var findFirst=(subject,sub2,start,end)=>{if(!subject||!sub2){return null}start=Math.max(ensureInteger(
|
|
8
|
-
start=start||0),0);end=Math.min(ensureInteger(end=end||subject.length),subject.length);const offset=subject.slice(start,end).indexOf(sub2);return offset===-1?null:offset+start};var findLast=(subject,sub2,start,end)=>{if(!subject||!sub2){return null}start=Math.max(ensureInteger(start=start||0),0);end=Math.min(ensureInteger(end=end||subject.length),subject.length);const offset=subject.slice(start,end).lastIndexOf(sub2);const result=offset===-1?null:offset+start;return result};var lower=subject=>subject.
|
|
9
|
-
toLowerCase();var ensurePadFuncParams=(name,width,padding)=>{padding=padding||" ";if(padding.length>1){throw new Error(`invalid value, ${name} expects its 'pad' parameter to be a valid string with a single codepoint`)}ensurePositiveInteger(width);return padding};var padLeft=(subject,width,padding)=>{padding=ensurePadFuncParams("pad_left",width,padding);return subject&&subject.padStart(width,padding)||""};var padRight=(subject,width,padding)=>{padding=ensurePadFuncParams("pad_right",width,padding);
|
|
10
|
-
return subject&&subject.padEnd(width,padding)||""};var replace=(subject,string,by,count)=>{if(count===0){return subject}if(!count){return subject.split(string).join(by)}ensurePositiveInteger(count);[...Array(count).keys()].map(()=>subject=subject.replace(string,by));return subject};var split=(subject,search2,count)=>{if(subject.length==0&&search2.length===0){return[]}if(count===null||count===void 0){return subject.split(search2)}ensurePositiveInteger(count);if(count===0){return[subject]}const split2=subject.
|
|
11
|
-
split(search2);return[...split2.slice(0,count),split2.slice(count).join(search2)]};var trim=(subject,chars)=>{return trimLeft(trimRight(subject,chars),chars)};var trimLeft=(subject,chars)=>{return trimImpl(subject,list=>new RegExp(`^[${list}]*(.*?)`),chars)};var trimRight=(subject,chars)=>{return trimImpl(subject,list=>new RegExp(`(.*?)[${list}]*$`),chars)};var trimImpl=(subject,regExper,chars)=>{const pattern=chars?chars.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&"):"\\s\x85";return subject.replace(regExper(
|
|
12
|
-
pattern),"$1")};var upper=subject=>subject.toUpperCase();var basicTokens={"(":"Lparen",")":"Rparen","*":"Star",",":"Comma",".":"Dot",":":"Colon","@":"Current","]":"Rbracket","{":"Lbrace","}":"Rbrace","+":"Plus","%":"Modulo","?":"Question","\u2212":"Minus","\xD7":"Multiply","\xF7":"Divide"};var operatorStartToken={"!":true,"<":true,"=":true,">":true,"&":true,"|":true,"/":true};var skipChars={" ":true,"\n":true,"\r":true," ":true};var StreamLexer=class{_current=0;_enable_legacy_literals=false;tokenize(stream,options){
|
|
13
|
-
const tokens=[];this._current=0;this._enable_legacy_literals=options?.enable_legacy_literals||false;let start;let identifier;let token;while(this._current<stream.length){if(isAlpha(stream[this._current])){start=this._current;identifier=this.consumeUnquotedIdentifier(stream);tokens.push({start,type:"UnquotedIdentifier",value:identifier})}else if(basicTokens[stream[this._current]]!==void 0){tokens.push({start:this._current,type:basicTokens[stream[this._current]],value:stream[this._current]});this.
|
|
14
|
-
_current+=1}else if(stream[this._current]==="$"){start=this._current;if(this._current+1<stream.length&&isAlpha(stream[this._current+1])){this._current+=1;identifier=this.consumeUnquotedIdentifier(stream);tokens.push({start,type:"Variable",value:identifier})}else{tokens.push({start,type:"Root",value:stream[this._current]});this._current+=1}}else if(stream[this._current]==="-"){if(this._current+1<stream.length&&isNum(stream[this._current+1])){const token2=this.consumeNumber(stream);token2&&tokens.
|
|
15
|
-
push(token2)}else{const token2={start:this._current,type:"Minus",value:"-"};tokens.push(token2);this._current+=1}}else if(isNum(stream[this._current])){token=this.consumeNumber(stream);tokens.push(token)}else if(stream[this._current]==="["){token=this.consumeLBracket(stream);tokens.push(token)}else if(stream[this._current]==='"'){start=this._current;identifier=this.consumeQuotedIdentifier(stream);tokens.push({start,type:"QuotedIdentifier",value:identifier})}else if(stream[this._current]===`'`){start=
|
|
16
|
-
this._current;identifier=this.consumeRawStringLiteral(stream);tokens.push({start,type:"Literal",value:identifier})}else if(stream[this._current]==="`"){start=this._current;const literal=this.consumeLiteral(stream);tokens.push({start,type:"Literal",value:literal})}else if(operatorStartToken[stream[this._current]]!==void 0){token=this.consumeOperator(stream);token&&tokens.push(token)}else if(skipChars[stream[this._current]]!==void 0){this._current+=1}else{const error=new Error(`Syntax error: unkno\
|
|
17
|
-
wn character: ${stream[this._current]}`);error.name="LexerError";throw error}}return tokens}consumeUnquotedIdentifier(stream){const start=this._current;this._current+=1;while(this._current<stream.length&&isAlphaNum(stream[this._current])){this._current+=1}return stream.slice(start,this._current)}consumeQuotedIdentifier(stream){const start=this._current;this._current+=1;const maxLength=stream.length;while(stream[this._current]!=='"'&&this._current<maxLength){let current=this._current;if(stream[current]===
|
|
18
|
-
"\\"&&(stream[current+1]==="\\"||stream[current+1]==='"')){current+=2}else{current+=1}this._current=current}this._current+=1;const[value,ok]=this.parseJSON(stream.slice(start,this._current));if(!ok){const error=new Error(`syntax: unexpected end of JSON input`);error.name="LexerError";throw error}return value}consumeRawStringLiteral(stream){const start=this._current;this._current+=1;const maxLength=stream.length;while(stream[this._current]!==`'`&&this._current<maxLength){let current=this._current;
|
|
19
|
-
if(stream[current]==="\\"&&(stream[current+1]==="\\"||stream[current+1]===`'`)){current+=2}else{current+=1}this._current=current}this._current+=1;const literal=stream.slice(start+1,this._current-1);return replace(replace(literal,`\\\\`,`\\`),`\\'`,`'`)}consumeNumber(stream){const start=this._current;this._current+=1;const maxLength=stream.length;while(isNum(stream[this._current])&&this._current<maxLength){this._current+=1}const value=parseInt(stream.slice(start,this._current),10);return{start,value,
|
|
20
|
-
type:"Number"}}consumeLBracket(stream){const start=this._current;this._current+=1;if(stream[this._current]==="?"){this._current+=1;return{start,type:"Filter",value:"[?"}}if(stream[this._current]==="]"){this._current+=1;return{start,type:"Flatten",value:"[]"}}return{start,type:"Lbracket",value:"["}}consumeOrElse(stream,peek,token,orElse){const start=this._current;this._current+=1;if(this._current<stream.length&&stream[this._current]===peek){this._current+=1;return{start,type:orElse,value:stream.slice(
|
|
21
|
-
start,this._current)}}return{start,type:token,value:stream[start]}}consumeOperator(stream){const start=this._current;const startingChar=stream[start];switch(startingChar){case"!":return this.consumeOrElse(stream,"=","Not","NE");case"<":return this.consumeOrElse(stream,"=","LT","LTE");case">":return this.consumeOrElse(stream,"=","GT","GTE");case"=":return this.consumeOrElse(stream,"=","Assign","EQ");case"&":return this.consumeOrElse(stream,"&","Expref","And");case"|":return this.consumeOrElse(stream,
|
|
22
|
-
"|","Pipe","Or");case"/":return this.consumeOrElse(stream,"/","Divide","Div")}}consumeLiteral(stream){this._current+=1;const start=this._current;const maxLength=stream.length;while(stream[this._current]!=="`"&&this._current<maxLength){let current=this._current;if(stream[current]==="\\"&&(stream[current+1]==="\\"||stream[current+1]==="`")){current+=2}else{current+=1}this._current=current}let literalString=stream.slice(start,this._current).trimStart();literalString=literalString.replace("\\`","`");
|
|
23
|
-
let literal=null;let ok=false;if(this.looksLikeJSON(literalString)){[literal,ok]=this.parseJSON(literalString)}if(!ok&&this._enable_legacy_literals){[literal,ok]=this.parseJSON(`"${literalString}"`)}if(!ok){const error=new Error(`Syntax error: unexpected end of JSON input or invalid format for a JSON literal: ${stream[this._current]}`);error.name="LexerError";throw error}this._current+=1;return literal}looksLikeJSON(literalString){const startingChars='[{"';const jsonLiterals=["true","false","nul\
|
|
24
|
-
l"];const numberLooking="-0123456789";if(literalString===""){return false}if(startingChars.includes(literalString[0])){return true}if(jsonLiterals.includes(literalString)){return true}if(numberLooking.includes(literalString[0])){const[_,ok]=this.parseJSON(literalString);return ok}return false}parseJSON(text){try{const json=JSON.parse(text);return[json,true]}catch{return[null,false]}}};var Lexer=new StreamLexer;var Lexer_default=Lexer;var bindingPower={["EOF"]:0,["Variable"]:0,["UnquotedIdentifie\
|
|
25
|
-
r"]:0,["QuotedIdentifier"]:0,["Rbracket"]:0,["Rparen"]:0,["Comma"]:0,["Rbrace"]:0,["Number"]:0,["Current"]:0,["Expref"]:0,["Root"]:0,["Assign"]:1,["Pipe"]:1,["Question"]:2,["Or"]:3,["And"]:4,["EQ"]:5,["GT"]:5,["LT"]:5,["GTE"]:5,["LTE"]:5,["NE"]:5,["Minus"]:6,["Plus"]:6,["Div"]:7,["Divide"]:7,["Modulo"]:7,["Multiply"]:7,["Flatten"]:9,["Star"]:20,["Filter"]:21,["Dot"]:40,["Not"]:45,["Lbrace"]:50,["Lbracket"]:55,["Lparen"]:60};var TokenParser=class _TokenParser{index=0;tokens=[];parse(expression,options){
|
|
26
|
-
this.loadTokens(expression,options||{enable_legacy_literals:false});this.index=0;const ast=this.expression(0);if(this.lookahead(0)!=="EOF"){const token=this.lookaheadToken(0);this.errorToken(token,`Syntax error: unexpected token type: ${token.type}, value: ${token.value}`)}return ast}loadTokens(expression,options){this.tokens=Lexer_default.tokenize(expression,options);this.tokens.push({type:"EOF",value:"",start:expression.length})}expression(rbp){const leftToken=this.lookaheadToken(0);this.advance();
|
|
27
|
-
let left=this.nud(leftToken);let currentTokenType=this.lookahead(0);while(rbp<bindingPower[currentTokenType]){this.advance();left=this.led(currentTokenType,left);currentTokenType=this.lookahead(0)}return left}lookahead(offset){return this.tokens[this.index+offset].type}lookaheadToken(offset){return this.tokens[this.index+offset]}advance(){this.index+=1}nud(token){switch(token.type){case"Variable":return{type:"Variable",name:token.value};case"Literal":return{type:"Literal",value:token.value};case"\
|
|
28
|
-
UnquotedIdentifier":{if(_TokenParser.isKeyword(token,"let")&&this.lookahead(0)==="Variable"){return this.parseLetExpression()}else{return{type:"Field",name:token.value}}}case"QuotedIdentifier":if(this.lookahead(0)==="Lparen"){throw new Error("Syntax error: quoted identifier not allowed for function names.")}else{return{type:"Field",name:token.value}}case"Not":{const child=this.expression(bindingPower.Not);return{type:"NotExpression",child}}case"Minus":{const child=this.expression(bindingPower.Minus);
|
|
29
|
-
return{type:"Unary",operator:token.type,operand:child}}case"Plus":{const child=this.expression(bindingPower.Plus);return{type:"Unary",operator:token.type,operand:child}}case"Star":{const left={type:"Identity"};return{type:"ValueProjection",left,right:this.parseProjectionRHS(bindingPower.Star)}}case"Filter":return this.led(token.type,{type:"Identity"});case"Lbrace":return this.parseMultiselectHash();case"Flatten":{const left={type:"Flatten",child:{type:"Identity"}};const right=this.parseProjectionRHS(
|
|
30
|
-
bindingPower.Flatten);return{type:"Projection",left,right}}case"Lbracket":{if(this.lookahead(0)==="Number"||this.lookahead(0)==="Colon"){const right=this.parseIndexExpression();return this.projectIfSlice({type:"Identity"},right)}if(this.lookahead(0)==="Star"&&this.lookahead(1)==="Rbracket"){this.advance();this.advance();const right=this.parseProjectionRHS(bindingPower.Star);return{left:{type:"Identity"},right,type:"Projection"}}return this.parseMultiselectList()}case"Current":return{type:"Curren\
|
|
31
|
-
t"};case"Root":return{type:"Root"};case"Expref":{const child=this.expression(bindingPower.Expref);return{type:"ExpressionReference",child}}case"Lparen":{const expression=this.expression(0);this.match("Rparen");return expression}default:this.errorToken(token)}}led(tokenName,left){switch(tokenName){case"Question":{const trueExpr=this.expression(0);this.match("Colon");const falseExpr=this.expression(0);return{type:"Ternary",condition:left,trueExpr,falseExpr}}case"Dot":{const rbp=bindingPower.Dot;if(this.
|
|
32
|
-
lookahead(0)!=="Star"){const right2=this.parseDotRHS(rbp);return{type:"Subexpression",left,right:right2}}this.advance();const right=this.parseProjectionRHS(rbp);return{type:"ValueProjection",left,right}}case"Pipe":{const right=this.expression(bindingPower.Pipe);return{type:"Pipe",left,right}}case"Or":{const right=this.expression(bindingPower.Or);return{type:"OrExpression",left,right}}case"And":{const right=this.expression(bindingPower.And);return{type:"AndExpression",left,right}}case"Lparen":{if(left.
|
|
33
|
-
type!=="Field"){throw new Error("Syntax error: expected a Field node")}const name=left.name;const args=this.parseCommaSeparatedExpressionsUntilToken("Rparen");const node={name,type:"Function",children:args};return node}case"Filter":{const condition=this.expression(0);this.match("Rbracket");const right=this.lookahead(0)==="Flatten"?{type:"Identity"}:this.parseProjectionRHS(bindingPower.Filter);return{type:"FilterProjection",left,right,condition}}case"Flatten":{const leftNode={type:"Flatten",child:left};
|
|
34
|
-
const right=this.parseProjectionRHS(bindingPower.Flatten);return{type:"Projection",left:leftNode,right}}case"Assign":{const leftNode=left;const right=this.expression(0);return{type:"Binding",variable:leftNode.name,reference:right}}case"EQ":case"NE":case"GT":case"GTE":case"LT":case"LTE":return this.parseComparator(left,tokenName);case"Plus":case"Minus":case"Multiply":case"Star":case"Divide":case"Modulo":case"Div":return this.parseArithmetic(left,tokenName);case"Lbracket":{const token=this.lookaheadToken(
|
|
35
|
-
0);if(token.type==="Number"||token.type==="Colon"){const right2=this.parseIndexExpression();return this.projectIfSlice(left,right2)}this.match("Star");this.match("Rbracket");const right=this.parseProjectionRHS(bindingPower.Star);return{type:"Projection",left,right}}default:return this.errorToken(this.lookaheadToken(0))}}static isKeyword(token,keyword){return token.type==="UnquotedIdentifier"&&token.value===keyword}match(tokenType){if(this.lookahead(0)===tokenType){this.advance();return}else{const token=this.
|
|
36
|
-
lookaheadToken(0);this.errorToken(token,`Syntax error: expected ${tokenType}, got: ${token.type}`)}}errorToken(token,message=""){const error=new Error(message||`Syntax error: invalid token (${token.type}): "${token.value}"`);error.name="ParserError";throw error}parseIndexExpression(){if(this.lookahead(0)==="Colon"||this.lookahead(1)==="Colon"){return this.parseSliceExpression()}const value=Number(this.lookaheadToken(0).value);this.advance();this.match("Rbracket");return{type:"Index",value}}projectIfSlice(left,right){
|
|
37
|
-
const indexExpr={type:"IndexExpression",left,right};if(right.type==="Slice"){return{left:indexExpr,right:this.parseProjectionRHS(bindingPower.Star),type:"Projection"}}return indexExpr}parseSliceExpression(){const parts=[null,null,null];let index=0;let current=this.lookaheadToken(0);while(current.type!="Rbracket"&&index<3){if(current.type==="Colon"){index++;if(index===3){this.errorToken(this.lookaheadToken(0),"Syntax error, too many colons in slice expression")}this.advance()}else if(current.type===
|
|
38
|
-
"Number"){const part=this.lookaheadToken(0).value;parts[index]=part;this.advance()}else{const next=this.lookaheadToken(0);this.errorToken(next,`Syntax error, unexpected token: ${next.value}(${next.type})`)}current=this.lookaheadToken(0)}this.match("Rbracket");const[start,stop,step]=parts;return{type:"Slice",start,stop,step}}parseLetExpression(){const separated=this.parseCommaSeparatedExpressionsUntilKeyword("in");const expression=this.expression(0);const bindings=separated.map(binding=>binding);
|
|
39
|
-
return{type:"LetExpression",bindings,expression}}parseCommaSeparatedExpressionsUntilKeyword(keyword){return this.parseCommaSeparatedExpressionsUntil(()=>{return _TokenParser.isKeyword(this.lookaheadToken(0),keyword)},()=>{this.advance()})}parseCommaSeparatedExpressionsUntilToken(token){return this.parseCommaSeparatedExpressionsUntil(()=>{return this.lookahead(0)===token},()=>{return this.match(token)})}parseCommaSeparatedExpressionsUntil(isEndToken,matchEndToken){const args=[];let expression;while(!isEndToken()){
|
|
40
|
-
expression=this.expression(0);if(this.lookahead(0)==="Comma"){this.match("Comma")}args.push(expression)}matchEndToken();return args}parseComparator(left,comparator){const right=this.expression(bindingPower[comparator]);return{type:"Comparator",name:comparator,left,right}}parseArithmetic(left,operator){const right=this.expression(bindingPower[operator]);return{type:"Arithmetic",operator,left,right}}parseDotRHS(rbp){const lookahead=this.lookahead(0);const exprTokens=["UnquotedIdentifier","QuotedId\
|
|
41
|
-
entifier","Star"];if(exprTokens.includes(lookahead)){return this.expression(rbp)}if(lookahead==="Lbracket"){this.match("Lbracket");return this.parseMultiselectList()}if(lookahead==="Lbrace"){this.match("Lbrace");return this.parseMultiselectHash()}const token=this.lookaheadToken(0);this.errorToken(token,`Syntax error, unexpected token: ${token.value}(${token.type})`)}parseProjectionRHS(rbp){if(bindingPower[this.lookahead(0)]<10){return{type:"Identity"}}if(this.lookahead(0)==="Lbracket"){return this.
|
|
42
|
-
expression(rbp)}if(this.lookahead(0)==="Filter"){return this.expression(rbp)}if(this.lookahead(0)==="Dot"){this.match("Dot");return this.parseDotRHS(rbp)}const token=this.lookaheadToken(0);this.errorToken(token,`Syntax error, unexpected token: ${token.value}(${token.type})`)}parseMultiselectList(){const expressions=[];while(this.lookahead(0)!=="Rbracket"){const expression=this.expression(0);expressions.push(expression);if(this.lookahead(0)==="Comma"){this.match("Comma");if(this.lookahead(0)==="R\
|
|
43
|
-
bracket"){throw new Error("Syntax error: unexpected token Rbracket")}}}this.match("Rbracket");return{type:"MultiSelectList",children:expressions}}parseMultiselectHash(){const pairs=[];const identifierTypes=["UnquotedIdentifier","QuotedIdentifier"];let keyToken;let keyName;let value;for(;;){keyToken=this.lookaheadToken(0);if(!identifierTypes.includes(keyToken.type)){throw new Error(`Syntax error: expecting an identifier token, got: ${keyToken.type}`)}keyName=keyToken.value;this.advance();this.match(
|
|
44
|
-
"Colon");value=this.expression(0);pairs.push({value,type:"KeyValuePair",name:keyName});if(this.lookahead(0)==="Comma"){this.match("Comma")}else if(this.lookahead(0)==="Rbrace"){this.match("Rbrace");break}}return{type:"MultiSelectHash",children:pairs}}};var Parser=new TokenParser;var Parser_default=Parser;var Text=class _Text{_text;constructor(text){this._text=text}get string(){return this._text}get length(){return this.codePoints.length}compareTo(other){return _Text.compare(this,new _Text(other))}static get comparer(){
|
|
45
|
-
const stringComparer=(left,right)=>{return new _Text(left).compareTo(right)};return stringComparer}static compare(left,right){const leftCp=left.codePoints;const rightCp=right.codePoints;for(let index=0;index<Math.min(leftCp.length,rightCp.length);index++){if(leftCp[index]===rightCp[index]){continue}return leftCp[index]-rightCp[index]>0?1:-1}return leftCp.length-rightCp.length>0?1:-1}reverse(){return String.fromCodePoint(...this.codePoints.reverse())}get codePoints(){const array=[...this._text].map(
|
|
46
|
-
s=>s.codePointAt(0));return array}};var createMathFunction=mathFn=>([value])=>mathFn(value);var createStringFunction=stringFn=>([subject])=>stringFn(subject);var createObjectFunction=objFn=>([obj])=>objFn(obj);var Runtime=class{_interpreter;_functionTable;_customFunctions=new Set;TYPE_NAME_TABLE=Object.freeze({[0]:"number",[1]:"any",[2]:"string",[3]:"array",[4]:"object",[5]:"boolean",[6]:"expression",[7]:"null",[8]:"Array<number>",[10]:"Array<object>",[9]:"Array<string>",[11]:"Array<Array<any>>"});constructor(interpreter){
|
|
47
|
-
this._interpreter=interpreter;this._functionTable=this.buildFunctionTable()}buildFunctionTable(){return{abs:{_func:createMathFunction(Math.abs),_signature:[{types:[0]}]},ceil:{_func:createMathFunction(Math.ceil),_signature:[{types:[0]}]},floor:{_func:createMathFunction(Math.floor),_signature:[{types:[0]}]},lower:{_func:createStringFunction(lower),_signature:[{types:[2]}]},upper:{_func:createStringFunction(upper),_signature:[{types:[2]}]},keys:{_func:createObjectFunction(Object.keys),_signature:[
|
|
48
|
-
{types:[4]}]},values:{_func:createObjectFunction(Object.values),_signature:[{types:[4]}]},avg:{_func:this.functionAvg,_signature:[{types:[8]}]},contains:{_func:this.functionContains,_signature:[{types:[2,3]},{types:[1]}]},ends_with:{_func:this.functionEndsWith,_signature:[{types:[2]},{types:[2]}]},find_first:{_func:this.functionFindFirst,_signature:[{types:[2]},{types:[2]},{types:[0],optional:true},{types:[0],optional:true}]},find_last:{_func:this.functionFindLast,_signature:[{types:[2]},{types:[
|
|
49
|
-
2]},{types:[0],optional:true},{types:[0],optional:true}]},from_items:{_func:this.functionFromItems,_signature:[{types:[11]}]},group_by:{_func:this.functionGroupBy,_signature:[{types:[3]},{types:[6]}]},items:{_func:this.functionItems,_signature:[{types:[4]}]},join:{_func:this.functionJoin,_signature:[{types:[2]},{types:[9]}]},length:{_func:this.functionLength,_signature:[{types:[2,3,4]}]},map:{_func:this.functionMap,_signature:[{types:[6]},{types:[3]}]},max:{_func:this.functionMax,_signature:[{types:[
|
|
50
|
-
8,9]}]},max_by:{_func:this.functionMaxBy,_signature:[{types:[3]},{types:[6]}]},merge:{_func:this.functionMerge,_signature:[{types:[4],variadic:true}]},min:{_func:this.functionMin,_signature:[{types:[8,9]}]},min_by:{_func:this.functionMinBy,_signature:[{types:[3]},{types:[6]}]},not_null:{_func:this.functionNotNull,_signature:[{types:[1],variadic:true}]},pad_left:{_func:this.functionPadLeft,_signature:[{types:[2]},{types:[0]},{types:[2],optional:true}]},pad_right:{_func:this.functionPadRight,_signature:[
|
|
51
|
-
{types:[2]},{types:[0]},{types:[2],optional:true}]},replace:{_func:this.functionReplace,_signature:[{types:[2]},{types:[2]},{types:[2]},{types:[0],optional:true}]},reverse:{_func:this.functionReverse,_signature:[{types:[2,3]}]},sort:{_func:this.functionSort,_signature:[{types:[9,8]}]},sort_by:{_func:this.functionSortBy,_signature:[{types:[3]},{types:[6]}]},split:{_func:this.functionSplit,_signature:[{types:[2]},{types:[2]},{types:[0],optional:true}]},starts_with:{_func:this.functionStartsWith,_signature:[
|
|
52
|
-
{types:[2]},{types:[2]}]},sum:{_func:this.functionSum,_signature:[{types:[8]}]},to_array:{_func:this.functionToArray,_signature:[{types:[1]}]},to_number:{_func:this.functionToNumber,_signature:[{types:[1]}]},to_string:{_func:this.functionToString,_signature:[{types:[1]}]},trim:{_func:this.functionTrim,_signature:[{types:[2]},{types:[2],optional:true}]},trim_left:{_func:this.functionTrimLeft,_signature:[{types:[2]},{types:[2],optional:true}]},trim_right:{_func:this.functionTrimRight,_signature:[{
|
|
53
|
-
types:[2]},{types:[2],optional:true}]},type:{_func:this.functionType,_signature:[{types:[1]}]},zip:{_func:this.functionZip,_signature:[{types:[3],variadic:true}]}}}registerFunction(name,customFunction,signature,options){const result=this._registerInternal(name,customFunction,signature,options);if(!result.success){throw new Error(result.message)}}_registerInternal(name,customFunction,signature,options={}){if(!name||typeof name!=="string"||name.trim()===""){return{success:false,reason:"invalid-nam\
|
|
54
|
-
e",message:"Function name must be a non-empty string"}}try{this.validateInputSignatures(name,signature)}catch(error){return{success:false,reason:"invalid-signature",message:error instanceof Error?error.message:"Invalid function signature"}}const{override=false,warn=false}=options;const exists=name in this._functionTable;if(exists&&!override){return{success:false,reason:"already-exists",message:`Function already defined: ${name}(). Use { override: true } to replace it.`}}if(exists&&override&&warn){
|
|
55
|
-
console.warn(`Warning: Overriding existing function: ${name}()`)}this._functionTable[name]={_func:customFunction.bind(this),_signature:signature};this._customFunctions.add(name);const message=exists?`Function ${name}() overridden successfully`:`Function ${name}() registered successfully`;return{success:true,message}}register(name,customFunction,signature,options={}){return this._registerInternal(name,customFunction,signature,options)}unregister(name){if(!this._customFunctions.has(name)){return false}
|
|
56
|
-
delete this._functionTable[name];this._customFunctions.delete(name);return true}isRegistered(name){return name in this._functionTable}getRegistered(){return Object.keys(this._functionTable)}getCustomFunctions(){return Array.from(this._customFunctions)}clearCustomFunctions(){for(const name of this._customFunctions){delete this._functionTable[name]}this._customFunctions.clear()}callFunction(name,resolvedArgs){const functionEntry=this._functionTable[name];if(functionEntry===void 0){throw new Error(
|
|
57
|
-
`Unknown function: ${name}()`)}this.validateArgs(name,resolvedArgs,functionEntry._signature);return functionEntry._func.call(this,resolvedArgs)}validateInputSignatures(name,signature){for(let i=0;i<signature.length;i+=1){if("variadic"in signature[i]&&i!==signature.length-1){throw new Error(`Invalid arity: ${name}() 'variadic' argument ${i+1} must occur last`)}}}validateArgs(name,args,signature){this.validateInputSignatures(name,signature);this.validateArity(name,args,signature);this.validateTypes(
|
|
58
|
-
name,args,signature)}validateArity(name,args,signature){const numberOfRequiredArgs=signature.filter(argSignature=>!(argSignature.optional??false)).length;const lastArgIsVariadic=signature[signature.length-1]?.variadic??false;const tooFewArgs=args.length<numberOfRequiredArgs;const tooManyArgs=args.length>signature.length;if(lastArgIsVariadic&&tooFewArgs||!lastArgIsVariadic&&(tooFewArgs||tooManyArgs)){const tooFewModifier=tooFewArgs&&(!lastArgIsVariadic&&numberOfRequiredArgs>1||lastArgIsVariadic)?
|
|
59
|
-
"at least ":"";const pluralized=signature.length>1;throw new Error(`Invalid arity: ${name}() takes ${tooFewModifier}${numberOfRequiredArgs} argument${pluralized&&"s"||""} but received ${args.length}`)}}validateTypes(name,args,signature){for(let i=0;i<signature.length;i+=1){const currentSpec=signature[i].types;const actualType=this.getTypeName(args[i]);if(actualType===void 0){continue}const typeMatched=currentSpec.some(expectedType=>this.typeMatches(actualType,expectedType,args[i]));if(!typeMatched){
|
|
60
|
-
const expected=currentSpec.map(typeId=>this.TYPE_NAME_TABLE[typeId]).join(" | ");throw new Error(`Invalid type: ${name}() expected argument ${i+1} to be type (${expected}) but received type ${this.TYPE_NAME_TABLE[actualType]} instead.`)}}}typeMatches(actual,expected,argValue){if(expected===1){return true}if(expected===9||expected===8||expected===10||expected===11||expected===3){if(expected===3){return actual===3}if(actual===3){let subtype;if(expected===8){subtype=0}else if(expected===10){subtype=
|
|
61
|
-
4}else if(expected===9){subtype=2}else if(expected===11){subtype=3}const array=argValue;for(let i=0;i<array.length;i+=1){const typeName=this.getTypeName(array[i]);if(typeName!==void 0&&subtype!==void 0&&!this.typeMatches(typeName,subtype,array[i])){return false}}return true}}else{return actual===expected}return false}getTypeName(obj){if(obj===null){return 7}if(typeof obj==="string"){return 2}if(typeof obj==="number"){return 0}if(typeof obj==="boolean"){return 5}if(Array.isArray(obj)){return 3}if(typeof obj===
|
|
62
|
-
"object"){if(obj.expref){return 6}return 4}return}createKeyFunction(exprefNode,allowedTypes){const interpreter=this._interpreter;const keyFunc=x=>{const current=interpreter.visit(exprefNode,x);if(!allowedTypes.includes(this.getTypeName(current))){const msg=`Invalid type: expected one of (${allowedTypes.map(t=>this.TYPE_NAME_TABLE[t]).join(" | ")}), received ${this.TYPE_NAME_TABLE[this.getTypeName(current)]}`;throw new Error(msg)}return current};return keyFunc}functionAvg=([inputArray])=>{if(!inputArray||
|
|
63
|
-
inputArray.length==0){return null}let sum=0;for(let i=0;i<inputArray.length;i+=1){sum+=inputArray[i]}return sum/inputArray.length};functionContains=([searchable,searchValue])=>{if(Array.isArray(searchable)){const array=searchable;return array.includes(searchValue)}if(typeof searchable==="string"){const text=searchable;if(typeof searchValue==="string"){return text.includes(searchValue)}}return null};functionEndsWith=resolvedArgs=>{const[searchStr,suffix]=resolvedArgs;return searchStr.includes(suffix,
|
|
64
|
-
searchStr.length-suffix.length)};functionFindFirst=this.createFindFunction(findFirst);functionFindLast=this.createFindFunction(findLast);createFindFunction(findFn){return resolvedArgs=>{const subject=resolvedArgs[0];const search2=resolvedArgs[1];const start=resolvedArgs.length>2?resolvedArgs[2]:void 0;const end=resolvedArgs.length>3?resolvedArgs[3]:void 0;return findFn(subject,search2,start,end)}}functionFromItems=([array])=>{array.map(pair=>{if(pair.length!=2||typeof pair[0]!=="string"){throw new Error(
|
|
65
|
-
"invalid value, each array must contain two elements, a pair of string and value")}});return Object.fromEntries(array)};functionGroupBy=([array,exprefNode])=>{const keyFunction=this.createKeyFunction(exprefNode,[2]);return array.reduce((acc,cur)=>{const k=keyFunction(cur??{});const target=acc[k]=acc[k]||[];target.push(cur);return acc},{})};functionItems=([inputValue])=>{return Object.entries(inputValue)};functionJoin=resolvedArgs=>{const[joinChar,listJoin]=resolvedArgs;return listJoin.join(joinChar)};functionLength=([
|
|
66
|
-
inputValue])=>{if(typeof inputValue==="string"){return new Text(inputValue).length}if(Array.isArray(inputValue)){return inputValue.length}return Object.keys(inputValue).length};functionMap=([exprefNode,elements])=>{if(!this._interpreter){return[]}const mapped=[];const interpreter=this._interpreter;for(let i=0;i<elements.length;i+=1){mapped.push(interpreter.visit(exprefNode,elements[i]))}return mapped};functionMax=([inputValue])=>{if(!inputValue.length){return null}const typeName=this.getTypeName(
|
|
67
|
-
inputValue[0]);if(typeName===0){return Math.max(...inputValue)}const elements=inputValue;let maxElement=elements[0];for(let i=1;i<elements.length;i+=1){if(maxElement.localeCompare(elements[i])<0){maxElement=elements[i]}}return maxElement};functionMaxBy=resolvedArgs=>{const exprefNode=resolvedArgs[1];const resolvedArray=resolvedArgs[0];const keyFunction=this.createKeyFunction(exprefNode,[0,2]);let maxNumber=-Infinity;let maxRecord;let current;for(let i=0;i<resolvedArray.length;i+=1){current=keyFunction&&
|
|
68
|
-
keyFunction(resolvedArray[i]);if(current!==void 0&¤t>maxNumber){maxNumber=current;maxRecord=resolvedArray[i]}}return maxRecord||null};functionMerge=resolvedArgs=>{let merged={};for(let i=0;i<resolvedArgs.length;i+=1){const current=resolvedArgs[i];merged=Object.assign(merged,current)}return merged};functionMin=([inputValue])=>{if(!inputValue.length){return null}const typeName=this.getTypeName(inputValue[0]);if(typeName===0){return Math.min(...inputValue)}const elements=inputValue;let minElement=elements[0];
|
|
69
|
-
for(let i=1;i<elements.length;i+=1){if(elements[i].localeCompare(minElement)<0){minElement=elements[i]}}return minElement};functionMinBy=resolvedArgs=>{const exprefNode=resolvedArgs[1];const resolvedArray=resolvedArgs[0];const keyFunction=this.createKeyFunction(exprefNode,[0,2]);let minNumber=Infinity;let minRecord;let current;for(let i=0;i<resolvedArray.length;i+=1){current=keyFunction&&keyFunction(resolvedArray[i]);if(current!==void 0&¤t<minNumber){minNumber=current;minRecord=resolvedArray[i]}}
|
|
70
|
-
return minRecord||null};functionNotNull=resolvedArgs=>{for(let i=0;i<resolvedArgs.length;i+=1){if(this.getTypeName(resolvedArgs[i])!==7){return resolvedArgs[i]}}return null};functionPadLeft=this.createPadFunction(padLeft);functionPadRight=this.createPadFunction(padRight);createPadFunction(padFn){return resolvedArgs=>{const subject=resolvedArgs[0];const width=resolvedArgs[1];const padding=resolvedArgs.length>2?resolvedArgs[2]:void 0;return padFn(subject,width,padding)}}functionReplace=resolvedArgs=>{
|
|
71
|
-
const subject=resolvedArgs[0];const string=resolvedArgs[1];const by=resolvedArgs[2];return replace(subject,string,by,resolvedArgs.length>3?resolvedArgs[3]:void 0)};functionSplit=resolvedArgs=>{const subject=resolvedArgs[0];const search2=resolvedArgs[1];return split(subject,search2,resolvedArgs.length>2?resolvedArgs[2]:void 0)};functionReverse=([inputValue])=>{const typeName=this.getTypeName(inputValue);if(typeName===2){return new Text(inputValue).reverse()}const reversedArray=inputValue.slice(0);
|
|
72
|
-
reversedArray.reverse();return reversedArray};functionSort=([inputValue])=>{if(inputValue.length==0){return inputValue}if(typeof inputValue[0]==="string"){return[...inputValue].sort(Text.comparer)}return[...inputValue].sort()};functionSortBy=resolvedArgs=>{const sortedArray=resolvedArgs[0].slice(0);if(sortedArray.length===0){return sortedArray}const interpreter=this._interpreter;const exprefNode=resolvedArgs[1];const requiredType=this.getTypeName(interpreter.visit(exprefNode,sortedArray[0]));if(requiredType!==
|
|
73
|
-
void 0&&![0,2].includes(requiredType)){throw new Error(`Invalid type: unexpected type (${this.TYPE_NAME_TABLE[requiredType]})`)}function throwInvalidTypeError(rt,item){throw new Error(`Invalid type: expected (${rt.TYPE_NAME_TABLE[requiredType]}), received ${rt.TYPE_NAME_TABLE[rt.getTypeName(item)]}`)}return sortedArray.sort((a,b)=>{const exprA=interpreter.visit(exprefNode,a);const exprB=interpreter.visit(exprefNode,b);if(this.getTypeName(exprA)!==requiredType){throwInvalidTypeError(this,exprA)}else if(this.
|
|
74
|
-
getTypeName(exprB)!==requiredType){throwInvalidTypeError(this,exprB)}if(requiredType===2){return Text.comparer(exprA,exprB)}return exprA-exprB})};functionStartsWith=([searchable,searchStr])=>{return searchable.startsWith(searchStr)};functionSum=([inputValue])=>{return inputValue.reduce((x,y)=>x+y,0)};functionToArray=([inputValue])=>{if(this.getTypeName(inputValue)===3){return inputValue}return[inputValue]};functionToNumber=([inputValue])=>{const typeName=this.getTypeName(inputValue);let convertedValue;
|
|
75
|
-
if(typeName===0){return inputValue}if(typeName===2){convertedValue=+inputValue;if(!isNaN(convertedValue)){return convertedValue}}return null};functionToString=([inputValue])=>{if(this.getTypeName(inputValue)===2){return inputValue}return JSON.stringify(inputValue)};functionTrim=this.createTrimFunction(trim);functionTrimLeft=this.createTrimFunction(trimLeft);functionTrimRight=this.createTrimFunction(trimRight);createTrimFunction(trimFn){return resolvedArgs=>{const subject=resolvedArgs[0];const chars=resolvedArgs.
|
|
76
|
-
length>1?resolvedArgs[1]:void 0;return trimFn(subject,chars)}}functionType=([inputValue])=>{switch(this.getTypeName(inputValue)){case 0:return"number";case 2:return"string";case 3:return"array";case 4:return"object";case 5:return"boolean";case 7:return"null";default:throw new Error("invalid-type")}};functionZip=array=>{const length=Math.min(...array.map(arr=>arr.length));const result=Array(length).fill(null).map((_,index)=>array.map(arr=>arr[index]));return result}};var ScopeChain=class _ScopeChain{inner=void 0;data={};get currentScopeData(){
|
|
77
|
-
return this.data}withScope(data){const outer=new _ScopeChain;outer.inner=this;outer.data=data;return outer}getValue(identifier){if(Object.prototype.hasOwnProperty.call(this.data,identifier)){return this.data[identifier]}if(this.inner){return this.inner.getValue(identifier)}return null}};var emptyScopeChain=new ScopeChain;var TreeInterpreter=class _TreeInterpreter{runtime;_rootValue=null;_scope;constructor(){this.runtime=new Runtime(this);this._scope=new ScopeChain}withScope(scope){const interpreter=new _TreeInterpreter;
|
|
78
|
-
interpreter.runtime._functionTable=this.runtime._functionTable;interpreter._rootValue=this._rootValue;interpreter._scope=this._scope.withScope(scope);return interpreter}search(node,value){this._rootValue=value;this._scope=emptyScopeChain;return this.visit(node,value)}visit(node,value){switch(node.type){case"Ternary":{const condition=this.visit(node.condition,value);if(!isFalse(condition)){return this.visit(node.trueExpr,value)}return this.visit(node.falseExpr,value)}case"Field":const identifier=node.
|
|
79
|
-
name;if(value===null||typeof value!=="object"||Array.isArray(value)){return null}return value[identifier]??null;case"LetExpression":{const{bindings,expression}=node;let scope={};bindings.forEach(binding=>{const reference=this.visit(binding,value);scope={...scope,...reference}});return this.withScope(scope).visit(expression,value)}case"Binding":{const{variable,reference}=node;const result=this.visit(reference,value);return{[variable]:result}}case"Variable":{const variable=node.name;if(!this._scope.
|
|
80
|
-
getValue(variable)&&!Object.prototype.hasOwnProperty.call(this._scope.currentScopeData,variable)){throw new Error(`Error referencing undefined variable ${variable}`)}return this._scope.getValue(variable)}case"IndexExpression":return this.visit(node.right,this.visit(node.left,value));case"Subexpression":{const result=this.visit(node.left,value);return result!=null?this.visit(node.right,result)??null:null}case"Index":{if(!Array.isArray(value)){return null}const index=node.value<0?value.length+node.
|
|
81
|
-
value:node.value;return value[index]??null}case"Slice":{if(!Array.isArray(value)&&typeof value!=="string"){return null}const{start,stop,step}=this.computeSliceParams(value.length,node);if(typeof value==="string"){const chars=[...value];const sliced=this.slice(chars,start,stop,step);return sliced.join("")}else{return this.slice(value,start,stop,step)}}case"Projection":{const{left,right}=node;let allowString=false;if(left.type==="IndexExpression"&&left.right.type==="Slice"){allowString=true}const base=this.
|
|
82
|
-
visit(left,value);if(allowString&&typeof base==="string"){return this.visit(right,base)}if(!Array.isArray(base)){return null}const collected=[];for(const elem of base){const current=this.visit(right,elem);if(current!==null){collected.push(current)}}return collected}case"ValueProjection":{const{left,right}=node;const base=this.visit(left,value);if(base===null||typeof base!=="object"||Array.isArray(base)){return null}const collected=[];const values=Object.values(base);for(const elem of values){const current=this.
|
|
83
|
-
visit(right,elem);if(current!==null){collected.push(current)}}return collected}case"FilterProjection":{const{left,right,condition}=node;const base=this.visit(left,value);if(!Array.isArray(base)){return null}const results=[];for(const elem of base){const matched=this.visit(condition,elem);if(isFalse(matched)){continue}const result=this.visit(right,elem);if(result!==null){results.push(result)}}return results}case"Arithmetic":{const first=this.visit(node.left,value);const second=this.visit(node.right,
|
|
84
|
-
value);switch(node.operator){case"Plus":return add(first,second);case"Minus":return sub(first,second);case"Multiply":case"Star":return mul(first,second);case"Divide":return divide(first,second);case"Modulo":return mod(first,second);case"Div":return div(first,second);default:throw new Error(`Syntax error: unknown arithmetic operator: ${node.operator}`)}}case"Unary":{const operand=this.visit(node.operand,value);switch(node.operator){case"Plus":ensureNumbers(operand);return operand;case"Minus":ensureNumbers(
|
|
85
|
-
operand);return-operand;default:throw new Error(`Syntax error: unknown arithmetic operator: ${node.operator}`)}}case"Comparator":{const first=this.visit(node.left,value);const second=this.visit(node.right,value);switch(node.name){case"EQ":return strictDeepEqual(first,second);case"NE":return!strictDeepEqual(first,second)}if(typeof first!=="number"||typeof second!=="number"){return null}switch(node.name){case"GT":return first>second;case"GTE":return first>=second;case"LT":return first<second;case"\
|
|
86
|
-
LTE":return first<=second}}case"Flatten":{const original=this.visit(node.child,value);return Array.isArray(original)?original.flat():null}case"Root":return this._rootValue;case"MultiSelectList":{const collected=[];for(const child of node.children){collected.push(this.visit(child,value))}return collected}case"MultiSelectHash":{const collected={};for(const child of node.children){collected[child.name]=this.visit(child.value,value)}return collected}case"OrExpression":{const result=this.visit(node.left,
|
|
87
|
-
value);if(isFalse(result)){return this.visit(node.right,value)}return result}case"AndExpression":{const result=this.visit(node.left,value);if(isFalse(result)){return result}return this.visit(node.right,value)}case"NotExpression":return isFalse(this.visit(node.child,value));case"Literal":return node.value;case"Pipe":return this.visit(node.right,this.visit(node.left,value));case"Function":{const args=[];for(const child of node.children){args.push(this.visit(child,value))}return this.runtime.callFunction(
|
|
88
|
-
node.name,args)}case"ExpressionReference":return{expref:true,...node.child};case"Current":case"Identity":return value}}computeSliceParams(arrayLength,sliceNode){let{start,stop,step}=sliceNode;if(step===null){step=1}else if(step===0){const error=new Error("Invalid value: slice step cannot be 0");error.name="RuntimeError";throw error}start=start===null?step<0?arrayLength-1:0:this.capSliceRange(arrayLength,start,step);stop=stop===null?step<0?-1:arrayLength:this.capSliceRange(arrayLength,stop,step);
|
|
89
|
-
return{start,stop,step}}capSliceRange(arrayLength,actualValue,step){let nextActualValue=actualValue;if(nextActualValue<0){nextActualValue+=arrayLength;if(nextActualValue<0){nextActualValue=step<0?-1:0}}else if(nextActualValue>=arrayLength){nextActualValue=step<0?arrayLength-1:arrayLength}return nextActualValue}slice(collection,start,end,step){const result=[];if(step>0){for(let i=start;i<end;i+=step){result.push(collection[i])}}else{for(let i=start;i>end;i+=step){result.push(collection[i])}}return result}};
|
|
90
|
-
var TreeInterpreterInstance=new TreeInterpreter;var TreeInterpreter_default=TreeInterpreterInstance;var TYPE_ANY=1;var TYPE_ARRAY=3;var TYPE_ARRAY_ARRAY=11;var TYPE_ARRAY_NUMBER=8;var TYPE_ARRAY_OBJECT=10;var TYPE_ARRAY_STRING=9;var TYPE_BOOLEAN=5;var TYPE_EXPREF=6;var TYPE_NULL=7;var TYPE_NUMBER=0;var TYPE_OBJECT=4;var TYPE_STRING=2;function compile(expression,options){const nodeTree=Parser_default.parse(expression,options);return nodeTree}function tokenize(expression,options){return Lexer_default.
|
|
91
|
-
tokenize(expression,options)}var registerFunction=(functionName,customFunction,signature,options)=>{TreeInterpreter_default.runtime.registerFunction(functionName,customFunction,signature,options)};var register=(name,customFunction,signature,options)=>{return TreeInterpreter_default.runtime.register(name,customFunction,signature,options)};var unregisterFunction=name=>{return TreeInterpreter_default.runtime.unregister(name)};var isRegistered=name=>{return TreeInterpreter_default.runtime.isRegistered(
|
|
92
|
-
name)};var getRegisteredFunctions=()=>{return TreeInterpreter_default.runtime.getRegistered()};var getCustomFunctions=()=>{return TreeInterpreter_default.runtime.getCustomFunctions()};var clearCustomFunctions=()=>{TreeInterpreter_default.runtime.clearCustomFunctions()};function search(data,expression,options){const nodeTree=Parser_default.parse(expression,options);return TreeInterpreter_default.search(nodeTree,data)}function Scope(){return new ScopeChain}var TreeInterpreter2=TreeInterpreter_default;
|
|
93
|
-
var jmespath={compile,registerFunction,register,unregisterFunction,isRegistered,getRegisteredFunctions,getCustomFunctions,clearCustomFunctions,search,tokenize,TreeInterpreter:TreeInterpreter2,TYPE_ANY,TYPE_ARRAY_NUMBER,TYPE_ARRAY_STRING,TYPE_ARRAY,TYPE_BOOLEAN,TYPE_EXPREF,TYPE_NULL,TYPE_NUMBER,TYPE_OBJECT,TYPE_STRING};export{Scope,TYPE_ANY,TYPE_ARRAY,TYPE_ARRAY_ARRAY,TYPE_ARRAY_NUMBER,TYPE_ARRAY_OBJECT,TYPE_ARRAY_STRING,TYPE_BOOLEAN,TYPE_EXPREF,TYPE_NULL,TYPE_NUMBER,TYPE_OBJECT,TYPE_STRING,TreeInterpreter2 as TreeInterpreter,clearCustomFunctions,compile,jmespath as default,getCustomFunctions,getRegisteredFunctions,isRegistered,jmespath,register,registerFunction,search,tokenize,unregisterFunction};
|