@jackwener/opencli 0.1.1 → 0.2.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.
Files changed (106) hide show
  1. package/README.md +9 -2
  2. package/README.zh-CN.md +9 -1
  3. package/SKILL.md +24 -0
  4. package/dist/bilibili.d.ts +6 -5
  5. package/dist/browser.d.ts +3 -1
  6. package/dist/browser.js +29 -2
  7. package/dist/cascade.d.ts +3 -2
  8. package/dist/clis/bbc/news.js +42 -0
  9. package/dist/clis/boss/search.d.ts +1 -0
  10. package/dist/clis/boss/search.js +47 -0
  11. package/dist/clis/ctrip/search.d.ts +1 -0
  12. package/dist/clis/ctrip/search.js +62 -0
  13. package/dist/clis/index.d.ts +8 -0
  14. package/dist/clis/index.js +16 -0
  15. package/dist/clis/reuters/search.d.ts +1 -0
  16. package/dist/clis/reuters/search.js +52 -0
  17. package/dist/clis/smzdm/search.d.ts +1 -0
  18. package/dist/clis/smzdm/search.js +66 -0
  19. package/dist/clis/weibo/hot.d.ts +1 -0
  20. package/dist/clis/weibo/hot.js +41 -0
  21. package/dist/clis/yahoo-finance/quote.d.ts +1 -0
  22. package/dist/clis/yahoo-finance/quote.js +74 -0
  23. package/dist/clis/youtube/search.d.ts +1 -0
  24. package/dist/clis/youtube/search.js +60 -0
  25. package/dist/engine.d.ts +2 -1
  26. package/dist/explore.js +1 -1
  27. package/dist/generate.js +2 -1
  28. package/dist/main.js +6 -4
  29. package/dist/output.d.ts +1 -1
  30. package/dist/output.js +12 -8
  31. package/dist/pipeline/executor.d.ts +9 -0
  32. package/dist/pipeline/executor.js +88 -0
  33. package/dist/pipeline/index.d.ts +5 -0
  34. package/dist/pipeline/index.js +5 -0
  35. package/dist/pipeline/steps/browser.d.ts +12 -0
  36. package/dist/pipeline/steps/browser.js +68 -0
  37. package/dist/pipeline/steps/fetch.d.ts +5 -0
  38. package/dist/pipeline/steps/fetch.js +50 -0
  39. package/dist/pipeline/steps/intercept.d.ts +5 -0
  40. package/dist/pipeline/steps/intercept.js +75 -0
  41. package/dist/pipeline/steps/tap.d.ts +12 -0
  42. package/dist/pipeline/steps/tap.js +130 -0
  43. package/dist/pipeline/steps/transform.d.ts +8 -0
  44. package/dist/pipeline/steps/transform.js +53 -0
  45. package/dist/pipeline/template.d.ts +16 -0
  46. package/dist/pipeline/template.js +172 -0
  47. package/dist/pipeline/template.test.d.ts +4 -0
  48. package/dist/pipeline/template.test.js +120 -0
  49. package/dist/pipeline/transform.test.d.ts +4 -0
  50. package/dist/pipeline/transform.test.js +90 -0
  51. package/dist/pipeline.d.ts +5 -7
  52. package/dist/pipeline.js +5 -549
  53. package/dist/registry.d.ts +3 -2
  54. package/dist/runtime.d.ts +2 -1
  55. package/dist/types.d.ts +27 -0
  56. package/dist/types.js +7 -0
  57. package/package.json +6 -3
  58. package/src/bilibili.ts +9 -7
  59. package/src/browser.ts +24 -3
  60. package/src/cascade.ts +3 -2
  61. package/src/clis/bbc/news.ts +42 -0
  62. package/src/clis/boss/search.ts +47 -0
  63. package/src/clis/ctrip/search.ts +62 -0
  64. package/src/clis/index.ts +24 -0
  65. package/src/clis/reuters/search.ts +52 -0
  66. package/src/clis/smzdm/search.ts +66 -0
  67. package/src/clis/weibo/hot.ts +41 -0
  68. package/src/clis/yahoo-finance/quote.ts +74 -0
  69. package/src/clis/youtube/search.ts +60 -0
  70. package/src/engine.ts +2 -1
  71. package/src/explore.ts +1 -1
  72. package/src/generate.ts +3 -1
  73. package/src/main.ts +7 -5
  74. package/src/output.ts +10 -6
  75. package/src/pipeline/executor.ts +98 -0
  76. package/src/pipeline/index.ts +6 -0
  77. package/src/pipeline/steps/browser.ts +67 -0
  78. package/src/pipeline/steps/fetch.ts +60 -0
  79. package/src/pipeline/steps/intercept.ts +78 -0
  80. package/src/pipeline/steps/tap.ts +137 -0
  81. package/src/pipeline/steps/transform.ts +50 -0
  82. package/src/pipeline/template.test.ts +125 -0
  83. package/src/pipeline/template.ts +157 -0
  84. package/src/pipeline/transform.test.ts +107 -0
  85. package/src/pipeline.ts +5 -529
  86. package/src/registry.ts +4 -2
  87. package/src/runtime.ts +3 -1
  88. package/src/types.ts +23 -0
  89. package/vitest.config.ts +7 -0
  90. package/dist/clis/github/search.js +0 -20
  91. package/dist/clis/github/trending.yaml +0 -58
  92. package/dist/promote.d.ts +0 -1
  93. package/dist/promote.js +0 -3
  94. package/dist/register.d.ts +0 -2
  95. package/dist/register.js +0 -2
  96. package/dist/scaffold.d.ts +0 -2
  97. package/dist/scaffold.js +0 -2
  98. package/dist/smoke.d.ts +0 -2
  99. package/dist/smoke.js +0 -2
  100. package/src/clis/github/search.ts +0 -21
  101. package/src/clis/github/trending.yaml +0 -58
  102. package/src/promote.ts +0 -3
  103. package/src/register.ts +0 -2
  104. package/src/scaffold.ts +0 -2
  105. package/src/smoke.ts +0 -2
  106. /package/dist/clis/{github/search.d.ts → bbc/news.d.ts} +0 -0
