@signaliz/sdk 1.0.67 → 1.0.68

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.
@@ -47,8 +47,6 @@ function publicRetryDetails(body) {
47
47
  ...body?.retry_strategy !== void 0 ? { retry_strategy: body.retry_strategy } : {},
48
48
  ...body?.credits_used !== void 0 ? { credits_used: body.credits_used } : {},
49
49
  ...body?.credits_charged !== void 0 ? { credits_charged: body.credits_charged } : {},
50
- ...body?.live_provider_called !== void 0 ? { live_provider_called: body.live_provider_called } : {},
51
- ...body?.estimated_external_cost_usd !== void 0 ? { estimated_external_cost_usd: body.estimated_external_cost_usd } : {},
52
50
  ...body?.job_id !== void 0 ? { job_id: body.job_id } : {},
53
51
  ...body?.idempotency_key !== void 0 ? { idempotency_key: body.idempotency_key } : {},
54
52
  ...body?.verification_run_id !== void 0 ? { verification_run_id: body.verification_run_id } : {},
@@ -201,10 +199,10 @@ var HttpClient = class {
201
199
  }),
202
200
  signal: controller.signal
203
201
  });
204
- const text = await res.text();
205
- const data = safeJson(text);
202
+ const text2 = await res.text();
203
+ const data = safeJson(text2);
206
204
  if (!res.ok) {
207
- const err = parseError(res.status, data ?? { message: text });
205
+ const err = parseError(res.status, data ?? { message: text2 });
208
206
  if (err.isRetryable && attempt < this.maxRetries) {
209
207
  if (err.details?.retry_strategy === "same_run_recovery") throw err;
210
208
  lastError = err;
@@ -218,7 +216,7 @@ var HttpClient = class {
218
216
  code: "INVALID_JSON",
219
217
  message: "MCP response was not valid JSON",
220
218
  errorType: "provider_error",
221
- details: { responseText: text.slice(0, 500) }
219
+ details: { responseText: text2.slice(0, 500) }
222
220
  });
223
221
  }
224
222
  const responseError = isRecord(data) && isRecord(data.error) ? data.error : null;
