@erdoai/cli 0.177.1 → 0.178.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 (2) hide show
  1. package/dist/index.js +211 -30
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -57,6 +57,72 @@ function describeRefreshWrites(strategy, mode, key, liveMode) {
57
57
  // src/index.ts
58
58
  import { readFileSync as readFileSync4, writeFileSync as writeFileSync3 } from "fs";
59
59
  import { basename } from "path";
60
+
61
+ // src/csv.ts
62
+ function parseCSV(text) {
63
+ const rows = [];
64
+ let row = [];
65
+ let field = "";
66
+ let quoted = false;
67
+ let closed = false;
68
+ let line = 1;
69
+ let quoteLine = 0;
70
+ let i = text.charCodeAt(0) === 65279 ? 1 : 0;
71
+ const endRow = () => {
72
+ row.push(field);
73
+ field = "";
74
+ closed = false;
75
+ if (row.some((cell) => cell.trim() !== "")) rows.push(row);
76
+ row = [];
77
+ };
78
+ for (; i < text.length; i++) {
79
+ const c = text[i];
80
+ if (quoted) {
81
+ if (c === '"') {
82
+ if (text[i + 1] === '"') {
83
+ field += '"';
84
+ i++;
85
+ } else {
86
+ quoted = false;
87
+ closed = true;
88
+ }
89
+ } else {
90
+ if (c === "\n" || c === "\r" && text[i + 1] !== "\n") line++;
91
+ field += c;
92
+ }
93
+ continue;
94
+ }
95
+ if (c === ",") {
96
+ row.push(field);
97
+ field = "";
98
+ closed = false;
99
+ } else if (c === "\n") {
100
+ endRow();
101
+ line++;
102
+ } else if (c === "\r") {
103
+ if (text[i + 1] === "\n") i++;
104
+ endRow();
105
+ line++;
106
+ } else if (closed) {
107
+ throw new Error(`CSV line ${line}: unexpected text after a closing quote; a quoted field must end at a comma or line end (write a literal quote as "")`);
108
+ } else if (c === '"') {
109
+ if (field !== "") {
110
+ throw new Error(`CSV line ${line}: a quote inside an unquoted field; quote the whole field and write the literal quote as ""`);
111
+ }
112
+ quoted = true;
113
+ quoteLine = line;
114
+ } else {
115
+ field += c;
116
+ }
117
+ }
118
+ if (quoted) {
119
+ throw new Error(`CSV line ${quoteLine}: a quoted field is never closed; the file ends inside it, so every line after it would be read as part of that one cell`);
120
+ }
121
+ if (field !== "" || row.length > 0 || closed) endRow();
122
+ return rows;
123
+ }
124
+
125
+ // src/index.ts
60
126
  import { password, select } from "@inquirer/prompts";
61
127
  import { Command as Command2, Option as Option2 } from "commander";
62
128
 
@@ -1366,8 +1432,12 @@ var ErdoClient = class {
1366
1432
  setProviderLeadSource(input) {
1367
1433
  return this.request("PUT", "/v1/provider-lead-sources", input, false);
1368
1434
  }
1369
- deleteProviderLeadSource(provider, accountId) {
1370
- const q = new URLSearchParams({ provider, account_id: accountId });
1435
+ importLeadSourceRows(input) {
1436
+ return this.request("POST", "/v1/provider-lead-sources/import", input, false);
1437
+ }
1438
+ deleteProviderLeadSource(by) {
1439
+ const q = new URLSearchParams("name" in by ? { name: by.name } : { provider: by.provider, account_id: by.accountId });
1440
+ if (by.ifUpdatedAt) q.set("if_updated_at", by.ifUpdatedAt);
1371
1441
  return this.request(
1372
1442
  "DELETE",
1373
1443
  `/v1/provider-lead-sources?${q.toString()}`
@@ -1560,6 +1630,7 @@ var ErdoClient = class {
1560
1630
  if (params?.priority) q.set("priority", params.priority);
1561
1631
  if (params?.limit) q.set("limit", String(params.limit));
1562
1632
  if (params?.offset) q.set("offset", String(params.offset));
1633
+ if (params?.waitingForStart) q.set("waiting_for_start", "true");
1563
1634
  const qs = q.toString();
1564
1635
  return this.request("GET", `/v1/lead-next-actions${qs ? `?${qs}` : ""}`);
1565
1636
  }
@@ -1771,9 +1842,10 @@ var ErdoClient = class {
1771
1842
  // Start or stop lending a connection to the organizations this one manages.
1772
1843
  // `managed_organizations` names the orgs it now serves — empty when this org
1773
1844
  // manages nobody yet, which is a truthful answer rather than a failure.
1774
- setIntegrationManagedAccess(integrationId, managedAccess) {
1845
+ setIntegrationManagedAccess(integrationId, managedAccess, scope = {}) {
1775
1846
  return this.request("POST", `/v1/integrations/${encodeURIComponent(integrationId)}/managed-access`, {
1776
- managed_access: managedAccess
1847
+ managed_access: managedAccess,
1848
+ ...scope
1777
1849
  });
1778
1850
  }
1779
1851
  // For a Pipedream-backed integration this is the full disconnect: the
@@ -7670,8 +7742,8 @@ voiceWidgetsCmd.command("realtime-model <widget> <model>").description("Choose t
7670
7742
  }
7671
7743
  });
7672
7744
  var datasetsCmd = program.command("datasets").description("Datasets");
7673
- var providerLeadSourcesCmd = program.command("provider-lead-sources").description("Manage LinkedIn lead form responses synced into a lead dataset");
7674
- providerLeadSourcesCmd.command("list").description("List LinkedIn lead form source declarations").option("--provider <provider>", "filter by ad platform provider").option("--account-id <id>", "filter by provider ad account id").action(async (opts) => {
7745
+ var providerLeadSourcesCmd = program.command("provider-lead-sources").description("Manage lead sources: LinkedIn lead forms, Google Sheets, webhooks and imports written into a lead dataset");
7746
+ providerLeadSourcesCmd.command("list").description("List lead source declarations").option("--provider <provider>", "filter by ad platform provider").option("--account-id <id>", "filter by provider ad account id").action(async (opts) => {
7675
7747
  try {
7676
7748
  print(await new ErdoClient().listProviderLeadSources({ provider: opts.provider, account_id: opts.accountId }));
7677
7749
  } catch (e) {
@@ -7685,7 +7757,9 @@ providerLeadSourcesCmd.command("forms").description("List LinkedIn lead forms av
7685
7757
  fail(e);
7686
7758
  }
7687
7759
  });
7688
- providerLeadSourcesCmd.command("set").description("Replace a provider lead form source declaration from JSON or flags").option("-f, --file <path>", "one JSON declaration object; use - to read from stdin").option("--dataset <slug>", "lead dataset slug").option("--provider <provider>", "ad platform provider", "linkedin_ads").option("--connection-id <id>", "native integration id from erdo integrations status linkedin_ads_sync or GET /v1/integrations").option("--account-id <id>", "numeric LinkedIn ad account id").option("--form <id>", "LinkedIn lead gen form id (repeatable)", collect, []).option("--disabled", "save the declaration disabled").action(async (opts) => {
7760
+ providerLeadSourcesCmd.command("set").description(
7761
+ "Save a lead source from JSON or flags. A LinkedIn source names a connection, ad account and forms; a google_sheets, webhook or import source names itself and carries a column mapping (use --file). --dry-run previews what it would write and saves nothing."
7762
+ ).option("-f, --file <path>", "one JSON declaration object; use - to read from stdin").option("--dataset <slug>", "lead dataset slug").option("--provider <provider>", "linkedin_ads, google_sheets, webhook or import", "linkedin_ads").option("--connection-id <id>", "native integration id from erdo integrations status linkedin_ads_sync or GET /v1/integrations").option("--account-id <id>", "numeric LinkedIn ad account id").option("--form <id>", "LinkedIn lead gen form id (repeatable)", collect, []).option("--name <name>", "a google_sheets, webhook or import source's name").option("--sheet-url <url>", "a google_sheets source's tab, as its address in the browser (open to anyone with the link)").option("--dry-run", "preview what the source would write; save nothing").option("--rotate-secret", "issue a webhook source a new secret").option("--disabled", "save the declaration disabled").option("--create-only", "refuse the save if a source with this name already exists").action(async (opts) => {
7689
7763
  try {
7690
7764
  let input;
7691
7765
  if (opts.file) {
@@ -7697,34 +7771,120 @@ providerLeadSourcesCmd.command("set").description("Replace a provider lead form
7697
7771
  connection_id: opts.connectionId,
7698
7772
  account_id: opts.accountId,
7699
7773
  forms: opts.form,
7700
- ...opts.disabled ? { enabled: false } : {}
7774
+ ...opts.name ? { name: opts.name } : {},
7775
+ ...opts.sheetUrl ? { sheet_url: opts.sheetUrl } : {}
7701
7776
  };
7702
7777
  }
7778
+ if (opts.disabled) input.enabled = false;
7779
+ if (opts.dryRun) input.dry_run = true;
7780
+ if (opts.rotateSecret) input.rotate_secret = true;
7781
+ if (opts.createOnly) input.create_only = true;
7703
7782
  const dataset = typeof input.dataset === "string" ? input.dataset.trim() : "";
7704
7783
  const provider = typeof input.provider === "string" ? input.provider.trim() : "";
7705
- const connectionID = typeof input.connection_id === "string" ? input.connection_id.trim() : "";
7706
- const accountID = typeof input.account_id === "string" ? input.account_id.trim() : "";
7707
- const forms = Array.isArray(input.forms) ? input.forms.filter((form) => typeof form === "string" && form.trim().length > 0) : [];
7708
7784
  if (!dataset) throw new Error("dataset must be a non-empty string");
7709
7785
  if (!provider) throw new Error("provider must be a non-empty string");
7710
- if (!connectionID) throw new Error("connection_id must be a non-empty string");
7711
- if (!accountID) throw new Error("account_id must be a non-empty string");
7712
- if (forms.length === 0) throw new Error("forms must contain at least one form");
7713
- print(await new ErdoClient().setProviderLeadSource({
7714
- ...input,
7715
- dataset,
7716
- provider,
7717
- connection_id: connectionID,
7718
- account_id: accountID,
7719
- forms
7720
- }));
7786
+ if (provider === "linkedin_ads") {
7787
+ const connectionID = typeof input.connection_id === "string" ? input.connection_id.trim() : "";
7788
+ const accountID = typeof input.account_id === "string" ? input.account_id.trim() : "";
7789
+ const forms = Array.isArray(input.forms) ? input.forms.filter((form) => typeof form === "string" && form.trim().length > 0) : [];
7790
+ if (!connectionID) throw new Error("connection_id must be a non-empty string");
7791
+ if (!accountID) throw new Error("account_id must be a non-empty string");
7792
+ if (forms.length === 0) throw new Error("forms must contain at least one form");
7793
+ print(await new ErdoClient().setProviderLeadSource({ ...input, dataset, provider: "linkedin_ads", connection_id: connectionID, account_id: accountID, forms }));
7794
+ return;
7795
+ }
7796
+ if (provider !== "google_sheets" && provider !== "webhook" && provider !== "import") {
7797
+ throw new Error("provider must be linkedin_ads, google_sheets, webhook or import");
7798
+ }
7799
+ const name = typeof input.name === "string" ? input.name.trim() : "";
7800
+ if (!name) throw new Error("name must be a non-empty string");
7801
+ if (typeof input.mapping !== "object" || input.mapping === null) throw new Error("mapping is required: put the declaration in a JSON file and pass --file");
7802
+ delete input.connection_id;
7803
+ delete input.account_id;
7804
+ delete input.forms;
7805
+ const saved = await new ErdoClient().setProviderLeadSource({ ...input, dataset, provider, name });
7806
+ print(saved);
7807
+ if (saved.webhook_secret) {
7808
+ process.stderr.write("The webhook secret is shown once. Store it now; send it as the X-Erdo-Lead-Source-Secret header.\n");
7809
+ }
7721
7810
  } catch (e) {
7722
7811
  fail(e);
7723
7812
  }
7724
7813
  });
7725
- providerLeadSourcesCmd.command("delete").description("Delete a provider lead form source declaration").option("--provider <provider>", "ad platform provider", "linkedin_ads").requiredOption("--account-id <id>", "numeric provider ad account id").action(async (opts) => {
7814
+ providerLeadSourcesCmd.command("import <name> <file>").description(
7815
+ "Import a CSV file into an import lead source. Every row is written as history: never alerted on, billed or followed up until started. Without --commit this is a dry run that previews the file and writes nothing."
7816
+ ).option("--commit", "write the rows (without it, only a preview)").option("--default-submitted-at <date>", "when these people got in touch, for rows the file does not date (YYYY-MM-DD or RFC 3339)").option("--start-follow-up", "after writing, start follow-up on each lead the import created (with --commit)").action(async (name, file, opts) => {
7726
7817
  try {
7727
- print(await new ErdoClient().deleteProviderLeadSource(opts.provider, opts.accountId));
7818
+ if (opts.startFollowUp && !opts.commit) throw new Error("--start-follow-up needs --commit");
7819
+ if (!file.toLowerCase().endsWith(".csv")) throw new Error("import reads CSV; export the sheet or workbook as CSV first");
7820
+ const records = parseCSV(readFileSync4(file, "utf8"));
7821
+ if (records.length === 0) throw new Error("the file is empty");
7822
+ const [header, ...rows] = records;
7823
+ const client = new ErdoClient();
7824
+ const batch = 1e3;
7825
+ const totals = { rows: rows.length, created: 0, existing: 0, already_written: 0, refused: 0, no_contact: 0, unreadable: 0, history: 0, test: 0 };
7826
+ const skipped = {};
7827
+ const created = /* @__PURE__ */ new Set();
7828
+ let preview;
7829
+ for (let start = 0; start < rows.length || start === 0; start += batch) {
7830
+ const result = await client.importLeadSourceRows({
7831
+ name,
7832
+ header,
7833
+ rows: rows.slice(start, start + batch),
7834
+ dry_run: !opts.commit,
7835
+ ...opts.defaultSubmittedAt ? { default_submitted_at: opts.defaultSubmittedAt } : {}
7836
+ });
7837
+ if (result.preview) {
7838
+ preview ??= result.preview;
7839
+ totals.history += result.preview.history;
7840
+ totals.already_written += result.preview.already_written;
7841
+ totals.test += result.preview.test;
7842
+ for (const [reason, n] of Object.entries(result.preview.skipped)) skipped[reason] = (skipped[reason] ?? 0) + n;
7843
+ } else {
7844
+ totals.created += result.created;
7845
+ totals.existing += result.existing;
7846
+ totals.already_written += result.already_written;
7847
+ totals.refused += result.refused;
7848
+ totals.no_contact += result.no_contact;
7849
+ totals.unreadable += result.unreadable;
7850
+ for (const lead of result.created_leads) created.add(lead);
7851
+ }
7852
+ if (rows.length === 0) break;
7853
+ }
7854
+ if (!opts.commit) {
7855
+ print({ dry_run: true, rows: totals.rows, history: totals.history, already_written: totals.already_written, test: totals.test, skipped, not_read: preview?.not_read ?? [], missing_fields: preview?.missing_fields ?? [], sample: preview?.sample ?? [] });
7856
+ process.stderr.write(`Dry run: nothing written. ${totals.history} rows would be written as history. Run again with --commit to write them.
7857
+ `);
7858
+ return;
7859
+ }
7860
+ const started = [];
7861
+ const notStarted = [];
7862
+ if (opts.startFollowUp && created.size > 0) {
7863
+ const sources = await client.listProviderLeadSources({ provider: "import" });
7864
+ const source = sources.provider_lead_sources.find((s) => s.name === name);
7865
+ if (!source) throw new Error(`lead source ${name} was not found after the import`);
7866
+ for (const lead of created) {
7867
+ try {
7868
+ await client.recordLeadNextAction(source.dataset, lead, { kind: "start", note: `Imported through ${name}` });
7869
+ started.push(lead);
7870
+ } catch (e) {
7871
+ notStarted.push({ lead, error: e instanceof Error ? e.message : String(e) });
7872
+ }
7873
+ }
7874
+ }
7875
+ print({ ...totals, created_leads: [...created], ...opts.startFollowUp ? { follow_up_started: started.length, follow_up_not_started: notStarted } : {} });
7876
+ } catch (e) {
7877
+ fail(e);
7878
+ }
7879
+ });
7880
+ providerLeadSourcesCmd.command("delete").description("Delete a lead source, by --name or by --provider and --account-id. Leads already written stay").option("--name <name>", "a google_sheets, webhook or import source's name").option("--provider <provider>", "ad platform provider", "linkedin_ads").option("--account-id <id>", "numeric provider ad account id").option("--if-updated-at <time>", "delete only the source with this updated_at from list").action(async (opts) => {
7881
+ try {
7882
+ if (opts.name) {
7883
+ print(await new ErdoClient().deleteProviderLeadSource({ name: opts.name, ifUpdatedAt: opts.ifUpdatedAt }));
7884
+ return;
7885
+ }
7886
+ if (!opts.accountId) throw new Error("pass --name, or --provider and --account-id");
7887
+ print(await new ErdoClient().deleteProviderLeadSource({ provider: opts.provider, accountId: opts.accountId, ifUpdatedAt: opts.ifUpdatedAt }));
7728
7888
  } catch (e) {
7729
7889
  fail(e);
7730
7890
  }
@@ -9038,7 +9198,10 @@ leadNextActionsCmd.command("list").description(
9038
9198
  ).option("--dataset <slug>", "narrow to one lead dataset").option(
9039
9199
  "--status <status>",
9040
9200
  "queued, pending_approval, executing, executed, approved (a text or call somebody said yes to, not yet carried out), rejected, expired, superseded, failed or recorded"
9041
- ).option("--priority <priority>", "high, medium or low").option("-l, --limit <n>", "maximum suggestions to return (default 50, maximum 200)", (v) => parseInt(v, 10)).option("--offset <n>", "skip that many suggestions, for paging", (v) => parseInt(v, 10)).option("--json", "print the raw JSON result instead of a table").action(
9201
+ ).option("--priority <priority>", "high, medium or low").option("-l, --limit <n>", "maximum suggestions to return (default 50, maximum 200)", (v) => parseInt(v, 10)).option("--offset <n>", "skip that many suggestions, for paging", (v) => parseInt(v, 10)).option(
9202
+ "--waiting-for-start",
9203
+ "with --dataset, list the leads the follow-up engine leaves until somebody starts them, and why"
9204
+ ).option("--json", "print the raw JSON result instead of a table").action(
9042
9205
  async (opts) => {
9043
9206
  try {
9044
9207
  const res = await new ErdoClient().listLeadNextActions({
@@ -9046,12 +9209,25 @@ leadNextActionsCmd.command("list").description(
9046
9209
  status: opts.status,
9047
9210
  priority: opts.priority,
9048
9211
  limit: opts.limit,
9049
- offset: opts.offset
9212
+ offset: opts.offset,
9213
+ waitingForStart: opts.waitingForStart
9050
9214
  });
9051
9215
  if (opts.json) {
9052
9216
  print(res);
9053
9217
  return;
9054
9218
  }
9219
+ if (opts.waitingForStart) {
9220
+ const waiting = res.waiting_for_start ?? [];
9221
+ if (waiting.length === 0) {
9222
+ console.log("No lead is waiting for somebody to start follow-up.");
9223
+ } else {
9224
+ printAlignedTable(
9225
+ ["lead", "reason"],
9226
+ waiting.map((w) => [w.lead_reference, w.reason])
9227
+ );
9228
+ }
9229
+ console.log("");
9230
+ }
9055
9231
  const items = res.next_actions ?? [];
9056
9232
  if (items.length === 0) {
9057
9233
  console.log("No lead next actions match.");
@@ -9485,11 +9661,16 @@ ${notes.join("\n")}`);
9485
9661
  fail(e);
9486
9662
  }
9487
9663
  });
9488
- integrationsCmd.command("managed-access <integration-id> <owner_only|managed_organizations>").description(
9489
- "Start or stop providing a connection to the organizations you manage \u2014 a vendor key your agency pays for, spendable by every client for as long as you manage it. Key-authenticated connections only"
9490
- ).action(async (integrationId, managedAccess) => {
9664
+ integrationsCmd.command("managed-access <integration-id> <owner_only|managed_organizations>").option("--managed-organization <id>", "Limit this operation to one managed organization").option("--ad-account <id>", "Assign one LinkedIn ad account to the managed organization").option("--client-integration <id>", "Use the managed organization's existing integration").option("--preserve-client-grant", "Assert the existing client's OAuth grant is independent of the manager and retain it on revoke").description(
9665
+ "Lend an API key to managed organizations, or assign a LinkedIn OAuth connection to one client with --managed-organization and --ad-account"
9666
+ ).action(async (integrationId, managedAccess, opts) => {
9491
9667
  try {
9492
- const res = await new ErdoClient().setIntegrationManagedAccess(integrationId, managedAccess);
9668
+ const res = await new ErdoClient().setIntegrationManagedAccess(integrationId, managedAccess, {
9669
+ managed_organization_id: opts.managedOrganization,
9670
+ ad_account_id: opts.adAccount,
9671
+ client_integration_id: opts.clientIntegration,
9672
+ preserve_client_grant: opts.preserveClientGrant
9673
+ });
9493
9674
  print(res);
9494
9675
  if (res.managed_access !== "managed_organizations") return;
9495
9676
  const orgs = res.managed_organizations ?? [];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@erdoai/cli",
3
- "version": "0.177.1",
3
+ "version": "0.178.0",
4
4
  "description": "Erdo CLI \u2014 drive datasets, pages, and evals from the terminal or CI",
5
5
  "type": "module",
6
6
  "bin": {