package/src/main.ts CHANGED
@@ -3,6 +3,7 @@
3
3
  * opencli — Make any website your CLI. AI-powered.
4
4
  */
5
5
 
6
+ import * as fs from 'node:fs';
6
7
  import * as os from 'node:os';
7
8
  import * as path from 'node:path';
8
9
  import { fileURLToPath } from 'node:url';
@@ -20,10 +21,14 @@ const __dirname = path.dirname(__filename);
20
21
  const BUILTIN_CLIS = path.resolve(__dirname, 'clis');
21
22
  const USER_CLIS = path.join(os.homedir(), '.opencli', 'clis');
22
23
 
24
+ // Read version from package.json (single source of truth)
25
+ const pkgJsonPath = path.resolve(__dirname, '..', 'package.json');
26
+ const PKG_VERSION = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf-8')).version ?? '0.0.0';
27
+
23
28
  discoverClis(BUILTIN_CLIS, USER_CLIS);
24
29
 
25
30
  const program = new Command();
26
- program.name('opencli').description('Make any website your CLI. Zero setup. AI-powered.').version('0.1.0');
31
+ program.name('opencli').description('Make any website your CLI. Zero setup. AI-powered.').version(PKG_VERSION);
27
32
 
28
33
  // ── Built-in commands ──────────────────────────────────────────────────────
29
34
 