@@ -303,9 +301,9 @@ function requestIdempotencyKey(body, automaticIdempotency) {
303
301
  function sleep(ms) {
304
302
  return new Promise((r) => setTimeout(r, ms));
305
303
  }
306
- function safeJson(text) {
304
+ function safeJson(text2) {
307
305
  try {
308
- return JSON.parse(text);
306
+ return JSON.parse(text2);
309
307
  } catch {
310
308
  return null;
311
309
  }
@@ -341,10 +339,10 @@ function unwrapMcpResponse(data) {
341
339
  }
342
340
  const content = isRecord(result) ? result.content : void 0;
343
341
  const firstContent = Array.isArray(content) ? content[0] : void 0;
344
- const text = isRecord(firstContent) ? firstContent.text : void 0;
345
- if (typeof text === "string") {
346
- const parsed = safeJson(text);
347
- return unwrapMcpPayload(parsed ?? text);
342
+ const text2 = isRecord(firstContent) ? firstContent.text : void 0;
343
+ if (typeof text2 === "string") {
344
+ const parsed = safeJson(text2);
345
+ return unwrapMcpPayload(parsed ?? text2);
348
346
  }
349
347
  return unwrapMcpPayload(result);
350
348
  }
@@ -491,8 +489,8 @@ function assertCompanySignalRows(body) {
491
489
  );
492
490
  if (Array.isArray(body.signal_types)) {
493
491
  body.signal_types.forEach(
494
- (signalType, index) => assertStringBytes(
495
- signalType,
492
+ (signalType2, index) => assertStringBytes(
493
+ signalType2,
496
494
  `signal_types[${index}]`,
497
495
  SIGNAL_TYPE_MAX_UTF8_BYTES,
498
496
  index
@@ -502,9 +500,11 @@ function assertCompanySignalRows(body) {
502
500
  requests.forEach((value, index) => {
503
501
  if (!value || typeof value !== "object" || Array.isArray(value)) return;
504
502
  const request = value;
503
+ const domain = request.domain ?? request.company_domain;
504
+ const domainField = request.domain !== void 0 ? "domain" : "company_domain";
505
505
  assertStringBytes(
506
- request.company_domain,
507
- `requests[${index}].company_domain`,
506
+ domain,
507
+ `requests[${index}].${domainField}`,
508
508
  DOMAIN_MAX_UTF8_BYTES,
509
509
  index
510
510
  );
@@ -584,6 +584,190 @@ function assertLargeCoreProductInputBounds(path, body) {
584
584
  );
585
585
  }
586
586
 
587
+ // src/public-signal-row.ts
588
+ var PUBLIC_COMPANY_SIGNAL_MAX_COVERAGE_COUNT = 10;
589
+ function recordValue(value) {
590
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
591
+ }
592
+ function text(value) {
593
+ return typeof value === "string" ? value.trim() : "";
594
+ }
595
+ function dateOnly(value) {
596
+ const raw = text(value);
597
+ const match = raw.match(/^\d{4}-\d{2}-\d{2}/);
598
+ if (!match) return "";
599
+ const parsed = /* @__PURE__ */ new Date(`${match[0]}T00:00:00.000Z`);
600
+ return Number.isFinite(parsed.getTime()) && parsed.toISOString().slice(0, 10) === match[0] ? match[0] : "";
601
+ }
602
+ function classificationSlug(value) {
603
+ const direct = text(value);
604
+ if (direct) return direct;
605
+ const classification = recordValue(value);
606
+ return text(classification.slug || classification.type || classification.name);
607
+ }
608
+ function signalType(signal) {
609
+ const raw = recordValue(signal.raw_data);
610
+ const generic = /* @__PURE__ */ new Set(["unclassified", "unknown", "other", "news", "signal"]);
611
+ for (const value of [
612
+ signal.signal_type,
613
+ classificationSlug(signal.signal_classification),
614
+ classificationSlug(signal.classification),
615
+ raw.signal_type,
616
+ classificationSlug(raw.signal_classification),
617
+ classificationSlug(raw.classification),
618
+ signal.type,
619
+ signal.category,
620
+ signal.event_type,
621
+ raw.type,
622
+ raw.category,
623
+ raw.event_type
624
+ ]) {
625
+ const candidate = text(value);
626
+ if (candidate && !generic.has(candidate.toLowerCase())) return candidate;
627
+ }
628
+ return "";
629
+ }
630
+ function verifiedHttpsUrl(value) {
631
+ const candidate = text(value);
632
+ if (!candidate || /\s/.test(candidate)) return "";
633
+ try {
634
+ const parsed = new URL(candidate);
635
+ return parsed.protocol === "https:" && Boolean(parsed.hostname) && !parsed.username && !parsed.password ? candidate : "";
636
+ } catch {
637
+ return "";
638
+ }
639
+ }
640
+ function normalizedDomain(value) {
641
+ const normalized = text(value).toLowerCase().replace(/^https?:\/\//, "").replace(/^www\./, "").split(/[/?#]/)[0].replace(/\.$/, "");
642
+ return /^(?=.{3,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/i.test(normalized) ? normalized : "";
643
+ }
644
+ function firstValid(values, normalize) {
645
+ for (const value of values) {
646
+ const normalized = normalize(value);
647
+ if (normalized) return normalized;
648
+ }
649
+ return "";
650
+ }
651
+ function publicSignalRow(value, fallbackCompany) {
652
+ const signal = recordValue(value);
653
+ const raw = recordValue(signal.raw_data);
654
+ const company = recordValue(signal.company);
655
+ const rawCompany = recordValue(raw.company);
656
+ const fallback = recordValue(fallbackCompany);
657
+ const row = {
658
+ signal_type: signalType(signal),
659
+ signal_title: firstValid([
660
+ signal.signal_title,
661
+ raw.signal_title,
662
+ signal.title,
663
+ raw.title,
664
+ signal.headline,
665
+ raw.headline,
666
+ signal.name,
667
+ raw.name
668
+ ], text),
669
+ signal_summary: firstValid([
670
+ signal.signal_summary,
671
+ raw.signal_summary,
672
+ signal.summary,
673
+ raw.summary,
674
+ signal.signal_content,
675
+ raw.signal_content,
676
+ signal.content,
677
+ raw.content,
678
+ signal.description,
679
+ raw.description
680
+ ], text),
681
+ source: firstValid([
682
+ signal.canonical_source_url,
683
+ signal.source_url,
684
+ signal.verified_source_url,
685
+ signal.signal_source,
686
+ signal.source,
687
+ signal.url,
688
+ raw.canonical_source_url,
689
+ raw.source_url,
690
+ raw.verified_source_url,
691
+ raw.signal_source,
692
+ raw.source,
693
+ raw.url
694
+ ], verifiedHttpsUrl),
695
+ date: firstValid([
696
+ signal.date,
697
+ signal.event_date,
698
+ signal.signal_date,
699
+ signal.published_date,
700
+ signal.published_at,
701
+ signal.detected_at,
702
+ signal.observed_at,
703
+ raw.date,
704
+ raw.event_date,
705
+ raw.signal_date,
706
+ raw.published_date,
707
+ raw.published_at,
708
+ raw.detected_at,
709
+ raw.observed_at
710
+ ], dateOnly),
711
+ company_name: text(
712
+ signal.company_name || company.name || company.company_name || raw.company_name || rawCompany.name || rawCompany.company_name || fallback.company_name || fallback.name
713
+ ),
714
+ domain: firstValid([
715
+ signal.company_domain,
716
+ signal.domain,
717
+ company.domain,
718
+ company.company_domain,
719
+ raw.company_domain,
720
+ raw.domain,
721
+ rawCompany.domain,
722
+ rawCompany.company_domain,
723
+ fallback.company_domain,
724
+ fallback.domain
725
+ ], normalizedDomain)
726
+ };
727
+ return row.signal_type && row.source && row.date && row.company_name && row.domain ? row : null;
728
+ }
729
+ function publicSignalRows(value, fallbackCompany) {
730
+ if (!Array.isArray(value)) return [];
731
+ return value.flatMap((item) => {
732
+ const row = publicSignalRow(item, fallbackCompany);
733
+ return row ? [row] : [];
734
+ });
735
+ }
736
+ function companySignalEventIdentities(value, row) {
737
+ const signal = recordValue(value);
738
+ const raw = recordValue(signal.raw_data);
739
+ const eventId = text(
740
+ signal.event_id || signal.eventId || signal.fact_id || signal.factId || raw.event_id || raw.eventId || raw.fact_id || raw.factId
741
+ ).toLowerCase();
742
+ return [
743
+ ...eventId ? [`event:${eventId}`] : [],
744
+ `source:${row.source.toLowerCase()}`
745
+ ];
746
+ }
747
+ function publicCompanySignalRows(value, fallbackCompany) {
748
+ if (!Array.isArray(value)) return [];
749
+ const seenEvents = /* @__PURE__ */ new Set();
750
+ const rows = [];
751
+ for (const item of value) {
752
+ const row = publicSignalRow(item, fallbackCompany);
753
+ if (!row) continue;
754
+ const identities = companySignalEventIdentities(item, row);
755
+ if (identities.some((identity) => seenEvents.has(identity))) continue;
756
+ identities.forEach((identity) => seenEvents.add(identity));
757
+ rows.push(row);
758
+ if (rows.length >= PUBLIC_COMPANY_SIGNAL_MAX_COVERAGE_COUNT) break;
759
+ }
760
+ return rows;
761
+ }
762
+ function oneSignalPerCompany(rows) {
763
+ const seen = /* @__PURE__ */ new Set();
764
+ return rows.filter((row) => {
765
+ if (seen.has(row.domain)) return false;
766
+ seen.add(row.domain);
767
+ return true;
768
+ });
769
+ }
770
+
587
771
  // ../../supabase/functions/_shared/find-email-identity.ts
588
772
  var LINKEDIN_PERSON_PROFILE_URL_PATTERN = "^[hH][tT][tT][pP][sS]://(?:[A-Za-z0-9-]+\\.)*[lL][iI][nN][kK][eE][dD][iI][nN]\\.[cC][oO][mM]/[iI][nN]/[^/?#]+/?(?:[?#].*)?$";
589
773
  var LINKEDIN_PERSON_PROFILE_URL_REGEX = new RegExp(LINKEDIN_PERSON_PROFILE_URL_PATTERN);
@@ -615,6 +799,27 @@ var Signaliz = class {
615
799
  constructor(config) {
616
800
  this.client = new HttpClient(config);
617
801
  }
802
+ /**
803
+ * The canonical Signal Awareness control plane used by the CLI and MCP.
804
+ * Manual runs accept a stable retry key and return an explicit billing
805
+ * receipt, including zero-credit available-data reuse.
806
+ */
807
+ async signalAwareness(request) {
808
+ const data = await this.client.post(
809
+ "api/v1/signal-awareness",
810
+ signalAwarenessRequestBody(request)
811
+ );
812
+ return normalizeSignalAwarenessResponse(data);
813
+ }
814
+ async createSignalMonitor(monitor) {
815
+ return this.signalAwareness({ action: "create", monitor });
816
+ }
817
+ async listSignalMonitors(limit, offset) {
818
+ return this.signalAwareness({ action: "list", limit, offset });
819
+ }
820
+ async runSignalMonitor(monitorId, idempotencyKey) {
821
+ return this.signalAwareness({ action: "manual_run", monitorId, idempotencyKey });
822
+ }
618
823
  async findEmail(params) {
619
824
  const request = findEmailRequestBody(params);
620
825
  assertFindEmailRequestIdentity(request);
@@ -684,14 +889,12 @@ var Signaliz = class {
684
889
  error,
685
890
  error_code: "INPUT_001",
686
891
  retry_eligible: false,
687
- credits_used: 0,
688
- live_provider_called: false
892
+ credits_used: 0
689
893
  });
690
894
  }
691
895
  const request = compact({
692
896
  email: email || void 0,
693
897
  verification_run_id: options?.verificationRunId,
694
- skip_cache: options?.skipCache,
695
898
  dry_run: options?.dryRun,
696
899
  idempotency_key: options?.idempotencyKey
697
900
  });
@@ -776,19 +979,38 @@ var Signaliz = class {
776
979
  );
777
980
  return normalizeSignalDiscoveryResult(params, data);
778
981
  }
982
+ /** Signals First is the customer-facing name for open-ended discovery. */
983
+ async discoverSignalsFirst(params) {
984
+ return this.discoverSignals(params);
985
+ }
986
+ async startFlow(params) {
987
+ validateSignalizFlowParams(params);
988
+ const data = await this.client.post(
989
+ "api/v1/flow",
990
+ signalizFlowRequestBody(params)
991
+ );
992
+ return data.dry_run === true ? normalizeSignalizFlowPlanResult(data) : normalizeSignalizFlowStartResult(data);
993
+ }
994
+ async getFlow(runId) {
995
+ const normalizedRunId = runId.trim();
996
+ if (!normalizedRunId || normalizedRunId.length > 200) {
997
+ throw new RangeError("runId must contain between 1 and 200 characters");
998
+ }
999
+ const data = await this.client.post(
1000
+ "api/v1/flow",
1001
+ { run_id: normalizedRunId },
1002
+ { automaticIdempotency: false }
1003
+ );
1004
+ return normalizeSignalizFlowStatus(data);
1005
+ }
779
1006
  async enrichCompanies(companies, options) {
780
1007
  validateBatchSize(companies);
781
1008
  companies.forEach(validateCompanySignalParams);
782
1009
  const requests = companies.map(companySignalRequestBody);
783
- if (companies.length > 25 && requests.some((request) => request.include_candidate_evidence === true)) {
784
- throw new RangeError(
785
- "includeCandidateEvidence is not supported in Company Signals batches larger than 25 because rejected evidence diagnostics are intentionally excluded from durable scale storage; split diagnostic requests into batches of at most 25."
786
- );
787
- }
788
1010
  const largeBatch = companySignalLargeBatchSubmission(requests);
789
1011
  if (companies.length > 25 && !largeBatch) {
790
1012
  throw new RangeError(
791
- "Company Signals batches larger than 25 require homogeneous new-enrichment rows with company identity only and uniform controls; split recovery or mixed-control rows into batches of at most 25."
1013
+ "Company Signals batches larger than 25 require homogeneous new-enrichment rows with a domain only; split recovery or mixed-context rows into batches of at most 25."
792
1014
  );
793
1015
  }
794
1016
  if (options?.dryRun === true) {
@@ -839,14 +1061,14 @@ var Signaliz = class {
839
1061
  if (total !== companies.length) {
840
1062
  throw new Error(`Company Signals batch returned ${total} results for ${companies.length} requests`);
841
1063
  }
842
- const batch = finalizeCoreBatch(
1064
+ const batch2 = finalizeCoreBatch(
843
1065
  companies.length,
844
1066
  startedAt,
845
1067
  recoverableRowsToRound(rows, "Company Signals"),
846
1068
  (item) => normalizeCompanySignalResult(companies[item.index], item.raw)
847
1069
  );
848
1070
  return compactKnownDuplicateBatch(
849
- batch,
1071
+ batch2,
850
1072
  dedupeExactBatchItems(
851
1073
  requests,
852
1074
  (request) => coreProductBatchRequestKey("api/v1/company-signals", request)
@@ -867,15 +1089,21 @@ var Signaliz = class {
867
1089
  return batchItemFailure(item.index, error instanceof Error ? error.message : String(error), item.raw);
868
1090
  }
869
1091
  });
870
- const compactedResults = compactExactDuplicateResults(results, options?.compactDuplicates === true);
871
- const succeeded = compactedResults.filter((item) => item.success).length;
872
- return {
1092
+ const batch = {
873
1093
  total: companies.length,
874
- succeeded,
875
- failed: companies.length - succeeded,
1094
+ succeeded: results.filter((item) => item.success).length,
1095
+ failed: companies.length - results.filter((item) => item.success).length,
876
1096
  durationMs: Date.now() - startedAt,
877
- results: compactedResults
1097
+ results
878
1098
  };
1099
+ return compactKnownDuplicateBatch(
1100
+ batch,
1101
+ dedupeExactBatchItems(
1102
+ requests,
1103
+ (request) => coreProductBatchRequestKey("api/v1/company-signals", request)
1104
+ ).sourceIndexByInput,
1105
+ options?.compactDuplicates === true
1106
+ );
879
1107
  }
880
1108
  async resumeCompanySignalBatch(jobId, options) {
881
1109
  const startedAt = Date.now();
@@ -904,7 +1132,7 @@ var Signaliz = class {
904
1132
  async createSignalCopyBatch(requests, options) {
905
1133
  validateBatchSize(requests);
906
1134
  requests.forEach(validateSignalToCopyParams);
907
- validateLargeAvailableDataSignalCopyBatch(requests);
1135
+ validateLargeSignalCopyBatch(requests);
908
1136
  if (options?.dryRun === true) {
909
1137
  return this.runCoreProductDryRun(
910
1138
  "api/v1/signal-to-copy",
@@ -917,7 +1145,7 @@ var Signaliz = class {
917
1145
  if (options?.waitForResult === false) {
918
1146
  return this.submitRecoverableCoreBatchJob(
919
1147
  "api/v1/signal-to-copy",
920
- requests.map(availableDataSignalCopyRequestBody),
1148
+ requests.map(durableSignalCopyRequestBody),
921
1149
  "Signal to Copy",
922
1150
  options.idempotencyKey,
923
1151
  requests.map((_, index) => index)
@@ -925,7 +1153,7 @@ var Signaliz = class {
925
1153
  }
926
1154
  const job = await this.submitRecoverableCoreBatchJob(
927
1155
  "api/v1/signal-to-copy",
928
- requests.map(availableDataSignalCopyRequestBody),
1156
+ requests.map(durableSignalCopyRequestBody),
929
1157
  "Signal to Copy",
930
1158
  options?.idempotencyKey,
931
1159
  requests.map((_, index) => index)
@@ -1463,8 +1691,6 @@ function batchItemFailure(index, error, raw) {
1463
1691
  const retryStrategy = raw?.retry_strategy ?? raw?.retryStrategy;
1464
1692
  const creditsUsed = raw?.credits_used ?? raw?.creditsUsed;
1465
1693
  const creditsCharged = raw?.credits_charged ?? raw?.creditsCharged;
1466
- const liveProviderCalled = raw?.live_provider_called ?? raw?.liveProviderCalled;
1467
- const estimatedExternalCostUsd = raw?.estimated_external_cost_usd ?? raw?.estimatedExternalCostUsd;
1468
1694
  const runId = [raw?.run_id, raw?.runId, raw?.signal_run_id, raw?.signalRunId].find((value) => typeof value === "string" && value.trim());
1469
1695
  const verificationRunId = raw?.verification_run_id ?? raw?.verificationRunId;
1470
1696
  const jobId = raw?.job_id ?? raw?.jobId;
@@ -1479,8 +1705,6 @@ function batchItemFailure(index, error, raw) {
1479
1705
  ...["new_idempotency_key", "same_run_recovery"].includes(String(retryStrategy)) ? { retryStrategy } : {},
1480
1706
  ...creditsUsed === 0 ? { creditsUsed: 0 } : {},
1481
1707
  ...creditsCharged === 0 ? { creditsCharged: 0 } : {},
1482
- ...liveProviderCalled === false ? { liveProviderCalled: false } : {},
1483
- ...estimatedExternalCostUsd === 0 ? { estimatedExternalCostUsd: 0 } : {},
1484
1708
  ...typeof runId === "string" && runId.trim() ? { runId: runId.trim() } : {},
1485
1709
  ...typeof verificationRunId === "string" && verificationRunId.trim() ? { verificationRunId: verificationRunId.trim() } : {},
1486
1710
  ...typeof jobId === "string" && jobId.trim() ? { jobId: jobId.trim() } : {},
@@ -1536,6 +1760,51 @@ function newBatchIdempotencyKey(label) {
1536
1760
  function compact(input) {
1537
1761
  return Object.fromEntries(Object.entries(input).filter(([, value]) => value !== void 0));
1538
1762
  }
1763
+ var INTERNAL_PRODUCT_RESULT_KEYS = /* @__PURE__ */ new Set([
1764
+ "billing_metadata",
1765
+ "historical_billing_metadata",
1766
+ "result_returned_from",
1767
+ "fresh_enrichment_used",
1768
+ "live_provider_called",
1769
+ "openrouter_called",
1770
+ "byo_openrouter_used",
1771
+ "ai_provider_called",
1772
+ "byo_ai_used",
1773
+ "estimated_external_cost_usd",
1774
+ "included_provider_cost_usd",
1775
+ "would_have_charged_credits",
1776
+ "available_data_only",
1777
+ "available_data_input_count",
1778
+ "unique_available_data_input_count"
1779
+ ]);
1780
+ var PUBLIC_PRODUCT_DATA_MEMO = /* @__PURE__ */ new WeakMap();
1781
+ function publicProductData(value, capability = "") {
1782
+ if (Array.isArray(value)) return value.map((item) => publicProductData(item, capability));
1783
+ if (!value || typeof value !== "object") return value;
1784
+ const source = value;
1785
+ const inferredCapability = String(source.capability || capability).toLowerCase();
1786
+ const cachedByCapability = PUBLIC_PRODUCT_DATA_MEMO.get(source);
1787
+ if (cachedByCapability?.has(inferredCapability)) return cachedByCapability.get(inferredCapability);
1788
+ const result = Object.fromEntries(Object.entries(source).flatMap(([key, raw]) => {
1789
+ const normalizedKey = key.toLowerCase();
1790
+ if (INTERNAL_PRODUCT_RESULT_KEYS.has(normalizedKey) || normalizedKey.includes("cache")) return [];
1791
+ if (typeof raw === "string" && (raw.toLowerCase().includes("cache") || raw === "available_data")) {
1792
+ if (["error", "message", "suggested_action", "failure_reason"].includes(normalizedKey)) {
1793
+ return [[key, "The result could not be finalized. Retry safely using the existing run or job ID."]];
1794
+ }
1795
+ if (["source", "email_source", "email_source_label", "verification_source", "provider_status"].includes(normalizedKey)) {
1796
+ const sourceLabel = inferredCapability.includes("verify") ? "email_verification" : inferredCapability.includes("find") ? "email_finder" : inferredCapability.includes("signal_to_copy") ? "signal_to_copy" : "company_signal_enrichment";
1797
+ return [[key, sourceLabel]];
1798
+ }
1799
+ return [];
1800
+ }
1801
+ return [[key, publicProductData(raw, inferredCapability)]];
1802
+ }));
1803
+ const memo = cachedByCapability || /* @__PURE__ */ new Map();
1804
+ memo.set(inferredCapability, result);
1805
+ if (!cachedByCapability) PUBLIC_PRODUCT_DATA_MEMO.set(source, memo);
1806
+ return result;
1807
+ }
1539
1808
  function findEmailRequestBody(params) {
1540
1809
  return compact({
1541
1810
  run_id: params.runId,
@@ -1545,7 +1814,7 @@ function findEmailRequestBody(params) {
1545
1814
  last_name: params.lastName,
1546
1815
  linkedin_url: params.linkedinUrl,
1547
1816
  company_name: params.companyName,
1548
- skip_cache: params.skipCache,
1817
+ wait_for_result: params.waitForResult,
1549
1818
  dry_run: params.dryRun,
1550
1819
  idempotency_key: params.idempotencyKey
1551
1820
  });
@@ -1560,11 +1829,10 @@ function assertFindEmailRequestIdentity(request) {
1560
1829
  }
1561
1830
  function verifyEmailBatchRequestBody(input, options) {
1562
1831
  if (typeof input === "string") {
1563
- return compact({ email: input, skip_cache: options?.skipCache });
1832
+ return compact({ email: input });
1564
1833
  }
1565
1834
  return compact({
1566
1835
  email: input.email,
1567
- skip_cache: input.skipCache ?? options?.skipCache,
1568
1836
  idempotency_key: input.idempotencyKey
1569
1837
  });
1570
1838
  }
@@ -1596,6 +1864,7 @@ function normalizeCoreProductDryRunResult(data) {
1596
1864
  };
1597
1865
  }
1598
1866
  function normalizeFindEmailResult(data) {
1867
+ data = publicProductData(data, "find_email");
1599
1868
  const processing = String(data.status || "").toLowerCase() === "processing";
1600
1869
  const failed = coreProductResponseFailed(data);
1601
1870
  const rawEmail = typeof data.email === "string" && data.email.trim() ? data.email.trim() : null;
@@ -1612,7 +1881,6 @@ function normalizeFindEmailResult(data) {
1612
1881
  const verificationAgeDays = typeof data.verification_age_days === "number" && Number.isFinite(data.verification_age_days) ? data.verification_age_days : null;
1613
1882
  const providerUsed = data.provider_used ?? data.provider ?? data.email_source ?? data.source ?? "unknown";
1614
1883
  const verificationSource = data.verification_source ?? providerUsed;
1615
- const billingMetadata = data.billing_metadata && typeof data.billing_metadata === "object" && !Array.isArray(data.billing_metadata) ? data.billing_metadata : void 0;
1616
1884
  return {
1617
1885
  success: processing || !failed && found,
1618
1886
  found,
@@ -1635,22 +1903,10 @@ function normalizeFindEmailResult(data) {
1635
1903
  verificationSource,
1636
1904
  verificationObservedAt: typeof data.verification_observed_at === "string" ? data.verification_observed_at : void 0,
1637
1905
  failureReason: data.failure_reason ?? (failed || !found ? "no_verified_email_found" : "none"),
1638
- creditsUsed: data.credits_used ?? billingMetadata?.credits_used,
1639
- creditsCharged: data.credits_charged ?? billingMetadata?.credits_charged,
1640
- estimatedExternalCostUsd: data.estimated_external_cost_usd ?? billingMetadata?.estimated_external_cost_usd,
1641
- billingMetadata,
1906
+ creditsUsed: data.credits_used,
1907
+ creditsCharged: data.credits_charged,
1642
1908
  billingReplayed: data.billing_replayed,
1643
1909
  idempotencyReplayed: data.idempotency_replayed,
1644
- historicalBillingMetadata: data.historical_billing_metadata,
1645
- resultReturnedFrom: data.result_returned_from ?? billingMetadata?.result_returned_from,
1646
- cacheHit: typeof data.cache_hit === "boolean" ? data.cache_hit : billingMetadata?.cache_hit,
1647
- negativeCacheHit: data.negative_cache_hit,
1648
- negativeCacheTtlSeconds: data.negative_cache_ttl_seconds,
1649
- cacheTier: data.cache_tier,
1650
- freshEnrichmentUsed: typeof data.fresh_enrichment_used === "boolean" ? data.fresh_enrichment_used : billingMetadata?.fresh_enrichment_used,
1651
- liveProviderCalled: typeof data.live_provider_called === "boolean" ? data.live_provider_called : billingMetadata?.live_provider_called,
1652
- openrouterCalled: typeof data.openrouter_called === "boolean" ? data.openrouter_called : billingMetadata?.openrouter_called,
1653
- byoOpenrouterUsed: typeof data.byo_openrouter_used === "boolean" ? data.byo_openrouter_used : billingMetadata?.byo_openrouter_used,
1654
1910
  error: processing || found ? void 0 : coreProductErrorMessage(data) ?? "No verified email found",
1655
1911
  errorCode: processing || found ? void 0 : coreProductErrorCode(data) ?? "EMAIL_NOT_FOUND",
1656
1912
  status: processing ? "processing" : "completed",
@@ -1662,18 +1918,17 @@ function normalizeFindEmailResult(data) {
1662
1918
  doNotAutoResubmit: data.do_not_auto_resubmit === true,
1663
1919
  recoveryMode: data.recovery_mode === "same_run" ? "same_run" : void 0,
1664
1920
  recoveryStatus: ["pending", "completed"].includes(String(data.recovery_status)) ? data.recovery_status : void 0,
1665
- cachePublicationStatus: data.cache_publication_status,
1666
- cachePublicationRetryEligible: data.cache_publication_retry_eligible,
1667
1921
  raw: data
1668
1922
  };
1669
1923
  }
1670
1924
  function normalizeVerifyEmailResult(email, data) {
1925
+ data = publicProductData(data, "verify_email");
1671
1926
  const failed = coreProductResponseFailed(data);
1672
1927
  const malformed = data.is_malformed === true || data.verification_verdict === "malformed" || data.verification_status === "malformed" || data.deliverability_status === "malformed";
1673
- const verificationStatus = String(
1928
+ const verificationStatus = normalizeVerifyEmailStatus(
1674
1929
  failed ? malformed ? "malformed" : "error" : data.verification_status ?? data.verification_verdict ?? data.deliverability_status ?? "unknown"
1675
- ).toLowerCase();
1676
- const deliverabilityStatus = String(data.deliverability_status ?? verificationStatus).toLowerCase();
1930
+ );
1931
+ const deliverabilityStatus = normalizeVerifyEmailStatus(data.deliverability_status ?? verificationStatus);
1677
1932
  const verified = !failed && (data.email_verified === true || ["valid", "deliverable"].includes(verificationStatus));
1678
1933
  const isCatchAll = data.email_is_catch_all ?? data.is_catch_all ?? data.catch_all ?? data.diagnostics?.is_catch_all ?? false;
1679
1934
  const verifiedForSending = !failed && data.verified_for_sending === true;
@@ -1694,10 +1949,12 @@ function normalizeVerifyEmailResult(email, data) {
1694
1949
  verifiedForSending,
1695
1950
  verificationStatus,
1696
1951
  deliverabilityStatus,
1697
- verificationVerdict: failed ? malformed ? "malformed" : "error" : data.verification_verdict ?? data.verification_status ?? "unknown",
1952
+ verificationVerdict: normalizeVerifyEmailStatus(
1953
+ failed ? malformed ? "malformed" : "error" : data.verification_verdict ?? verificationStatus
1954
+ ),
1698
1955
  isRoleAccount: data.is_role_account === true || data.email_is_role_account === true || data.role === true,
1699
1956
  quality: typeof data.quality === "string" ? data.quality : null,
1700
- recommendation: typeof data.recommendation === "string" ? data.recommendation : verifiedForSending ? "send" : ["unknown", "verifier_error"].includes(verificationStatus) ? "manual_review" : "do_not_send",
1957
+ recommendation: normalizeVerifyEmailRecommendation(data.recommendation, verificationStatus, verifiedForSending),
1701
1958
  smtpStatus: data.smtp_status ?? (isCatchAll ? "accept_all" : verifiedForSending ? "accepted" : "not_checked"),
1702
1959
  providerStatus: data.provider_status ?? verificationStatus,
1703
1960
  failureReason: data.failure_reason ?? (verifiedForSending ? "none" : isCatchAll ? "catch_all_domain_not_send_safe" : "verification_not_send_safe"),
@@ -1708,53 +1965,47 @@ function normalizeVerifyEmailResult(email, data) {
1708
1965
  billingReplayed: data.billing_replayed,
1709
1966
  idempotencyReplayed: data.idempotency_replayed,
1710
1967
  creditsUsed: data.credits_used,
1711
- billingMetadata: data.billing_metadata,
1712
- historicalBillingMetadata: data.historical_billing_metadata,
1713
- resultReturnedFrom: data.result_returned_from,
1714
- cacheHit: data.cache_hit,
1715
- negativeCacheHit: data.negative_cache_hit,
1716
- negativeCacheTtlSeconds: data.negative_cache_ttl_seconds,
1717
- cacheTier: data.cache_tier,
1718
- freshEnrichmentUsed: data.fresh_enrichment_used,
1719
- liveProviderCalled: data.live_provider_called,
1720
- openrouterCalled: data.openrouter_called,
1721
- byoOpenrouterUsed: data.byo_openrouter_used,
1722
- estimatedExternalCostUsd: data.estimated_external_cost_usd,
1723
1968
  runId: data.run_id ?? verificationRunId,
1724
- cachePublicationStatus: data.cache_publication_status,
1725
- cachePublicationRetryEligible: data.cache_publication_retry_eligible,
1726
1969
  suggestedAction: data.suggested_action,
1727
1970
  raw: data
1728
1971
  };
1729
1972
  }
1973
+ function normalizeVerifyEmailStatus(value) {
1974
+ const status = String(value ?? "").trim().toLowerCase();
1975
+ if (status === "deliverable" || status === "accepted" || status === "verified") return "valid";
1976
+ if (status === "undeliverable" || status === "rejected") return "invalid";
1977
+ if ([
1978
+ "valid",
1979
+ "invalid",
1980
+ "catch_all",
1981
+ "role",
1982
+ "disposable",
1983
+ "unknown",
1984
+ "verifier_error",
1985
+ "malformed",
1986
+ "error"
1987
+ ].includes(status)) return status;
1988
+ return "unknown";
1989
+ }
1990
+ function normalizeVerifyEmailRecommendation(value, verificationStatus, verifiedForSending) {
1991
+ const recommendation = String(value ?? "").trim().toLowerCase();
1992
+ if (recommendation === "send" || recommendation === "do_not_send" || recommendation === "manual_review") {
1993
+ return recommendation;
1994
+ }
1995
+ if (verifiedForSending) return "send";
1996
+ return verificationStatus === "unknown" || verificationStatus === "verifier_error" ? "manual_review" : "do_not_send";
1997
+ }
1730
1998
  function companySignalRequestBody(params) {
1731
- const online = params.online ?? true;
1732
1999
  return compact({
1733
2000
  signal_run_id: params.signalRunId,
1734
- company_domain: params.companyDomain,
1735
- company_name: params.companyName,
1736
- research_prompt: params.researchPrompt,
1737
- signal_types: params.signalTypes,
1738
- target_signal_count: params.targetSignalCount,
1739
- lookback_days: params.lookbackDays,
1740
- online,
1741
- enable_deep_search: params.enableDeepSearch ?? online,
1742
- search_mode: params.searchMode ?? "balanced",
1743
- include_summary: params.includeSummary,
1744
- enable_outreach_intelligence: params.enableOutreachIntelligence,
1745
- enable_predictive_intelligence: params.enablePredictiveIntelligence,
1746
- skip_cache: params.skipCache,
1747
- include_candidate_evidence: params.includeCandidateEvidence,
1748
- wait_for_result: true,
1749
- max_wait_ms: params.maxWaitMs,
2001
+ domain: params.domain ?? params.companyDomain,
1750
2002
  dry_run: params.dryRun,
1751
2003
  idempotency_key: params.idempotencyKey
1752
2004
  });
1753
2005
  }
1754
2006
  function validateCompanySignalParams(params) {
1755
- validateCoreProductMaxWaitMs(params.maxWaitMs);
1756
- if (params.targetSignalCount !== void 0 && (!Number.isInteger(params.targetSignalCount) || params.targetSignalCount < 1 || params.targetSignalCount > 15)) {
1757
- throw new RangeError("targetSignalCount must be an integer between 1 and 15");
2007
+ if (!params.signalRunId && !(params.domain ?? params.companyDomain)?.trim()) {
2008
+ throw new TypeError("Company Signals requires domain");
1758
2009
  }
1759
2010
  if (params.lookbackDays !== void 0 && (!Number.isInteger(params.lookbackDays) || params.lookbackDays < 1 || params.lookbackDays > 365)) {
1760
2011
  throw new RangeError("lookbackDays must be an integer between 1 and 365");
@@ -1762,25 +2013,11 @@ function validateCompanySignalParams(params) {
1762
2013
  }
1763
2014
  function companySignalParamsFromRecoveredRow(row) {
1764
2015
  return {
1765
- companyDomain: row.company?.domain ?? row.company_domain,
1766
- companyName: row.company?.name ?? row.company_name,
2016
+ domain: row.company?.domain ?? row.company_domain,
1767
2017
  signalRunId: row.signal_run_id ?? row.run_id
1768
2018
  };
1769
2019
  }
1770
- var COMPANY_SIGNAL_LARGE_BATCH_CONTROL_FIELDS = [
1771
- "research_prompt",
1772
- "signal_types",
1773
- "target_signal_count",
1774
- "lookback_days",
1775
- "online",
1776
- "enable_deep_search",
1777
- "search_mode",
1778
- "include_summary",
1779
- "enable_outreach_intelligence",
1780
- "enable_predictive_intelligence",
1781
- "skip_cache",
1782
- "include_candidate_evidence"
1783
- ];
2020
+ var COMPANY_SIGNAL_LARGE_BATCH_CONTROL_FIELDS = [];
1784
2021
  function companySignalLargeBatchSubmission(requests) {
1785
2022
  if (requests.length <= 25) return null;
1786
2023
  if (requests.some(
@@ -1797,67 +2034,158 @@ function companySignalLargeBatchSubmission(requests) {
1797
2034
  COMPANY_SIGNAL_LARGE_BATCH_CONTROL_FIELDS.filter((field) => request[field] !== void 0).map((field) => [field, request[field]])
1798
2035
  );
1799
2036
  if (JSON.stringify(requestControls) !== controlKey) return null;
1800
- const hasIdentity = typeof request.company_domain === "string" && request.company_domain.trim() || typeof request.company_name === "string" && request.company_name.trim();
2037
+ const hasIdentity = typeof request.domain === "string" && request.domain.trim();
1801
2038
  if (!hasIdentity) return null;
1802
2039
  }
1803
2040
  return {
1804
- requests: requests.map((request) => compact({
1805
- company_domain: request.company_domain,
1806
- company_name: request.company_name
1807
- })),
2041
+ requests: requests.map((request) => compact({ domain: request.domain })),
1808
2042
  submissionFields
1809
2043
  };
1810
2044
  }
1811
2045
  function normalizeCompanySignalResult(params, data) {
2046
+ data = publicProductData(data, "company_signals");
1812
2047
  const failed = coreProductResponseFailed(data);
1813
2048
  const rawSignals = failed ? [] : data.signals ?? data.signal_feed ?? [];
2049
+ const fallbackCompany = {
2050
+ name: data.company_name ?? data.company?.name ?? params.domain ?? params.companyDomain ?? null,
2051
+ domain: data.company_domain ?? data.domain ?? data.company?.domain ?? params.domain ?? params.companyDomain ?? null
2052
+ };
2053
+ const signalRows = publicCompanySignalRows(rawSignals, fallbackCompany);
2054
+ const company = {
2055
+ name: fallbackCompany.name ?? signalRows[0]?.company_name ?? null,
2056
+ domain: fallbackCompany.domain ?? signalRows[0]?.domain ?? null
2057
+ };
2058
+ const signals = signalRows.map(companySignalOutputRow);
1814
2059
  return {
1815
2060
  success: !failed,
1816
2061
  error: failed ? coreProductErrorMessage(data) : void 0,
1817
2062
  errorCode: failed ? coreProductErrorCode(data) : void 0,
1818
2063
  status: data.status,
1819
2064
  signalRunId: data.signal_run_id ?? data.run_id ?? params.signalRunId,
1820
- company: {
1821
- name: data.company?.name ?? params.companyName ?? null,
1822
- domain: data.company?.domain ?? params.companyDomain ?? null
1823
- },
1824
- signals: rawSignals.map((signal) => {
1825
- return {
1826
- id: signal.id,
1827
- title: signal.title ?? "",
1828
- type: signal.type ?? signal.signal_type ?? "unknown",
1829
- content: signal.content ?? signal.description ?? "",
1830
- date: signal.date ?? null,
1831
- detectedAt: signal.detected_at ?? null,
1832
- datePrecision: signal.date_precision,
1833
- sourceUrl: signal.source_url ?? signal.url ?? null,
1834
- sourceType: signal.source_type,
1835
- confidence: signal.confidence ?? signal.confidence_score ?? null,
1836
- signalFamily: signal.signal_family,
1837
- eventType: signal.signal_event_type,
1838
- eventLabel: signal.signal_event_label,
1839
- classification: signal.signal_classification ?? null
1840
- };
1841
- }),
1842
- signalCount: failed ? 0 : data.signal_count ?? data.total_signals ?? rawSignals.length,
1843
- signalSummary: failed ? null : data.signal_summary ?? null,
1844
- intelligence: failed ? null : data.intelligence ?? null,
1845
- copyFuel: failed ? null : data.copy_fuel ?? null,
1846
- evidenceValidation: failed ? void 0 : data.evidence_validation,
1847
- evidenceSources: failed ? [] : data.metadata?.evidence_sources ?? data.evidence_sources,
1848
- evidenceCount: failed ? 0 : data.evidence_count,
1849
- evidenceCountTotal: failed ? 0 : data.evidence_count_total,
1850
- evidenceSourcesOmitted: failed ? 0 : data.evidence_sources_omitted,
1851
- evidenceScope: failed ? void 0 : data.evidence_scope,
1852
- billingMetadata: data.billing_metadata,
1853
- resultReturnedFrom: data.result_returned_from,
1854
- cacheHit: data.cache_hit,
1855
- freshEnrichmentUsed: data.fresh_enrichment_used,
1856
- creditsUsed: data.credits_used,
1857
- liveProviderCalled: data.live_provider_called,
1858
- aiProviderCalled: data.ai_provider_called,
1859
- byoAiUsed: data.byo_ai_used,
1860
- raw: data
2065
+ company,
2066
+ signals,
2067
+ signalCount: signals.length,
2068
+ creditsUsed: data.credits_used
2069
+ };
2070
+ }
2071
+ function companySignalOutputRow(row) {
2072
+ return {
2073
+ date: row.date,
2074
+ signal_type: row.signal_type,
2075
+ signal_title: row.signal_title,
2076
+ signal_summary: row.signal_summary,
2077
+ source: row.source
2078
+ };
2079
+ }
2080
+ function validateSignalizFlowParams(params) {
2081
+ const query = typeof params.signalQuery === "string" ? params.signalQuery.trim() : "";
2082
+ const offer = typeof params.campaignOffer === "string" ? params.campaignOffer.trim() : "";
2083
+ if (query.length < 2 || query.length > 2e3) throw new RangeError("signalQuery must contain between 2 and 2000 characters");
2084
+ if (!offer || offer.length > 4e3) throw new RangeError("campaignOffer must contain between 1 and 4000 characters");
2085
+ if (params.signalLimit !== void 0 && (!Number.isInteger(params.signalLimit) || params.signalLimit < 1 || params.signalLimit > 25)) {
2086
+ throw new RangeError("signalLimit must be an integer between 1 and 25");
2087
+ }
2088
+ if (params.peoplePerCompany !== void 0 && (!Number.isInteger(params.peoplePerCompany) || params.peoplePerCompany < 1 || params.peoplePerCompany > 5)) {
2089
+ throw new RangeError("peoplePerCompany must be an integer between 1 and 5");
2090
+ }
2091
+ if (params.lookbackDays !== void 0 && (!Number.isInteger(params.lookbackDays) || params.lookbackDays < 1 || params.lookbackDays > 365)) {
2092
+ throw new RangeError("lookbackDays must be an integer between 1 and 365");
2093
+ }
2094
+ if (params.peopleTitles !== void 0 && (!Array.isArray(params.peopleTitles) || params.peopleTitles.length > 20 || params.peopleTitles.some((title) => typeof title !== "string" || !title.trim()))) {
2095
+ throw new TypeError("peopleTitles must contain at most 20 non-empty titles");
2096
+ }
2097
+ }
2098
+ function signalizFlowRequestBody(params) {
2099
+ const requestedFlowId = typeof params.flowId === "string" ? params.flowId.trim() : "";
2100
+ const requestedIdempotencyKey = typeof params.idempotencyKey === "string" ? params.idempotencyKey.trim() : "";
2101
+ const flowId = requestedFlowId || requestedIdempotencyKey || `sdk-flow-${globalThis.crypto?.randomUUID?.() || `${Date.now()}-${Math.random().toString(16).slice(2)}`}`;
2102
+ const idempotencyKey = requestedIdempotencyKey || `signaliz-flow:${flowId}`;
2103
+ return compact({
2104
+ signal_query: params.signalQuery.trim(),
2105
+ campaign_offer: params.campaignOffer.trim(),
2106
+ signal_limit: params.signalLimit,
2107
+ lookback_days: params.lookbackDays,
2108
+ icp_context: params.icpContext?.trim(),
2109
+ people_titles: params.peopleTitles?.map((title) => title.trim()),
2110
+ people_per_company: params.peoplePerCompany,
2111
+ copy_research_prompt: params.copyResearchPrompt?.trim(),
2112
+ approval_required: params.approvalRequired,
2113
+ flow_id: flowId,
2114
+ idempotency_key: idempotencyKey,
2115
+ dry_run: params.dryRun
2116
+ });
2117
+ }
2118
+ function normalizeSignalizFlowPlan(data) {
2119
+ const plan = data.plan && typeof data.plan === "object" ? data.plan : {};
2120
+ const billing = plan.billing && typeof plan.billing === "object" ? plan.billing : {};
2121
+ return {
2122
+ plannedCompanyCount: Number(plan.planned_company_count ?? 0),
2123
+ plannedPeoplePerCompany: Number(plan.planned_people_per_company ?? 0),
2124
+ maximumReviewCandidates: Number(plan.maximum_review_candidates ?? 0),
2125
+ safeguards: Array.isArray(plan.safeguards) ? plan.safeguards.filter((value) => typeof value === "string") : [],
2126
+ billing: { additionalFlowFeeCredits: Number(billing.additional_flow_fee_credits ?? 0), chargeBasis: String(billing.charge_basis ?? "") }
2127
+ };
2128
+ }
2129
+ function normalizeSignalizFlowPlanResult(data) {
2130
+ if (data.success !== true) throw new Error(String(data.error || "Signaliz Flow plan is unavailable."));
2131
+ return { success: true, dryRun: true, status: "PLANNED", flowId: String(data.flow_id ?? ""), plan: normalizeSignalizFlowPlan(data), creditsCharged: 0 };
2132
+ }
2133
+ function normalizeSignalizFlowStartResult(data) {
2134
+ if (data.success !== true || typeof data.run_id !== "string" || !data.run_id.trim()) {
2135
+ throw new Error(String(data.error || "Signaliz Flow could not be started."));
2136
+ }
2137
+ return { success: true, flowId: String(data.flow_id ?? ""), runId: data.run_id, status: "TRIGGERED", statusEndpoint: "api/v1/flow", message: String(data.message ?? "") };
2138
+ }
2139
+ var FLOW_SIGNAL_LIST_KEYS = /* @__PURE__ */ new Set(["signals", "signal_feed", "company_signals", "signal_results"]);
2140
+ var FLOW_SINGLE_SIGNAL_KEYS = /* @__PURE__ */ new Set(["signal", "source_signal"]);
2141
+ function publicSignalizFlowResult(value) {
2142
+ if (Array.isArray(value)) return value.map(publicSignalizFlowResult);
2143
+ if (!value || typeof value !== "object") return value;
2144
+ const source = value;
2145
+ return Object.fromEntries(Object.entries(source).flatMap(([key, raw]) => {
2146
+ const normalizedKey = key.toLowerCase();
2147
+ if (normalizedKey === "raw" || normalizedKey === "raw_data") return [];
2148
+ if (FLOW_SIGNAL_LIST_KEYS.has(normalizedKey)) {
2149
+ return [[key, oneSignalPerCompany(publicSignalRows(raw))]];
2150
+ }
2151
+ if (FLOW_SINGLE_SIGNAL_KEYS.has(normalizedKey)) {
2152
+ const row = publicSignalRow(raw);
2153
+ return row ? [[key, row]] : [];
2154
+ }
2155
+ return [[key, publicSignalizFlowResult(raw)]];
2156
+ }));
2157
+ }
2158
+ function normalizeSignalizFlowBilling(value) {
2159
+ if (!value || typeof value !== "object") return void 0;
2160
+ const billing = value;
2161
+ return {
2162
+ creditsCharged: Number(billing.credits_charged ?? 0),
2163
+ billingStatus: billing.billing_status === "charged" ? "charged" : "included_or_waived",
2164
+ chargeBasis: String(billing.charge_basis ?? ""),
2165
+ receipt: Array.isArray(billing.receipt) ? billing.receipt.map((line) => ({
2166
+ capability: line.capability,
2167
+ successfulResults: Number(line.successful_results ?? 0),
2168
+ creditsCharged: Number(line.credits_charged ?? 0)
2169
+ })).filter((line) => ["company_signals", "find_email", "signal_to_copy"].includes(line.capability)) : []
2170
+ };
2171
+ }
2172
+ function normalizeSignalizFlowStatus(data) {
2173
+ if (data.success !== true || typeof data.run_id !== "string" || !data.run_id.trim()) {
2174
+ throw new Error(String(data.error || "Signaliz Flow status is unavailable."));
2175
+ }
2176
+ const publicData = publicProductData(data, "signaliz_flow");
2177
+ const result = publicData.result && typeof publicData.result === "object" ? publicSignalizFlowResult(publicData.result) : {};
2178
+ const billing = normalizeSignalizFlowBilling(result.billing);
2179
+ if (billing) result.billing = billing;
2180
+ const status = String(publicData.status || "").toLowerCase();
2181
+ return {
2182
+ success: true,
2183
+ runId: String(publicData.run_id),
2184
+ status: status === "completed" || status === "failed" ? status : "running",
2185
+ result,
2186
+ createdAt: typeof publicData.created_at === "string" ? publicData.created_at : void 0,
2187
+ updatedAt: typeof publicData.updated_at === "string" ? publicData.updated_at : void 0,
2188
+ completedAt: typeof publicData.completed_at === "string" ? publicData.completed_at : void 0
1861
2189
  };
1862
2190
  }
1863
2191
  var SIGNAL_DISCOVERY_SOURCES = /* @__PURE__ */ new Set(["web", "news"]);
@@ -1890,10 +2218,32 @@ function validateSignalDiscoveryParams(params) {
1890
2218
  if (params.lookbackDays !== void 0 && (!Number.isInteger(params.lookbackDays) || params.lookbackDays < 1 || params.lookbackDays > 365)) {
1891
2219
  throw new RangeError("lookbackDays must be an integer between 1 and 365");
1892
2220
  }
2221
+ validateSignalDateWindow(params);
1893
2222
  if (params.sources !== void 0 && (!Array.isArray(params.sources) || params.sources.length < 1 || params.sources.length > 2 || params.sources.some((source) => !SIGNAL_DISCOVERY_SOURCES.has(source)))) {
1894
2223
  throw new TypeError("sources must contain only web or news");
1895
2224
  }
1896
2225
  }
2226
+ function validateSignalDateWindow(params) {
2227
+ const afterDate = params.afterDate?.trim();
2228
+ const beforeDate = params.beforeDate?.trim();
2229
+ if ((afterDate || beforeDate) && params.lookbackDays !== void 0) {
2230
+ throw new RangeError("afterDate/beforeDate cannot be combined with lookbackDays");
2231
+ }
2232
+ const parseDate = (value, field) => {
2233
+ if (value === void 0) return void 0;
2234
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) throw new RangeError(`${field} must use YYYY-MM-DD format`);
2235
+ const timestamp = Date.parse(`${value}T00:00:00Z`);
2236
+ if (!Number.isFinite(timestamp) || new Date(timestamp).toISOString().slice(0, 10) !== value) {
2237
+ throw new RangeError(`${field} must be a valid calendar date`);
2238
+ }
2239
+ return timestamp;
2240
+ };
2241
+ const afterTimestamp = parseDate(afterDate, "afterDate");
2242
+ const beforeTimestamp = parseDate(beforeDate, "beforeDate");
2243
+ if (afterTimestamp !== void 0 && beforeTimestamp !== void 0 && beforeTimestamp < afterTimestamp) {
2244
+ throw new RangeError("beforeDate must be on or after afterDate");
2245
+ }
2246
+ }
1897
2247
  function signalDiscoveryRequestBody(params) {
1898
2248
  const runId = typeof params.signalSearchRunId === "string" ? params.signalSearchRunId.trim() : "";
1899
2249
  if (runId) {
@@ -1902,6 +2252,8 @@ function signalDiscoveryRequestBody(params) {
1902
2252
  // An explicit limit expands or narrows the retained qualified cohort;
1903
2253
  // omitting it preserves the original preview size.
1904
2254
  limit: params.limit,
2255
+ after_date: params.afterDate?.trim(),
2256
+ before_date: params.beforeDate?.trim(),
1905
2257
  dry_run: params.dryRun,
1906
2258
  idempotency_key: params.idempotencyKey
1907
2259
  });
@@ -1912,6 +2264,8 @@ function signalDiscoveryRequestBody(params) {
1912
2264
  limit: params.limit ?? 100,
1913
2265
  sources: params.sources,
1914
2266
  lookback_days: params.lookbackDays,
2267
+ after_date: params.afterDate?.trim(),
2268
+ before_date: params.beforeDate?.trim(),
1915
2269
  dry_run: params.dryRun,
1916
2270
  idempotency_key: params.idempotencyKey
1917
2271
  });
@@ -1920,106 +2274,25 @@ function normalizeSignalDiscoveryResult(params, data) {
1920
2274
  const rawSignals = Array.isArray(data.signals) ? data.signals : [];
1921
2275
  const rawStatus = String(data.status || "").toLowerCase();
1922
2276
  const status = SIGNAL_DISCOVERY_STATUSES.has(rawStatus) ? rawStatus : rawSignals.length > 0 ? "completed" : "failed";
1923
- const signals = rawSignals.map(normalizeSignalDiscoverySignal);
2277
+ const requestedCount = Number(data.requested_count ?? params.limit);
2278
+ const signals = oneSignalPerCompany(publicSignalRows(rawSignals)).slice(
2279
+ 0,
2280
+ Number.isFinite(requestedCount) && requestedCount > 0 ? requestedCount : void 0
2281
+ );
1924
2282
  return {
1925
2283
  success: data.success !== false,
1926
2284
  status,
1927
2285
  capability: "signals_everything",
1928
2286
  signalSearchRunId: String(data.signal_search_run_id ?? params.signalSearchRunId ?? ""),
1929
2287
  query: String(data.query ?? params.query ?? ""),
1930
- requestedCount: Number(data.requested_count ?? params.limit ?? 100),
2288
+ ...Number.isFinite(requestedCount) && requestedCount > 0 ? { requestedCount } : {},
1931
2289
  nextPollAfterSeconds: typeof data.next_poll_after_seconds === "number" ? data.next_poll_after_seconds : void 0,
1932
2290
  signals,
1933
2291
  signalCount: signals.length,
1934
- availableCompanySignalCount: Number.isFinite(Number(data.available_company_signal_count)) ? Number(data.available_company_signal_count) : void 0,
1935
- sourceLanes: Array.isArray(data.source_lanes) ? data.source_lanes.filter((lane) => typeof lane === "string") : void 0,
1936
- evidenceValidation: data.evidence_validation && typeof data.evidence_validation === "object" ? data.evidence_validation : void 0,
1937
- discoveryDiagnostics: data.discovery_diagnostics && typeof data.discovery_diagnostics === "object" ? data.discovery_diagnostics : void 0,
1938
- identityResolution: data.identity_resolution && typeof data.identity_resolution === "object" ? data.identity_resolution : void 0,
1939
- costGuardrail: normalizeSignalDiscoveryCostGuardrail(data.cost_guardrail),
1940
- warnings: Array.isArray(data.warnings) ? data.warnings.filter((warning) => typeof warning === "string") : void 0,
1941
- raw: data
1942
- };
1943
- }
1944
- function normalizeSignalDiscoveryCostGuardrail(value) {
1945
- if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
1946
- const guardrail = value;
1947
- const maxCost = Number(guardrail.max_cost_per_qualified_signal_usd);
1948
- const withinLimit = guardrail.within_limit === true;
1949
- if (!Number.isFinite(maxCost)) return void 0;
1950
- const numberOrNullable = (candidate) => {
1951
- if (candidate === null) return null;
1952
- const numeric = Number(candidate);
1953
- return Number.isFinite(numeric) ? numeric : void 0;
1954
- };
1955
- const numberOrUndefined = (candidate) => {
1956
- const numeric = Number(candidate);
1957
- return Number.isFinite(numeric) ? numeric : void 0;
1958
- };
1959
- return {
1960
- maxCostPerQualifiedSignalUsd: maxCost,
1961
- projectedSourceCostUsd: numberOrNullable(guardrail.projected_source_cost_usd),
1962
- maxSourceCostUsd: numberOrNullable(guardrail.max_source_cost_usd),
1963
- projectedCostPerRequestedCompanySignalUsd: numberOrNullable(
1964
- guardrail.projected_cost_per_requested_company_signal_usd
1965
- ),
1966
- sourceCostUsd: numberOrNullable(guardrail.source_cost_usd),
1967
- costSource: ["observed", "catalog_preflight", "catalog_bounded", "mixed", "unavailable"].includes(String(guardrail.cost_source)) ? String(guardrail.cost_source) : void 0,
1968
- identityResolutionCostUsd: numberOrNullable(guardrail.identity_resolution_cost_usd),
1969
- identityCostSource: [
1970
- "observed_zero_credit_receipts",
1971
- "contractual_zero_cost",
1972
- "not_used",
1973
- "unavailable"
1974
- ].includes(String(guardrail.identity_cost_source)) ? String(guardrail.identity_cost_source) : void 0,
1975
- identityProviderRequests: numberOrUndefined(guardrail.identity_provider_requests),
1976
- qualifiedCompanySignalCount: numberOrUndefined(guardrail.qualified_company_signal_count),
1977
- returnedCompanySignalCount: numberOrUndefined(guardrail.returned_company_signal_count),
1978
- availableCompanySignalCount: numberOrUndefined(guardrail.available_company_signal_count),
1979
- acquisitionCandidateLimit: numberOrUndefined(guardrail.acquisition_candidate_limit),
1980
- minimumQualifiedCompanySignals: numberOrUndefined(guardrail.minimum_qualified_company_signals),
1981
- costPerQualifiedSignalUsd: numberOrNullable(guardrail.cost_per_qualified_signal_usd),
1982
- withinLimit
1983
- };
1984
- }
1985
- function normalizeSignalDiscoverySignal(value) {
1986
- const signal = value && typeof value === "object" && !Array.isArray(value) ? value : {};
1987
- const company = signal.company && typeof signal.company === "object" && !Array.isArray(signal.company) ? signal.company : {};
1988
- const companyName = String(company.name ?? signal.company_name ?? "").trim();
1989
- const companyDomain = String(company.domain ?? signal.company_domain ?? "").trim();
1990
- if (!companyName || !companyDomain) {
1991
- throw new Error("Signals Everything response violated the company attribution contract.");
1992
- }
1993
- const eventDate = String(signal.event_date ?? signal.date ?? signal.signal_date ?? "").trim();
1994
- const sourceUrl = String(signal.source_url ?? signal.url ?? "").trim();
1995
- const evidence = Array.isArray(signal.evidence) ? signal.evidence.map((item) => ({
1996
- url: String(item?.url ?? "").trim(),
1997
- publishedAt: String(item?.published_at ?? item?.publishedAt ?? "").trim(),
1998
- source: String(item?.source ?? "").trim()
1999
- })).filter((item) => Boolean(item.url)) : [];
2000
- if (!eventDate || !sourceUrl || !evidence.some((item) => item.url === sourceUrl && item.publishedAt === eventDate)) {
2001
- throw new Error("Signals Everything response violated the dated-evidence and source-URL contract.");
2002
- }
2003
- return {
2004
- id: signal.id,
2005
- company: {
2006
- name: companyName,
2007
- domain: companyDomain,
2008
- linkedinUrl: company.linkedin_url ?? signal.company_linkedin_url ?? void 0
2009
- },
2010
- title: signal.title ?? "",
2011
- type: signal.type ?? signal.signal_type ?? "unknown",
2012
- summary: signal.summary ?? signal.content ?? signal.description ?? "",
2013
- eventDate,
2014
- evidence,
2015
- content: signal.summary ?? signal.content ?? signal.description ?? "",
2016
- date: signal.event_date ?? signal.date ?? signal.signal_date ?? null,
2017
- detectedAt: signal.event_date ?? signal.detected_at ?? null,
2018
- sourceUrl,
2019
- sourceType: signal.source_type ?? null,
2020
- confidence: signal.confidence ?? signal.confidence_score ?? null,
2021
- classification: signal.signal_classification ?? signal.classification ?? null,
2022
- raw: signal
2292
+ creditsUsed: Number.isFinite(Number(data.credits_used)) ? Number(data.credits_used) : 0,
2293
+ creditsCharged: Number.isFinite(Number(data.credits_charged)) ? Number(data.credits_charged) : 0,
2294
+ billingStatus: data.billing_status === "included" ? "included" : void 0,
2295
+ idempotencyReplayed: typeof data.idempotency_replayed === "boolean" ? data.idempotency_replayed : void 0
2023
2296
  };
2024
2297
  }
2025
2298
  function validateBatchSize(items) {
@@ -2073,9 +2346,6 @@ function normalizedBatchDomain(value) {
2073
2346
  function normalizedBatchLinkedIn(value) {
2074
2347
  return normalizedBatchText(value).replace(/\/+$/, "");
2075
2348
  }
2076
- function normalizedBatchList(value) {
2077
- return Array.isArray(value) ? value.map(normalizedBatchText).filter(Boolean).sort() : [];
2078
- }
2079
2349
  function normalizedFindEmailBatchName(request) {
2080
2350
  const fullName = normalizedBatchText(request.full_name);
2081
2351
  const componentName = [normalizedBatchText(request.first_name), normalizedBatchText(request.last_name)].filter(Boolean).join(" ");
@@ -2090,39 +2360,24 @@ function coreProductBatchRequestKey(path, request) {
2090
2360
  normalizedBatchDomain(request.company_domain),
2091
2361
  normalizedBatchLinkedIn(request.linkedin_url),
2092
2362
  normalizedBatchText(request.company_name),
2093
- request.skip_cache === true || request.bypass_cache === true,
2094
2363
  normalizedBatchIdempotencyKey(request.idempotency_key)
2095
2364
  ]);
2096
2365
  }
2097
2366
  if (path === "api/v1/verify-email") {
2098
2367
  return JSON.stringify([
2099
2368
  normalizedBatchText(request.email),
2100
- request.skip_cache === true || request.bypass_cache === true,
2101
2369
  request.skip_catch_all_verification === true,
2102
2370
  request.skip_esp_check === true,
2103
2371
  normalizedBatchIdempotencyKey(request.idempotency_key)
2104
2372
  ]);
2105
2373
  }
2106
2374
  if (path === "api/v1/company-signals") {
2107
- const online = request.online !== false;
2108
- const deepSearch = request.enable_deep_search === void 0 ? online : request.enable_deep_search !== false;
2109
2375
  return JSON.stringify([
2110
2376
  normalizedBatchText(request.signal_run_id),
2111
2377
  normalizedBatchDomain(request.company_domain || request.domain),
2112
2378
  normalizedBatchText(request.company_name),
2113
- normalizedBatchText(request.company_id),
2114
- normalizedBatchLinkedIn(request.linkedin_url),
2115
- normalizedBatchText(request.industry),
2116
2379
  typeof request.research_prompt === "string" ? request.research_prompt.trim() : "",
2117
- normalizedBatchList(request.signal_types),
2118
- Number(request.target_signal_count) || null,
2119
2380
  Number(request.lookback_days) || null,
2120
- online,
2121
- deepSearch,
2122
- normalizedBatchText(request.search_mode || "balanced"),
2123
- request.enable_outreach_intelligence === true,
2124
- request.enable_predictive_intelligence === true,
2125
- request.skip_cache === true || request.bypass_cache === true,
2126
2381
  normalizedBatchIdempotencyKey(request.idempotency_key)
2127
2382
  ]);
2128
2383
  }
@@ -2132,9 +2387,12 @@ function coreProductBatchRequestKey(path, request) {
2132
2387
  typeof request.title === "string" ? request.title.trim() : "",
2133
2388
  typeof request.campaign_offer === "string" ? request.campaign_offer.trim() : "",
2134
2389
  typeof request.research_prompt === "string" ? request.research_prompt.trim() : "",
2390
+ normalizedBatchText(request.copy_evidence_mode),
2135
2391
  Number(request.lookback_days) || null,
2136
2392
  typeof request.signal_run_id === "string" ? request.signal_run_id.trim() : "",
2137
- request.skip_cache === true,
2393
+ typeof request.signal_search_run_id === "string" ? request.signal_search_run_id.trim() : "",
2394
+ typeof request.fact_id === "string" ? request.fact_id.trim() : "",
2395
+ typeof request.event_id === "string" ? request.event_id.trim() : "",
2138
2396
  request.enable_deep_search === true,
2139
2397
  normalizedBatchIdempotencyKey(request.idempotency_key)
2140
2398
  ]);
@@ -2239,43 +2497,60 @@ function signalToCopyRequestBody(params) {
2239
2497
  person_name: params.personName,
2240
2498
  title: params.title,
2241
2499
  campaign_offer: params.campaignOffer,
2242
- research_prompt: params.researchPrompt,
2243
- lookback_days: params.lookbackDays,
2500
+ copy_evidence_mode: params.copyEvidenceMode,
2501
+ lookback_days: 365,
2244
2502
  signal_run_id: params.signalRunId,
2245
- skip_cache: params.skipCache,
2503
+ signal_search_run_id: params.signalSearchRunId,
2504
+ fact_id: params.factId,
2505
+ event_id: params.eventId,
2246
2506
  enable_deep_search: params.enableDeepSearch,
2247
2507
  max_wait_ms: params.maxWaitMs,
2248
2508
  dry_run: params.dryRun,
2249
2509
  idempotency_key: params.idempotencyKey
2250
2510
  });
2251
2511
  }
2252
- function validateLargeAvailableDataSignalCopyBatch(requests) {
2512
+ function validateLargeSignalCopyBatch(requests) {
2253
2513
  if (requests.length <= 25) return;
2254
2514
  const invalidIndex = requests.findIndex(
2255
- (request) => request.skipCache === true || request.enableDeepSearch === true || Boolean(request.idempotencyKey?.trim()) || request.maxWaitMs !== void 0 || request.pollIntervalMs !== void 0 || request.waitForResult === false || !request.companyDomain?.trim() || !request.personName?.trim() || !request.title?.trim() || !request.campaignOffer?.trim()
2515
+ (request) => Boolean(request.idempotencyKey?.trim()) || request.maxWaitMs !== void 0 || request.pollIntervalMs !== void 0 || request.waitForResult === false || Boolean(request.signalSearchRunId?.trim()) || Boolean(request.factId?.trim()) || Boolean(request.eventId?.trim()) || !request.companyDomain?.trim() || !request.personName?.trim() || !request.title?.trim() || !request.campaignOffer?.trim()
2256
2516
  );
2257
2517
  if (invalidIndex >= 0) {
2258
2518
  throw new RangeError(
2259
- `Signal to Copy batches larger than 25 are available-data-only; row ${invalidIndex} requests fresh/deep/synchronous controls or lacks required recipient fields. Split fresh requests into batches of at most 25.`
2519
+ `Signal to Copy batch row ${invalidIndex} uses canonical references (supported only in synchronous batches of 25 or fewer), uses unsupported row-level execution controls, or lacks required recipient fields. Put wait and idempotency controls in the batch options.`
2260
2520
  );
2261
2521
  }
2262
2522
  }
2263
- function availableDataSignalCopyRequestBody(params) {
2523
+ function durableSignalCopyRequestBody(params) {
2264
2524
  return compact({
2265
2525
  company_domain: params.companyDomain,
2266
2526
  person_name: params.personName,
2267
2527
  title: params.title,
2268
2528
  campaign_offer: params.campaignOffer,
2269
- research_prompt: params.researchPrompt,
2270
- lookback_days: params.lookbackDays,
2271
- signal_run_id: params.signalRunId
2529
+ copy_evidence_mode: params.copyEvidenceMode,
2530
+ lookback_days: 365,
2531
+ signal_run_id: params.signalRunId,
2532
+ signal_search_run_id: params.signalSearchRunId,
2533
+ fact_id: params.factId,
2534
+ event_id: params.eventId,
2535
+ enable_deep_search: params.enableDeepSearch
2272
2536
  });
2273
2537
  }
2274
2538
  function validateSignalToCopyParams(params) {
2275
2539
  validateCoreProductMaxWaitMs(params.maxWaitMs);
2540
+ if (params.copyEvidenceMode !== void 0 && !["signal_led", "firmographic"].includes(params.copyEvidenceMode)) {
2541
+ throw new RangeError("copyEvidenceMode must be signal_led or firmographic");
2542
+ }
2276
2543
  if (params.lookbackDays !== void 0 && (!Number.isInteger(params.lookbackDays) || params.lookbackDays < 1 || params.lookbackDays > 365)) {
2277
2544
  throw new RangeError("lookbackDays must be an integer between 1 and 365");
2278
2545
  }
2546
+ if (params.signalSearchRunId !== void 0 && !params.signalSearchRunId.trim()) {
2547
+ throw new TypeError("signalSearchRunId must be a non-empty string");
2548
+ }
2549
+ for (const [field, value] of [["factId", params.factId], ["eventId", params.eventId]]) {
2550
+ if (value !== void 0 && !/^[0-9a-f]{64}$/.test(value.trim())) {
2551
+ throw new TypeError(`${field} must be a lowercase 64-character SHA-256 identifier`);
2552
+ }
2553
+ }
2279
2554
  if (typeof params.signalRunId === "string" && params.signalRunId.trim()) return;
2280
2555
  const missing = [
2281
2556
  ["companyDomain", params.companyDomain],
@@ -2294,6 +2569,7 @@ function validateCoreProductMaxWaitMs(value) {
2294
2569
  }
2295
2570
  }
2296
2571
  function normalizeSignalToCopyResult(data) {
2572
+ data = publicProductData(data, "signal_to_copy");
2297
2573
  const failed = coreProductResponseFailed(data);
2298
2574
  return {
2299
2575
  success: !failed,
@@ -2302,6 +2578,11 @@ function normalizeSignalToCopyResult(data) {
2302
2578
  status: data.status,
2303
2579
  runId: data.run_id ?? data.signal_run_id,
2304
2580
  companySignalRunId: data.company_signal_run_id,
2581
+ signalSearchRunId: data.signal_search_run_id,
2582
+ factId: data.fact_id,
2583
+ eventId: data.event_id,
2584
+ canonicalSourceUrl: data.canonical_source_url,
2585
+ evidenceReuse: data.evidence_reuse,
2305
2586
  resumeContextPersisted: data.resume_context_persisted,
2306
2587
  strongestSignal: failed ? "" : data.strongest_signal ?? "",
2307
2588
  whyNow: failed ? "" : data.why_now ?? "",
@@ -2310,17 +2591,11 @@ function normalizeSignalToCopyResult(data) {
2310
2591
  confidence: failed ? 0 : data.confidence ?? 0,
2311
2592
  evidenceUrl: failed ? "" : data.evidence_url ?? "",
2312
2593
  researchPrompt: data.research_prompt,
2594
+ copyEvidenceMode: data.copy_evidence_mode,
2313
2595
  empty: data.empty,
2314
2596
  emptyReason: data.empty_reason,
2315
2597
  researchMetadata: failed ? void 0 : data.research_metadata,
2316
- billingMetadata: data.billing_metadata,
2317
- resultReturnedFrom: data.result_returned_from,
2318
- cacheHit: data.cache_hit,
2319
- freshEnrichmentUsed: data.fresh_enrichment_used,
2320
2598
  creditsUsed: data.credits_used,
2321
- liveProviderCalled: data.live_provider_called,
2322
- aiProviderCalled: data.ai_provider_called,
2323
- byoAiUsed: data.byo_ai_used,
2324
2599
  unlimitedSignalToCopy: data.unlimited_signal_to_copy,
2325
2600
  signalToCopyEntitlement: data.signal_to_copy_entitlement,
2326
2601
  variations: (failed ? [] : data.variations ?? []).map((variation) => ({
@@ -2334,6 +2609,117 @@ function normalizeSignalToCopyResult(data) {
2334
2609
  raw: data
2335
2610
  };
2336
2611
  }
2612
+ function signalAwarenessMonitorRequest(monitor) {
2613
+ return compact({
2614
+ company_name: monitor.companyName,
2615
+ domain: monitor.domain,
2616
+ template: monitor.template,
2617
+ signal_config: monitor.signalConfig,
2618
+ schedule_cron: monitor.scheduleCron,
2619
+ webhook_url: monitor.webhookUrl
2620
+ });
2621
+ }
2622
+ function signalAwarenessRequestBody(request) {
2623
+ return compact({
2624
+ action: request.action,
2625
+ monitor_id: request.monitorId,
2626
+ monitor: request.monitor ? signalAwarenessMonitorRequest(request.monitor) : void 0,
2627
+ monitors: request.monitors?.map(signalAwarenessMonitorRequest),
2628
+ defaults: request.defaults,
2629
+ updates: request.updates,
2630
+ limit: request.limit,
2631
+ offset: request.offset,
2632
+ idempotency_key: request.idempotencyKey,
2633
+ dry_run: request.dryRun
2634
+ });
2635
+ }
2636
+ function normalizeSignalAwarenessResponse(data) {
2637
+ const payload = data.data && typeof data.data === "object" ? data.data : data;
2638
+ const signals = Array.isArray(payload.signals) ? oneSignalPerCompany(payload.signals.flatMap(normalizeSignalAwarenessSignal)) : void 0;
2639
+ const monitors = Array.isArray(payload.monitors) ? payload.monitors.map(normalizeSignalAwarenessMonitor).filter((value) => value !== void 0) : void 0;
2640
+ const monitor = normalizeSignalAwarenessMonitor(payload.monitor);
2641
+ const run = normalizeSignalAwarenessRun(payload.run);
2642
+ const billing = payload.billing && typeof payload.billing === "object" ? payload.billing : {};
2643
+ const creditsUsed = Number(payload.credits_used ?? billing.credits_used);
2644
+ return {
2645
+ success: data.success !== false,
2646
+ ...monitors ? { monitors } : {},
2647
+ ...monitor ? { monitor } : {},
2648
+ ...signals ? { signals } : {},
2649
+ ...signals ? { signalCount: signals.length } : {},
2650
+ ...typeof payload.monitor_id === "string" ? { monitorId: payload.monitor_id } : {},
2651
+ ...typeof payload.run_id === "string" ? { runId: payload.run_id } : {},
2652
+ ...run ? { run } : {},
2653
+ ...Number.isInteger(creditsUsed) && creditsUsed >= 0 ? { creditsUsed } : {},
2654
+ ...Number.isFinite(Number(payload.created)) ? { created: Number(payload.created) } : {},
2655
+ ...Number.isFinite(Number(payload.skipped)) ? { skipped: Number(payload.skipped) } : {},
2656
+ ...Number.isFinite(Number(payload.total)) ? { total: Number(payload.total) } : {},
2657
+ ...Number.isFinite(Number(payload.limit)) ? { limit: Number(payload.limit) } : {},
2658
+ ...Number.isFinite(Number(payload.offset)) ? { offset: Number(payload.offset) } : {},
2659
+ ...typeof payload.has_more === "boolean" ? { hasMore: payload.has_more } : {},
2660
+ ...payload.idempotent_replay === true ? { idempotentReplay: true } : {}
2661
+ };
2662
+ }
2663
+ function signalAwarenessRecord(value) {
2664
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
2665
+ }
2666
+ function signalAwarenessText(value, maximum = 500) {
2667
+ return typeof value === "string" && value.trim() && value.trim().length <= maximum ? value.trim() : void 0;
2668
+ }
2669
+ function signalAwarenessCount(value) {
2670
+ const numeric = Number(value);
2671
+ return Number.isInteger(numeric) && numeric >= 0 ? numeric : void 0;
2672
+ }
2673
+ function normalizeSignalAwarenessMonitor(value) {
2674
+ const monitor = signalAwarenessRecord(value);
2675
+ const result = {};
2676
+ const id = signalAwarenessText(monitor.id, 200);
2677
+ const companyName = signalAwarenessText(monitor.company_name, 300);
2678
+ const domain = signalAwarenessText(monitor.domain, 253);
2679
+ const status = signalAwarenessText(monitor.status, 80);
2680
+ const schedule = signalAwarenessText(monitor.schedule, 120);
2681
+ if (id) result.id = id;
2682
+ if (companyName) result.company_name = companyName;
2683
+ if (domain) result.domain = domain;
2684
+ if (status) result.status = status;
2685
+ if (schedule) result.schedule = schedule;
2686
+ for (const key of ["last_run_at", "next_run_at", "created_at", "updated_at"]) {
2687
+ const timestamp = signalAwarenessText(monitor[key], 64);
2688
+ if (timestamp && Number.isFinite(Date.parse(timestamp))) result[key] = timestamp;
2689
+ }
2690
+ return Object.keys(result).length > 0 ? result : void 0;
2691
+ }
2692
+ function normalizeSignalAwarenessRun(value) {
2693
+ const run = signalAwarenessRecord(value);
2694
+ const result = {};
2695
+ const id = signalAwarenessText(run.id, 200);
2696
+ const monitorId = signalAwarenessText(run.monitor_id, 200);
2697
+ const status = signalAwarenessText(run.status, 80);
2698
+ const signalsFound = signalAwarenessCount(run.signals_found);
2699
+ if (id) result.id = id;
2700
+ if (monitorId) result.monitor_id = monitorId;
2701
+ if (status) result.status = status;
2702
+ if (signalsFound !== void 0) result.signals_found = signalsFound;
2703
+ for (const key of ["started_at", "completed_at", "created_at"]) {
2704
+ const timestamp = signalAwarenessText(run[key], 64);
2705
+ if (timestamp && Number.isFinite(Date.parse(timestamp))) result[key] = timestamp;
2706
+ }
2707
+ return Object.keys(result).length > 0 ? result : void 0;
2708
+ }
2709
+ function normalizeSignalAwarenessSignal(value) {
2710
+ const signal = value && typeof value === "object" && !Array.isArray(value) ? value : {};
2711
+ const rawData = signal.raw_data && typeof signal.raw_data === "object" && !Array.isArray(signal.raw_data) ? signal.raw_data : {};
2712
+ const row = publicSignalRow({
2713
+ ...rawData,
2714
+ ...signal,
2715
+ signal_type: signal.signal_type ?? rawData.signal_type,
2716
+ source_url: signal.canonical_source_url ?? rawData.canonical_source_url ?? signal.source_url ?? rawData.source_url ?? rawData.url,
2717
+ date: signal.date ?? signal.event_date ?? signal.detected_at ?? rawData.date ?? rawData.event_date ?? rawData.detected_at ?? rawData.observed_at,
2718
+ company_name: signal.company_name ?? rawData.company_name,
2719
+ company_domain: signal.domain ?? signal.company_domain ?? rawData.company_domain ?? rawData.domain
2720
+ });
2721
+ return row ? [row] : [];
2722
+ }
2337
2723
  function isPendingSignalResponse(data) {
2338
2724
  if (coreProductResponseFailed(data)) return false;
2339
2725
  return ["triggered", "queued", "processing", "pending", "pending_version", "waiting_for_deploy"].includes(String(data.status || "").toLowerCase());