@engini/cli 0.21.0 → 0.23.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 (3) hide show
  1. package/README.md +12 -6
  2. package/dist/cli.js +118 -35
  3. package/package.json +2 -2
package/README.md CHANGED
@@ -64,7 +64,7 @@ resulting, plus explicit added/removed lists) rather than just echoing the
64
64
  outgoing request.
65
65
 
66
66
  A trigger instance (`ti_…`) is an entity, not a workflow step — created from a
67
- trigger type against a connection. There are two ways to receive its events, and
67
+ trigger type, against a connection when the application requires one. There are two ways to receive its events, and
68
68
  they need opposite code: a **destination** is production delivery (signed via
69
69
  `destinations`); `listen` is a live SSE stream for local dev only (unsigned, no
70
70
  delivery guarantees). `events` is the historical log with real delivery state;
@@ -96,9 +96,15 @@ engini connect monday --json # → {need:"fields", resume:"engi
96
96
  engini connect monday --auth 0 --field ApiKey=<key> # creates → checks → refreshes
97
97
 
98
98
  # OAuth2 (e.g. outlook) — never opens a browser for the agent
99
- engini connect outlook --json # → {need:"oauth", sign_in_url, state, resume:"engini connect outlook --oauth-state <state>"}
100
- # show sign_in_url to the user; after they sign in:
101
- engini connect outlook --oauth-state <state> # polls token → creates → checks → refreshes
99
+ engini connect outlook --json # → {need:"oauth", sign_in_url, state, state_expires_in_seconds, resume:"engini connect outlook --auth 0 --oauth-state <state>"}
100
+ # show sign_in_url to the user - they must sign in within state_expires_in_seconds of
101
+ # minting; past that the server has purged the state and the resume below fails fast, not hangs:
102
+ engini connect outlook --auth 0 --oauth-state <state> # polls token → creates → checks → refreshes
103
+
104
+ # re-authenticate an EXISTING OAuth2 connection in place — same sign-in flow,
105
+ # but --oauth-state alone (no --field/--name/--metadata) is a valid edit and
106
+ # keeps the connection id instead of minting a new one
107
+ engini connections update 481 --oauth-state <state>
102
108
 
103
109
  # object selection (apps that support it) — resume never re-creates
104
110
  engini connect <app> --json # → {need:"objects", connection_id, objects, resume:"engini connect <app> --connection <id> --object <id>"}
@@ -106,8 +112,8 @@ engini connect <app> --connection <id> --object 5 --object 9
106
112
  ```
107
113
 
108
114
  The same steps are available as standalone primitives: `connections sign-in-url`
109
- / `oauth-complete` (OAuth) and `connections create` / `check` / `refresh` /
110
- `objects` / `select-objects`.
115
+ / `oauth-complete` (OAuth), `connections update` (re-authenticate in place), and
116
+ `connections create` / `check` / `refresh` / `objects` / `select-objects`.
111
117
 
112
118
  ## Output & exit codes
113
119
 
package/dist/cli.js CHANGED
@@ -442,7 +442,7 @@ function saveConfig(config, path = configPath()) {
442
442
  }
443
443
 
444
444
  // src/version.ts
445
- var VERSION = true ? "0.21.0" : "0.0.0";
445
+ var VERSION = true ? "0.23.0" : "0.0.0";
446
446
 
447
447
  // src/http.ts
448
448
  var USER_AGENT_PREFIX = `engini-cli/${VERSION}`;
@@ -592,6 +592,7 @@ async function safeTrigger(action, what) {
592
592
  var OAUTH_DONE = /* @__PURE__ */ new Set(["completed", "complete", "success", "succeeded"]);
593
593
  var OAUTH_FAILED = /* @__PURE__ */ new Set(["failed", "error", "cancelled", "canceled", "denied"]);
594
594
  var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
595
+ var OAUTH_STATE_TTL_SECONDS = 300;
595
596
  function collect(value, previous = []) {
596
597
  return [...previous, value];
597
598
  }
@@ -648,6 +649,13 @@ async function pollAccessToken(client, state, opts) {
648
649
  const deadline = Date.now() + opts.timeout * 1e3;
649
650
  for (; ; ) {
650
651
  const resp = await client.connections.getAccessToken(state);
652
+ if (resp == null) {
653
+ fail(
654
+ 4 /* NOT_FOUND */,
655
+ `OAuth sign-in state not found - it may have expired (states are purged ${OAUTH_STATE_TTL_SECONDS} seconds after they're minted) or never existed.`,
656
+ "Start over: `engini connect <app>` mints a fresh sign_in_url + state."
657
+ );
658
+ }
651
659
  const status = (resp.status ?? "").toLowerCase();
