jitsu-cli 2.14.0-beta.8 → 2.14.0-beta.85

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 (41) hide show
  1. package/bin/jitsu +3 -0
  2. package/build.mts +39 -0
  3. package/compiled/package.json +16 -22
  4. package/compiled/src/commands/build.js +16 -24
  5. package/compiled/src/commands/config/handlers.js +292 -0
  6. package/compiled/src/commands/config/index.js +148 -0
  7. package/compiled/src/commands/config/resources.js +88 -0
  8. package/compiled/src/commands/default-workspace.js +39 -0
  9. package/compiled/src/commands/deploy.js +3 -4
  10. package/compiled/src/commands/spec.js +31 -0
  11. package/compiled/src/index.js +21 -2
  12. package/compiled/src/lib/api-client.js +52 -0
  13. package/compiled/src/lib/auth-file.js +67 -0
  14. package/compiled/src/lib/body-builder.js +53 -0
  15. package/compiled/src/lib/body-fields.js +47 -0
  16. package/compiled/src/lib/compiled-function.js +23 -21
  17. package/compiled/src/lib/dotted.js +34 -0
  18. package/compiled/src/lib/renderer.js +33 -0
  19. package/compiled/src/lib/spec.js +11 -0
  20. package/dist/main.js +46358 -92868
  21. package/dist/main.js.map +7 -1
  22. package/package.json +16 -22
  23. package/src/commands/build.ts +21 -26
  24. package/src/commands/config/handlers.ts +339 -0
  25. package/src/commands/config/index.ts +171 -0
  26. package/src/commands/config/resources.ts +110 -0
  27. package/src/commands/default-workspace.ts +44 -0
  28. package/src/commands/deploy.ts +3 -2
  29. package/src/commands/spec.ts +32 -0
  30. package/src/index.ts +34 -17
  31. package/src/lib/api-client.ts +64 -0
  32. package/src/lib/auth-file.ts +83 -0
  33. package/src/lib/body-builder.ts +68 -0
  34. package/src/lib/body-fields.ts +61 -0
  35. package/src/lib/compiled-function.ts +30 -23
  36. package/src/lib/dotted.ts +43 -0
  37. package/src/lib/renderer.ts +44 -0
  38. package/src/lib/spec.ts +32 -0
  39. package/dist/140.js +0 -452
  40. package/dist/140.js.map +0 -1
  41. package/webpack.config.cjs +0 -53