@@ -49,10 +54,7 @@ program.command('validate').description('Validate CLI definitions').argument('[t
49
54
  program.command('verify').description('Validate + smoke test').argument('[target]').option('--smoke', 'Run smoke tests', false)
50
55
  .action(async (target, opts) => { const { verifyClis, renderVerifyReport } = await import('./verify.js'); const r = await verifyClis({ builtinClis: BUILTIN_CLIS, userClis: USER_CLIS, target, smoke: opts.smoke }); console.log(renderVerifyReport(r)); process.exitCode = r.ok ? 0 : 1; });
51
56
 
52
- program.command('explore').description('Explore a website').argument('<url>').option('--site <name>').option('--goal <text>').option('--wait <s>', '', '3')
53
- .action(async (url, opts) => { const { exploreUrl, renderExploreSummary } = await import('./explore.js'); console.log(renderExploreSummary(await exploreUrl(url, { BrowserFactory: PlaywrightMCP, site: opts.site, goal: opts.goal, waitSeconds: parseFloat(opts.wait) }))); });
54
-
55
- program.command('probe').description('Probe a website: discover APIs, stores, and recommend strategies').argument('<url>').option('--site <name>').option('--goal <text>').option('--wait <s>', '', '3')
57
+ program.command('explore').alias('probe').description('Explore a website: discover APIs, stores, and recommend strategies').argument('<url>').option('--site <name>').option('--goal <text>').option('--wait <s>', '', '3')
56
58
  .action(async (url, opts) => { const { exploreUrl, renderExploreSummary } = await import('./explore.js'); console.log(renderExploreSummary(await exploreUrl(url, { BrowserFactory: PlaywrightMCP, site: opts.site, goal: opts.goal, waitSeconds: parseFloat(opts.wait) }))); });
57
59
 
58
60
  program.command('synthesize').description('Synthesize CLIs from explore').argument('<target>').option('--top <n>', '', '3')
package/src/output.ts CHANGED
@@ -1,9 +1,10 @@
1
1
  /**
2
- * Output formatting: table, JSON, Markdown, CSV.
2
+ * Output formatting: table, JSON, Markdown, CSV, YAML.
3
3
  */
4
4
 
5
5
  import chalk from 'chalk';
6
6
  import Table from 'cli-table3';
7
+ import yaml from 'js-yaml';
7
8
 
8
9
  export interface RenderOptions {
9
10
  fmt?: string;
@@ -23,6 +24,7 @@ export function render(data: any, opts: RenderOptions = {}): void {
23
24
  case 'json': renderJson(data); break;
24
25
  case 'md': case 'markdown': renderMarkdown(data, opts); break;
25
26
  case 'csv': renderCsv(data, opts); break;
27
+ case 'yaml': case 'yml': renderYaml(data); break;
26
28
  default: renderTable(data, opts); break;
27
29
  }
28
30
  }
@@ -32,16 +34,14 @@ function renderTable(data: any, opts: RenderOptions): void {
32
34
  if (!rows.length) { console.log(chalk.dim('(no data)')); return; }
33
35
  const columns = opts.columns ?? Object.keys(rows[0]);
34
36
 
35
- const header = columns.map((c, i) => i === 0 ? '#' : capitalize(c));
37
+ const header = columns.map(c => capitalize(c));
36
38
  const table = new Table({
37
39
  head: header.map(h => chalk.bold(h)),
38
40
  style: { head: [], border: [] },
39
41
  wordWrap: true,
40
42
  wrapOnWordBoundary: true,
41
- colWidths: columns.map((c, i) => {
42
- if (i === 0) return 4;
43
- if (c === 'url' || c === 'description') return null as any;
44
- if (c === 'title' || c === 'name' || c === 'repo') return null as any;
43
+ colWidths: columns.map((_c, i) => {
44
+ if (i === 0) return 6;
45
45
  return null as any;
46
46
  }).filter(() => true),
47
47
  });
@@ -91,6 +91,10 @@ function renderCsv(data: any, opts: RenderOptions): void {
91
91
  }
92
92
  }
93
93
 
94
+ function renderYaml(data: any): void {
95
+ console.log(yaml.dump(data, { sortKeys: false, lineWidth: 120, noRefs: true }));
96
+ }
97
+
94
98
  function capitalize(s: string): string {
95
99
  return s.charAt(0).toUpperCase() + s.slice(1);
96
100
  }
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Pipeline executor: runs YAML pipeline steps sequentially.
3
+ */
4
+
5
+ import chalk from 'chalk';
6
+ import type { IPage } from '../types.js';
7
+ import { stepNavigate, stepClick, stepType, stepWait, stepPress, stepSnapshot, stepEvaluate } from './steps/browser.js';
8
+ import { stepFetch } from './steps/fetch.js';
9
+ import { stepSelect, stepMap, stepFilter, stepSort, stepLimit } from './steps/transform.js';
10
+ import { stepIntercept } from './steps/intercept.js';
11
+ import { stepTap } from './steps/tap.js';
12
+
13
+ export interface PipelineContext {
14
+ args?: Record<string, any>;
15
+ debug?: boolean;
16
+ }
17
+
18
+ /** Step handler signature */
19
+ type StepHandler = (page: IPage | null, params: any, data: any, args: Record<string, any>) => Promise<any>;
20
+
21
+ /** Registry of all available step handlers */
22
+ const STEP_HANDLERS: Record<string, StepHandler> = {
23
+ navigate: stepNavigate as StepHandler,
24
+ fetch: stepFetch,
25
+ select: stepSelect as StepHandler,
26
+ evaluate: stepEvaluate as StepHandler,
27
+ snapshot: stepSnapshot as StepHandler,
28
+ click: stepClick as StepHandler,
29
+ type: stepType as StepHandler,
30
+ wait: stepWait as StepHandler,
31
+ press: stepPress as StepHandler,
32
+ map: stepMap as StepHandler,
33
+ filter: stepFilter as StepHandler,
34
+ sort: stepSort as StepHandler,
35
+ limit: stepLimit as StepHandler,
36
+ intercept: stepIntercept as StepHandler,
37
+ tap: stepTap as StepHandler,
38
+ };
39
+
40
+ export async function executePipeline(
41
+ page: IPage | null,
42
+ pipeline: any[],
43
+ ctx: PipelineContext = {},
44
+ ): Promise<any> {
45
+ const args = ctx.args ?? {};
46
+ const debug = ctx.debug ?? false;
47
+ let data: any = null;
48
+ const total = pipeline.length;
49
+
50
+ for (let i = 0; i < pipeline.length; i++) {
51
+ const step = pipeline[i];
52
+ if (!step || typeof step !== 'object') continue;
53
+ for (const [op, params] of Object.entries(step)) {
54
+ if (debug) debugStepStart(i + 1, total, op, params);
55
+
56
+ const handler = STEP_HANDLERS[op];
57
+ if (handler) {
58
+ data = await handler(page, params, data, args);
59
+ } else {
60
+ if (debug) process.stderr.write(` ${chalk.yellow('⚠')} Unknown step: ${op}\n`);
61
+ }
62
+
63
+ // Detect error objects returned by steps (e.g. tap store not found)
64
+ if (data && typeof data === 'object' && !Array.isArray(data) && data.error) {
65
+ process.stderr.write(` ${chalk.yellow('⚠')} ${chalk.yellow(op)}: ${data.error}\n`);
66
+ if (data.hint) process.stderr.write(` ${chalk.dim('💡')} ${chalk.dim(data.hint)}\n`);
67
+ }
68
+ if (debug) debugStepResult(op, data);
69
+ }
70
+ }
71
+ return data;
72
+ }
73
+
74
+ function debugStepStart(stepNum: number, total: number, op: string, params: any): void {
75
+ let preview = '';
76
+ if (typeof params === 'string') {
77
+ preview = params.length <= 80 ? ` → ${params}` : ` → ${params.slice(0, 77)}...`;
78
+ } else if (params && typeof params === 'object' && !Array.isArray(params)) {
79
+ preview = ` (${Object.keys(params).join(', ')})`;
80
+ }
81
+ process.stderr.write(` ${chalk.dim(`[${stepNum}/${total}]`)} ${chalk.bold.cyan(op)}${preview}\n`);
82
+ }
83
+
84
+ function debugStepResult(op: string, data: any): void {
85
+ if (data === null || data === undefined) {
86
+ process.stderr.write(` ${chalk.dim('→ (no data)')}\n`);
87
+ } else if (Array.isArray(data)) {
88
+ process.stderr.write(` ${chalk.dim(`→ ${data.length} items`)}\n`);
89
+ } else if (typeof data === 'object') {
90
+ const keys = Object.keys(data).slice(0, 5);
91
+ process.stderr.write(` ${chalk.dim(`→ dict (${keys.join(', ')}${Object.keys(data).length > 5 ? '...' : ''})`)}\n`);
92
+ } else if (typeof data === 'string') {
93
+ const p = data.slice(0, 60).replace(/\n/g, '\\n');
94
+ process.stderr.write(` ${chalk.dim(`→ "${p}${data.length > 60 ? '...' : ''}"`)}\n`);
95
+ } else {
96
+ process.stderr.write(` ${chalk.dim(`→ ${typeof data}`)}\n`);
97
+ }
98
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Pipeline module: re-exports for backward compatibility.
3
+ */
4
+
5
+ export { executePipeline, type PipelineContext } from './executor.js';
6
+ export { render, evalExpr, resolvePath, normalizeEvaluateSource, type RenderContext } from './template.js';
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Pipeline step: navigate, click, type, wait, press, snapshot.
3
+ * Browser interaction primitives.
4
+ */
5
+
6
+ import type { IPage } from '../../types.js';
7
+ import { render, normalizeEvaluateSource } from '../template.js';
8
+
9
+ export async function stepNavigate(page: IPage, params: any, data: any, args: Record<string, any>): Promise<any> {
10
+ const url = render(params, { args, data });
11
+ await page.goto(String(url));
12
+ return data;
13
+ }
14
+
15
+ export async function stepClick(page: IPage, params: any, data: any, args: Record<string, any>): Promise<any> {
16
+ await page.click(String(render(params, { args, data })).replace(/^@/, ''));
17
+ return data;
18
+ }
19
+
20
+ export async function stepType(page: IPage, params: any, data: any, args: Record<string, any>): Promise<any> {
21
+ if (typeof params === 'object' && params) {
22
+ const ref = String(render(params.ref ?? '', { args, data })).replace(/^@/, '');
23
+ const text = String(render(params.text ?? '', { args, data }));
24
+ await page.typeText(ref, text);
25
+ if (params.submit) await page.pressKey('Enter');
26
+ }
27
+ return data;
28
+ }
29
+
30
+ export async function stepWait(page: IPage, params: any, data: any, args: Record<string, any>): Promise<any> {
31
+ if (typeof params === 'number') await page.wait(params);
32
+ else if (typeof params === 'object' && params) {
33
+ if ('text' in params) {
34
+ const timeout = params.timeout ?? 10;
35
+ const start = Date.now();
36
+ while ((Date.now() - start) / 1000 < timeout) {
37
+ const snap = await page.snapshot({ raw: true });
38
+ if (typeof snap === 'string' && snap.includes(params.text)) break;
39
+ await page.wait(0.5);
40
+ }
41
+ } else if ('time' in params) await page.wait(Number(params.time));
42
+ } else if (typeof params === 'string') await page.wait(Number(render(params, { args, data })));
43
+ return data;
44
+ }
45
+
46
+ export async function stepPress(page: IPage, params: any, data: any, args: Record<string, any>): Promise<any> {
47
+ await page.pressKey(String(render(params, { args, data })));
48
+ return data;
49
+ }
50
+
51
+ export async function stepSnapshot(page: IPage, params: any, _data: any, _args: Record<string, any>): Promise<any> {
52
+ const opts = (typeof params === 'object' && params) ? params : {};
53
+ return page.snapshot({ interactive: opts.interactive ?? false, compact: opts.compact ?? false, maxDepth: opts.max_depth, raw: opts.raw ?? false });
54
+ }
55
+
56
+ export async function stepEvaluate(page: IPage, params: any, data: any, args: Record<string, any>): Promise<any> {
57
+ const js = String(render(params, { args, data }));
58
+ let result = await page.evaluate(normalizeEvaluateSource(js));
59
+ // MCP may return JSON as a string — auto-parse it
60
+ if (typeof result === 'string') {
61
+ const trimmed = result.trim();
62
+ if ((trimmed.startsWith('[') && trimmed.endsWith(']')) || (trimmed.startsWith('{') && trimmed.endsWith('}'))) {
63
+ try { result = JSON.parse(trimmed); } catch {}
64
+ }
65
+ }
66
+ return result;
67
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Pipeline step: fetch — HTTP API requests.
3
+ */
4
+
5
+ import type { IPage } from '../../types.js';
6
+ import { render } from '../template.js';
7
+
8
+ /** Single URL fetch helper */
9
+ async function fetchSingle(
10
+ page: IPage | null, url: string, method: string,
11
+ queryParams: Record<string, any>, headers: Record<string, any>,
12
+ args: Record<string, any>, data: any,
13
+ ): Promise<any> {
14
+ const renderedParams: Record<string, string> = {};
15
+ for (const [k, v] of Object.entries(queryParams)) renderedParams[k] = String(render(v, { args, data }));
16
+ const renderedHeaders: Record<string, string> = {};
17
+ for (const [k, v] of Object.entries(headers)) renderedHeaders[k] = String(render(v, { args, data }));
18
+
19
+ let finalUrl = url;
20
+ if (Object.keys(renderedParams).length > 0) {
21
+ const qs = new URLSearchParams(renderedParams).toString();
22
+ finalUrl = `${finalUrl}${finalUrl.includes('?') ? '&' : '?'}${qs}`;
23
+ }
24
+
25
+ if (page === null) {
26
+ const resp = await fetch(finalUrl, { method: method.toUpperCase(), headers: renderedHeaders });
27
+ return resp.json();
28
+ }
29
+
30
+ const headersJs = JSON.stringify(renderedHeaders);
31
+ const escapedUrl = finalUrl.replace(/"/g, '\\"');
32
+ return page.evaluate(`
33
+ async () => {
34
+ const resp = await fetch("${escapedUrl}", {
35
+ method: "${method}", headers: ${headersJs}, credentials: "include"
36
+ });
37
+ return await resp.json();
38
+ }
39
+ `);
40
+ }
41
+
42
+ export async function stepFetch(page: IPage | null, params: any, data: any, args: Record<string, any>): Promise<any> {
43
+ const urlOrObj = typeof params === 'string' ? params : (params?.url ?? '');
44
+ const method = params?.method ?? 'GET';
45
+ const queryParams: Record<string, any> = params?.params ?? {};
46
+ const headers: Record<string, any> = params?.headers ?? {};
47
+ const urlTemplate = String(urlOrObj);
48
+
49
+ // Per-item fetch when data is array and URL references item
50
+ if (Array.isArray(data) && urlTemplate.includes('item')) {
51
+ const results: any[] = [];
52
+ for (let i = 0; i < data.length; i++) {
53
+ const itemUrl = String(render(urlTemplate, { args, data, item: data[i], index: i }));
54
+ results.push(await fetchSingle(page, itemUrl, method, queryParams, headers, args, data));
55
+ }
56
+ return results;
57
+ }
58
+ const url = render(urlOrObj, { args, data });
59
+ return fetchSingle(page, String(url), method, queryParams, headers, args, data);
60
+ }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Pipeline step: intercept — declarative XHR interception.
3
+ */
4
+
5
+ import type { IPage } from '../../types.js';
6
+ import { render } from '../template.js';
7
+
8
+ export async function stepIntercept(page: IPage, params: any, data: any, args: Record<string, any>): Promise<any> {
9
+ const cfg = typeof params === 'object' ? params : {};
10
+ const trigger = cfg.trigger ?? '';
11
+ const capturePattern = cfg.capture ?? '';
12
+ const timeout = cfg.timeout ?? 8;
13
+ const selectPath = cfg.select ?? null;
14
+
15
+ if (!capturePattern) return data;
16
+
17
+ // Step 1: Execute the trigger action
18
+ if (trigger.startsWith('navigate:')) {
19
+ const url = render(trigger.slice('navigate:'.length), { args, data });
20
+ await page.goto(String(url));
21
+ } else if (trigger.startsWith('evaluate:')) {
22
+ const js = trigger.slice('evaluate:'.length);
23
+ const { normalizeEvaluateSource } = await import('../template.js');
24
+ await page.evaluate(normalizeEvaluateSource(render(js, { args, data }) as string));
25
+ } else if (trigger.startsWith('click:')) {
26
+ const ref = render(trigger.slice('click:'.length), { args, data });
27
+ await page.click(String(ref).replace(/^@/, ''));
28
+ } else if (trigger === 'scroll') {
29
+ await page.scroll('down');
30
+ }
31
+
32
+ // Step 2: Wait a bit for network requests to fire
33
+ await page.wait(Math.min(timeout, 3));
34
+
35
+ // Step 3: Get network requests and find matching ones
36
+ const rawNetwork = await page.networkRequests(false);
37
+ const matchingResponses: any[] = [];
38
+
39
+ if (typeof rawNetwork === 'string') {
40
+ const lines = rawNetwork.split('\n');
41
+ for (const line of lines) {
42
+ const match = line.match(/\[?(GET|POST)\]?\s+(\S+)\s*(?:=>|→)\s*\[?(\d+)\]?/i);
43
+ if (match) {
44
+ const [, , url, status] = match;
45
+ if (url.includes(capturePattern) && status === '200') {
46
+ try {
47
+ const body = await page.evaluate(`
48
+ async () => {
49
+ try {
50
+ const resp = await fetch(${JSON.stringify(url)}, { credentials: 'include' });
51
+ if (!resp.ok) return null;
52
+ return await resp.json();
53
+ } catch { return null; }
54
+ }
55
+ `);
56
+ if (body) matchingResponses.push(body);
57
+ } catch {}
58
+ }
59
+ }
60
+ }
61
+ }
62
+
63
+ // Step 4: Select from response if specified
64
+ let result = matchingResponses.length === 1 ? matchingResponses[0] :
65
+ matchingResponses.length > 1 ? matchingResponses : data;
66
+
67
+ if (selectPath && result) {
68
+ let current = result;
69
+ for (const part of String(selectPath).split('.')) {
70
+ if (current && typeof current === 'object' && !Array.isArray(current)) {
71
+ current = current[part];
72
+ } else break;
73
+ }
74
+ result = current ?? result;
75
+ }
76
+
77
+ return result;
78
+ }
@@ -0,0 +1,137 @@
1
+ /**
2
+ * Pipeline step: tap — declarative Store Action Bridge.
3
+ *
4
+ * Generates a self-contained IIFE that:
5
+ * 1. Injects fetch + XHR dual interception proxy
6
+ * 2. Finds the Pinia/Vuex store and calls the action
7
+ * 3. Captures the response matching the URL pattern
8
+ * 4. Auto-cleans up interception in finally block
9
+ * 5. Returns the captured data (optionally sub-selected)
10
+ */
11
+
12
+ import type { IPage } from '../../types.js';
13
+ import { render } from '../template.js';
14
+
15
+ export async function stepTap(page: IPage, params: any, data: any, args: Record<string, any>): Promise<any> {
16
+ const cfg = typeof params === 'object' ? params : {};
17
+ const storeName = String(render(cfg.store ?? '', { args, data }));
18
+ const actionName = String(render(cfg.action ?? '', { args, data }));
19
+ const capturePattern = String(render(cfg.capture ?? '', { args, data }));
20
+ const timeout = cfg.timeout ?? 5;
21
+ const selectPath = cfg.select ? String(render(cfg.select, { args, data })) : null;
22
+ const framework = cfg.framework ?? null;
23
+ const actionArgs = cfg.args ?? [];
24
+
25
+ if (!storeName || !actionName) throw new Error('tap: store and action are required');
26
+
27
+ // Build select chain for the captured response
28
+ const selectChain = selectPath
29
+ ? selectPath.split('.').map((p: string) => `?.[${JSON.stringify(p)}]`).join('')
30
+ : '';
31
+
32
+ // Serialize action arguments
33
+ const actionArgsRendered = actionArgs.map((a: any) => {
34
+ const rendered = render(a, { args, data });
35
+ return JSON.stringify(rendered);
36
+ });
37
+ const actionCall = actionArgsRendered.length
38
+ ? `store[${JSON.stringify(actionName)}](${actionArgsRendered.join(', ')})`
39
+ : `store[${JSON.stringify(actionName)}]()`;
40
+
41
+ const js = `
42
+ async () => {
43
+ // ── 1. Setup capture proxy (fetch + XHR dual interception) ──
44
+ let captured = null;
45
+ const capturePattern = ${JSON.stringify(capturePattern)};
46
+
47
+ // Intercept fetch API
48
+ const origFetch = window.fetch;
49
+ window.fetch = async function(...fetchArgs) {
50
+ const resp = await origFetch.apply(this, fetchArgs);
51
+ try {
52
+ const url = typeof fetchArgs[0] === 'string' ? fetchArgs[0]
53
+ : fetchArgs[0] instanceof Request ? fetchArgs[0].url : String(fetchArgs[0]);
54
+ if (capturePattern && url.includes(capturePattern) && !captured) {
55
+ try { captured = await resp.clone().json(); } catch {}
56
+ }
57
+ } catch {}
58
+ return resp;
59
+ };
60
+
61
+ // Intercept XMLHttpRequest
62
+ const origXhrOpen = XMLHttpRequest.prototype.open;
63
+ const origXhrSend = XMLHttpRequest.prototype.send;
64
+ XMLHttpRequest.prototype.open = function(method, url) {
65
+ this.__tapUrl = String(url);
66
+ return origXhrOpen.apply(this, arguments);
67
+ };
68
+ XMLHttpRequest.prototype.send = function(body) {
69
+ if (capturePattern && this.__tapUrl?.includes(capturePattern)) {
70
+ const xhr = this;
71
+ const origHandler = xhr.onreadystatechange;
72
+ xhr.onreadystatechange = function() {
73
+ if (xhr.readyState === 4 && !captured) {
74
+ try { captured = JSON.parse(xhr.responseText); } catch {}
75
+ }
76
+ if (origHandler) origHandler.apply(this, arguments);
77
+ };
78
+ const origOnload = xhr.onload;
79
+ xhr.onload = function() {
80
+ if (!captured) { try { captured = JSON.parse(xhr.responseText); } catch {} }
81
+ if (origOnload) origOnload.apply(this, arguments);
82
+ };
83
+ }
84
+ return origXhrSend.apply(this, arguments);
85
+ };
86
+
87
+ try {
88
+ // ── 2. Find store ──
89
+ let store = null;
90
+ const storeName = ${JSON.stringify(storeName)};
91
+ const fw = ${JSON.stringify(framework)};
92
+
93
+ const app = document.querySelector('#app');
94
+ if (!fw || fw === 'pinia') {
95
+ try {
96
+ const pinia = app?.__vue_app__?.config?.globalProperties?.$pinia;
97
+ if (pinia?._s) store = pinia._s.get(storeName);
98
+ } catch {}
99
+ }
100
+ if (!store && (!fw || fw === 'vuex')) {
101
+ try {
102
+ const vuexStore = app?.__vue_app__?.config?.globalProperties?.$store
103
+ ?? app?.__vue__?.$store;
104
+ if (vuexStore) {
105
+ store = { [${JSON.stringify(actionName)}]: (...a) => vuexStore.dispatch(storeName + '/' + ${JSON.stringify(actionName)}, ...a) };
106
+ }
107
+ } catch {}
108
+ }
109
+
110
+ if (!store) return { error: 'Store not found: ' + storeName, hint: 'Page may not be fully loaded or store name may be incorrect' };
111
+ if (typeof store[${JSON.stringify(actionName)}] !== 'function') {
112
+ return { error: 'Action not found: ' + ${JSON.stringify(actionName)} + ' on store ' + storeName,
113
+ hint: 'Available: ' + Object.keys(store).filter(k => typeof store[k] === 'function' && !k.startsWith('$') && !k.startsWith('_')).join(', ') };
114
+ }
115
+
116
+ // ── 3. Call store action ──
117
+ await ${actionCall};
118
+
119
+ // ── 4. Wait for network response ──
120
+ const deadline = Date.now() + ${timeout} * 1000;
121
+ while (!captured && Date.now() < deadline) {
122
+ await new Promise(r => setTimeout(r, 200));
123
+ }
124
+ } finally {
125
+ // ── 5. Always restore originals ──
126
+ window.fetch = origFetch;
127
+ XMLHttpRequest.prototype.open = origXhrOpen;
128
+ XMLHttpRequest.prototype.send = origXhrSend;
129
+ }
130
+
131
+ if (!captured) return { error: 'No matching response captured for pattern: ' + capturePattern };
132
+ return captured${selectChain} ?? captured;
133
+ }
134
+ `;
135
+
136
+ return page.evaluate(js);
137
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Pipeline steps: data transforms — select, map, filter, sort, limit.
3
+ */
4
+
5
+ import { render, evalExpr } from '../template.js';
6
+
7
+ export async function stepSelect(_page: any, params: any, data: any, args: Record<string, any>): Promise<any> {
8
+ const pathStr = String(render(params, { args, data }));
9
+ if (data && typeof data === 'object') {
10
+ let current = data;
11
+ for (const part of pathStr.split('.')) {
12
+ if (current && typeof current === 'object' && !Array.isArray(current)) current = (current as any)[part];
13
+ else if (Array.isArray(current) && /^\d+$/.test(part)) current = current[parseInt(part, 10)];
14
+ else return null;
15
+ }
16
+ return current;
17
+ }
18
+ return data;
19
+ }
20
+
21
+ export async function stepMap(_page: any, params: any, data: any, args: Record<string, any>): Promise<any> {
22
+ if (!data || typeof data !== 'object') return data;
23
+ let items: any[] = Array.isArray(data) ? data : [data];
24
+ if (!Array.isArray(data) && typeof data === 'object' && 'data' in data) items = data.data;
25
+ const result: any[] = [];
26
+ for (let i = 0; i < items.length; i++) {
27
+ const item = items[i];
28
+ const row: Record<string, any> = {};
29
+ for (const [key, template] of Object.entries(params)) row[key] = render(template, { args, data, item, index: i });
30
+ result.push(row);
31
+ }
32
+ return result;
33
+ }
34
+
35
+ export async function stepFilter(_page: any, params: any, data: any, args: Record<string, any>): Promise<any> {
36
+ if (!Array.isArray(data)) return data;
37
+ return data.filter((item, i) => evalExpr(String(params), { args, item, index: i }));
38
+ }
39
+
40
+ export async function stepSort(_page: any, params: any, data: any, _args: Record<string, any>): Promise<any> {
41
+ if (!Array.isArray(data)) return data;
42
+ const key = typeof params === 'object' ? (params.by ?? '') : String(params);
43
+ const reverse = typeof params === 'object' ? params.order === 'desc' : false;
44
+ return [...data].sort((a, b) => { const va = a[key] ?? ''; const vb = b[key] ?? ''; const cmp = va < vb ? -1 : va > vb ? 1 : 0; return reverse ? -cmp : cmp; });
45
+ }
46
+
47
+ export async function stepLimit(_page: any, params: any, data: any, args: Record<string, any>): Promise<any> {
48
+ if (!Array.isArray(data)) return data;
49
+ return data.slice(0, Number(render(params, { args, data })));
50
+ }