652
660
  if (OAUTH_DONE.has(status)) return resp;
653
661
  if (OAUTH_FAILED.has(status)) {
@@ -662,13 +670,14 @@ async function pollAccessToken(client, state, opts) {
662
670
  function oauthFields(token) {
663
671
  const fields = {};
664
672
  for (const [key, value] of Object.entries(token.connectionData ?? {})) {
665
- if (value === null || value === void 0) continue;
673
+ if (value === null || value === void 0 || value === "") continue;
666
674
  fields[key] = typeof value === "string" ? value : JSON.stringify(value);
667
675
  }
668
676
  return fields;
669
677
  }
670
678
 
671
679
  // src/connect.ts
680
+ var PLACEHOLDER = "<value>";
672
681
  function connectionsUrl(config) {
673
682
  return `${config.identity_url.replace(/\/+$/, "")}/connections#integrations`;
674
683
  }
@@ -711,7 +720,7 @@ async function connectBody(application, opts) {
711
720
  return;
712
721
  }
713
722
  const name = await resolveName(opts.name, application);
714
- const credentials = method.requiresOAuthSignIn ? await oauthFieldsFor(client, application, method, opts.oauthState, timing) : { fields: await collectFields(method, application, opts.field) };
723
+ const credentials = method.requiresOAuthSignIn ? await oauthFieldsFor(client, application, method, opts.oauthState, opts.field, timing) : { fields: await collectFields(method, application, parseFields(opts.field)) };
715
724
  progress(`Creating connection '${name}'\u2026`);
716
725
  const created = await client.connections.create(
717
726
  application,
@@ -800,7 +809,7 @@ async function chooseAuth(methods, auth, application) {
800
809
  resume: `engini connect ${application} --auth <id>`
801
810
  });
802
811
  }
803
- async function collectFields(method, application, field) {
812
+ async function collectFields(method, application, provided, oauthState) {
804
813
  async function readSecretField(label) {
805
814
  const { value, truncated } = await promptHidden(label);
806
815
  if (truncated) {
@@ -812,8 +821,10 @@ async function collectFields(method, application, field) {
812
821
  }
813
822
  return value;
814
823
  }
815
- const provided = parseFields(field);
816
824
  const schema = method.connectionFields.filter((f) => !f.isHidden);
825
+ for (const [k, v] of Object.entries(provided)) {
826
+ if (v === PLACEHOLDER) delete provided[k];
827
+ }
817
828
  const required = schema.filter((f) => f.isRequired);
818
829
  const missing = required.filter((f) => !(f.fieldName in provided));
819
830
  if (missing.length === 0) return provided;
@@ -826,13 +837,19 @@ async function collectFields(method, application, field) {
826
837
  }
827
838
  return provided;
828
839
  }
829
- const fieldsFlags = required.map((f) => `--field ${f.fieldName}=<value>`).join(" ");
840
+ const fieldsFlags = missing.map((f) => `--field ${f.fieldName}=${PLACEHOLDER}`).join(" ");
841
+ const resumeParts = [
842
+ `engini connect ${application}`,
843
+ `--auth ${method.authenticationId}`,
844
+ ...oauthState ? [`--oauth-state ${oauthState}`] : [],
845
+ fieldsFlags
846
+ ].filter(Boolean);
830
847
  return need({
831
848
  need: "fields",
832
849
  application,
833
850
  authentication_id: method.authenticationId,
834
851
  fields: schema.map(fieldSummary),
835
- resume: `engini connect ${application} --auth ${method.authenticationId} ${fieldsFlags}`
852
+ resume: resumeParts.join(" ")
836
853
  });
837
854
  }
838
855
  async function resolveName(name, application) {
@@ -870,27 +887,64 @@ async function resolveObjects(objs, connectionId, application) {
870
887
  resume: `engini connect ${app} --connection ${connectionId} --object <id>`
871
888
  });
872
889
  }
873
- async function oauthFieldsFor(client, application, method, oauthState, timing) {
890
+ async function oauthFieldsFor(client, application, method, oauthState, field, timing) {
891
+ const cliFields = parseFields(field);
874
892
  if (oauthState) {
875
893
  const token = await pollAccessToken(client, oauthState, timing);
876
- return { fields: oauthFields(token), state: oauthState };
894
+ const merged = { ...cliFields, ...oauthFields(token) };
895
+ return { fields: await collectFields(method, application, merged, oauthState), state: oauthState };
877
896
  }
878
- const resp = await client.connections.getSignInUrl(application, method.authenticationId);
897
+ const resp = await client.connections.getSignInUrl(application, method.authenticationId, {
898
+ fields: field && field.length > 0 ? cliFields : void 0
899
+ });
879
900
  if (isTty() && timing.wait) {
880
901
  openBrowser(resp.signInUrl);
881
902
  progress(`Opened ${resp.signInUrl} \u2014 complete the sign-in in your browser.`);
882
903
  const token = await pollAccessToken(client, resp.state, timing);
883
- return { fields: oauthFields(token), state: resp.state };
904
+ const merged = { ...cliFields, ...oauthFields(token) };
905
+ return { fields: await collectFields(method, application, merged, resp.state), state: resp.state };
884
906
  }
907
+ const secretFields = new Set(
908
+ method.connectionFields.filter(isSecretField).map((f) => f.fieldName)
909
+ );
885
910
  return need({
886
911
  need: "oauth",
887
912
  application,
888
913
  authentication_id: method.authenticationId,
889
914
  sign_in_url: resp.signInUrl,
890
915
  state: resp.state,
891
- resume: `engini connect ${application} --oauth-state ${resp.state}`
916
+ // The state is perishable - the server purges it this long after minting, regardless of
917
+ // whether anyone has signed in yet - so a caller replaying `resume` late (the common case
918
+ // once a human is in the loop) can tell a stale state from one that's still good.
919
+ state_expires_in_seconds: OAUTH_STATE_TTL_SECONDS,
920
+ // Replayable verbatim: --auth plus every --field the caller already passed, so resuming
921
+ // this exact string never falls back to need:"auth" or silently drops --field again
922
+ // (reproduced against production with the old bare `--oauth-state <state>` hint). A
923
+ // password field's value is placeholdered rather than echoed (never print a secret to
924
+ // stdout), and every value is shell-quoted when it needs it (field values can contain
925
+ // spaces or shell metacharacters).
926
+ resume: [
927
+ `engini connect ${application}`,
928
+ `--auth ${method.authenticationId}`,
929
+ `--oauth-state ${resp.state}`,
930
+ ...(field ?? []).map((spec) => resumeFieldFlag(spec, secretFields))
931
+ ].join(" ")
892
932
  });
893
933
  }
934
+ var SAFE_BAREWORD = /^[A-Za-z0-9_@%+:,./=-]+$/;
935
+ function shellQuoteFieldSpec(spec) {
936
+ if (SAFE_BAREWORD.test(spec)) return spec;
937
+ return `'${spec.replace(/'/g, `'\\''`)}'`;
938
+ }
939
+ function isSecretField(f) {
940
+ return f.isPassword || Boolean(f.maskInLogs);
941
+ }
942
+ function resumeFieldFlag(spec, secretFields) {
943
+ const eq = spec.indexOf("=");
944
+ const key = spec.slice(0, eq);
945
+ if (secretFields.has(key)) return `--field ${key}=${PLACEHOLDER}`;
946
+ return `--field ${shellQuoteFieldSpec(spec)}`;
947
+ }
894
948
  function fieldLabel(f) {
895
949
  const label = clean(f.fieldDescription) ?? f.fieldName;
896
950
  const placeholder = clean(f.placeholder);
@@ -913,8 +967,7 @@ function methodSummary(m) {
913
967
  };
914
968
  }
915
969
  function methodHelpUrl(m) {
916
- const value = m.helpUrl;
917
- return typeof value === "string" && value.trim() !== "" ? value : null;
970
+ return typeof m.helpUrl === "string" && m.helpUrl.trim() !== "" ? m.helpUrl : null;
918
971
  }
919
972
  function fieldSummary(f) {
920
973
  return {
@@ -1648,12 +1701,12 @@ ON-PREMISE AGENTS
1648
1701
 
1649
1702
  TRIGGERS
1650
1703
  A trigger instance (ti_\u2026) is an entity, not a workflow step - created from a trigger
1651
- type (a catalog slug) against a connection.
1704
+ type (a catalog slug), against a connection when the application requires one.
1652
1705
  triggers types [--app <slug>] [--search <q>] [--connection <id>] List the catalog.
1653
1706
  triggers types get <trigger_slug> [--app <slug>] config_schema/payload_schema/parameters.
1654
1707
  triggers list [--app <s>] [--connection <id>] [--status <s>] [--include workflow] [--top <n>]
1655
1708
  triggers get <trigger_id> Status, schedule, last-error detail.
1656
- triggers create <trigger_slug> --connection <name|id> [--config <json>] [--every <n><s|m|h|d>]
1709
+ triggers create <trigger_slug> [--connection <name|id>] [--config <json>] [--every <n><s|m|h|d>]
1657
1710
  [--weekdays <spec>] [--window <HH:mm-HH:mm>] [--listen <col>...] [--destination <name>]
1658
1711
  [--dedupe-window-hours <n>]
1659
1712
  triggers enable <id> | triggers disable <id> Toggle capture; not a delete.
@@ -3755,6 +3808,9 @@ function registerToolsets(program) {
3755
3808
  import { EnginiNotFoundError as EnginiNotFoundError2 } from "@engini/sdk";
3756
3809
 
3757
3810
  // src/triggers/shared.ts
3811
+ import {
3812
+ EnginiValidationError as EnginiValidationError2
3813
+ } from "@engini/sdk";
3758
3814
  var TRIGGER_ID_RE = /^ti_[A-Za-z0-9]+$/;
3759
3815
  function parseTriggerId(raw) {
3760
3816
  if (raw === void 0 || raw === "") fail(2 /* USAGE */, "A trigger id is required.");
@@ -3778,6 +3834,19 @@ function parseConfig(raw) {
3778
3834
  fail(2 /* USAGE */, `--config is not valid JSON: '${raw}'.`);
3779
3835
  }
3780
3836
  }
3837
+ function rewriteConnectionRequired(err, triggerSlug) {
3838
+ if (!(err instanceof EnginiValidationError2) || err.errorCode !== "EMPTY_QUERY") {
3839
+ return err;
3840
+ }
3841
+ const namesConnection = err.details.some(
3842
+ (d) => d.field === "connection_id"
3843
+ );
3844
+ if (!namesConnection) return err;
3845
+ return new EnginiValidationError2(
3846
+ `Trigger type '${triggerSlug}' requires a connection. Pass --connection NAME|ID.`,
3847
+ { errorCode: err.errorCode, details: err.details }
3848
+ );
3849
+ }
3781
3850
  var WEEKDAY_NAMES = {
3782
3851
  sun: 0,
3783
3852
  mon: 1,
@@ -3885,6 +3954,7 @@ function summarizeEvent(e) {
3885
3954
 
3886
3955
  // src/triggers/create.ts
3887
3956
  function connectionRef(raw) {
3957
+ if (raw === void 0) return {};
3888
3958
  return /^\d+$/.test(raw) ? { connectionId: Number(raw) } : { connectionName: raw };
3889
3959
  }
3890
3960
  async function hasAccountDefaultDestination() {
@@ -3898,8 +3968,11 @@ async function hasAccountDefaultDestination() {
3898
3968
  }
3899
3969
  async function createBody4(triggerSlug, opts) {
3900
3970
  if (triggerSlug === void 0 || triggerSlug === "") fail(2 /* USAGE */, "A trigger_slug is required.");
3901
- if (opts.connection === void 0 || opts.connection === "") {
3902
- fail(2 /* USAGE */, "--connection is required (a connection name or id).");
3971
+ if (opts.connection === "") {
3972
+ fail(
3973
+ 2 /* USAGE */,
3974
+ "--connection cannot be empty; omit the flag entirely to use the trigger type's own connection, or pass a name or id."
3975
+ );
3903
3976
  }
3904
3977
  const config = parseConfig(opts.config);
3905
3978
  const schedule = parseSchedule(opts);
@@ -3908,7 +3981,7 @@ async function createBody4(triggerSlug, opts) {
3908
3981
  printOutput({
3909
3982
  would_create: {
3910
3983
  trigger_slug: triggerSlug,
3911
- connection: opts.connection,
3984
+ connection: opts.connection ?? null,
3912
3985
  config,
3913
3986
  schedule,
3914
3987
  listen_columns: opts.listen,
@@ -3923,17 +3996,21 @@ async function createBody4(triggerSlug, opts) {
3923
3996
  const dest = await apiErrors(async () => buildClient().triggers.destinations.get(opts.destination));
3924
3997
  destinationId = dest.id;
3925
3998
  }
3926
- const trigger = await apiErrors(
3927
- async () => buildClient().triggers.create({
3928
- triggerSlug,
3929
- ...connectionRef(opts.connection),
3930
- config,
3931
- schedule,
3932
- listenColumns: opts.listen,
3933
- destinationId,
3934
- dedupeWindowHours
3935
- })
3936
- );
3999
+ const trigger = await apiErrors(async () => {
4000
+ try {
4001
+ return await buildClient().triggers.create({
4002
+ triggerSlug,
4003
+ ...connectionRef(opts.connection),
4004
+ config,
4005
+ schedule,
4006
+ listenColumns: opts.listen,
4007
+ destinationId,
4008
+ dedupeWindowHours
4009
+ });
4010
+ } catch (err) {
4011
+ throw rewriteConnectionRequired(err, triggerSlug);
4012
+ }
4013
+ });
3937
4014
  if (opts.destination === void 0) {
3938
4015
  const hasDefault = await apiErrors(hasAccountDefaultDestination);
3939
4016
  if (!hasDefault) {
@@ -3949,7 +4026,10 @@ async function createBody4(triggerSlug, opts) {
3949
4026
  });
3950
4027
  }
3951
4028
  function registerTriggerCreate(triggers) {
3952
- const create = triggers.command("create").description("Create a trigger instance from a trigger type.").argument("[trigger_slug]", "Trigger type slug, as listed by `types`").option("--connection <name|id>", "The connection to run against (required)").option("--config <json>", "The trigger activity's own inputs, as JSON (server-validated)").option("--every <n><s|m|h|d>", "Polling cadence, e.g. 15m, 2h, 1d").option("--weekdays <spec>", "e.g. mon-fri, sun,wed \u2014 only meaningful with a week schedule").option("--window <HH:mm-HH:mm>", "Restrict polling to a time-of-day window").option("--listen <column>", "A column to watch (repeatable)", collect3, []).option("--destination <name>", "Deliver to this named destination instead of the account default").option("--dedupe-window-hours <n>", "Hours to suppress duplicate events");
4029
+ const create = triggers.command("create").description("Create a trigger instance from a trigger type.").argument("[trigger_slug]", "Trigger type slug, as listed by `types`").option(
4030
+ "--connection <name|id>",
4031
+ "The connection to run against (defaults to the trigger type's own connection for types that need none)"
4032
+ ).option("--config <json>", "The trigger activity's own inputs, as JSON (server-validated)").option("--every <n><s|m|h|d>", "Polling cadence, e.g. 15m, 2h, 1d").option("--weekdays <spec>", "e.g. mon-fri, sun,wed \u2014 only meaningful with a week schedule").option("--window <HH:mm-HH:mm>", "Restrict polling to a time-of-day window").option("--listen <column>", "A column to watch (repeatable)", collect3, []).option("--destination <name>", "Deliver to this named destination instead of the account default").option("--dedupe-window-hours <n>", "Hours to suppress duplicate events");
3953
4033
  create.addHelpText(
3954
4034
  "after",
3955
4035
  "\nExamples:\n engini triggers create monday_item_created --connection 12 --dry-run\n engini triggers create monday_item_created --connection billing --every 15m\n engini triggers create netsuite_record_updated --connection 3 --weekdays mon-fri --window 09:00-17:00"
@@ -4213,7 +4293,7 @@ function sign(secret, bodyBytes) {
4213
4293
  const mac = createHmac("sha256", Buffer.from(secret, "utf8")).update(Buffer.concat([Buffer.from(`${t}.`, "utf8"), bodyBytes])).digest("hex");
4214
4294
  return `t=${t},v1=${mac}`;
4215
4295
  }
4216
- async function forwardEvent(frame, url, secret) {
4296
+ async function forwardEvent(frame, url, secret, signal) {
4217
4297
  const body = buildDeliveryBody(frame);
4218
4298
  const bytes = Buffer.from(JSON.stringify(body), "utf8");
4219
4299
  const headers = {
@@ -4227,7 +4307,7 @@ async function forwardEvent(frame, url, secret) {
4227
4307
  }
4228
4308
  if (secret) headers["X-Engini-Signature"] = sign(secret, bytes);
4229
4309
  try {
4230
- const res = await fetch(url, { method: "POST", headers, body: bytes });
4310
+ const res = await fetch(url, { method: "POST", headers, body: bytes, signal });
4231
4311
  if (!res.ok) {
4232
4312
  console.error(`forward to ${url} failed: HTTP ${res.status}`);
4233
4313
  return false;
@@ -4246,8 +4326,10 @@ async function listenBody(opts) {
4246
4326
  );
4247
4327
  }
4248
4328
  let interrupted = false;
4329
+ const controller = new AbortController();
4249
4330
  const onSigint = () => {
4250
4331
  interrupted = true;
4332
+ controller.abort();
4251
4333
  };
4252
4334
  process.once("SIGINT", onSigint);
4253
4335
  let events = 0;
@@ -4260,14 +4342,15 @@ async function listenBody(opts) {
4260
4342
  triggerSlug: opts.slug,
4261
4343
  applicationSlug: opts.app,
4262
4344
  since: opts.since,
4263
- autoResume: opts.resume
4345
+ autoResume: opts.resume,
4346
+ signal: controller.signal
4264
4347
  });
4265
4348
  for await (const frame of stream) {
4266
4349
  if (interrupted) break;
4267
4350
  events += 1;
4268
4351
  emitEvent(frame);
4269
4352
  if (opts.forward !== void 0) {
4270
- const ok = await forwardEvent(frame, opts.forward, secret);
4353
+ const ok = await forwardEvent(frame, opts.forward, secret, controller.signal);
4271
4354
  if (ok) forwarded += 1;
4272
4355
  else failed += 1;
4273
4356
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@engini/cli",
3
- "version": "0.21.0",
3
+ "version": "0.23.0",
4
4
  "description": "Engini CLI — machine-first command line over the Engini Public API",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -26,7 +26,7 @@
26
26
  "test": "vitest run"
27
27
  },
28
28
  "dependencies": {
29
- "@engini/sdk": "^0.21.0",
29
+ "@engini/sdk": "^0.23.0",
30
30
  "commander": "^12.1.0",
31
31
  "smol-toml": "^1.3.0"
32
32
  },