@@ -0,0 +1,110 @@
1
+ // Single source of truth for the `jitsu config <noun>` command tree.
2
+ // `kind` selects which verb handlers apply; `type` is the segment used in
3
+ // /api/{workspaceId}/config/{type} for standard config objects.
4
+
5
+ export type ResourceKind = "configObject" | "workspace" | "link" | "profile-builder";
6
+
7
+ export type Resource = {
8
+ noun: string;
9
+ aliases: string[];
10
+ kind: ResourceKind;
11
+ type?: string;
12
+ supportsTest?: boolean;
13
+ // Description used in `--help`.
14
+ description: string;
15
+ };
16
+
17
+ export const resources: Resource[] = [
18
+ {
19
+ noun: "workspaces",
20
+ aliases: ["workspace"],
21
+ kind: "workspace",
22
+ description: "Workspaces accessible to the current user",
23
+ },
24
+ {
25
+ noun: "destinations",
26
+ aliases: ["destination", "dest"],
27
+ kind: "configObject",
28
+ type: "destination",
29
+ supportsTest: true,
30
+ description: "Destinations (warehouses, databases, services receiving events)",
31
+ },
32
+ {
33
+ noun: "streams",
34
+ aliases: ["stream"],
35
+ kind: "configObject",
36
+ type: "stream",
37
+ supportsTest: true,
38
+ description: "Event streams (formerly known as sources)",
39
+ },
40
+ {
41
+ noun: "functions",
42
+ aliases: ["function", "fn"],
43
+ kind: "configObject",
44
+ type: "function",
45
+ description: "User-defined functions (UDFs). For dev workflow see `jitsu deploy`.",
46
+ },
47
+ {
48
+ noun: "services",
49
+ aliases: ["service"],
50
+ kind: "configObject",
51
+ type: "service",
52
+ supportsTest: true,
53
+ description: "External connector services (Airbyte protocol)",
54
+ },
55
+ {
56
+ noun: "domains",
57
+ aliases: ["domain"],
58
+ kind: "configObject",
59
+ type: "domain",
60
+ description: "Custom ingestion domains",
61
+ },
62
+ {
63
+ noun: "misc",
64
+ aliases: [],
65
+ kind: "configObject",
66
+ type: "misc",
67
+ description: "Miscellaneous configuration entities (free-form)",
68
+ },
69
+ {
70
+ noun: "notifications",
71
+ aliases: ["notification"],
72
+ kind: "configObject",
73
+ type: "notification",
74
+ description: "Alert channels (email/Slack)",
75
+ },
76
+ {
77
+ noun: "connections",
78
+ aliases: ["connection", "link", "links"],
79
+ kind: "link",
80
+ description: "Connections between streams/services and destinations",
81
+ },
82
+ {
83
+ noun: "profile-builders",
84
+ aliases: ["profile-builder"],
85
+ kind: "profile-builder",
86
+ description: "Profile builders (identity stitching)",
87
+ },
88
+ ];
89
+
90
+ export type Verb = "list" | "get" | "create" | "update" | "delete" | "test";
91
+
92
+ // Which verbs apply to a given resource kind.
93
+ export function verbsFor(kind: ResourceKind): Verb[] {
94
+ switch (kind) {
95
+ case "configObject":
96
+ return ["list", "get", "create", "update", "delete"];
97
+ case "workspace":
98
+ return ["list", "get", "create", "update", "delete"];
99
+ case "link":
100
+ // link has no per-id GET; list+create(upsert)+update(alias)+delete
101
+ return ["list", "create", "update", "delete"];
102
+ case "profile-builder":
103
+ return ["list", "create", "update", "delete"];
104
+ }
105
+ }
106
+
107
+ export function findResource(name: string): Resource | undefined {
108
+ const lower = name.toLowerCase();
109
+ return resources.find(r => r.noun === lower || r.aliases.includes(lower));
110
+ }
@@ -0,0 +1,44 @@
1
+ import { ApiClient, ApiError } from "../lib/api-client";
2
+ import { authFilePath, readAuthFile, resolveAuth, updateAuthFile } from "../lib/auth-file";
3
+ import { red } from "../lib/chalk-code-highlight";
4
+
5
+ export type DefaultWorkspaceOpts = {
6
+ host?: string;
7
+ apikey?: string;
8
+ };
9
+
10
+ export async function setDefaultWorkspace(idOrSlug: string, opts: DefaultWorkspaceOpts) {
11
+ try {
12
+ const auth = resolveAuth(opts);
13
+ const client = new ApiClient(auth);
14
+ let workspace: { id: string; slug?: string; name?: string };
15
+ try {
16
+ workspace = await client.request({
17
+ method: "GET",
18
+ path: `/api/workspace/${encodeURIComponent(idOrSlug)}`,
19
+ });
20
+ } catch (e) {
21
+ if (e instanceof ApiError && e.status === 404) {
22
+ throw new Error(`Workspace '${idOrSlug}' not found (or you don't have access)`);
23
+ }
24
+ throw e;
25
+ }
26
+ updateAuthFile({ defaultWorkspace: workspace.id });
27
+ const label = workspace.slug ? `${workspace.slug} (${workspace.id})` : workspace.id;
28
+ console.log(`Default workspace set to ${label}.`);
29
+ console.log(`Saved to ${authFilePath()}.`);
30
+ } catch (e) {
31
+ console.error(red(`Error: ${e instanceof Error ? e.message : String(e)}`));
32
+ process.exit(1);
33
+ }
34
+ }
35
+
36
+ export async function unsetDefaultWorkspace() {
37
+ const file = readAuthFile();
38
+ if (!file?.defaultWorkspace) {
39
+ console.log("No default workspace is set.");
40
+ return;
41
+ }
42
+ updateAuthFile({ defaultWorkspace: undefined });
43
+ console.log("Default workspace unset.");
44
+ }
@@ -3,7 +3,6 @@ import { homedir } from "os";
3
3
  import inquirer from "inquirer";
4
4
  import { existsSync, readdirSync, readFileSync } from "fs";
5
5
  import { loadPackageJson } from "./shared";
6
- import fetch from "node-fetch";
7
6
  import cuid from "cuid";
8
7
  import { b, green, red } from "../lib/chalk-code-highlight";
9
8
  import { getFunctionFromFilePath } from "../lib/compiled-function";
@@ -151,6 +150,7 @@ async function deployFunctions(
151
150
  })`
152
151
  );
153
152
  await deployFunction(
153
+ projectDir,
154
154
  { host, apikey },
155
155
  packageJson,
156
156
  workspace,
@@ -162,6 +162,7 @@ async function deployFunctions(
162
162
  }
163
163
 
164
164
  async function deployFunction(
165
+ projectDir: string,
165
166
  { host, apikey }: Args,
166
167
  packageJson: any,
167
168
  workspace: Workspace,
@@ -171,7 +172,7 @@ async function deployFunction(
171
172
  ) {
172
173
  const code = readFileSync(file, "utf-8");
173
174
 
174
- const wrapped = await getFunctionFromFilePath(file, kind, profileBuilders);
175
+ const wrapped = await getFunctionFromFilePath(projectDir, file, kind, profileBuilders);
175
176
  const meta = wrapped.meta;
176
177
  if (meta) {
177
178
  console.log(` meta: slug=${meta.slug}, name=${meta.name || "not set"}`);
@@ -0,0 +1,32 @@
1
+ import { Command } from "commander";
2
+ import { red } from "../lib/chalk-code-highlight";
3
+ import { normalizeHost, readAuthFile, resolveAuth } from "../lib/auth-file";
4
+ import { fetchSpec } from "../lib/spec";
5
+ import { DEFAULT_OUTPUT, SUPPORTED_OUTPUTS, print } from "../lib/renderer";
6
+
7
+ export function buildSpecCommand(): Command {
8
+ return new Command("spec")
9
+ .description("Print the live OpenAPI spec served at /api/spec")
10
+ .option("-o, --output <format>", `Output format: ${SUPPORTED_OUTPUTS.join(", ")}`, DEFAULT_OUTPUT)
11
+ .option("-h, --host <host>", "Jitsu host (overrides ~/.jitsu/jitsu-cli.json)")
12
+ .option("-k, --apikey <api-key>", "API key (overrides ~/.jitsu/jitsu-cli.json)")
13
+ .action(async (opts: { output?: string; host?: string; apikey?: string }) => {
14
+ try {
15
+ // Pass a placeholder apikey if missing — /api/spec is public, but resolveAuth
16
+ // expects an apikey. Fall back to a synthetic one if user has no auth file.
17
+ const auth = (() => {
18
+ try {
19
+ return resolveAuth(opts);
20
+ } catch {
21
+ const host = opts.host ?? readAuthFile()?.host ?? "https://use.jitsu.com";
22
+ return { host: normalizeHost(host), apikey: "anonymous" };
23
+ }
24
+ })();
25
+ const spec = await fetchSpec(auth);
26
+ print(spec, opts.output);
27
+ } catch (e) {
28
+ console.error(red(`Error: ${e instanceof Error ? e.message : String(e)}`));
29
+ process.exit(1);
30
+ }
31
+ });
32
+ }
package/src/index.ts CHANGED
@@ -8,12 +8,27 @@ import { test } from "./commands/test";
8
8
 
9
9
  import { jitsuCliVersion, jitsuCliPackageName } from "./lib/version";
10
10
  import { whoami } from "./commands/whoami";
11
+ import { buildConfigCommand } from "./commands/config";
12
+ import { buildSpecCommand } from "./commands/spec";
13
+ import { setDefaultWorkspace, unsetDefaultWorkspace } from "./commands/default-workspace";
14
+ import { preprocessArgv } from "./lib/body-fields";
11
15
 
12
- console.log(figlet.textSync("Jitsu CLI", { horizontalLayout: "full" }));
16
+ // Pull ad-hoc body field flags (--name=val, --credentials.password=...) out of argv
17
+ // before Commander parses it. Reserved option names are left in place.
18
+ process.argv = preprocessArgv(process.argv);
19
+
20
+ // Figlet banner is decorative — write it to stderr so `jitsu config ... -o json | jq`
21
+ // works without filtering. Skip it entirely when stdout is being piped or for spec output
22
+ // (which is also typically piped to other tools).
23
+ const isPipedStdout = !process.stdout.isTTY;
24
+ if (!isPipedStdout) {
25
+ process.stderr.write(figlet.textSync("Jitsu CLI", { horizontalLayout: "full" }) + "\n");
26
+ }
13
27
 
14
28
  const p = new Command();
15
29
 
16
- p.name(jitsuCliPackageName).description("CLI command to create, test and deploy extensions for Jitsu Next");
30
+ p.name(jitsuCliPackageName).description("Jitsu CLI manage workspaces, configuration objects, and extensions");
31
+
17
32
  p.command("init")
18
33
  .description("Initialize a new Jitsu extension project")
19
34
  .arguments("[dir]")
@@ -31,19 +46,6 @@ p.command("test")
31
46
  .option("-d, --dir <dir>", "the directory of project. (Optional). By default, current directory is used")
32
47
  .action(test);
33
48
 
34
- // p.command("run")
35
- // .description("Check extensions on provided event, config and persistent storage state")
36
- // .option("-d, --dir <dir>", "the directory of project. (Optional). By default, current directory is used")
37
- // .option(
38
- // "-n, --name <name>",
39
- // "name of function file to check (optional). Required if multiple functions are defined in project"
40
- // )
41
- // .option("-t, --type <type>", "entity type to run", "function")
42
- // .requiredOption("-e, --event <file_or_json>", "path to file with event json or event json as a string")
43
- // .option("-p, --props <file_or_json>", "path to file with config json or config json as a string. (Optional)")
44
- // .option("-s, --store <file_or_json>", "path to file with state json or state json as a string. (Optional)")
45
- // .action(run);
46
-
47
49
  p.command("whoami")
48
50
  .description("Check if current user is logged in. Shows user's info if logged in")
49
51
  .option("-h, --host <host>", "Jitsu host or base url", "https://use.jitsu.com")
@@ -56,6 +58,7 @@ p.command("login")
56
58
  .option("-h, --host <host>", "Jitsu host or base url", "https://use.jitsu.com")
57
59
  .option("-k, --apikey <api-key>", "Jitsu user's Api Key. (Optional). Disables interactive login.")
58
60
  .action(login);
61
+
59
62
  p.command("logout").description("Logout").option("-f, --force", "Do not ask for confirmation").action(logout);
60
63
 
61
64
  p.command("deploy")
@@ -75,9 +78,23 @@ p.command("deploy")
75
78
  .option("-n, --name <name...>", "limit deploy to provided entities only. (Optional)")
76
79
  .action(deploy);
77
80
 
78
- //version
81
+ p.command("set-default-workspace")
82
+ .description(
83
+ "Save a default workspace to ~/.jitsu/jitsu-cli.json. Subsequent `jitsu config` commands use it when -w is omitted."
84
+ )
85
+ .argument("<id-or-slug>", "Workspace id or slug")
86
+ .option("-h, --host <host>", "Jitsu host (overrides ~/.jitsu/jitsu-cli.json)")
87
+ .option("-k, --apikey <api-key>", "API key in form keyId:secret (overrides ~/.jitsu/jitsu-cli.json)")
88
+ .action(setDefaultWorkspace);
89
+
90
+ p.command("unset-default-workspace")
91
+ .description("Remove the saved default workspace from ~/.jitsu/jitsu-cli.json")
92
+ .action(unsetDefaultWorkspace);
93
+
94
+ p.addCommand(buildConfigCommand());
95
+ p.addCommand(buildSpecCommand());
96
+
79
97
  p.version(jitsuCliPackageName + " " + jitsuCliVersion, "-v, --version");
80
- //help
81
98
  p.helpOption("--help", "display help for command");
82
99
 
83
100
  p.parse();
@@ -0,0 +1,64 @@
1
+ import { AuthInfo } from "./auth-file";
2
+
3
+ export type ApiRequest = {
4
+ method?: "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
5
+ path: string;
6
+ query?: Record<string, string | number | boolean | undefined | null>;
7
+ body?: unknown;
8
+ };
9
+
10
+ export class ApiError extends Error {
11
+ status: number;
12
+ payload: unknown;
13
+ constructor(status: number, message: string, payload: unknown) {
14
+ super(message);
15
+ this.status = status;
16
+ this.payload = payload;
17
+ }
18
+ }
19
+
20
+ export class ApiClient {
21
+ constructor(private auth: AuthInfo) {}
22
+
23
+ url(path: string, query?: ApiRequest["query"]): string {
24
+ const base = this.auth.host;
25
+ const p = path.startsWith("/") ? path : `/${path}`;
26
+ if (!query) return `${base}${p}`;
27
+ const qs = Object.entries(query)
28
+ .filter(([, v]) => v !== undefined && v !== null && v !== "")
29
+ .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`)
30
+ .join("&");
31
+ return qs ? `${base}${p}?${qs}` : `${base}${p}`;
32
+ }
33
+
34
+ async request<T = unknown>(req: ApiRequest): Promise<T> {
35
+ const method = req.method ?? "GET";
36
+ const headers: Record<string, string> = {
37
+ Accept: "application/json",
38
+ Authorization: `Bearer ${this.auth.apikey}`,
39
+ };
40
+ let body: string | undefined;
41
+ if (req.body !== undefined) {
42
+ headers["Content-Type"] = "application/json";
43
+ body = JSON.stringify(req.body);
44
+ }
45
+ const res = await fetch(this.url(req.path, req.query), { method, headers, body });
46
+ const text = await res.text();
47
+ let parsed: unknown = text;
48
+ if (text && res.headers.get("content-type")?.includes("application/json")) {
49
+ try {
50
+ parsed = JSON.parse(text);
51
+ } catch {
52
+ // fall through with raw text
53
+ }
54
+ }
55
+ if (!res.ok) {
56
+ const msg =
57
+ (parsed && typeof parsed === "object" && "message" in (parsed as any)
58
+ ? String((parsed as any).message)
59
+ : undefined) ?? `HTTP ${res.status} ${method} ${req.path}`;
60
+ throw new ApiError(res.status, msg, parsed);
61
+ }
62
+ return parsed as T;
63
+ }
64
+ }
@@ -0,0 +1,83 @@
1
+ import * as fs from "fs";
2
+ import { mkdirSync, readFileSync, writeFileSync } from "fs";
3
+ import { homedir } from "os";
4
+
5
+ export type AuthInfo = { host: string; apikey: string };
6
+
7
+ export type AuthFile = {
8
+ host?: string;
9
+ apikey?: string;
10
+ defaultWorkspace?: string;
11
+ };
12
+
13
+ const DEFAULT_HOST = "https://use.jitsu.com";
14
+
15
+ export function authFilePath(): string {
16
+ return `${homedir()}/.jitsu/jitsu-cli.json`;
17
+ }
18
+
19
+ export function readAuthFile(): AuthFile | undefined {
20
+ const path = authFilePath();
21
+ if (!fs.existsSync(path)) return undefined;
22
+ return JSON.parse(readFileSync(path, { encoding: "utf-8" }));
23
+ }
24
+
25
+ // Merge `patch` into the existing auth file, creating the file (and parent dir)
26
+ // if necessary. Setting a field to `undefined` removes it.
27
+ export function updateAuthFile(patch: Partial<AuthFile>): AuthFile {
28
+ const path = authFilePath();
29
+ const existing = readAuthFile() ?? {};
30
+ const next: AuthFile = { ...existing };
31
+ for (const [k, v] of Object.entries(patch)) {
32
+ if (v === undefined) delete (next as any)[k];
33
+ else (next as any)[k] = v;
34
+ }
35
+ mkdirSync(`${homedir()}/.jitsu`, { recursive: true });
36
+ writeFileSync(path, JSON.stringify(next, null, 2));
37
+ return next;
38
+ }
39
+
40
+ export function readDefaultWorkspace(): string | undefined {
41
+ return readAuthFile()?.defaultWorkspace;
42
+ }
43
+
44
+ // Resolve host + apikey for an authenticated CLI command. Order of precedence:
45
+ // 1. --host / --apikey flags
46
+ // 2. ~/.jitsu/jitsu-cli.json
47
+ // 3. JITSU_HOST / JITSU_APIKEY env vars
48
+ // 4. https://use.jitsu.com (host only)
49
+ export function resolveAuth(opts: { host?: string; apikey?: string }): AuthInfo {
50
+ let host = opts.host;
51
+ let apikey = opts.apikey;
52
+
53
+ if (!host || !apikey) {
54
+ const file = readAuthFile();
55
+ if (file) {
56
+ if (!host) host = file.host;
57
+ if (!apikey) apikey = file.apikey;
58
+ }
59
+ }
60
+
61
+ if (!host) host = process.env.JITSU_HOST;
62
+ if (!apikey) apikey = process.env.JITSU_APIKEY;
63
+ if (!host) host = DEFAULT_HOST;
64
+
65
+ if (!apikey) {
66
+ throw new Error("Not authenticated. Run `jitsu login`, set JITSU_APIKEY, or pass --apikey <key>.");
67
+ }
68
+
69
+ return { host: normalizeHost(host), apikey };
70
+ }
71
+
72
+ export function normalizeHost(host: string): string {
73
+ let url = host;
74
+ if (!url.startsWith("http")) {
75
+ if (url.startsWith("localhost") || /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/.test(url)) {
76
+ url = "http://" + url;
77
+ } else {
78
+ url = "https://" + url;
79
+ }
80
+ }
81
+ if (url.endsWith("/")) url = url.slice(0, -1);
82
+ return url;
83
+ }
@@ -0,0 +1,68 @@
1
+ import * as fs from "fs";
2
+ import yaml from "js-yaml";
3
+ import { parseScalar, setDottedPath } from "./dotted";
4
+
5
+ export type BodySources = {
6
+ // Path to a yaml/json file. `-` means stdin.
7
+ file?: string;
8
+ // Inline JSON string (full body or partial).
9
+ json?: string;
10
+ // Already-parsed dotted-path fields, e.g. { "credentials.password": "secret" }.
11
+ fields?: Record<string, string>;
12
+ };
13
+
14
+ // Builds a single request body by merging (deep) sources in this order:
15
+ // 1. -f / --file
16
+ // 2. --json
17
+ // 3. dotted-path flags
18
+ // Later sources override earlier ones at the leaf level. Arrays are replaced, not concatenated.
19
+ // Returns undefined if no source is provided.
20
+ export function buildBody(sources: BodySources): unknown {
21
+ const layers: any[] = [];
22
+ if (sources.file) layers.push(loadFile(sources.file));
23
+ if (sources.json) layers.push(parseInlineJson(sources.json));
24
+ if (sources.fields && Object.keys(sources.fields).length > 0) {
25
+ const obj: any = {};
26
+ for (const [path, raw] of Object.entries(sources.fields)) {
27
+ setDottedPath(obj, path, parseScalar(raw));
28
+ }
29
+ layers.push(obj);
30
+ }
31
+ if (layers.length === 0) return undefined;
32
+ return layers.reduce((acc, layer) => deepMerge(acc, layer), {});
33
+ }
34
+
35
+ function loadFile(path: string): unknown {
36
+ const text = path === "-" ? fs.readFileSync(0, "utf-8") : fs.readFileSync(path, "utf-8");
37
+ // js-yaml's safeLoad handles JSON too (JSON is valid YAML). But trim first — empty file is null.
38
+ const parsed = yaml.load(text);
39
+ if (parsed === null || parsed === undefined) {
40
+ throw new Error(`File ${path} parsed as empty`);
41
+ }
42
+ return parsed;
43
+ }
44
+
45
+ function parseInlineJson(s: string): unknown {
46
+ try {
47
+ return JSON.parse(s);
48
+ } catch (e) {
49
+ throw new Error(`--json value is not valid JSON: ${(e as Error).message}`);
50
+ }
51
+ }
52
+
53
+ function isPlainObject(v: unknown): v is Record<string, unknown> {
54
+ return typeof v === "object" && v !== null && !Array.isArray(v);
55
+ }
56
+
57
+ function deepMerge(target: any, source: any): any {
58
+ if (!isPlainObject(target) || !isPlainObject(source)) return source;
59
+ const out: any = { ...target };
60
+ for (const [k, v] of Object.entries(source)) {
61
+ if (isPlainObject(v) && isPlainObject(out[k])) {
62
+ out[k] = deepMerge(out[k], v);
63
+ } else {
64
+ out[k] = v;
65
+ }
66
+ }
67
+ return out;
68
+ }
@@ -0,0 +1,61 @@
1
+ // Pre-extracts body field flags from process.argv before Commander parses it.
2
+ //
3
+ // Why: we want users to write `--credentials.password=secret` and `--destinationType=postgres`
4
+ // as ad-hoc body fields, but Commander would reject unknown options. The simplest robust
5
+ // solution is to filter argv: anything matching `--<name>=<value>` whose head segment is NOT
6
+ // a reserved Commander option is captured here, and the rest is left for Commander.
7
+ //
8
+ // Single global stash is fine because the CLI runs one command per process.
9
+
10
+ // Reserved option names — any `--name=value` whose head is in this set is left for Commander.
11
+ // Everything else becomes a body field (top-level for flat names, nested for dotted ones).
12
+ const RESERVED = new Set([
13
+ "workspace",
14
+ "output",
15
+ "host",
16
+ "apikey",
17
+ "file",
18
+ "json",
19
+ "cascade",
20
+ "strict",
21
+ "from",
22
+ "to",
23
+ "help",
24
+ "version",
25
+ ]);
26
+
27
+ const fields: Record<string, string> = {};
28
+
29
+ // Activate body-field extraction only for the `config` command group. Otherwise the
30
+ // preprocessor would steal flags from `deploy --type=function --name=foo` etc.
31
+ function shouldExtract(argv: string[]): boolean {
32
+ for (let i = 2; i < argv.length; i++) {
33
+ const a = argv[i];
34
+ if (a.startsWith("-")) continue;
35
+ return a === "config";
36
+ }
37
+ return false;
38
+ }
39
+
40
+ export function preprocessArgv(argv: string[]): string[] {
41
+ if (!shouldExtract(argv)) return argv;
42
+ const out: string[] = [];
43
+ for (const arg of argv) {
44
+ const m = /^--([a-zA-Z][\w.-]*)=([\s\S]*)$/.exec(arg);
45
+ if (m) {
46
+ const head = m[1].split(".")[0];
47
+ if (!RESERVED.has(head)) {
48
+ fields[m[1]] = m[2];
49
+ continue;
50
+ }
51
+ }
52
+ out.push(arg);
53
+ }
54
+ return out;
55
+ }
56
+
57
+ export function consumeBodyFields(): Record<string, string> {
58
+ const copy = { ...fields };
59
+ for (const k of Object.keys(fields)) delete fields[k];
60
+ return copy;
61
+ }
@@ -1,7 +1,8 @@
1
1
  import { JitsuFunction } from "@jitsu/protocols/functions";
2
2
  import fs from "fs";
3
- import { rollup } from "rollup";
3
+ import * as esbuild from "esbuild";
4
4
  import { assertDefined, assertTrue } from "juava";
5
+ import path from "path";
5
6
 
6
7
  export type CompiledFunction = {
7
8
  func: JitsuFunction;
@@ -14,10 +15,11 @@ export type CompiledFunction = {
14
15
  };
15
16
 
16
17
  function getSlug(filePath: string) {
17
- return filePath.split("/").pop()?.replace(".ts", "");
18
+ return filePath.split("/").pop()?.replace(".ts", "").replace(".js", "");
18
19
  }
19
20
 
20
21
  export async function getFunctionFromFilePath(
22
+ projectDir: string,
21
23
  filePath: string,
22
24
  kind: "function" | "profile",
23
25
  profileBuilders: any[] = []
@@ -28,29 +30,34 @@ export async function getFunctionFromFilePath(
28
30
  throw new Error(`Cannot load function from file ${filePath}: path is not a file`);
29
31
  }
30
32
 
31
- const bundle = await rollup({
32
- input: [filePath],
33
- external: ["@jitsu/functions-lib"],
34
- logLevel: "silent",
33
+ // Transform ESM to CJS without bundling - just convert the module format
34
+ // This avoids resolving dependencies which may be symlinked
35
+ const result = await esbuild.transform(fs.readFileSync(filePath, "utf-8"), {
36
+ loader: filePath.endsWith(".ts") ? "ts" : "js",
37
+ format: "cjs",
38
+ platform: "node",
35
39
  });
36
40
 
37
- const output = await bundle.generate({
38
- file: filePath,
39
- format: "commonjs",
40
- });
41
-
42
- const exports: Record<string, any> = {} as Record<string, any>;
43
- eval(output.output[0].code);
41
+ const code = result.code;
42
+ const module: { exports: Record<string, any> } = { exports: {} };
43
+ const exports = module.exports;
44
+ // Provide require stub for external imports that we mock out
45
+ const require = (id: string) => {
46
+ // External dependencies are not needed for config extraction
47
+ return {};
48
+ };
49
+ eval(code);
50
+ // After eval, module.exports contains the actual exports
51
+ const moduleExports = module.exports;
44
52
  assertDefined(
45
- exports.default,
46
- `Function from ${filePath} doesn't have default export. Exported symbols: ${Object.keys(exports)}`
53
+ moduleExports.default,
54
+ `Function from ${filePath} doesn't have default export. Exported symbols: ${Object.keys(moduleExports)}`
47
55
  );
48
- assertTrue(typeof exports.default === "function", `Default export from ${filePath} is not a function`);
49
-
50
- let name = exports.config?.name || exports.config?.slug || getSlug(filePath);
51
- let id = exports.config?.id;
56
+ assertTrue(typeof moduleExports.default === "function", `Default export from ${filePath} is not a function`);
57
+ let name = moduleExports.config?.name || moduleExports.config?.slug || getSlug(filePath);
58
+ let id = moduleExports.config?.id;
52
59
  if (kind === "profile") {
53
- const profileBuilderId = exports.config?.profileBuilderId;
60
+ const profileBuilderId = moduleExports.config?.profileBuilderId;
54
61
  const profileBuilder = profileBuilders.find(pb => pb.id === profileBuilderId);
55
62
  if (!profileBuilder) {
56
63
  throw new Error(
@@ -67,12 +74,12 @@ export async function getFunctionFromFilePath(
67
74
  }
68
75
 
69
76
  return {
70
- func: exports.default,
77
+ func: moduleExports.default,
71
78
  meta: {
72
- slug: exports.config?.slug || getSlug(filePath),
79
+ slug: moduleExports.config?.slug || getSlug(filePath),
73
80
  id: id,
74
81
  name: name,
75
- description: exports.config?.description,
82
+ description: moduleExports.config?.description,
76
83
  },
77
84
  };
78
85
  }