@haakco/custd-sdk 0.0.0-stage → 3.71.1
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.
- package/README.md +958 -2
- package/dist/admin-accounting-evidence.d.ts +48 -0
- package/dist/admin-accounting-evidence.js +24 -0
- package/dist/admin-app-releases.d.ts +116 -0
- package/dist/admin-app-releases.js +8 -0
- package/dist/admin-apps.d.ts +120 -0
- package/dist/admin-apps.js +47 -0
- package/dist/admin-auth-project-domain.d.ts +125 -0
- package/dist/admin-auth-project-domain.js +37 -0
- package/dist/admin-auth-projects.d.ts +989 -0
- package/dist/admin-auth-projects.js +527 -0
- package/dist/admin-campaign-email.d.ts +120 -0
- package/dist/admin-campaign-email.js +64 -0
- package/dist/admin-client-setup.d.ts +122 -0
- package/dist/admin-client-setup.js +408 -0
- package/dist/admin-data-labels.d.ts +124 -0
- package/dist/admin-data-labels.js +51 -0
- package/dist/admin-data-scopes.d.ts +93 -0
- package/dist/admin-data-scopes.js +154 -0
- package/dist/admin-email-relay.d.ts +66 -0
- package/dist/admin-email-relay.js +25 -0
- package/dist/admin-environment-policy.d.ts +32 -0
- package/dist/admin-environment-policy.js +26 -0
- package/dist/admin-error-issues.d.ts +91 -0
- package/dist/admin-error-issues.js +52 -0
- package/dist/admin-event-types.d.ts +57 -0
- package/dist/admin-event-types.js +28 -0
- package/dist/admin-impersonation.d.ts +48 -0
- package/dist/admin-impersonation.js +27 -0
- package/dist/admin-ingest-claims.d.ts +35 -0
- package/dist/admin-ingest-claims.js +26 -0
- package/dist/admin-managed-audit.d.ts +13 -0
- package/dist/admin-managed-audit.js +13 -0
- package/dist/admin-measurement-projects.d.ts +166 -0
- package/dist/admin-measurement-projects.js +120 -0
- package/dist/admin-notification-destinations.d.ts +31 -0
- package/dist/admin-notification-destinations.js +19 -0
- package/dist/admin-notification-webhooks.d.ts +64 -0
- package/dist/admin-notification-webhooks.js +42 -0
- package/dist/admin-oauth-client-admissions.d.ts +65 -0
- package/dist/admin-oauth-client-admissions.js +46 -0
- package/dist/admin-offboarding.d.ts +123 -0
- package/dist/admin-offboarding.js +129 -0
- package/dist/admin-predictions.d.ts +266 -0
- package/dist/admin-predictions.js +93 -0
- package/dist/admin-privacy-erasures.d.ts +74 -0
- package/dist/admin-privacy-erasures.js +73 -0
- package/dist/admin-retention.d.ts +99 -0
- package/dist/admin-retention.js +60 -0
- package/dist/admin-rls.d.ts +94 -0
- package/dist/admin-rls.js +33 -0
- package/dist/admin-sdk-usage.d.ts +41 -0
- package/dist/admin-sdk-usage.js +23 -0
- package/dist/admin-site-ai.d.ts +72 -0
- package/dist/admin-site-ai.js +1 -0
- package/dist/admin-site-analytics.d.ts +52 -0
- package/dist/admin-site-analytics.js +14 -0
- package/dist/admin-site-audit-pages.d.ts +76 -0
- package/dist/admin-site-audit-pages.js +27 -0
- package/dist/admin-site-campaign-links.d.ts +40 -0
- package/dist/admin-site-campaign-links.js +9 -0
- package/dist/admin-site-domains.d.ts +733 -0
- package/dist/admin-site-domains.js +768 -0
- package/dist/admin-site-export.d.ts +76 -0
- package/dist/admin-site-export.js +15 -0
- package/dist/admin-site-insights-tasks.d.ts +44 -0
- package/dist/admin-site-insights-tasks.js +28 -0
- package/dist/admin-site-insights.d.ts +527 -0
- package/dist/admin-site-insights.js +61 -0
- package/dist/admin-site-links.d.ts +87 -0
- package/dist/admin-site-links.js +16 -0
- package/dist/admin-site-monitors.d.ts +110 -0
- package/dist/admin-site-monitors.js +25 -0
- package/dist/admin-site-next-actions.d.ts +93 -0
- package/dist/admin-site-next-actions.js +36 -0
- package/dist/admin-site-page-queries.d.ts +63 -0
- package/dist/admin-site-page-queries.js +20 -0
- package/dist/admin-site-rankings.d.ts +98 -0
- package/dist/admin-site-rankings.js +46 -0
- package/dist/admin-site-regional-trends.d.ts +30 -0
- package/dist/admin-site-regional-trends.js +1 -0
- package/dist/admin-site-saved-reports.d.ts +45 -0
- package/dist/admin-site-saved-reports.js +13 -0
- package/dist/admin-site-search-pool.d.ts +77 -0
- package/dist/admin-site-search-pool.js +41 -0
- package/dist/admin-site-search-value.d.ts +97 -0
- package/dist/admin-site-search-value.js +29 -0
- package/dist/admin-site-status-page.d.ts +57 -0
- package/dist/admin-site-status-page.js +10 -0
- package/dist/admin-site-traffic.d.ts +145 -0
- package/dist/admin-site-traffic.js +32 -0
- package/dist/admin-site-web-data.d.ts +258 -0
- package/dist/admin-site-web-data.js +60 -0
- package/dist/admin-subject-exports.d.ts +79 -0
- package/dist/admin-subject-exports.js +44 -0
- package/dist/admin-support-access.d.ts +32 -0
- package/dist/admin-support-access.js +21 -0
- package/dist/admin-system.d.ts +283 -0
- package/dist/admin-system.js +65 -0
- package/dist/admin-tenant-storage.d.ts +35 -0
- package/dist/admin-tenant-storage.js +24 -0
- package/dist/admin-timeplans.d.ts +512 -0
- package/dist/admin-timeplans.js +200 -0
- package/dist/admin-uncertainty-models.d.ts +42 -0
- package/dist/admin-uncertainty-models.js +53 -0
- package/dist/admin-usage.d.ts +124 -0
- package/dist/admin-usage.js +169 -0
- package/dist/admin-users.d.ts +124 -0
- package/dist/admin-users.js +82 -0
- package/dist/admin-workflow-timings.d.ts +367 -0
- package/dist/admin-workflow-timings.js +117 -0
- package/dist/analytics-events.d.ts +167 -0
- package/dist/analytics-events.js +197 -0
- package/dist/analytics-reads.d.ts +81 -0
- package/dist/analytics-reads.js +5 -0
- package/dist/app-account.d.ts +84 -0
- package/dist/app-account.js +177 -0
- package/dist/app-alerts.d.ts +120 -0
- package/dist/app-alerts.js +44 -0
- package/dist/app-items.d.ts +786 -0
- package/dist/app-items.js +524 -0
- package/dist/app-live.d.ts +84 -0
- package/dist/app-live.js +228 -0
- package/dist/app-meetings.d.ts +95 -0
- package/dist/app-meetings.js +26 -0
- package/dist/app-models.d.ts +271 -0
- package/dist/app-models.js +83 -0
- package/dist/app-push.d.ts +64 -0
- package/dist/app-push.js +178 -0
- package/dist/backend-lifecycle.d.ts +85 -0
- package/dist/backend-lifecycle.js +212 -0
- package/dist/browser-manifest.json +7 -0
- package/dist/browser-script-BWnwDjAC.js +711 -0
- package/dist/browser-script.d.ts +1 -0
- package/dist/browser-script.js +5 -0
- package/dist/browser-sign-in.d.ts +153 -0
- package/dist/browser-sign-in.js +410 -0
- package/dist/browser-tracker.d.ts +142 -0
- package/dist/browser-tracker.js +775 -0
- package/dist/browser-web-vitals.d.ts +22 -0
- package/dist/browser-web-vitals.js +116 -0
- package/dist/browser.d.ts +10 -0
- package/dist/browser.js +10 -0
- package/dist/download-stream.d.ts +16 -0
- package/dist/download-stream.js +55 -0
- package/dist/error-capture.d.ts +62 -0
- package/dist/error-capture.js +168 -0
- package/dist/hosted-app.d.ts +115 -0
- package/dist/hosted-app.js +275 -0
- package/dist/index.d.ts +2324 -0
- package/dist/index.js +2226 -0
- package/dist/ingest-operations.d.ts +483 -0
- package/dist/ingest-operations.js +154 -0
- package/dist/measurement.d.ts +164 -0
- package/dist/measurement.js +104 -0
- package/dist/mobile-adapter.d.ts +25 -0
- package/dist/mobile-adapter.js +57 -0
- package/dist/mobile-context.d.ts +32 -0
- package/dist/mobile-context.js +156 -0
- package/dist/mobile-queue.d.ts +22 -0
- package/dist/mobile-queue.js +73 -0
- package/dist/oauth.d.ts +1 -0
- package/dist/oauth.js +8 -0
- package/dist/parsers.d.ts +149 -0
- package/dist/parsers.js +115 -0
- package/dist/public-reads.d.ts +79 -0
- package/dist/public-reads.js +57 -0
- package/dist/reporting-catalogue.d.ts +264 -0
- package/dist/reporting-catalogue.js +5 -0
- package/dist/reporting-state.d.ts +46 -0
- package/dist/reporting-state.js +76 -0
- package/dist/response-lists.d.ts +16 -0
- package/dist/response-lists.generated.d.ts +7 -0
- package/dist/response-lists.generated.js +1927 -0
- package/dist/response-lists.js +70 -0
- package/dist/response-validation.d.ts +30 -0
- package/dist/response-validation.js +94 -0
- package/dist/runtime-readiness.d.ts +30 -0
- package/dist/runtime-readiness.js +150 -0
- package/dist/schema-registry.d.ts +45 -0
- package/dist/schema-registry.js +9 -0
- package/dist/secure-url.d.ts +4 -0
- package/dist/secure-url.js +23 -0
- package/dist/site-ai-owner.d.ts +34 -0
- package/dist/site-ai-owner.js +99 -0
- package/dist/site-monitor-reports.d.ts +15 -0
- package/dist/site-monitor-reports.js +87 -0
- package/dist/testing/fake-custd.d.ts +150 -0
- package/dist/testing/fake-custd.js +842 -0
- package/dist/testing/fake-results.d.ts +30 -0
- package/dist/testing/fake-results.js +293 -0
- package/dist/testing.d.ts +2 -0
- package/dist/testing.js +3 -0
- package/dist/version.d.ts +10 -0
- package/dist/version.js +10 -0
- package/package.json +57 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,2226 @@
|
|
|
1
|
+
import { AuthProjectAdminClient } from "./admin-auth-projects.js";
|
|
2
|
+
import { ClientSetupClient } from "./admin-client-setup.js";
|
|
3
|
+
import { DataLabelAdminClient } from "./admin-data-labels.js";
|
|
4
|
+
import { DataScopeAdminClient, validDataScopeCode } from "./admin-data-scopes.js";
|
|
5
|
+
import { OffboardingClient, } from "./admin-offboarding.js";
|
|
6
|
+
import { PredictionAdminClient } from "./admin-predictions.js";
|
|
7
|
+
import { PrivacyErasureClient } from "./admin-privacy-erasures.js";
|
|
8
|
+
import { RetentionClient } from "./admin-retention.js";
|
|
9
|
+
import { SiteDomainAdminClient } from "./admin-site-domains.js";
|
|
10
|
+
import { SiteInsightsAdminClient } from "./admin-site-insights-tasks.js";
|
|
11
|
+
import { SubjectExportClient } from "./admin-subject-exports.js";
|
|
12
|
+
import { TenantStorageClient } from "./admin-tenant-storage.js";
|
|
13
|
+
import { responseDownloadStream } from "./download-stream.js";
|
|
14
|
+
import { isLocalHostname } from "./secure-url.js";
|
|
15
|
+
export { AUTH_PROJECT_DOMAIN_CONVERGENCES, AUTH_PROJECT_DOMAIN_IMAGE_COMPONENTS, AUTH_PROJECT_DOMAIN_IMAGE_SOURCES, AUTH_PROJECT_DOMAIN_LIFECYCLES, AUTH_PROJECT_DOMAIN_STATUSES, } from "./admin-auth-project-domain.js";
|
|
16
|
+
export { ADMIN_USER_GLOBAL_STATES, ADMIN_USER_MEMBERSHIP_STATES, ADMIN_USER_ROLES, AdminUserAdminClient, } from "./admin-users.js";
|
|
17
|
+
export { WORKFLOW_TIMING_FACT_KINDS, WORKFLOW_TIMING_STATES, WorkflowTimingAdminClient, } from "./admin-workflow-timings.js";
|
|
18
|
+
import { AccountingEvidenceAdminClient } from "./admin-accounting-evidence.js";
|
|
19
|
+
import { CampaignEmailAdminClient } from "./admin-campaign-email.js";
|
|
20
|
+
import { EmailRelayAdminClient } from "./admin-email-relay.js";
|
|
21
|
+
import { EnvironmentPolicyAdminClient } from "./admin-environment-policy.js";
|
|
22
|
+
import { ErrorIssueAdminClient } from "./admin-error-issues.js";
|
|
23
|
+
import { EventTypeAdminClient } from "./admin-event-types.js";
|
|
24
|
+
import { ImpersonationAdminClient } from "./admin-impersonation.js";
|
|
25
|
+
import { IngestClaimAdminClient } from "./admin-ingest-claims.js";
|
|
26
|
+
import { ManagedAuditAdminClient } from "./admin-managed-audit.js";
|
|
27
|
+
import { AdminMeasurementNamespace } from "./admin-measurement-projects.js";
|
|
28
|
+
import { NotificationDestinationAdminClient } from "./admin-notification-destinations.js";
|
|
29
|
+
import { NotificationWebhookAdminClient } from "./admin-notification-webhooks.js";
|
|
30
|
+
import { OAuthClientAdmissionAdminClient } from "./admin-oauth-client-admissions.js";
|
|
31
|
+
import { RlsAdminClient } from "./admin-rls.js";
|
|
32
|
+
import { SdkUsageAdminClient } from "./admin-sdk-usage.js";
|
|
33
|
+
import { SupportAccessAdminClient } from "./admin-support-access.js";
|
|
34
|
+
import { SystemAdminClient } from "./admin-system.js";
|
|
35
|
+
import { TimePlanAdminClient } from "./admin-timeplans.js";
|
|
36
|
+
import { UncertaintyModelAdminClient } from "./admin-uncertainty-models.js";
|
|
37
|
+
import { UsageAdminClient } from "./admin-usage.js";
|
|
38
|
+
import { AdminUserAdminClient } from "./admin-users.js";
|
|
39
|
+
import { WorkflowTimingAdminClient } from "./admin-workflow-timings.js";
|
|
40
|
+
import { AnalyticsEventClient } from "./analytics-events.js";
|
|
41
|
+
import { BackendLifecycleClient } from "./backend-lifecycle.js";
|
|
42
|
+
import { IngestOperationsClient } from "./ingest-operations.js";
|
|
43
|
+
import { MeasurementClient } from "./measurement.js";
|
|
44
|
+
import { basicAuthorization } from "./oauth.js";
|
|
45
|
+
import { ParserClient } from "./parsers.js";
|
|
46
|
+
import { PublicReadClient } from "./public-reads.js";
|
|
47
|
+
import { emptyApiNullLists } from "./response-lists.js";
|
|
48
|
+
import { eventSchemaPath, schemaRegistryPath, } from "./schema-registry.js";
|
|
49
|
+
import { redeemSiteAIOwnerHandoff } from "./site-ai-owner.js";
|
|
50
|
+
import { SDK_IDENTITY } from "./version.js";
|
|
51
|
+
export { APP_ERROR_CODES, APP_REASON_CODES, APP_SIGN_IN_MODES, APP_STATUSES, } from "./admin-apps.js";
|
|
52
|
+
export { AuthProjectAdminClient, AuthProjectRealmNotConvergedError, AuthProjectRealmProvisionError, } from "./admin-auth-projects.js";
|
|
53
|
+
export { ClientSetupClient, validateClientSetupManifest, } from "./admin-client-setup.js";
|
|
54
|
+
export { DataLabelAdminClient, } from "./admin-data-labels.js";
|
|
55
|
+
export { DataScopeAdminClient, validDataScopeCode, validDataScopeName, } from "./admin-data-scopes.js";
|
|
56
|
+
export { OffboardingClient, } from "./admin-offboarding.js";
|
|
57
|
+
export { PredictionAdminClient, } from "./admin-predictions.js";
|
|
58
|
+
export { PrivacyErasureClient, PrivacyErasureError, } from "./admin-privacy-erasures.js";
|
|
59
|
+
export { RetentionClient, } from "./admin-retention.js";
|
|
60
|
+
export { SITE_ANALYTICS_CONNECTION_NOT_FOUND_CODE, SITE_ANALYTICS_PROPERTY_INVALID_CODE, SITE_ANALYTICS_PROVIDER_GA4, SiteAnalyticsUnavailableReport, } from "./admin-site-analytics.js";
|
|
61
|
+
export { SITE_AUDIT_PAGES_DEFAULT_LIMIT, SITE_AUDIT_PAGES_MAX_LIMIT, SITE_LIGHTHOUSE_MAX_EXTRA_PAGES, SITE_LIGHTHOUSE_PAGE_NOT_EXTRA_CODE, SiteAuditPageIndexability, SiteAuditRun, } from "./admin-site-audit-pages.js";
|
|
62
|
+
export { SITE_CAMPAIGN_LINK_LIMIT_CODE, SITE_CAMPAIGN_LINK_TAKEN_CODE, SITE_CAMPAIGN_LINKS_MAX, } from "./admin-site-campaign-links.js";
|
|
63
|
+
export { SITE_BROWSER_COLLECTOR_MODES, SITE_DOMAIN_NOT_VERIFIED_CODE, SITE_FINDING_DISMISSAL_SCOPES, SITE_SEARCH_CONNECTION_NOT_FOUND_CODE, SITE_SEARCH_NOT_CONFIGURED_CODE, SITE_SEARCH_RETRY_NOT_FAILING_CODE, SiteDomainAdminClient, SiteRule, } from "./admin-site-domains.js";
|
|
64
|
+
export { SITE_INSIGHTS_EXPORT_SCHEMA, SITE_INSIGHTS_EXPORT_SEARCH_METRICS_MAX_LIMIT, SiteSearchMetricDimension, } from "./admin-site-export.js";
|
|
65
|
+
export { IndexNowSubmissionStatus, SITE_CHOICE_REQUIRED_CODE, SITE_INDEXNOW_DOMAIN_UNVERIFIED_CODE, SITE_INDEXNOW_KEY_UNVERIFIED_CODE, SITE_INDEXNOW_LIMIT_CODE, SITE_INDEXNOW_NOT_ENABLED_CODE, SITE_INDEXNOW_URLS_INVALID_CODE, SITE_PAGE_NOT_ON_DOMAIN_CODE, SITE_PAGE_NOT_READ_CODE, SITE_PAGE_RECHECK_LIMIT_CODE, SITE_PAGE_RECHECK_READ_LIMIT, SITE_SEARCH_INSPECTION_LIMIT_CODE, SITE_SEARCH_INSPECTION_NOT_CONNECTED_CODE, SITE_SEARCH_INSPECTION_URL_INVALID_CODE, SiteGeneratedFormat, SitePageCheckScope, SitePageRecheckState, SiteRemedyKind, } from "./admin-site-insights.js";
|
|
66
|
+
export { SiteInsightsAdminClient, SiteInsightsTaskName, } from "./admin-site-insights-tasks.js";
|
|
67
|
+
export { SiteLinkSource, SiteLinkSourceStatus, } from "./admin-site-links.js";
|
|
68
|
+
export { PRIVATE_UPTIME_FAILURES, PRIVATE_UPTIME_STATUSES, SITE_HEARTBEAT_OUTCOMES, SITE_HEARTBEAT_STATUSES, } from "./admin-site-monitors.js";
|
|
69
|
+
export { SITE_NEXT_ACTIONS_MAX, SiteNextActionKind, SiteNextActionPlace, SiteNotChecked, } from "./admin-site-next-actions.js";
|
|
70
|
+
export { SitePageLinkSourceWhere, SitePageQueriesState, SiteTitleTemplate, } from "./admin-site-page-queries.js";
|
|
71
|
+
export { SITE_RANKINGS_DAYS_INVALID_CODE, SITE_RANKINGS_DEFAULT_DAYS, SITE_RANKINGS_MAX_DAYS, SITE_TRACKED_KEYWORD_ALL, SITE_TRACKED_KEYWORD_DEFAULT_NOTIFY_POSITION, SITE_TRACKED_KEYWORD_DUPLICATE_CODE, SITE_TRACKED_KEYWORD_INVALID_CODE, SITE_TRACKED_KEYWORD_LIMIT_CODE, SITE_TRACKED_KEYWORD_NOT_FOUND_CODE, SITE_TRACKED_KEYWORDS_MAX, SiteRankDevice, SiteRankingsSource, SiteRankState, SiteTrackedKeywordStatus, } from "./admin-site-rankings.js";
|
|
72
|
+
export { SAVED_SITE_REPORT_LIMIT_CODE, SAVED_SITE_REPORT_NAME_TAKEN_CODE, SITE_SAVED_REPORTS_MAX, SiteReportTemplate, } from "./admin-site-saved-reports.js";
|
|
73
|
+
export { SEARCH_POOL_MIN_CONTRIBUTORS, SEARCH_POOL_MIN_IMPRESSIONS, SEARCH_POOL_QUERIES_DEFAULT_LIMIT, SEARCH_POOL_QUERIES_MAX_LIMIT, SEARCH_POOL_SEARCH_MAX_LENGTH, SEARCH_POOL_TERMS_VERSION, SEARCH_POOL_WINDOW_DAYS, SearchPoolAccess, SearchPoolDemandBand, SITE_SEARCH_POOL_NOT_JOINED_CODE, SITE_SEARCH_POOL_QUERY_INVALID_CODE, SITE_SEARCH_POOL_SETTING_INVALID_CODE, SITE_SEARCH_POOL_SITE_BOUND_CODE, } from "./admin-site-search-pool.js";
|
|
74
|
+
export { SITE_FINDING_IMPACT_DEFAULT_DAYS, SITE_FINDING_IMPACT_MAX_DAYS, SITE_FINDING_IMPACT_MIN_DAYS, SITE_SEARCH_VALUE_DEFAULT_DAYS, SITE_SEARCH_VALUE_MAX_DAYS, SITE_SEARCH_VALUE_MAX_GOALS, SITE_SEARCH_VALUE_MAX_PAGES, SiteFindingImpactStatus, SiteSearchGoalStatus, } from "./admin-site-search-value.js";
|
|
75
|
+
export { siteStatusPagePublicUrl, } from "./admin-site-status-page.js";
|
|
76
|
+
export { ACCESS_LOG_HOUR_INVALID_CODE, AccessLogHourStatus, SiteCrawlerIdentity, SiteReferrerClass, SiteTrafficDayCoverage, TRAFFIC_OTHER_KEY, } from "./admin-site-traffic.js";
|
|
77
|
+
export { SITE_KEYWORD_DEMAND_SOURCE_BING, SITE_KEYWORD_LIST_LIMIT_CODE, SITE_KEYWORD_LIST_NOT_FOUND_CODE, SiteContentGapCoverage, SiteKeywordDemandState, SiteTopicTrendSource, SiteTopicTrendStatus, SiteTrancoBand, SiteWebDomainRole, SiteWebInventoryStatus, SiteWebPageSource, } from "./admin-site-web-data.js";
|
|
78
|
+
export { SubjectExportClient, } from "./admin-subject-exports.js";
|
|
79
|
+
export { TenantStorageClient, } from "./admin-tenant-storage.js";
|
|
80
|
+
export { TimePlanAdminClient, validateTimePlanDefinition, } from "./admin-timeplans.js";
|
|
81
|
+
export { USAGE_DEFAULT_LIMIT, USAGE_MAX_LIMIT, UsageAdminClient, } from "./admin-usage.js";
|
|
82
|
+
export { ANALYTICS_MAX_LABEL_FILTERS, ANALYTICS_MAX_RANGE_DAYS, ANALYTICS_RANGE_GROUP_BY, AnalyticsEventClient, } from "./analytics-events.js";
|
|
83
|
+
export { BackendLifecycleClient, createVerifiedOffboardingExportReceiver, } from "./backend-lifecycle.js";
|
|
84
|
+
export { BrowserSignIn, createSignInCodeChallenge, DEFAULT_SIGN_IN_SCOPES, SIGN_IN_ERROR_CODES, SIGN_IN_STATUSES, SignInError, signInConfigFromDiscovery, } from "./browser-sign-in.js";
|
|
85
|
+
export { DEFAULT_PARSER_FRAMING_MAX_LINES, DEFAULT_PARSER_FRAMING_MAX_RECORD_BYTES, MAX_PARSER_FRAMING_LINES, MAX_PARSER_FRAMING_RECORD_BYTES, ParserClient, } from "./parsers.js";
|
|
86
|
+
export { classifyReportingData, getReportingViewState, reportingQueryKey, } from "./reporting-state.js";
|
|
87
|
+
export { checkRuntimeReadiness, } from "./runtime-readiness.js";
|
|
88
|
+
export { createMobileAsyncQueueStorage, createMobileFlushTriggers, } from "./mobile-adapter.js";
|
|
89
|
+
export { createMobileEvent, } from "./mobile-context.js";
|
|
90
|
+
export { AsyncEventQueue } from "./mobile-queue.js";
|
|
91
|
+
/**
|
|
92
|
+
* Mint a fresh key from the current time and a random UUIDv4. Mint it ONCE per
|
|
93
|
+
* request object so a resend reuses the key; a genuinely repeated occurrence
|
|
94
|
+
* needs a new request object and therefore a new key.
|
|
95
|
+
*/
|
|
96
|
+
export function createRawRequestIdempotencyKey() {
|
|
97
|
+
return `${Date.now()}:${randomUUID()}`;
|
|
98
|
+
}
|
|
99
|
+
/** Mint one prepared request with a fresh, retained idempotency key. */
|
|
100
|
+
export function createRawIngestRequest(input) {
|
|
101
|
+
return { ...input, idempotencyKey: createRawRequestIdempotencyKey() };
|
|
102
|
+
}
|
|
103
|
+
export class AdminWorkflowError extends Error {
|
|
104
|
+
constructor(status, reason, code, safeNextAction) {
|
|
105
|
+
let message = `custd: ${reason || "admin workflow request failed"} (status ${status})`;
|
|
106
|
+
if (code)
|
|
107
|
+
message += ` [code=${code}]`;
|
|
108
|
+
if (safeNextAction)
|
|
109
|
+
message += ` [safeNextAction=${safeNextAction}]`;
|
|
110
|
+
super(message);
|
|
111
|
+
this.status = status;
|
|
112
|
+
this.reason = reason;
|
|
113
|
+
this.code = code;
|
|
114
|
+
this.safeNextAction = safeNextAction;
|
|
115
|
+
this.name = "AdminWorkflowError";
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
export class CustdRequestError extends Error {
|
|
119
|
+
constructor(status, code, retryability, nextAction, problem, options) {
|
|
120
|
+
super(`custd: request failed [code=${code}]`);
|
|
121
|
+
this.status = status;
|
|
122
|
+
this.code = code;
|
|
123
|
+
this.retryability = retryability;
|
|
124
|
+
this.nextAction = nextAction;
|
|
125
|
+
this.problem = problem;
|
|
126
|
+
this.name = "CustdRequestError";
|
|
127
|
+
this.cause = options?.cause;
|
|
128
|
+
}
|
|
129
|
+
get unavailable() {
|
|
130
|
+
return (this.code === "oauth_unavailable" ||
|
|
131
|
+
this.status === null ||
|
|
132
|
+
this.status === 429 ||
|
|
133
|
+
(this.status !== null && this.status >= 500));
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* CustdRawAcceptanceUnknownError reports that a raw upload's acceptance could
|
|
138
|
+
* not be determined: the connection failed before a response arrived, the 202
|
|
139
|
+
* acceptance body was missing or malformed, or the response carried a status
|
|
140
|
+
* that does not prove rejection. The request may or may not have landed, so
|
|
141
|
+
* this error carries no retry guidance (`retryability` "none", `nextAction`
|
|
142
|
+
* "escalate"): there is no verified occurrence identity, and replaying the POST
|
|
143
|
+
* could double-land accepted records. The cause never carries the request
|
|
144
|
+
* payload or a token.
|
|
145
|
+
*/
|
|
146
|
+
export class CustdRawAcceptanceUnknownError extends Error {
|
|
147
|
+
constructor(options) {
|
|
148
|
+
super("custd: raw upload acceptance is unknown; the request may or may not have landed and must not be replayed");
|
|
149
|
+
this.name = "CustdRawAcceptanceUnknownError";
|
|
150
|
+
this.retryability = "none";
|
|
151
|
+
this.nextAction = { action: "escalate" };
|
|
152
|
+
this.cause = options?.cause;
|
|
153
|
+
this.operationKey = options?.operationKey;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
/** A 404 on schema audit: the named tenant does not exist. */
|
|
157
|
+
export const SCHEMA_AUDIT_TENANT_NOT_FOUND_CODE = "schema_audit_tenant_not_found";
|
|
158
|
+
/** A 400 on schema audit: the request names no tenantSlug. */
|
|
159
|
+
export const SCHEMA_AUDIT_TENANT_SLUG_REQUIRED_CODE = "schema_audit_tenant_slug_required";
|
|
160
|
+
function publicAdminSite(site) {
|
|
161
|
+
const { writeKey: _writeKey, ...safeSite } = site;
|
|
162
|
+
return {
|
|
163
|
+
...safeSite,
|
|
164
|
+
allowedOrigins: site.allowedOrigins ?? [],
|
|
165
|
+
allowedEnvironments: site.allowedEnvironments ?? [],
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
export class MemoryQueueStorage {
|
|
169
|
+
constructor() {
|
|
170
|
+
this.events = [];
|
|
171
|
+
}
|
|
172
|
+
load() {
|
|
173
|
+
return [...this.events];
|
|
174
|
+
}
|
|
175
|
+
save(events) {
|
|
176
|
+
this.events = [...events];
|
|
177
|
+
}
|
|
178
|
+
clear() {
|
|
179
|
+
this.events = [];
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
export class LocalStorageQueueStorage {
|
|
183
|
+
constructor(key = "custd_event_queue") {
|
|
184
|
+
this.key = key;
|
|
185
|
+
}
|
|
186
|
+
load() {
|
|
187
|
+
if (typeof localStorage === "undefined") {
|
|
188
|
+
return [];
|
|
189
|
+
}
|
|
190
|
+
const raw = localStorage.getItem(this.key);
|
|
191
|
+
if (!raw) {
|
|
192
|
+
return [];
|
|
193
|
+
}
|
|
194
|
+
try {
|
|
195
|
+
const parsed = JSON.parse(raw);
|
|
196
|
+
if (Array.isArray(parsed)) {
|
|
197
|
+
return parsed;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
catch {
|
|
201
|
+
return [];
|
|
202
|
+
}
|
|
203
|
+
return [];
|
|
204
|
+
}
|
|
205
|
+
save(events) {
|
|
206
|
+
if (typeof localStorage === "undefined") {
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
localStorage.setItem(this.key, JSON.stringify(events));
|
|
210
|
+
}
|
|
211
|
+
clear() {
|
|
212
|
+
if (typeof localStorage === "undefined") {
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
localStorage.removeItem(this.key);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
export class CustdClient {
|
|
219
|
+
constructor(config) {
|
|
220
|
+
this.queue = [];
|
|
221
|
+
this.onlineHandler = null;
|
|
222
|
+
this.batchTimer = null;
|
|
223
|
+
this.removeFlushTriggers = [];
|
|
224
|
+
this.oauthToken = null;
|
|
225
|
+
this.config = config;
|
|
226
|
+
this.baseUrl = config.baseUrl.replace(/\/$/, "");
|
|
227
|
+
const fetchImpl = config.fetch ?? globalThis.fetch;
|
|
228
|
+
this.fetchImpl = (input, init) => fetchImpl(input, init);
|
|
229
|
+
assertSecureOrLocalHTTP(this.baseUrl, "baseUrl");
|
|
230
|
+
if (config.oauth) {
|
|
231
|
+
assertSecureOrLocalHTTP(config.oauth.tokenUrl, "tokenUrl");
|
|
232
|
+
this.getToken = (options) => this.fetchOAuthToken(config.oauth, options);
|
|
233
|
+
}
|
|
234
|
+
else if (config.getToken) {
|
|
235
|
+
this.getToken = config.getToken;
|
|
236
|
+
}
|
|
237
|
+
else {
|
|
238
|
+
throw new Error("custd: getToken or oauth config is required");
|
|
239
|
+
}
|
|
240
|
+
// The SDK's own identity is authoritative: a caller may add default
|
|
241
|
+
// headers, but cannot accidentally drop the release Custd records.
|
|
242
|
+
this.defaultHeaders = { ...(config.defaultHeaders ?? {}), "X-Custd-Sdk": SDK_IDENTITY };
|
|
243
|
+
this.actingCompanySlug = config.actingCompanySlug?.trim() ?? "";
|
|
244
|
+
this.retry = normalizeRetryOptions(config.retry);
|
|
245
|
+
this.batch = config.batch;
|
|
246
|
+
this.queueEnabled = config.queue?.enabled ?? config.batch != null;
|
|
247
|
+
this.queueStorage = config.queue?.storage ?? new MemoryQueueStorage();
|
|
248
|
+
this.maxQueueSize = config.queue?.maxQueueSize ?? 1000;
|
|
249
|
+
this.flushOnOnline = config.queue?.flushOnOnline ?? true;
|
|
250
|
+
this.compressionEnabled = config.compression?.enabled ?? true;
|
|
251
|
+
this.compressionThresholdBytes = config.compression?.thresholdBytes ?? 1024;
|
|
252
|
+
this.admin = new AdminNamespace((method, path, body, options) => this.adminRequest(method, path, body, options), (method, path, body, options) => this.apiRequest(method, path, body, options), (path, options) => this.offboardingDownload(path, options), (path, options) => this.auditExportDownload(path, options));
|
|
253
|
+
this.provisioning = new ProvisioningNamespace((method, path, body, options) => this.apiRequest(method, path, body, options));
|
|
254
|
+
this.reporting = new ReportingNamespace((method, path, body, options) => this.apiRequest(method, path, body, options), (path, options) => this.apiDownload(path, options));
|
|
255
|
+
this.schemas = new SchemaNamespace((method, path, body) => this.apiRequest(method, path, body));
|
|
256
|
+
this.analytics = new AnalyticsEventClient((method, path, body, options) => this.apiRequest(method, path, body, options));
|
|
257
|
+
this.parsers = new ParserClient((method, path, body, options) => this.apiRequest(method, path, body, options));
|
|
258
|
+
this.measurement = new MeasurementClient((method, path, body, options) => this.apiRequest(method, path, body, options));
|
|
259
|
+
this.ingestOperations = new IngestOperationsClient((method, path, body, options, headers) => this.apiRequest(method, path, body, options, headers), this.actingCompanySlug);
|
|
260
|
+
this.publicReads = new PublicReadClient((path, headers, options) => this.publicRead(path, headers, options), (path, body, options) => this.publicWrite(path, body, options));
|
|
261
|
+
if (this.queueEnabled) {
|
|
262
|
+
this.queue = this.queueStorage.load();
|
|
263
|
+
}
|
|
264
|
+
if (this.batch?.flushIntervalMs && this.batch.flushIntervalMs > 0) {
|
|
265
|
+
this.batchTimer = setInterval(() => {
|
|
266
|
+
void this.flush();
|
|
267
|
+
}, this.batch.flushIntervalMs);
|
|
268
|
+
}
|
|
269
|
+
if (this.flushOnOnline && typeof window !== "undefined" && typeof window.addEventListener === "function") {
|
|
270
|
+
this.onlineHandler = () => void this.flush();
|
|
271
|
+
window.addEventListener("online", this.onlineHandler);
|
|
272
|
+
}
|
|
273
|
+
this.removeFlushTriggers = (config.queue?.flushTriggers ?? []).map((install) => install(() => this.flush()));
|
|
274
|
+
}
|
|
275
|
+
// fromProvisionedProducer builds an event-producing client directly from a
|
|
276
|
+
// provisioned producer bundle, hiding the OAuth wiring.
|
|
277
|
+
static fromProvisionedProducer(credentials) {
|
|
278
|
+
if (!credentials.clientSecret) {
|
|
279
|
+
throw new Error("custd: provisioned producer bundle is missing the client secret");
|
|
280
|
+
}
|
|
281
|
+
return new CustdClient({
|
|
282
|
+
baseUrl: credentials.baseUrl,
|
|
283
|
+
oauth: {
|
|
284
|
+
clientId: credentials.clientId,
|
|
285
|
+
clientSecret: credentials.clientSecret,
|
|
286
|
+
tokenUrl: credentials.tokenUrl,
|
|
287
|
+
audience: credentials.audience,
|
|
288
|
+
scopes: credentials.scopes,
|
|
289
|
+
},
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
static fromBrokerEnv(env, options = {}) {
|
|
293
|
+
const baseUrl = options.baseUrl ?? brokerBaseUrl(env);
|
|
294
|
+
return new CustdClient({
|
|
295
|
+
...options,
|
|
296
|
+
baseUrl,
|
|
297
|
+
oauth: {
|
|
298
|
+
clientId: requireBrokerEnv(env, "CUSTD_PROVISIONING_CLIENT_ID", "PROVISIONING_CLIENT_ID"),
|
|
299
|
+
clientSecret: requireBrokerEnv(env, "CUSTD_PROVISIONING_CLIENT_SECRET", "PROVISIONING_CLIENT_SECRET"),
|
|
300
|
+
tokenUrl: requireBrokerEnv(env, "CUSTD_PROVISIONING_TOKEN_URL", "PROVISIONING_TOKEN_URL"),
|
|
301
|
+
audience: brokerEnvValue(env, "CUSTD_PROVISIONING_AUDIENCE", "PROVISIONING_AUDIENCE"),
|
|
302
|
+
scopes: options.scopes ?? ["admin", "producers.provision"],
|
|
303
|
+
},
|
|
304
|
+
});
|
|
305
|
+
}
|
|
306
|
+
async fetchOAuthToken(config, options) {
|
|
307
|
+
const now = Date.now();
|
|
308
|
+
if (this.oauthToken && this.oauthToken.expiresAtMs > now + 30000) {
|
|
309
|
+
return this.oauthToken.value;
|
|
310
|
+
}
|
|
311
|
+
const body = new URLSearchParams();
|
|
312
|
+
body.set("grant_type", "client_credentials");
|
|
313
|
+
if (config.audience) {
|
|
314
|
+
body.set("audience", config.audience);
|
|
315
|
+
}
|
|
316
|
+
if (config.scopes && config.scopes.length > 0) {
|
|
317
|
+
body.set("scope", config.scopes.join(" "));
|
|
318
|
+
}
|
|
319
|
+
let response;
|
|
320
|
+
try {
|
|
321
|
+
response = await this.fetchImpl(config.tokenUrl, {
|
|
322
|
+
method: "POST",
|
|
323
|
+
headers: {
|
|
324
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
325
|
+
Authorization: basicAuthorization(config.clientId, config.clientSecret),
|
|
326
|
+
},
|
|
327
|
+
body,
|
|
328
|
+
signal: options?.signal,
|
|
329
|
+
});
|
|
330
|
+
if (!response.ok) {
|
|
331
|
+
const requestError = await responseRequestError(response, "oauth_unavailable");
|
|
332
|
+
if (requestError.code !== "oauth_unavailable") {
|
|
333
|
+
throw new CustdRequestError(requestError.status, "oauth_unavailable", requestError.retryability, requestError.nextAction, requestError.problem);
|
|
334
|
+
}
|
|
335
|
+
throw requestError;
|
|
336
|
+
}
|
|
337
|
+
const token = (await response.json());
|
|
338
|
+
if (typeof token?.access_token !== "string" || token.access_token.trim() === "") {
|
|
339
|
+
throw new Error("custd: token response missing access_token");
|
|
340
|
+
}
|
|
341
|
+
this.oauthToken = {
|
|
342
|
+
value: token.access_token,
|
|
343
|
+
expiresAtMs: now + Math.max(0, token.expires_in ?? 300) * 1000,
|
|
344
|
+
};
|
|
345
|
+
return token.access_token;
|
|
346
|
+
}
|
|
347
|
+
catch (error) {
|
|
348
|
+
if (error instanceof CustdRequestError)
|
|
349
|
+
throw error;
|
|
350
|
+
if (error instanceof Error && error.name === "AbortError")
|
|
351
|
+
throw error;
|
|
352
|
+
throw new CustdRequestError(response?.status ?? null, "oauth_unavailable", "bounded", { action: "retry", maxRetries: 1 }, undefined, { cause: error });
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
async ingestEvent(event) {
|
|
356
|
+
const prepared = prepareEvent(event);
|
|
357
|
+
validateEvent(prepared);
|
|
358
|
+
return this.sendWithRetry(prepared);
|
|
359
|
+
}
|
|
360
|
+
async track(event) {
|
|
361
|
+
const prepared = prepareEvent(event);
|
|
362
|
+
validateEvent(prepared);
|
|
363
|
+
applyEnvironmentLabel(prepared, this.config.environment);
|
|
364
|
+
if (!this.queueEnabled) {
|
|
365
|
+
return this.sendWithRetry(prepared);
|
|
366
|
+
}
|
|
367
|
+
this.enqueue(prepared);
|
|
368
|
+
if (this.batch) {
|
|
369
|
+
const maxBatchSize = this.batch.maxBatchSize ?? 0;
|
|
370
|
+
if (maxBatchSize > 0 && this.queue.length >= maxBatchSize) {
|
|
371
|
+
await this.flush();
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
else if (isOnline()) {
|
|
375
|
+
await this.flush();
|
|
376
|
+
}
|
|
377
|
+
return undefined;
|
|
378
|
+
}
|
|
379
|
+
enqueue(event) {
|
|
380
|
+
if (!this.queueEnabled) {
|
|
381
|
+
return;
|
|
382
|
+
}
|
|
383
|
+
if (this.queue.length >= this.maxQueueSize) {
|
|
384
|
+
this.queue.shift();
|
|
385
|
+
}
|
|
386
|
+
this.queue.push(event);
|
|
387
|
+
this.queueStorage.save(this.queue);
|
|
388
|
+
}
|
|
389
|
+
async flush() {
|
|
390
|
+
if (!this.queueEnabled || this.queue.length === 0) {
|
|
391
|
+
return;
|
|
392
|
+
}
|
|
393
|
+
if (!isOnline()) {
|
|
394
|
+
return;
|
|
395
|
+
}
|
|
396
|
+
const maxBatchSize = this.batch?.maxBatchSize ?? this.queue.length;
|
|
397
|
+
const toSend = this.queue.splice(0, maxBatchSize);
|
|
398
|
+
try {
|
|
399
|
+
await this.sendBatchWithRetry(toSend);
|
|
400
|
+
}
|
|
401
|
+
catch (err) {
|
|
402
|
+
this.queue = [...toSend, ...this.queue];
|
|
403
|
+
this.queueStorage.save(this.queue);
|
|
404
|
+
throw err;
|
|
405
|
+
}
|
|
406
|
+
this.queueStorage.save(this.queue);
|
|
407
|
+
}
|
|
408
|
+
close() {
|
|
409
|
+
if (this.batchTimer) {
|
|
410
|
+
clearInterval(this.batchTimer);
|
|
411
|
+
this.batchTimer = null;
|
|
412
|
+
}
|
|
413
|
+
if (this.onlineHandler && typeof window !== "undefined" && typeof window.removeEventListener === "function") {
|
|
414
|
+
window.removeEventListener("online", this.onlineHandler);
|
|
415
|
+
this.onlineHandler = null;
|
|
416
|
+
}
|
|
417
|
+
for (const remove of this.removeFlushTriggers) {
|
|
418
|
+
remove();
|
|
419
|
+
}
|
|
420
|
+
this.removeFlushTriggers = [];
|
|
421
|
+
}
|
|
422
|
+
/**
|
|
423
|
+
* Upload raw, line-delimited content for the bound parser.
|
|
424
|
+
*
|
|
425
|
+
* X-Parser-UUID binds the parser exactly as direct collectors do. When
|
|
426
|
+
* `target` is supplied its paired subClient/resource codes are appended as
|
|
427
|
+
* query parameters: a declarative default the backend applies to records with
|
|
428
|
+
* no canonical selection and refuses to let override an explicit selection.
|
|
429
|
+
*
|
|
430
|
+
* The route answers 202 Accepted, so the status alone is not success. Read
|
|
431
|
+
* `processed` and `failed` on the returned result.
|
|
432
|
+
*
|
|
433
|
+
* A transport failure or an unusable acceptance body cannot prove whether the
|
|
434
|
+
* upload landed, so it throws {@link CustdRawAcceptanceUnknownError} — which
|
|
435
|
+
* carries no retry guidance — rather than a retryable transport error.
|
|
436
|
+
* Replaying the POST could double-land accepted records; the SDK never retries
|
|
437
|
+
* this operation automatically.
|
|
438
|
+
*/
|
|
439
|
+
async ingestRawLines(request, options) {
|
|
440
|
+
const parserUuid = assertRawParserUuid(request.parserUuid);
|
|
441
|
+
const params = new URLSearchParams();
|
|
442
|
+
if (request.target !== undefined) {
|
|
443
|
+
assertRawSourceTarget(request.target);
|
|
444
|
+
params.set("subClient", request.target.subClient);
|
|
445
|
+
params.set("resource", request.target.resource);
|
|
446
|
+
}
|
|
447
|
+
const query = params.size > 0 ? `?${params.toString()}` : "";
|
|
448
|
+
const token = await this.getToken(options);
|
|
449
|
+
const headers = {
|
|
450
|
+
...this.defaultHeaders,
|
|
451
|
+
"Content-Type": "text/plain; charset=utf-8",
|
|
452
|
+
Authorization: `Bearer ${token}`,
|
|
453
|
+
"X-Parser-UUID": parserUuid,
|
|
454
|
+
};
|
|
455
|
+
const operationKey = request.idempotencyKey;
|
|
456
|
+
if (operationKey !== undefined && operationKey !== "") {
|
|
457
|
+
headers["Idempotency-Key"] = operationKey;
|
|
458
|
+
}
|
|
459
|
+
let response;
|
|
460
|
+
try {
|
|
461
|
+
response = await this.fetchImpl(`${this.baseUrl}/api/v1/raw${query}`, {
|
|
462
|
+
method: "POST",
|
|
463
|
+
headers,
|
|
464
|
+
body: request.content,
|
|
465
|
+
signal: options?.signal,
|
|
466
|
+
});
|
|
467
|
+
}
|
|
468
|
+
catch (error) {
|
|
469
|
+
// A disconnect cannot prove whether the upload landed; offer no retry.
|
|
470
|
+
throw new CustdRawAcceptanceUnknownError({ cause: error, operationKey });
|
|
471
|
+
}
|
|
472
|
+
if (!response.ok) {
|
|
473
|
+
if (this.retry.retryOnStatuses.includes(response.status)) {
|
|
474
|
+
throw new CustdRawAcceptanceUnknownError({ operationKey });
|
|
475
|
+
}
|
|
476
|
+
throw await problemError(response, `custd: raw ingest failed with status ${response.status}`);
|
|
477
|
+
}
|
|
478
|
+
let value;
|
|
479
|
+
try {
|
|
480
|
+
value = await response.json();
|
|
481
|
+
}
|
|
482
|
+
catch (error) {
|
|
483
|
+
throw new CustdRawAcceptanceUnknownError({ cause: error, operationKey });
|
|
484
|
+
}
|
|
485
|
+
return validateRawIngestResult(value, operationKey);
|
|
486
|
+
}
|
|
487
|
+
async sendWithRetry(event) {
|
|
488
|
+
return withRetry(this.retry, async () => {
|
|
489
|
+
const token = await this.getToken();
|
|
490
|
+
const response = await this.fetchImpl(`${this.baseUrl}/api/v1/events`, {
|
|
491
|
+
method: "POST",
|
|
492
|
+
headers: {
|
|
493
|
+
"Content-Type": "application/json",
|
|
494
|
+
Authorization: `Bearer ${token}`,
|
|
495
|
+
...this.defaultHeaders,
|
|
496
|
+
},
|
|
497
|
+
body: JSON.stringify(event),
|
|
498
|
+
});
|
|
499
|
+
if (!response.ok) {
|
|
500
|
+
const retryable = this.retry.retryOnStatuses.includes(response.status);
|
|
501
|
+
if (retryable) {
|
|
502
|
+
throw new RetryableError(`custd: retryable status ${response.status}`);
|
|
503
|
+
}
|
|
504
|
+
throw await problemError(response, `custd: request failed with status ${response.status}`);
|
|
505
|
+
}
|
|
506
|
+
return response;
|
|
507
|
+
});
|
|
508
|
+
}
|
|
509
|
+
async sendBatchWithRetry(events) {
|
|
510
|
+
const json = JSON.stringify({ events });
|
|
511
|
+
const { body, contentEncoding } = await this.encodeBatchBody(json);
|
|
512
|
+
return withRetry(this.retry, async () => {
|
|
513
|
+
const token = await this.getToken();
|
|
514
|
+
const headers = {
|
|
515
|
+
"Content-Type": "application/json",
|
|
516
|
+
Authorization: `Bearer ${token}`,
|
|
517
|
+
...this.defaultHeaders,
|
|
518
|
+
};
|
|
519
|
+
if (contentEncoding) {
|
|
520
|
+
headers["Content-Encoding"] = contentEncoding;
|
|
521
|
+
}
|
|
522
|
+
const response = await this.fetchImpl(`${this.baseUrl}/api/v1/events/batch`, {
|
|
523
|
+
method: "POST",
|
|
524
|
+
headers,
|
|
525
|
+
body,
|
|
526
|
+
});
|
|
527
|
+
await this.assertBatchResponse(response);
|
|
528
|
+
return response;
|
|
529
|
+
});
|
|
530
|
+
}
|
|
531
|
+
// encodeBatchBody gzip-compresses the serialized batch body when compression
|
|
532
|
+
// is enabled and the body meets the threshold. It falls back to the raw JSON
|
|
533
|
+
// string (no Content-Encoding) when compression is disabled, below threshold,
|
|
534
|
+
// or CompressionStream is unavailable in the runtime.
|
|
535
|
+
async encodeBatchBody(json) {
|
|
536
|
+
if (!this.compressionEnabled || json.length < this.compressionThresholdBytes) {
|
|
537
|
+
return { body: json };
|
|
538
|
+
}
|
|
539
|
+
if (typeof CompressionStream === "undefined") {
|
|
540
|
+
return { body: json };
|
|
541
|
+
}
|
|
542
|
+
const stream = new Blob([json]).stream().pipeThrough(new CompressionStream("gzip"));
|
|
543
|
+
const compressed = new Uint8Array(await new Response(stream).arrayBuffer());
|
|
544
|
+
return { body: compressed, contentEncoding: "gzip" };
|
|
545
|
+
}
|
|
546
|
+
async assertBatchResponse(response) {
|
|
547
|
+
if (!response.ok) {
|
|
548
|
+
const retryable = this.retry.retryOnStatuses.includes(response.status);
|
|
549
|
+
if (retryable) {
|
|
550
|
+
throw new RetryableError(`custd: retryable status ${response.status}`);
|
|
551
|
+
}
|
|
552
|
+
throw await problemError(response, `custd: request failed with status ${response.status}`);
|
|
553
|
+
}
|
|
554
|
+
const text = await response.text();
|
|
555
|
+
if (text === "") {
|
|
556
|
+
return;
|
|
557
|
+
}
|
|
558
|
+
const body = JSON.parse(text);
|
|
559
|
+
// Validate every per-event result, not just HTTP status: a 202 envelope can
|
|
560
|
+
// still carry rejected events with their own non-2xx status and problem.
|
|
561
|
+
const failed = (body.results ?? []).filter((r) => r.success === false);
|
|
562
|
+
if (failed.length > 0) {
|
|
563
|
+
throw new CustdProblemError(this.batchRejectionMessage(response.status, body.results, failed), undefined, failed);
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
// Names the rejected events (uuid, status, reason) so a partial batch failure
|
|
567
|
+
// is diagnosable without re-probing the API. The list is capped to keep the
|
|
568
|
+
// message bounded.
|
|
569
|
+
batchRejectionMessage(status, results, failed) {
|
|
570
|
+
const maxList = 10;
|
|
571
|
+
const parts = failed.slice(0, maxList).map((r) => {
|
|
572
|
+
const reason = r.error?.detail || r.error?.title || "no error detail";
|
|
573
|
+
return `${r.eventUuid ?? "unknown"} [status ${r.status ?? status}] ${reason}`;
|
|
574
|
+
});
|
|
575
|
+
if (failed.length > maxList) {
|
|
576
|
+
parts.push(`+${failed.length - maxList} more`);
|
|
577
|
+
}
|
|
578
|
+
return `custd: batch rejected ${failed.length} of ${results?.length ?? failed.length} event(s): ${parts.join("; ")}`;
|
|
579
|
+
}
|
|
580
|
+
async adminRequest(method, path, body, options) {
|
|
581
|
+
return this.apiRequest(method, `/admin${this.actingCompanyPath(path)}`, body, options);
|
|
582
|
+
}
|
|
583
|
+
// actingCompanyPath names the configured acting company in the `companySlug` query
|
|
584
|
+
// the admin routes read, keeping a selector the call already set.
|
|
585
|
+
actingCompanyPath(path) {
|
|
586
|
+
if (this.actingCompanySlug === "") {
|
|
587
|
+
return path;
|
|
588
|
+
}
|
|
589
|
+
const [route, query = ""] = path.split("?", 2);
|
|
590
|
+
const params = new URLSearchParams(query);
|
|
591
|
+
if (params.get("companySlug")) {
|
|
592
|
+
return path;
|
|
593
|
+
}
|
|
594
|
+
params.set("companySlug", this.actingCompanySlug);
|
|
595
|
+
return `${route}?${params.toString()}`;
|
|
596
|
+
}
|
|
597
|
+
async adminDownload(path, operation, options) {
|
|
598
|
+
const token = await this.getToken(options);
|
|
599
|
+
const response = await this.fetchImpl(`${this.baseUrl}/api/v1/admin${this.actingCompanyPath(path)}`, {
|
|
600
|
+
method: "GET",
|
|
601
|
+
headers: { Authorization: `Bearer ${token}`, ...this.defaultHeaders },
|
|
602
|
+
signal: options?.signal,
|
|
603
|
+
});
|
|
604
|
+
if (!response.ok) {
|
|
605
|
+
throw new Error(`custd: ${operation} failed with status ${response.status}`);
|
|
606
|
+
}
|
|
607
|
+
return response;
|
|
608
|
+
}
|
|
609
|
+
async offboardingDownload(path, options) {
|
|
610
|
+
const response = await this.adminDownload(path, "offboarding download", options);
|
|
611
|
+
const lengthHeader = response.headers.get("content-length")?.trim() ?? "";
|
|
612
|
+
const byteSize = Number(lengthHeader);
|
|
613
|
+
const checksumSha256 = (response.headers.get("x-checksum-sha256") ?? "").trim().toLowerCase();
|
|
614
|
+
if (!/^\d+$/.test(lengthHeader) || !Number.isSafeInteger(byteSize)) {
|
|
615
|
+
await response.body?.cancel();
|
|
616
|
+
throw new Error("custd: offboarding download content length is invalid");
|
|
617
|
+
}
|
|
618
|
+
if (!/^[a-f0-9]{64}$/.test(checksumSha256)) {
|
|
619
|
+
await response.body?.cancel();
|
|
620
|
+
throw new Error("custd: offboarding download checksum header is invalid");
|
|
621
|
+
}
|
|
622
|
+
return { ...responseDownloadStream(response, "offboarding download", byteSize), byteSize, checksumSha256 };
|
|
623
|
+
}
|
|
624
|
+
async auditExportDownload(path, options) {
|
|
625
|
+
return responseDownloadStream(await this.adminDownload(path, "audit export", options), "audit export");
|
|
626
|
+
}
|
|
627
|
+
async apiRequest(method, path, body, options, headers) {
|
|
628
|
+
const token = await this.getToken(options);
|
|
629
|
+
let response;
|
|
630
|
+
try {
|
|
631
|
+
response = await this.fetchImpl(`${this.baseUrl}/api/v1${path}`, {
|
|
632
|
+
method,
|
|
633
|
+
headers: {
|
|
634
|
+
...requestContentType(body),
|
|
635
|
+
Authorization: `Bearer ${token}`,
|
|
636
|
+
...this.defaultHeaders,
|
|
637
|
+
...headers,
|
|
638
|
+
...(options?.idempotencyKey ? { "Idempotency-Key": options.idempotencyKey } : {}),
|
|
639
|
+
...(options?.owningUserUuid ? { "X-Custd-Owning-User-UUID": options.owningUserUuid } : {}),
|
|
640
|
+
},
|
|
641
|
+
body: requestBody(body),
|
|
642
|
+
signal: options?.signal,
|
|
643
|
+
});
|
|
644
|
+
}
|
|
645
|
+
catch (error) {
|
|
646
|
+
throw transportRequestError(error);
|
|
647
|
+
}
|
|
648
|
+
if (!response.ok) {
|
|
649
|
+
const text = await response.text().catch(() => "");
|
|
650
|
+
let errorCode = "";
|
|
651
|
+
let detail = "";
|
|
652
|
+
let safeNextAction = "";
|
|
653
|
+
let workflowEnvelope = false;
|
|
654
|
+
if (text.length > 0) {
|
|
655
|
+
try {
|
|
656
|
+
const parsed = JSON.parse(text);
|
|
657
|
+
errorCode = parsed.code || "";
|
|
658
|
+
detail = parsed.detail || parsed.error || parsed.message || parsed.title || "";
|
|
659
|
+
safeNextAction = parsed.safeNextAction || parsed.safe_next_action || "";
|
|
660
|
+
workflowEnvelope = typeof parsed.error === "string" && (errorCode.length > 0 || safeNextAction.length > 0);
|
|
661
|
+
}
|
|
662
|
+
catch {
|
|
663
|
+
detail = text.slice(0, 200);
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
let message = detail.length > 0
|
|
667
|
+
? `custd: ${detail} (status ${response.status})`
|
|
668
|
+
: `custd: request failed with status ${response.status}`;
|
|
669
|
+
if (errorCode.length > 0) {
|
|
670
|
+
message = `${message} [error=${errorCode}]`;
|
|
671
|
+
}
|
|
672
|
+
if (safeNextAction.length > 0) {
|
|
673
|
+
message = `${message} [safeNextAction=${safeNextAction}]`;
|
|
674
|
+
}
|
|
675
|
+
if (workflowEnvelope) {
|
|
676
|
+
throw new AdminWorkflowError(response.status, detail, errorCode, safeNextAction);
|
|
677
|
+
}
|
|
678
|
+
throw await responseRequestError(response, errorCode || "request_failed", message, text);
|
|
679
|
+
}
|
|
680
|
+
if (response.status === 204) {
|
|
681
|
+
return undefined;
|
|
682
|
+
}
|
|
683
|
+
return emptyApiNullLists(method, `/api/v1${path}`, (await response.json()));
|
|
684
|
+
}
|
|
685
|
+
// publicRead issues a GET that carries none of the client's own credentials.
|
|
686
|
+
async publicRead(path, headers, options) {
|
|
687
|
+
let response;
|
|
688
|
+
try {
|
|
689
|
+
response = await this.fetchImpl(`${this.baseUrl}/api/v1${path}`, {
|
|
690
|
+
method: "GET",
|
|
691
|
+
headers: { ...headers, "X-Custd-Sdk": SDK_IDENTITY },
|
|
692
|
+
signal: options?.signal,
|
|
693
|
+
});
|
|
694
|
+
}
|
|
695
|
+
catch (error) {
|
|
696
|
+
throw transportRequestError(error);
|
|
697
|
+
}
|
|
698
|
+
if (!response.ok)
|
|
699
|
+
throw await responseRequestError(response, "request_failed");
|
|
700
|
+
return emptyApiNullLists("GET", `/api/v1${path}`, (await response.json()));
|
|
701
|
+
}
|
|
702
|
+
/**
|
|
703
|
+
* Opens a data-space owner's AI settings session from a handoff, on the broker's hub server.
|
|
704
|
+
* hubOrigin is the broker's registered hub origin; the session never sends this client's credential.
|
|
705
|
+
*/
|
|
706
|
+
redeemSiteAIOwnerHandoff(handoff, hubOrigin, options) {
|
|
707
|
+
const failure = (response) => responseRequestError(response, "request_failed");
|
|
708
|
+
return redeemSiteAIOwnerHandoff({ fetch: this.fetchImpl, failure }, handoff, hubOrigin, options);
|
|
709
|
+
}
|
|
710
|
+
// publicWrite posts JSON that carries none of the client's own credentials and expects no body back.
|
|
711
|
+
async publicWrite(path, body, options) {
|
|
712
|
+
let response;
|
|
713
|
+
try {
|
|
714
|
+
response = await this.fetchImpl(`${this.baseUrl}/api/v1${path}`, {
|
|
715
|
+
method: "POST",
|
|
716
|
+
headers: { "Content-Type": "application/json", "X-Custd-Sdk": SDK_IDENTITY },
|
|
717
|
+
body: JSON.stringify(body),
|
|
718
|
+
signal: options?.signal,
|
|
719
|
+
});
|
|
720
|
+
}
|
|
721
|
+
catch (error) {
|
|
722
|
+
throw transportRequestError(error);
|
|
723
|
+
}
|
|
724
|
+
if (!response.ok)
|
|
725
|
+
throw await responseRequestError(response, "request_failed");
|
|
726
|
+
}
|
|
727
|
+
async apiDownload(path, options) {
|
|
728
|
+
const token = await this.getToken(options);
|
|
729
|
+
const response = await this.fetchImpl(`${this.baseUrl}/api/v1${path}`, {
|
|
730
|
+
method: "GET",
|
|
731
|
+
headers: { Authorization: `Bearer ${token}`, ...this.defaultHeaders },
|
|
732
|
+
signal: options?.signal,
|
|
733
|
+
});
|
|
734
|
+
if (!response.ok)
|
|
735
|
+
throw new Error(`custd: report export download failed with status ${response.status}`);
|
|
736
|
+
const declared = Number(response.headers.get("content-length") ?? "0");
|
|
737
|
+
if (declared > 64 * 1024 * 1024)
|
|
738
|
+
throw new Error("custd: report export download exceeds 64 MiB");
|
|
739
|
+
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
740
|
+
if (bytes.byteLength > 64 * 1024 * 1024)
|
|
741
|
+
throw new Error("custd: report export download exceeds 64 MiB");
|
|
742
|
+
return bytes;
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
// A byte body is a file upload sent as raw bytes, a form is a multipart upload whose boundary fetch
|
|
746
|
+
// sets, and every other body is JSON.
|
|
747
|
+
function requestContentType(body) {
|
|
748
|
+
if (body instanceof FormData)
|
|
749
|
+
return {};
|
|
750
|
+
return { "Content-Type": body instanceof Uint8Array ? "application/octet-stream" : "application/json" };
|
|
751
|
+
}
|
|
752
|
+
function requestBody(body) {
|
|
753
|
+
if (body === undefined)
|
|
754
|
+
return undefined;
|
|
755
|
+
if (body instanceof FormData)
|
|
756
|
+
return body;
|
|
757
|
+
if (body instanceof Uint8Array)
|
|
758
|
+
return Uint8Array.from(body);
|
|
759
|
+
return JSON.stringify(body);
|
|
760
|
+
}
|
|
761
|
+
class ReportingNamespace {
|
|
762
|
+
constructor(request, download) {
|
|
763
|
+
this.request = request;
|
|
764
|
+
this.download = download;
|
|
765
|
+
}
|
|
766
|
+
createExport(input, options) {
|
|
767
|
+
if (!input.dashboardKey || input.formats.length < 1 || input.formats.length > 8)
|
|
768
|
+
throw new Error("custd: report export requires a dashboard key and 1 to 8 formats");
|
|
769
|
+
return this.request("POST", "/reporting/exports", input, options);
|
|
770
|
+
}
|
|
771
|
+
async listExports(limit = 50, options) {
|
|
772
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > 100)
|
|
773
|
+
throw new Error("custd: report export limit must be between 1 and 100");
|
|
774
|
+
const list = await this.request("GET", `/reporting/exports?limit=${limit}`, undefined, options);
|
|
775
|
+
return { exports: list.exports ?? [] };
|
|
776
|
+
}
|
|
777
|
+
getExport(exportId, options) {
|
|
778
|
+
assertUuid(exportId, "exportId");
|
|
779
|
+
return this.request("GET", `/reporting/exports/${encodeURIComponent(exportId)}`, undefined, options);
|
|
780
|
+
}
|
|
781
|
+
cancelExport(exportId, reason = "", options) {
|
|
782
|
+
assertUuid(exportId, "exportId");
|
|
783
|
+
return this.request("POST", `/reporting/exports/${encodeURIComponent(exportId)}/cancel`, { reason }, options);
|
|
784
|
+
}
|
|
785
|
+
downloadExport(exportId, artifactId, options) {
|
|
786
|
+
assertUuid(exportId, "exportId");
|
|
787
|
+
assertUuid(artifactId, "artifactId");
|
|
788
|
+
return this.download(`/reporting/exports/${encodeURIComponent(exportId)}/artifacts/${encodeURIComponent(artifactId)}`, options);
|
|
789
|
+
}
|
|
790
|
+
/** Exports a completed time-plan run's frozen report source in one to eight formats. */
|
|
791
|
+
async createCompletedRunExport(input, options) {
|
|
792
|
+
if (input.formats.length < 1 || input.formats.length > 8)
|
|
793
|
+
throw new Error("custd: completed run export requires 1 to 8 formats");
|
|
794
|
+
const job = await this.request("POST", "/reporting/exports/completed-run", input, options);
|
|
795
|
+
return { ...job, formats: job.formats ?? [] };
|
|
796
|
+
}
|
|
797
|
+
/** Lists the dashboards the tenant can open. */
|
|
798
|
+
async dashboards(options) {
|
|
799
|
+
const response = await this.request("GET", "/reporting/dashboards", undefined, options);
|
|
800
|
+
return {
|
|
801
|
+
dashboards: (response.dashboards ?? []).map((entry) => ({
|
|
802
|
+
...entry,
|
|
803
|
+
interactions: entry.interactions ?? [],
|
|
804
|
+
exportFormats: entry.exportFormats ?? [],
|
|
805
|
+
})),
|
|
806
|
+
};
|
|
807
|
+
}
|
|
808
|
+
/** Starts, or returns, the data generation that backs one dashboard view. */
|
|
809
|
+
async generateDashboardData(input, options) {
|
|
810
|
+
const generation = await this.request("POST", "/reporting/dashboard-data-generations", input, options);
|
|
811
|
+
return {
|
|
812
|
+
...generation,
|
|
813
|
+
datasetRowCounts: generation.datasetRowCounts ?? [],
|
|
814
|
+
datasetSchemas: (generation.datasetSchemas ?? []).map((schema) => ({ ...schema, columns: schema.columns ?? [] })),
|
|
815
|
+
};
|
|
816
|
+
}
|
|
817
|
+
/** Renders one query against a pack definition that is not published. */
|
|
818
|
+
async previewDraft(input, options) {
|
|
819
|
+
const data = await this.request("POST", "/reporting/draft-preview", input, options);
|
|
820
|
+
emptyNullBuckets(data);
|
|
821
|
+
if (!isRenderedWidgetData(data)) {
|
|
822
|
+
throw new Error("custd: invalid reporting draft preview response");
|
|
823
|
+
}
|
|
824
|
+
return data;
|
|
825
|
+
}
|
|
826
|
+
dashboard(key, options) {
|
|
827
|
+
return this.request("GET", `/reporting/dashboards/${encodeURIComponent(key)}`, undefined, options);
|
|
828
|
+
}
|
|
829
|
+
receipt(receiptUuid, options) {
|
|
830
|
+
assertUuid(receiptUuid, "receiptUuid");
|
|
831
|
+
return this.request("GET", `/processing/${encodeURIComponent(receiptUuid)}`, undefined, options);
|
|
832
|
+
}
|
|
833
|
+
outputs(options) {
|
|
834
|
+
return this.request("GET", "/reporting/outputs", undefined, options);
|
|
835
|
+
}
|
|
836
|
+
output(outputUuid, options) {
|
|
837
|
+
assertUuid(outputUuid, "outputUuid");
|
|
838
|
+
return this.request("GET", `/reporting/outputs/${encodeURIComponent(outputUuid)}`, undefined, options);
|
|
839
|
+
}
|
|
840
|
+
queryOutput(outputUuid, request, options) {
|
|
841
|
+
assertUuid(outputUuid, "outputUuid");
|
|
842
|
+
return this.request("POST", `/reporting/outputs/${encodeURIComponent(outputUuid)}/query`, request, options);
|
|
843
|
+
}
|
|
844
|
+
async query(request, options) {
|
|
845
|
+
const data = await this.request("POST", "/reporting/query", request, options);
|
|
846
|
+
emptyNullBuckets(data);
|
|
847
|
+
if (!isRenderedWidgetData(data)) {
|
|
848
|
+
throw new Error("custd: invalid reporting query response");
|
|
849
|
+
}
|
|
850
|
+
if (data.trust && containsForbiddenReportingTrustKey(data.trust)) {
|
|
851
|
+
throw new Error("custd: unsafe reporting trust diagnostics");
|
|
852
|
+
}
|
|
853
|
+
return data;
|
|
854
|
+
}
|
|
855
|
+
async subjectInsight(request, options) {
|
|
856
|
+
if (!isValidSubjectInsightRequest(request)) {
|
|
857
|
+
throw new Error("custd: invalid subject insight request");
|
|
858
|
+
}
|
|
859
|
+
const response = await this.request("POST", "/reporting/insights/subject", request, options);
|
|
860
|
+
if (isRecord(response))
|
|
861
|
+
emptyNullBuckets(response.data);
|
|
862
|
+
if (!isSubjectInsightResponse(response)) {
|
|
863
|
+
throw new Error("custd: invalid subject insight response");
|
|
864
|
+
}
|
|
865
|
+
if (response.data.trust && containsForbiddenReportingTrustKey(response.data.trust)) {
|
|
866
|
+
throw new Error("custd: unsafe reporting trust diagnostics");
|
|
867
|
+
}
|
|
868
|
+
return response;
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
function assertUuid(value, field) {
|
|
872
|
+
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)) {
|
|
873
|
+
throw new Error(`custd: ${field} must be a UUID`);
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
function isValidSubjectInsightRequest(request) {
|
|
877
|
+
const allowedKeys = new Set(["template", "subject", "from", "to", "rangeDays"]);
|
|
878
|
+
if (!request ||
|
|
879
|
+
!isRecord(request) ||
|
|
880
|
+
Object.keys(request).some((key) => !allowedKeys.has(key)) ||
|
|
881
|
+
typeof request.template !== "string" ||
|
|
882
|
+
!/^[a-z][a-z0-9_]{0,127}$/.test(request.template) ||
|
|
883
|
+
typeof request.subject !== "string" ||
|
|
884
|
+
request.subject.trim() === "" ||
|
|
885
|
+
request.subject.length > 512) {
|
|
886
|
+
return false;
|
|
887
|
+
}
|
|
888
|
+
const hasRangeDays = request.rangeDays !== undefined;
|
|
889
|
+
const hasFrom = request.from !== undefined;
|
|
890
|
+
const hasTo = request.to !== undefined;
|
|
891
|
+
if (hasRangeDays === (hasFrom || hasTo))
|
|
892
|
+
return false;
|
|
893
|
+
if (request.rangeDays !== undefined) {
|
|
894
|
+
return Number.isInteger(request.rangeDays) && request.rangeDays >= 1 && request.rangeDays <= 366;
|
|
895
|
+
}
|
|
896
|
+
if (typeof request.from !== "string" || typeof request.to !== "string")
|
|
897
|
+
return false;
|
|
898
|
+
if (!isValidRfc3339(request.from) || !isValidRfc3339(request.to))
|
|
899
|
+
return false;
|
|
900
|
+
const from = Date.parse(request.from);
|
|
901
|
+
const to = Date.parse(request.to);
|
|
902
|
+
return Number.isFinite(from) && Number.isFinite(to) && to > from && to - from <= 366 * 24 * 60 * 60 * 1000;
|
|
903
|
+
}
|
|
904
|
+
function isValidRfc3339(value) {
|
|
905
|
+
const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-](\d{2}):(\d{2}))$/.exec(value);
|
|
906
|
+
if (!match)
|
|
907
|
+
return false;
|
|
908
|
+
const [, yearText, monthText, dayText, hourText, minuteText, secondText, offsetHourText, offsetMinuteText] = match;
|
|
909
|
+
const year = Number(yearText);
|
|
910
|
+
const month = Number(monthText);
|
|
911
|
+
const day = Number(dayText);
|
|
912
|
+
const hour = Number(hourText);
|
|
913
|
+
const minute = Number(minuteText);
|
|
914
|
+
const second = Number(secondText);
|
|
915
|
+
const offsetHour = offsetHourText === undefined ? 0 : Number(offsetHourText);
|
|
916
|
+
const offsetMinute = offsetMinuteText === undefined ? 0 : Number(offsetMinuteText);
|
|
917
|
+
const leapYear = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
|
|
918
|
+
const daysInMonth = [31, leapYear ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1] ?? 0;
|
|
919
|
+
return (month >= 1 &&
|
|
920
|
+
month <= 12 &&
|
|
921
|
+
day >= 1 &&
|
|
922
|
+
day <= daysInMonth &&
|
|
923
|
+
hour <= 23 &&
|
|
924
|
+
minute <= 59 &&
|
|
925
|
+
second <= 59 &&
|
|
926
|
+
offsetHour <= 24 &&
|
|
927
|
+
offsetMinute <= 59 &&
|
|
928
|
+
(offsetHour !== 24 || offsetMinute === 0));
|
|
929
|
+
}
|
|
930
|
+
/** A JSON null bucket list decodes as empty. */
|
|
931
|
+
function emptyNullBuckets(value) {
|
|
932
|
+
if (isRecord(value) && value.buckets === null)
|
|
933
|
+
value.buckets = [];
|
|
934
|
+
}
|
|
935
|
+
function isSubjectInsightResponse(value) {
|
|
936
|
+
if (!isRecord(value) || !isRenderedWidgetData(value.data))
|
|
937
|
+
return false;
|
|
938
|
+
return true;
|
|
939
|
+
}
|
|
940
|
+
function isRenderedWidgetData(value) {
|
|
941
|
+
return (isRecord(value) &&
|
|
942
|
+
Array.isArray(value.buckets) &&
|
|
943
|
+
value.buckets.every(isRenderedWidgetBucket) &&
|
|
944
|
+
isRenderedMetricValue(value.value) &&
|
|
945
|
+
isInteger(value.queryDurationMs) &&
|
|
946
|
+
isOptionalInteger(value.parquetUriCount) &&
|
|
947
|
+
isInteger(value.snapshotAgeMs) &&
|
|
948
|
+
isInteger(value.eventLagP95Ms) &&
|
|
949
|
+
(value.metadata === undefined || isReportingQueryMetadata(value.metadata)) &&
|
|
950
|
+
(value.sources === undefined || (Array.isArray(value.sources) && value.sources.every(isReportingSourceSummary))) &&
|
|
951
|
+
isOptionalStringArray(value.warnings) &&
|
|
952
|
+
(value.delta === undefined || isRenderedMetricValue(value.delta)) &&
|
|
953
|
+
isOptionalFiniteNumber(value.deltaPercent) &&
|
|
954
|
+
isOptionalString(value.deltaLabel) &&
|
|
955
|
+
isOptionalString(value.secondaryLabel) &&
|
|
956
|
+
(value.trust === undefined || isRenderedReportingTrust(value.trust)));
|
|
957
|
+
}
|
|
958
|
+
function isRenderedWidgetBucket(value) {
|
|
959
|
+
return (isRecord(value) &&
|
|
960
|
+
typeof value.date === "string" &&
|
|
961
|
+
isRenderedMetricValue(value.value) &&
|
|
962
|
+
typeof value.source === "string" &&
|
|
963
|
+
isInteger(value.queryDurationMs) &&
|
|
964
|
+
isOptionalInteger(value.parquetUriCount) &&
|
|
965
|
+
isOptionalString(value.message) &&
|
|
966
|
+
(value.secondary === undefined || isRenderedMetricValue(value.secondary)));
|
|
967
|
+
}
|
|
968
|
+
function isRenderedMetricValue(value) {
|
|
969
|
+
return (isRecord(value) &&
|
|
970
|
+
isFiniteNumber(value.value) &&
|
|
971
|
+
typeof value.unit === "string" &&
|
|
972
|
+
isInteger(value.sampleCount) &&
|
|
973
|
+
typeof value.dataSufficiency === "string" &&
|
|
974
|
+
typeof value.complete === "boolean" &&
|
|
975
|
+
(value.truncated === undefined || typeof value.truncated === "boolean"));
|
|
976
|
+
}
|
|
977
|
+
function isReportingQueryMetadata(value) {
|
|
978
|
+
return (isRecord(value) &&
|
|
979
|
+
typeof value.resolvedTemplate === "string" &&
|
|
980
|
+
isOptionalString(value.rangeStart) &&
|
|
981
|
+
isOptionalString(value.rangeEnd) &&
|
|
982
|
+
isInteger(value.effectiveMaxRows) &&
|
|
983
|
+
isInteger(value.returnedRows) &&
|
|
984
|
+
isInteger(value.returnedBuckets) &&
|
|
985
|
+
isInteger(value.coveredWindows));
|
|
986
|
+
}
|
|
987
|
+
function isReportingSourceSummary(value) {
|
|
988
|
+
return (isRecord(value) &&
|
|
989
|
+
typeof value.kind === "string" &&
|
|
990
|
+
isInteger(value.count) &&
|
|
991
|
+
isOptionalString(value.coverageStart) &&
|
|
992
|
+
isOptionalString(value.coverageEnd) &&
|
|
993
|
+
typeof value.completeness === "string");
|
|
994
|
+
}
|
|
995
|
+
function isRenderedReportingTrust(value) {
|
|
996
|
+
return (isRecord(value) &&
|
|
997
|
+
typeof value.status === "string" &&
|
|
998
|
+
typeof value.dataFreshness === "string" &&
|
|
999
|
+
typeof value.retryability === "string" &&
|
|
1000
|
+
isReportingNextActionHint(value.nextAction) &&
|
|
1001
|
+
isOptionalString(value.lastExport) &&
|
|
1002
|
+
isOptionalString(value.schemaVersion) &&
|
|
1003
|
+
isOptionalString(value.contractVersion) &&
|
|
1004
|
+
typeof value.rollupState === "string" &&
|
|
1005
|
+
isOptionalStringArray(value.queryWarnings) &&
|
|
1006
|
+
typeof value.coverage === "string" &&
|
|
1007
|
+
isOptionalString(value.permissionClass) &&
|
|
1008
|
+
typeof value.captureState === "string" &&
|
|
1009
|
+
typeof value.consentState === "string" &&
|
|
1010
|
+
typeof value.exportState === "string" &&
|
|
1011
|
+
isOptionalString(value.partialReason) &&
|
|
1012
|
+
isOptionalString(value.unavailableReason));
|
|
1013
|
+
}
|
|
1014
|
+
function isReportingNextActionHint(value) {
|
|
1015
|
+
return (isRecord(value) &&
|
|
1016
|
+
typeof value.action === "string" &&
|
|
1017
|
+
isOptionalInteger(value.pollAfterSeconds) &&
|
|
1018
|
+
isOptionalInteger(value.maxRetries));
|
|
1019
|
+
}
|
|
1020
|
+
function isFiniteNumber(value) {
|
|
1021
|
+
return typeof value === "number" && Number.isFinite(value);
|
|
1022
|
+
}
|
|
1023
|
+
function isInteger(value) {
|
|
1024
|
+
return typeof value === "number" && Number.isInteger(value);
|
|
1025
|
+
}
|
|
1026
|
+
function isOptionalFiniteNumber(value) {
|
|
1027
|
+
return value === undefined || isFiniteNumber(value);
|
|
1028
|
+
}
|
|
1029
|
+
function isOptionalInteger(value) {
|
|
1030
|
+
return value === undefined || isInteger(value);
|
|
1031
|
+
}
|
|
1032
|
+
function isOptionalString(value) {
|
|
1033
|
+
return value === undefined || typeof value === "string";
|
|
1034
|
+
}
|
|
1035
|
+
function isOptionalStringArray(value) {
|
|
1036
|
+
return value === undefined || (Array.isArray(value) && value.every((item) => typeof item === "string"));
|
|
1037
|
+
}
|
|
1038
|
+
function isRecord(value) {
|
|
1039
|
+
return typeof value === "object" && value !== null;
|
|
1040
|
+
}
|
|
1041
|
+
class SchemaNamespace {
|
|
1042
|
+
constructor(request) {
|
|
1043
|
+
this.request = request;
|
|
1044
|
+
}
|
|
1045
|
+
validate(input) {
|
|
1046
|
+
return this.request("POST", "/schemas/validate", input);
|
|
1047
|
+
}
|
|
1048
|
+
dryRun(input) {
|
|
1049
|
+
return this.request("POST", "/schemas/dry-run", input);
|
|
1050
|
+
}
|
|
1051
|
+
infer(input) {
|
|
1052
|
+
return this.request("POST", "/schemas/infer", input);
|
|
1053
|
+
}
|
|
1054
|
+
/** Lists the tenant's event types. */
|
|
1055
|
+
async list() {
|
|
1056
|
+
const eventTypes = await this.request("GET", schemaRegistryPath);
|
|
1057
|
+
return { eventTypes: eventTypes ?? [] };
|
|
1058
|
+
}
|
|
1059
|
+
/** Lists an event type's schema versions. */
|
|
1060
|
+
async listVersions(eventType) {
|
|
1061
|
+
const versions = await this.request("GET", `${eventSchemaPath(eventType)}/versions`);
|
|
1062
|
+
return { versions: versions ?? [] };
|
|
1063
|
+
}
|
|
1064
|
+
/** Returns one version's JSON Schema document. */
|
|
1065
|
+
async get(eventType, version) {
|
|
1066
|
+
return { schema: await this.request("GET", eventSchemaPath(eventType, version)) };
|
|
1067
|
+
}
|
|
1068
|
+
/** Stores a schema version, creating the event type when it is new, and returns the event type. */
|
|
1069
|
+
register(input) {
|
|
1070
|
+
return this.request("POST", schemaRegistryPath, input);
|
|
1071
|
+
}
|
|
1072
|
+
/** Makes one version the event type's active schema. */
|
|
1073
|
+
activate(eventType, version) {
|
|
1074
|
+
return this.request("POST", `${eventSchemaPath(eventType, version)}/active`);
|
|
1075
|
+
}
|
|
1076
|
+
/** Lets events validate against one version again. */
|
|
1077
|
+
enable(eventType, version) {
|
|
1078
|
+
return this.request("PUT", `${eventSchemaPath(eventType, version)}/enabled`);
|
|
1079
|
+
}
|
|
1080
|
+
/** Deprecates one version so new events no longer validate against it. */
|
|
1081
|
+
disable(eventType, version) {
|
|
1082
|
+
return this.request("DELETE", `${eventSchemaPath(eventType, version)}/enabled`);
|
|
1083
|
+
}
|
|
1084
|
+
/** Retires the tenant's event type. Its schemas and stored events stay readable. */
|
|
1085
|
+
disableEventType(eventType) {
|
|
1086
|
+
return this.request("DELETE", eventSchemaPath(eventType));
|
|
1087
|
+
}
|
|
1088
|
+
async sendTestEvent(event) {
|
|
1089
|
+
const prepared = prepareEvent(event);
|
|
1090
|
+
validateEvent(prepared);
|
|
1091
|
+
const response = await this.request("POST", "/events", prepared);
|
|
1092
|
+
if (!response.success || response.eventUuid !== prepared.eventUuid) {
|
|
1093
|
+
throw new Error("custd: test event was not accepted by ingest");
|
|
1094
|
+
}
|
|
1095
|
+
return response;
|
|
1096
|
+
}
|
|
1097
|
+
}
|
|
1098
|
+
class AdminNamespace {
|
|
1099
|
+
constructor(request, nonAdminRequest, offboardingDownload, auditExportDownload) {
|
|
1100
|
+
this.dataLabels = new DataLabelAdminClient(request);
|
|
1101
|
+
this.dataScopes = new DataScopeAdminClient(request);
|
|
1102
|
+
this.tenants = new AdminTenantNamespace(request);
|
|
1103
|
+
this.lifecycle = new BackendLifecycleClient(request, offboardingDownload);
|
|
1104
|
+
this.clientSetup = new ClientSetupClient(request);
|
|
1105
|
+
this.oauthClients = new AdminOAuthClientNamespace(request);
|
|
1106
|
+
this.sites = new AdminSiteNamespace(request);
|
|
1107
|
+
this.siteDomains = new SiteDomainAdminClient(nonAdminRequest);
|
|
1108
|
+
this.siteInsights = new SiteInsightsAdminClient(request);
|
|
1109
|
+
this.schemas = new AdminSchemaNamespace(request);
|
|
1110
|
+
this.measurement = new AdminMeasurementNamespace(request);
|
|
1111
|
+
this.predictions = new PredictionAdminClient(request);
|
|
1112
|
+
this.privacy = new AdminPrivacyNamespace(request);
|
|
1113
|
+
this.retention = new RetentionClient(request);
|
|
1114
|
+
this.storageAlerts = new AdminStorageAlertsNamespace(request);
|
|
1115
|
+
this.audit = new AdminAuditNamespace(request, auditExportDownload);
|
|
1116
|
+
this.offboarding = new OffboardingClient(request, offboardingDownload);
|
|
1117
|
+
this.reportingPacks = new AdminReportingPacksNamespace(request);
|
|
1118
|
+
this.tenantStorage = new TenantStorageClient(nonAdminRequest);
|
|
1119
|
+
this.subjectExports = new SubjectExportClient(request);
|
|
1120
|
+
this.privacyErasures = new PrivacyErasureClient(request);
|
|
1121
|
+
this.timePlans = new TimePlanAdminClient(request);
|
|
1122
|
+
this.usage = new UsageAdminClient(request);
|
|
1123
|
+
this.authProjects = new AuthProjectAdminClient(request);
|
|
1124
|
+
this.workflowTimings = new WorkflowTimingAdminClient(request);
|
|
1125
|
+
this.users = new AdminUserAdminClient(request);
|
|
1126
|
+
this.uncertaintyModels = new UncertaintyModelAdminClient(request);
|
|
1127
|
+
this.impersonation = new ImpersonationAdminClient(request);
|
|
1128
|
+
this.supportAccess = new SupportAccessAdminClient(request);
|
|
1129
|
+
this.system = new SystemAdminClient(request);
|
|
1130
|
+
this.environmentPolicy = new EnvironmentPolicyAdminClient(request);
|
|
1131
|
+
this.rls = new RlsAdminClient(request);
|
|
1132
|
+
this.oauthClientAdmissions = new OAuthClientAdmissionAdminClient(request);
|
|
1133
|
+
this.sdkUsage = new SdkUsageAdminClient(request);
|
|
1134
|
+
this.ingestClaims = new IngestClaimAdminClient(request);
|
|
1135
|
+
this.accountingEvidence = new AccountingEvidenceAdminClient(request);
|
|
1136
|
+
this.webhooks = new NotificationWebhookAdminClient(request);
|
|
1137
|
+
this.notificationDestinations = new NotificationDestinationAdminClient(nonAdminRequest);
|
|
1138
|
+
this.emailRelay = new EmailRelayAdminClient(request);
|
|
1139
|
+
this.campaignEmail = new CampaignEmailAdminClient(request);
|
|
1140
|
+
this.eventTypes = new EventTypeAdminClient(request);
|
|
1141
|
+
this.errorIssues = new ErrorIssueAdminClient(nonAdminRequest);
|
|
1142
|
+
this.managedAudit = new ManagedAuditAdminClient(nonAdminRequest);
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
class ProvisioningNamespace {
|
|
1146
|
+
constructor(request) {
|
|
1147
|
+
this.dataSpaces = new ProvisioningDataSpaceNamespace(request);
|
|
1148
|
+
this.producers = new ProvisioningProducerNamespace(request);
|
|
1149
|
+
this.reservations = new ProvisioningReservationsNamespace(request);
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1152
|
+
/** Producer reservations under one data space. A system administrator names the parent tenant. */
|
|
1153
|
+
class ProvisioningReservationsNamespace {
|
|
1154
|
+
constructor(request) {
|
|
1155
|
+
this.request = request;
|
|
1156
|
+
}
|
|
1157
|
+
reserve(dataSpaceSlug, body, parentCompanySlug) {
|
|
1158
|
+
return this.request("POST", reservationsPath(dataSpaceSlug, "", parentCompanySlug), body);
|
|
1159
|
+
}
|
|
1160
|
+
list(dataSpaceSlug, parentCompanySlug) {
|
|
1161
|
+
return this.request("GET", reservationsPath(dataSpaceSlug, "", parentCompanySlug));
|
|
1162
|
+
}
|
|
1163
|
+
claim(dataSpaceSlug, producerSlug, body, parentCompanySlug) {
|
|
1164
|
+
return this.request("POST", reservationsPath(dataSpaceSlug, `/${encodeURIComponent(producerSlug)}/claim`, parentCompanySlug), body);
|
|
1165
|
+
}
|
|
1166
|
+
release(dataSpaceSlug, producerSlug, parentCompanySlug) {
|
|
1167
|
+
return this.request("DELETE", reservationsPath(dataSpaceSlug, `/${encodeURIComponent(producerSlug)}`, parentCompanySlug));
|
|
1168
|
+
}
|
|
1169
|
+
}
|
|
1170
|
+
function reservationsPath(dataSpaceSlug, suffix, parentCompanySlug) {
|
|
1171
|
+
return `/data-spaces/${encodeURIComponent(dataSpaceSlug)}/producer-reservations${suffix}${parentQuery(parentCompanySlug)}`;
|
|
1172
|
+
}
|
|
1173
|
+
class ProvisioningDataSpaceNamespace {
|
|
1174
|
+
constructor(request) {
|
|
1175
|
+
this.request = request;
|
|
1176
|
+
}
|
|
1177
|
+
/** Creates a data space under the caller's company; a system administrator names the parent tenant. */
|
|
1178
|
+
create(dataSpace, parentCompanySlug) {
|
|
1179
|
+
return this.request("POST", `/data-spaces${parentQuery(parentCompanySlug)}`, dataSpace);
|
|
1180
|
+
}
|
|
1181
|
+
/** Lists the caller's data spaces; a system administrator names the parent tenant. */
|
|
1182
|
+
list(parentCompanySlug) {
|
|
1183
|
+
return this.request("GET", `/data-spaces${parentQuery(parentCompanySlug)}`);
|
|
1184
|
+
}
|
|
1185
|
+
/** Reads retained storage per data space. A system administrator names the parent tenant. */
|
|
1186
|
+
async usage(parentCompanySlug) {
|
|
1187
|
+
const summary = await this.request("GET", `/data-spaces/usage${parentQuery(parentCompanySlug)}`);
|
|
1188
|
+
return { ...summary, dataSpaces: summary.dataSpaces ?? [] };
|
|
1189
|
+
}
|
|
1190
|
+
revoke(slug, parentCompanySlug) {
|
|
1191
|
+
return this.request("DELETE", `/data-spaces/${encodeURIComponent(slug)}${parentQuery(parentCompanySlug)}`);
|
|
1192
|
+
}
|
|
1193
|
+
/** Asks Custd to erase everything a data space holds. The answer is the accepted request, not the finished erasure. */
|
|
1194
|
+
erase(slug, parentCompanySlug) {
|
|
1195
|
+
return this.request("POST", `/data-spaces/${encodeURIComponent(slug)}/erasure${parentQuery(parentCompanySlug)}`);
|
|
1196
|
+
}
|
|
1197
|
+
getErasure(slug, parentCompanySlug) {
|
|
1198
|
+
return this.request("GET", `/data-spaces/${encodeURIComponent(slug)}/erasure${parentQuery(parentCompanySlug)}`);
|
|
1199
|
+
}
|
|
1200
|
+
/** Reads whether a data space's signing producers are ready and what ingest refused. */
|
|
1201
|
+
async getSigningStatus(slug, parentCompanySlug) {
|
|
1202
|
+
const path = `/data-spaces/${encodeURIComponent(slug)}/signing-status${parentQuery(parentCompanySlug)}`;
|
|
1203
|
+
const status = await this.request("GET", path);
|
|
1204
|
+
return {
|
|
1205
|
+
...status,
|
|
1206
|
+
producers: (status.producers ?? []).map((producer) => ({
|
|
1207
|
+
...producer,
|
|
1208
|
+
keyFingerprints: producer.keyFingerprints ?? [],
|
|
1209
|
+
})),
|
|
1210
|
+
};
|
|
1211
|
+
}
|
|
1212
|
+
/**
|
|
1213
|
+
* Moves a parent's Site, with every record keyed to it, into the data space. Its credentials keep their
|
|
1214
|
+
* client id and secret. Repeating it answers `already_adopted`.
|
|
1215
|
+
*/
|
|
1216
|
+
async adoptSite(slug, siteUuid, parentCompanySlug) {
|
|
1217
|
+
const path = `/data-spaces/${encodeURIComponent(slug)}/sites/${encodeURIComponent(siteUuid)}/adopt${parentQuery(parentCompanySlug)}`;
|
|
1218
|
+
const adoption = await this.request("POST", path);
|
|
1219
|
+
return { ...adoption, credentialClientIds: adoption.credentialClientIds ?? [] };
|
|
1220
|
+
}
|
|
1221
|
+
}
|
|
1222
|
+
function parentQuery(parentCompanySlug) {
|
|
1223
|
+
return parentCompanySlug ? `?${new URLSearchParams({ parentCompanySlug })}` : "";
|
|
1224
|
+
}
|
|
1225
|
+
function provisionedProducer(credentials) {
|
|
1226
|
+
return {
|
|
1227
|
+
...credentials,
|
|
1228
|
+
scopes: credentials.scopes ?? [],
|
|
1229
|
+
allowedEnvironments: credentials.allowedEnvironments ?? [],
|
|
1230
|
+
};
|
|
1231
|
+
}
|
|
1232
|
+
class ProvisioningProducerNamespace {
|
|
1233
|
+
constructor(request) {
|
|
1234
|
+
this.request = request;
|
|
1235
|
+
}
|
|
1236
|
+
async provision(request) {
|
|
1237
|
+
return provisionedProducer(await this.request("POST", "/producer-provisioning", request));
|
|
1238
|
+
}
|
|
1239
|
+
async list(companySlug) {
|
|
1240
|
+
const query = companySlug ? `?companySlug=${encodeURIComponent(companySlug)}` : "";
|
|
1241
|
+
const response = await this.request("GET", `/producer-provisioning${query}`);
|
|
1242
|
+
return { producers: (response.producers ?? []).map(publicProducer) };
|
|
1243
|
+
}
|
|
1244
|
+
async get(clientId) {
|
|
1245
|
+
return publicProducer(await this.request("GET", `/producer-provisioning/${encodeURIComponent(clientId)}`));
|
|
1246
|
+
}
|
|
1247
|
+
rotateSecret(clientId) {
|
|
1248
|
+
return this.request("POST", `/producer-provisioning/${encodeURIComponent(clientId)}/rotate-secret`);
|
|
1249
|
+
}
|
|
1250
|
+
/**
|
|
1251
|
+
* Sets the environment recorded for this producer. It is the authenticated
|
|
1252
|
+
* default for events that do not declare their own, not a per-environment
|
|
1253
|
+
* credential: one producer is expected to carry every environment unless an
|
|
1254
|
+
* operator deliberately restricts it.
|
|
1255
|
+
*/
|
|
1256
|
+
async updateEnvironment(clientId, environment) {
|
|
1257
|
+
const path = `/producer-provisioning/${encodeURIComponent(clientId)}/environment`;
|
|
1258
|
+
return publicProducer(await this.request("PATCH", path, { environment }));
|
|
1259
|
+
}
|
|
1260
|
+
/** Replaces the public keys a producer minted with the hosting-email-delivery template signs with. */
|
|
1261
|
+
async setSigningKeys(clientId, update) {
|
|
1262
|
+
const path = `/producer-provisioning/${encodeURIComponent(clientId)}/signing-keys`;
|
|
1263
|
+
return signingKeys(await this.request("PUT", path, update));
|
|
1264
|
+
}
|
|
1265
|
+
/** Reads the public keys, and their fingerprints, a signing producer's events are verified with. */
|
|
1266
|
+
async getSigningKeys(clientId) {
|
|
1267
|
+
const path = `/producer-provisioning/${encodeURIComponent(clientId)}/signing-keys`;
|
|
1268
|
+
return signingKeys(await this.request("GET", path));
|
|
1269
|
+
}
|
|
1270
|
+
revoke(clientId) {
|
|
1271
|
+
return this.request("DELETE", `/producer-provisioning/${encodeURIComponent(clientId)}`);
|
|
1272
|
+
}
|
|
1273
|
+
}
|
|
1274
|
+
function signingKeys(keys) {
|
|
1275
|
+
return { ...keys, publicKeys: keys.publicKeys ?? [], keyFingerprints: keys.keyFingerprints ?? [] };
|
|
1276
|
+
}
|
|
1277
|
+
function publicProducer(producer) {
|
|
1278
|
+
return { ...producer, scopes: producer.scopes ?? [], allowedEnvironments: producer.allowedEnvironments ?? [] };
|
|
1279
|
+
}
|
|
1280
|
+
function historicalCleanupReceipt(wire) {
|
|
1281
|
+
return {
|
|
1282
|
+
companyId: wire.company_id,
|
|
1283
|
+
requestedByKind: wire.requested_by_kind,
|
|
1284
|
+
requestedAt: wire.requested_at,
|
|
1285
|
+
completedAt: wire.completed_at,
|
|
1286
|
+
finalState: wire.final_state,
|
|
1287
|
+
perStore: (wire.per_store ?? []).map((store) => ({
|
|
1288
|
+
store: store.store,
|
|
1289
|
+
retentionClass: store.retention_class,
|
|
1290
|
+
deletedCount: store.deleted_count,
|
|
1291
|
+
retainedExceptionsCount: store.retained_exceptions_count,
|
|
1292
|
+
})),
|
|
1293
|
+
...(wire.waiver ? { waiver: wire.waiver } : {}),
|
|
1294
|
+
sha256: wire.sha256,
|
|
1295
|
+
};
|
|
1296
|
+
}
|
|
1297
|
+
function tenantCompanyPath(slug, action, companyId) {
|
|
1298
|
+
if (!Number.isInteger(companyId) || companyId <= 0) {
|
|
1299
|
+
throw new Error("custd: company id must be a positive integer");
|
|
1300
|
+
}
|
|
1301
|
+
return `/tenants/${encodeURIComponent(slug)}/${action}?companyId=${companyId}`;
|
|
1302
|
+
}
|
|
1303
|
+
class AdminTenantNamespace {
|
|
1304
|
+
constructor(request) {
|
|
1305
|
+
this.request = request;
|
|
1306
|
+
}
|
|
1307
|
+
create(tenant) {
|
|
1308
|
+
return this.request("POST", "/tenants", tenant);
|
|
1309
|
+
}
|
|
1310
|
+
list() {
|
|
1311
|
+
return this.request("GET", "/tenants");
|
|
1312
|
+
}
|
|
1313
|
+
get(slug) {
|
|
1314
|
+
return this.request("GET", `/tenants/${encodeURIComponent(slug)}`);
|
|
1315
|
+
}
|
|
1316
|
+
delete(slug) {
|
|
1317
|
+
return this.request("DELETE", `/tenants/${encodeURIComponent(slug)}`);
|
|
1318
|
+
}
|
|
1319
|
+
/**
|
|
1320
|
+
* Permanently removes an already deleted tenant once its cleanup is finished.
|
|
1321
|
+
* The server refuses an unready tenant with a conflict.
|
|
1322
|
+
*/
|
|
1323
|
+
finalize(slug, companyId) {
|
|
1324
|
+
return this.request("POST", tenantCompanyPath(slug, "finalize", companyId));
|
|
1325
|
+
}
|
|
1326
|
+
/**
|
|
1327
|
+
* Runs the credential-revoking, queue, database and object-storage cleanup for a
|
|
1328
|
+
* deleted tenant. The idempotencyKey is required: repeat it to retry the same cleanup.
|
|
1329
|
+
*/
|
|
1330
|
+
async historicalCleanup(slug, companyId, options = {}) {
|
|
1331
|
+
const path = tenantCompanyPath(slug, "historical-cleanup", companyId);
|
|
1332
|
+
if (!options.idempotencyKey?.trim()) {
|
|
1333
|
+
throw new Error("custd: historical cleanup idempotency key is required");
|
|
1334
|
+
}
|
|
1335
|
+
const wire = await this.request("POST", path, undefined, options);
|
|
1336
|
+
return historicalCleanupReceipt(wire);
|
|
1337
|
+
}
|
|
1338
|
+
getDataSpaceEntitlement(slug) {
|
|
1339
|
+
return this.request("GET", `/tenants/${encodeURIComponent(slug)}/data-space-entitlement`);
|
|
1340
|
+
}
|
|
1341
|
+
updateDataSpaceEntitlement(slug, body) {
|
|
1342
|
+
return this.request("PUT", `/tenants/${encodeURIComponent(slug)}/data-space-entitlement`, body);
|
|
1343
|
+
}
|
|
1344
|
+
updateStorageLimit(slug, body) {
|
|
1345
|
+
return this.request("PUT", `/tenants/${encodeURIComponent(slug)}/storage-limit`, body);
|
|
1346
|
+
}
|
|
1347
|
+
}
|
|
1348
|
+
// Custd requires a canonical UUIDv7 Idempotency-Key on every OAuth client
|
|
1349
|
+
// mutation, so one is generated when the caller does not supply it. A caller that
|
|
1350
|
+
// retries the same mutation should pass its own key to reuse it; a caller that
|
|
1351
|
+
// checks for an existing client first, as a reconcile does, is safe either way.
|
|
1352
|
+
class AdminOAuthClientNamespace {
|
|
1353
|
+
constructor(request) {
|
|
1354
|
+
this.request = request;
|
|
1355
|
+
}
|
|
1356
|
+
async create(client, options = {}) {
|
|
1357
|
+
const created = await this.request("POST", "/oauth-clients", client, mutationOptions(options));
|
|
1358
|
+
const { loginSetup } = created;
|
|
1359
|
+
return {
|
|
1360
|
+
...created,
|
|
1361
|
+
scopes: created.scopes ?? [],
|
|
1362
|
+
...(loginSetup
|
|
1363
|
+
? {
|
|
1364
|
+
loginSetup: { ...loginSetup, scopes: loginSetup.scopes ?? [], redirectUris: loginSetup.redirectUris ?? [] },
|
|
1365
|
+
}
|
|
1366
|
+
: {}),
|
|
1367
|
+
};
|
|
1368
|
+
}
|
|
1369
|
+
list() {
|
|
1370
|
+
return this.request("GET", "/oauth-clients");
|
|
1371
|
+
}
|
|
1372
|
+
get(clientId) {
|
|
1373
|
+
return this.request("GET", `/oauth-clients/${encodeURIComponent(clientId)}`);
|
|
1374
|
+
}
|
|
1375
|
+
delete(clientId, options = {}) {
|
|
1376
|
+
return this.request("DELETE", `/oauth-clients/${encodeURIComponent(clientId)}`, undefined, mutationOptions(options));
|
|
1377
|
+
}
|
|
1378
|
+
rotateSecret(clientId, options = {}) {
|
|
1379
|
+
return this.request("POST", `/oauth-clients/${encodeURIComponent(clientId)}/rotate-secret`, undefined, mutationOptions(options));
|
|
1380
|
+
}
|
|
1381
|
+
/**
|
|
1382
|
+
* Issues a new secret for a client whose current secret nobody holds. The new secret is shown only
|
|
1383
|
+
* in this response.
|
|
1384
|
+
*/
|
|
1385
|
+
replaceUnknownSecret(clientId, options = {}) {
|
|
1386
|
+
return this.request("POST", `/oauth-clients/${encodeURIComponent(clientId)}/replace-unknown-secret`, undefined, mutationOptions(options));
|
|
1387
|
+
}
|
|
1388
|
+
updateScopes(clientId, body, options = {}) {
|
|
1389
|
+
return this.request("PATCH", `/oauth-clients/${encodeURIComponent(clientId)}/scopes`, body, mutationOptions(options));
|
|
1390
|
+
}
|
|
1391
|
+
}
|
|
1392
|
+
function mutationOptions(options) {
|
|
1393
|
+
return { ...options, idempotencyKey: options.idempotencyKey ?? uuidv7() };
|
|
1394
|
+
}
|
|
1395
|
+
class AdminSiteNamespace {
|
|
1396
|
+
constructor(request) {
|
|
1397
|
+
this.request = request;
|
|
1398
|
+
}
|
|
1399
|
+
create(site) {
|
|
1400
|
+
return this.request("POST", "/sites", site);
|
|
1401
|
+
}
|
|
1402
|
+
async list() {
|
|
1403
|
+
const response = await this.request("GET", "/sites");
|
|
1404
|
+
return { sites: (response.sites ?? []).map(publicAdminSite) };
|
|
1405
|
+
}
|
|
1406
|
+
async get(siteUuid) {
|
|
1407
|
+
const site = await this.request("GET", `/sites/${encodeURIComponent(siteUuid)}`);
|
|
1408
|
+
return publicAdminSite(site);
|
|
1409
|
+
}
|
|
1410
|
+
async update(siteUuid, body) {
|
|
1411
|
+
const site = await this.request("PATCH", `/sites/${encodeURIComponent(siteUuid)}`, body);
|
|
1412
|
+
return publicAdminSite(site);
|
|
1413
|
+
}
|
|
1414
|
+
delete(siteUuid) {
|
|
1415
|
+
return this.request("DELETE", `/sites/${encodeURIComponent(siteUuid)}`);
|
|
1416
|
+
}
|
|
1417
|
+
rotateWriteKey(siteUuid) {
|
|
1418
|
+
return this.request("POST", `/sites/${encodeURIComponent(siteUuid)}/rotate-write-key`);
|
|
1419
|
+
}
|
|
1420
|
+
}
|
|
1421
|
+
class AdminSchemaNamespace {
|
|
1422
|
+
constructor(request) {
|
|
1423
|
+
this.request = request;
|
|
1424
|
+
}
|
|
1425
|
+
validate(body) {
|
|
1426
|
+
return this.request("POST", "/schema/validate", body);
|
|
1427
|
+
}
|
|
1428
|
+
enableVersion(tenantSlug, eventTypeSlug, body) {
|
|
1429
|
+
return this.request("POST", `/schema/${encodeURIComponent(tenantSlug)}/${encodeURIComponent(eventTypeSlug)}/enable`, body);
|
|
1430
|
+
}
|
|
1431
|
+
register(tenantSlug, eventTypeSlug, body) {
|
|
1432
|
+
return this.request("POST", `/schema/${encodeURIComponent(tenantSlug)}/${encodeURIComponent(eventTypeSlug)}/register`, body);
|
|
1433
|
+
}
|
|
1434
|
+
dryRun(tenantSlug, eventTypeSlug, body) {
|
|
1435
|
+
return this.request("POST", `/schema/${encodeURIComponent(tenantSlug)}/${encodeURIComponent(eventTypeSlug)}/dry-run`, body);
|
|
1436
|
+
}
|
|
1437
|
+
async audit(tenantSlug) {
|
|
1438
|
+
const query = tenantSlug ? `?${new URLSearchParams({ tenantSlug })}` : "";
|
|
1439
|
+
const audit = await this.request("GET", `/schema/audit${query}`);
|
|
1440
|
+
return { ...audit, schemas: (audit.schemas ?? []).map(schemaAuditResult) };
|
|
1441
|
+
}
|
|
1442
|
+
}
|
|
1443
|
+
function schemaAuditResult(result) {
|
|
1444
|
+
const compile = (pass) => ({ ...pass, issues: pass.issues ?? [] });
|
|
1445
|
+
return {
|
|
1446
|
+
...result,
|
|
1447
|
+
issueCodes: result.issueCodes ?? [],
|
|
1448
|
+
legacyCompile: compile(result.legacyCompile),
|
|
1449
|
+
sharedCompile: compile(result.sharedCompile),
|
|
1450
|
+
exampleValidation: { ...result.exampleValidation, issueCodes: result.exampleValidation.issueCodes ?? [] },
|
|
1451
|
+
};
|
|
1452
|
+
}
|
|
1453
|
+
function privacyRules(rules) {
|
|
1454
|
+
return { ...rules, rules: rules.rules ?? [] };
|
|
1455
|
+
}
|
|
1456
|
+
class AdminPrivacyNamespace {
|
|
1457
|
+
constructor(request) {
|
|
1458
|
+
this.request = request;
|
|
1459
|
+
}
|
|
1460
|
+
async getRules(companySlug) {
|
|
1461
|
+
const query = companySlug ? `?${new URLSearchParams({ companySlug })}` : "";
|
|
1462
|
+
return privacyRules(await this.request("GET", `/privacy/rules${query}`));
|
|
1463
|
+
}
|
|
1464
|
+
async setRules(body) {
|
|
1465
|
+
return privacyRules(await this.request("PUT", "/privacy/rules", body));
|
|
1466
|
+
}
|
|
1467
|
+
mapIdentifier(companySlug, body) {
|
|
1468
|
+
return this.request("POST", `/privacy/identifiers/${encodeURIComponent(companySlug)}/map`, body);
|
|
1469
|
+
}
|
|
1470
|
+
async listIdentifierMappings(companySlug) {
|
|
1471
|
+
const list = await this.request("GET", `/privacy/identifiers/${encodeURIComponent(companySlug)}`);
|
|
1472
|
+
return { ...list, mappings: list.mappings ?? [] };
|
|
1473
|
+
}
|
|
1474
|
+
async listConsent(subjectId, companySlug) {
|
|
1475
|
+
const params = new URLSearchParams({ subjectId });
|
|
1476
|
+
if (companySlug)
|
|
1477
|
+
params.set("companySlug", companySlug);
|
|
1478
|
+
const response = await this.request("GET", `/privacy/consent?${params}`);
|
|
1479
|
+
return { ...response, records: response.records ?? [] };
|
|
1480
|
+
}
|
|
1481
|
+
recordConsent(body) {
|
|
1482
|
+
return this.request("POST", "/privacy/consent", body);
|
|
1483
|
+
}
|
|
1484
|
+
revokeConsent(subjectId, revoke) {
|
|
1485
|
+
const params = new URLSearchParams({ purpose: revoke.purpose });
|
|
1486
|
+
if (revoke.source)
|
|
1487
|
+
params.set("source", revoke.source);
|
|
1488
|
+
if (revoke.companySlug)
|
|
1489
|
+
params.set("companySlug", revoke.companySlug);
|
|
1490
|
+
return this.request("DELETE", `/privacy/consent/${encodeURIComponent(subjectId)}?${params}`);
|
|
1491
|
+
}
|
|
1492
|
+
}
|
|
1493
|
+
class AdminStorageAlertsNamespace {
|
|
1494
|
+
constructor(request) {
|
|
1495
|
+
this.request = request;
|
|
1496
|
+
}
|
|
1497
|
+
listRules(tenantSlug) {
|
|
1498
|
+
return this.request("GET", `/storage/alerts/${encodeURIComponent(tenantSlug)}`);
|
|
1499
|
+
}
|
|
1500
|
+
createRule(tenantSlug, body) {
|
|
1501
|
+
return this.request("POST", `/storage/alerts/${encodeURIComponent(tenantSlug)}`, body);
|
|
1502
|
+
}
|
|
1503
|
+
deleteRule(tenantSlug, ruleId) {
|
|
1504
|
+
return this.request("DELETE", `/storage/alerts/${encodeURIComponent(tenantSlug)}/${encodeURIComponent(ruleId)}`);
|
|
1505
|
+
}
|
|
1506
|
+
async listEvents(tenantSlug) {
|
|
1507
|
+
const response = await this.request("GET", `/storage/alerts/${encodeURIComponent(tenantSlug)}/events`);
|
|
1508
|
+
return { events: response.events ?? [] };
|
|
1509
|
+
}
|
|
1510
|
+
}
|
|
1511
|
+
const auditDisclosureStates = new Set(["available", "redacted", "not_recorded"]);
|
|
1512
|
+
function mapAdminAuditChange(value) {
|
|
1513
|
+
if (!isRecord(value) || typeof value.field !== "string")
|
|
1514
|
+
return undefined;
|
|
1515
|
+
const change = { field: value.field };
|
|
1516
|
+
if ("before" in value)
|
|
1517
|
+
change.before = value.before;
|
|
1518
|
+
if ("after" in value)
|
|
1519
|
+
change.after = value.after;
|
|
1520
|
+
return change;
|
|
1521
|
+
}
|
|
1522
|
+
function mapAdminAuditNetwork(value) {
|
|
1523
|
+
if (!isRecord(value))
|
|
1524
|
+
return undefined;
|
|
1525
|
+
const ipAddressState = value.ipAddressState;
|
|
1526
|
+
const userAgentState = value.userAgentState;
|
|
1527
|
+
if (!auditDisclosureStates.has(ipAddressState) ||
|
|
1528
|
+
!auditDisclosureStates.has(userAgentState))
|
|
1529
|
+
return undefined;
|
|
1530
|
+
return {
|
|
1531
|
+
...(typeof value.ipAddress === "string" ? { ipAddress: value.ipAddress } : {}),
|
|
1532
|
+
ipAddressState: ipAddressState,
|
|
1533
|
+
...(typeof value.userAgent === "string" ? { userAgent: value.userAgent } : {}),
|
|
1534
|
+
userAgentState: userAgentState,
|
|
1535
|
+
};
|
|
1536
|
+
}
|
|
1537
|
+
function mapAdminAuditRetention(value) {
|
|
1538
|
+
if (!isRecord(value) ||
|
|
1539
|
+
typeof value.eventMaxAgeSeconds !== "number" ||
|
|
1540
|
+
typeof value.ipAddressMaxAgeSeconds !== "number" ||
|
|
1541
|
+
typeof value.userAgentMaxAgeSeconds !== "number")
|
|
1542
|
+
return undefined;
|
|
1543
|
+
return {
|
|
1544
|
+
eventMaxAgeSeconds: value.eventMaxAgeSeconds,
|
|
1545
|
+
ipAddressMaxAgeSeconds: value.ipAddressMaxAgeSeconds,
|
|
1546
|
+
userAgentMaxAgeSeconds: value.userAgentMaxAgeSeconds,
|
|
1547
|
+
};
|
|
1548
|
+
}
|
|
1549
|
+
function mapAdminAuditEvent(event) {
|
|
1550
|
+
if (typeof event.eventId !== "string" || !AUDIT_EVENT_UUID_PATTERN.test(event.eventId)) {
|
|
1551
|
+
throw new Error("custd: audit event response eventId must be a UUID");
|
|
1552
|
+
}
|
|
1553
|
+
const details = event.details;
|
|
1554
|
+
const actorRoles = Array.isArray(event.actorRoles)
|
|
1555
|
+
? event.actorRoles.filter((role) => typeof role === "string")
|
|
1556
|
+
: [];
|
|
1557
|
+
const changes = Array.isArray(event.changes)
|
|
1558
|
+
? event.changes.map(mapAdminAuditChange).filter((change) => change !== undefined)
|
|
1559
|
+
: [];
|
|
1560
|
+
const network = mapAdminAuditNetwork(event.network);
|
|
1561
|
+
return {
|
|
1562
|
+
eventId: event.eventId,
|
|
1563
|
+
tenantSlug: event.tenantSlug,
|
|
1564
|
+
actorKind: event.actorKind,
|
|
1565
|
+
...(event.actorReference !== undefined ? { actorReference: event.actorReference } : {}),
|
|
1566
|
+
actorDisplayName: event.actorDisplayName,
|
|
1567
|
+
...(actorRoles.length > 0 ? { actorRoles } : {}),
|
|
1568
|
+
action: event.action,
|
|
1569
|
+
resourceType: event.resourceType,
|
|
1570
|
+
...(event.resourceId !== undefined ? { resourceId: event.resourceId } : {}),
|
|
1571
|
+
outcome: event.outcome,
|
|
1572
|
+
...(event.correlationId !== undefined ? { correlationId: event.correlationId } : {}),
|
|
1573
|
+
...(event.operationId !== undefined ? { operationId: event.operationId } : {}),
|
|
1574
|
+
...(changes.length > 0 ? { changes } : {}),
|
|
1575
|
+
...(details !== undefined && typeof details === "object" && !Array.isArray(details) ? { details } : {}),
|
|
1576
|
+
...(network !== undefined ? { network } : {}),
|
|
1577
|
+
...(event.domainHistory !== undefined ? { domainHistory: event.domainHistory } : {}),
|
|
1578
|
+
createdAt: event.createdAt,
|
|
1579
|
+
};
|
|
1580
|
+
}
|
|
1581
|
+
function mapAdminReportingPackAuditEvent(event) {
|
|
1582
|
+
return {
|
|
1583
|
+
action: event.action,
|
|
1584
|
+
...(event.actorReference !== undefined ? { actorReference: event.actorReference } : {}),
|
|
1585
|
+
actorDisplayName: event.actorDisplayName,
|
|
1586
|
+
resourceType: event.resourceType,
|
|
1587
|
+
packKey: event.packKey,
|
|
1588
|
+
createdAt: event.createdAt,
|
|
1589
|
+
};
|
|
1590
|
+
}
|
|
1591
|
+
const AUDIT_EVENT_UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
1592
|
+
class AdminAuditNamespace {
|
|
1593
|
+
constructor(request, download) {
|
|
1594
|
+
this.request = request;
|
|
1595
|
+
this.download = download;
|
|
1596
|
+
}
|
|
1597
|
+
auditQuery(options, includePagination = true) {
|
|
1598
|
+
if (!options) {
|
|
1599
|
+
return "";
|
|
1600
|
+
}
|
|
1601
|
+
const params = new URLSearchParams();
|
|
1602
|
+
if (options.scope)
|
|
1603
|
+
params.set("scope", options.scope);
|
|
1604
|
+
if (options.companySlug)
|
|
1605
|
+
params.set("companySlug", options.companySlug);
|
|
1606
|
+
if (options.affectedTenantSlug)
|
|
1607
|
+
params.set("affectedTenantSlug", options.affectedTenantSlug);
|
|
1608
|
+
if (options.since)
|
|
1609
|
+
params.set("since", options.since);
|
|
1610
|
+
if (options.until)
|
|
1611
|
+
params.set("until", options.until);
|
|
1612
|
+
if (options.actorKind)
|
|
1613
|
+
params.set("actorKind", options.actorKind);
|
|
1614
|
+
if (options.actorReference)
|
|
1615
|
+
params.set("actorReference", options.actorReference);
|
|
1616
|
+
if (options.action)
|
|
1617
|
+
params.set("action", options.action);
|
|
1618
|
+
if (options.resourceType)
|
|
1619
|
+
params.set("resourceType", options.resourceType);
|
|
1620
|
+
if (options.resourceId)
|
|
1621
|
+
params.set("resourceId", options.resourceId);
|
|
1622
|
+
if (options.outcome)
|
|
1623
|
+
params.set("outcome", options.outcome);
|
|
1624
|
+
if (options.correlationId)
|
|
1625
|
+
params.set("correlationId", options.correlationId);
|
|
1626
|
+
if (options.environmentId)
|
|
1627
|
+
params.set("environmentId", options.environmentId);
|
|
1628
|
+
if (includePagination && typeof options.limit === "number")
|
|
1629
|
+
params.set("limit", String(options.limit));
|
|
1630
|
+
if (includePagination && options.cursor)
|
|
1631
|
+
params.set("cursor", options.cursor);
|
|
1632
|
+
const query = params.toString();
|
|
1633
|
+
return query.length === 0 ? "" : `?${query}`;
|
|
1634
|
+
}
|
|
1635
|
+
auditLookupQuery(options) {
|
|
1636
|
+
if (!options)
|
|
1637
|
+
return "";
|
|
1638
|
+
const params = new URLSearchParams();
|
|
1639
|
+
if (options.scope)
|
|
1640
|
+
params.set("scope", options.scope);
|
|
1641
|
+
if (options.companySlug)
|
|
1642
|
+
params.set("companySlug", options.companySlug);
|
|
1643
|
+
const query = params.toString();
|
|
1644
|
+
return query.length === 0 ? "" : `?${query}`;
|
|
1645
|
+
}
|
|
1646
|
+
async listEvents(options) {
|
|
1647
|
+
const response = await this.request("GET", `/audit/events${this.auditQuery(options)}`);
|
|
1648
|
+
const retention = mapAdminAuditRetention(response.retention);
|
|
1649
|
+
return {
|
|
1650
|
+
events: (response.events ?? []).map(mapAdminAuditEvent),
|
|
1651
|
+
nextCursor: response.nextCursor ?? {},
|
|
1652
|
+
...(typeof response.coverageBeginsAt === "string" ? { coverageBeginsAt: response.coverageBeginsAt } : {}),
|
|
1653
|
+
...(retention === undefined ? {} : { retention }),
|
|
1654
|
+
};
|
|
1655
|
+
}
|
|
1656
|
+
async getEvent(eventId, options) {
|
|
1657
|
+
const response = await this.request("GET", `/audit/events/${encodeURIComponent(eventId)}${this.auditLookupQuery(options)}`);
|
|
1658
|
+
return mapAdminAuditEvent(response);
|
|
1659
|
+
}
|
|
1660
|
+
exportEvents(options, format = "json") {
|
|
1661
|
+
if (format !== "csv" && format !== "json") {
|
|
1662
|
+
return Promise.reject(new Error("custd: audit export format must be csv or json"));
|
|
1663
|
+
}
|
|
1664
|
+
const query = this.auditQuery(options, false);
|
|
1665
|
+
const suffix = query.length > 0 ? `${query}&format=${format}` : `?format=${format}`;
|
|
1666
|
+
return this.download(`/audit/events/export${suffix}`);
|
|
1667
|
+
}
|
|
1668
|
+
async listReportingPackEvents(packKey) {
|
|
1669
|
+
const response = await this.request("GET", `/reporting-packs/audit-events?packKey=${encodeURIComponent(packKey)}`);
|
|
1670
|
+
return { events: (response.events ?? []).map(mapAdminReportingPackAuditEvent) };
|
|
1671
|
+
}
|
|
1672
|
+
}
|
|
1673
|
+
class AdminReportingPacksNamespace {
|
|
1674
|
+
constructor(request) {
|
|
1675
|
+
this.request = request;
|
|
1676
|
+
}
|
|
1677
|
+
listDrafts() {
|
|
1678
|
+
return this.request("GET", "/reporting-packs/drafts");
|
|
1679
|
+
}
|
|
1680
|
+
/** List the reviewed setup templates (each with its canonical definition). */
|
|
1681
|
+
listSetupTemplates() {
|
|
1682
|
+
return this.request("GET", "/reporting-packs/setup-templates");
|
|
1683
|
+
}
|
|
1684
|
+
/**
|
|
1685
|
+
* Apply typed bindings to one reviewed setup template and return the
|
|
1686
|
+
* server-built definition. Pure build: the server creates no data, grants no
|
|
1687
|
+
* scope, and writes no generation; post the result through createDraft/preview
|
|
1688
|
+
* only when the caller intends to.
|
|
1689
|
+
*/
|
|
1690
|
+
bindSetupTemplate(kind, body) {
|
|
1691
|
+
return this.request("POST", `/reporting-packs/setup-templates/${encodeURIComponent(kind)}/bind`, body);
|
|
1692
|
+
}
|
|
1693
|
+
getDraft(draftId) {
|
|
1694
|
+
return this.request("GET", `/reporting-packs/drafts/${encodeURIComponent(draftId)}`);
|
|
1695
|
+
}
|
|
1696
|
+
createDraft(body) {
|
|
1697
|
+
return this.request("POST", "/reporting-packs/drafts", body);
|
|
1698
|
+
}
|
|
1699
|
+
updateDraft(draftId, body) {
|
|
1700
|
+
return this.request("PUT", `/reporting-packs/drafts/${encodeURIComponent(draftId)}`, body);
|
|
1701
|
+
}
|
|
1702
|
+
validate(body) {
|
|
1703
|
+
return this.request("POST", "/reporting-packs/validate", body);
|
|
1704
|
+
}
|
|
1705
|
+
preview(body) {
|
|
1706
|
+
return this.request("POST", "/reporting-packs/preview", body);
|
|
1707
|
+
}
|
|
1708
|
+
publish(draftId) {
|
|
1709
|
+
return this.request("POST", `/reporting-packs/drafts/${encodeURIComponent(draftId)}/publish`);
|
|
1710
|
+
}
|
|
1711
|
+
restart(draftId) {
|
|
1712
|
+
return this.request("POST", `/reporting-packs/drafts/${encodeURIComponent(draftId)}/restart`);
|
|
1713
|
+
}
|
|
1714
|
+
getGeneration(generationId) {
|
|
1715
|
+
return this.request("GET", `/reporting-packs/generations/${encodeURIComponent(generationId)}`);
|
|
1716
|
+
}
|
|
1717
|
+
getGenerationStatus(generationId) {
|
|
1718
|
+
return this.request("GET", `/reporting-packs/generations/${encodeURIComponent(generationId)}/status`);
|
|
1719
|
+
}
|
|
1720
|
+
rollbackGeneration(generationId) {
|
|
1721
|
+
return this.request("POST", `/reporting-packs/generations/${encodeURIComponent(generationId)}/rollback`);
|
|
1722
|
+
}
|
|
1723
|
+
async listGenerationValidity() {
|
|
1724
|
+
const response = await this.request("GET", "/reporting-packs/generation-validity");
|
|
1725
|
+
return { generations: response.generations ?? [] };
|
|
1726
|
+
}
|
|
1727
|
+
getRollupProvenance(generationId) {
|
|
1728
|
+
return this.request("GET", `/reporting-packs/generations/${encodeURIComponent(generationId)}/rollup-provenance`);
|
|
1729
|
+
}
|
|
1730
|
+
}
|
|
1731
|
+
// redactedProvisionedProducer returns the display-safe view of a provisioned
|
|
1732
|
+
// producer bundle, omitting the client secret so it is safe for dashboards.
|
|
1733
|
+
export function redactedProvisionedProducer(credentials) {
|
|
1734
|
+
const { clientSecret: _clientSecret, ...rest } = credentials;
|
|
1735
|
+
return rest;
|
|
1736
|
+
}
|
|
1737
|
+
export function validateEvent(event) {
|
|
1738
|
+
const missing = [];
|
|
1739
|
+
if (!event.eventUuid)
|
|
1740
|
+
missing.push("eventUuid");
|
|
1741
|
+
if (!event.eventTypeSlug)
|
|
1742
|
+
missing.push("eventTypeSlug");
|
|
1743
|
+
if (!event.schemaVersion)
|
|
1744
|
+
missing.push("schemaVersion");
|
|
1745
|
+
if (!event.timestamp)
|
|
1746
|
+
missing.push("timestamp");
|
|
1747
|
+
if (!event.sessionId)
|
|
1748
|
+
missing.push("sessionId");
|
|
1749
|
+
if (!event.anonymousId)
|
|
1750
|
+
missing.push("anonymousId");
|
|
1751
|
+
if (!event.companySlug)
|
|
1752
|
+
missing.push("companySlug");
|
|
1753
|
+
if (!event.context)
|
|
1754
|
+
missing.push("context");
|
|
1755
|
+
if (!event.payload)
|
|
1756
|
+
missing.push("payload");
|
|
1757
|
+
const deviceType = event.context?.device?.type;
|
|
1758
|
+
if (!deviceType)
|
|
1759
|
+
missing.push("context.device.type");
|
|
1760
|
+
if (missing.length > 0) {
|
|
1761
|
+
throw new Error(`custd: missing required fields: ${missing.join(", ")}`);
|
|
1762
|
+
}
|
|
1763
|
+
validateEnvironmentValue(event.environment ?? "");
|
|
1764
|
+
validateProducerLabels(event);
|
|
1765
|
+
}
|
|
1766
|
+
const labelKeyPattern = /^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/;
|
|
1767
|
+
/** Reserved envelope label carrying a declared environment. */
|
|
1768
|
+
export const environmentLabelKey = "custd.environment";
|
|
1769
|
+
const environmentValuePattern = /^[a-z][a-z0-9-]{0,31}$/;
|
|
1770
|
+
/**
|
|
1771
|
+
* Checks a declared environment against the contract ingest applies, so a
|
|
1772
|
+
* rejected declaration fails locally instead of failing the event at the API.
|
|
1773
|
+
*/
|
|
1774
|
+
export function validateEnvironmentValue(value) {
|
|
1775
|
+
if (value === "")
|
|
1776
|
+
return;
|
|
1777
|
+
if (value !== value.trim() || !environmentValuePattern.test(value)) {
|
|
1778
|
+
throw new Error(`custd: environment ${JSON.stringify(value)} must be lowercase letters, digits and hyphens, at most 32 characters`);
|
|
1779
|
+
}
|
|
1780
|
+
if (value === "unclassified") {
|
|
1781
|
+
throw new Error('custd: environment "unclassified" is reserved');
|
|
1782
|
+
}
|
|
1783
|
+
}
|
|
1784
|
+
/**
|
|
1785
|
+
* Stamps the effective environment onto the envelope labels. An event-level
|
|
1786
|
+
* declaration wins over the client default, and a label the caller set is never
|
|
1787
|
+
* overwritten.
|
|
1788
|
+
*/
|
|
1789
|
+
export function applyEnvironmentLabel(event, clientEnvironment) {
|
|
1790
|
+
const effective = event.environment || clientEnvironment || "";
|
|
1791
|
+
if (effective === "")
|
|
1792
|
+
return;
|
|
1793
|
+
event.labels = { ...(event.labels ?? {}) };
|
|
1794
|
+
if (event.labels[environmentLabelKey] === undefined) {
|
|
1795
|
+
event.labels[environmentLabelKey] = effective;
|
|
1796
|
+
}
|
|
1797
|
+
}
|
|
1798
|
+
function validateProducerLabels(event) {
|
|
1799
|
+
if ("resolvedLabels" in event || "vocabularyFingerprint" in event) {
|
|
1800
|
+
throw new Error("custd: server-owned label fields are not accepted");
|
|
1801
|
+
}
|
|
1802
|
+
if (event.labels === undefined)
|
|
1803
|
+
return;
|
|
1804
|
+
if (event.labels === null || typeof event.labels !== "object" || Array.isArray(event.labels)) {
|
|
1805
|
+
throw new Error("custd: labels must be an object of strings");
|
|
1806
|
+
}
|
|
1807
|
+
const entries = Object.entries(event.labels);
|
|
1808
|
+
if (entries.length > 16)
|
|
1809
|
+
throw new Error("custd: labels may contain at most 16 entries");
|
|
1810
|
+
for (const [key, value] of entries) {
|
|
1811
|
+
if (!labelKeyPattern.test(key) || utf8Bytes(key) > 64 || key.startsWith("custd.")) {
|
|
1812
|
+
throw new Error(`custd: labels.${key} has an invalid key`);
|
|
1813
|
+
}
|
|
1814
|
+
if (typeof value !== "string" || value === "" || value !== value.trim() || utf8Bytes(value) > 128) {
|
|
1815
|
+
throw new Error(`custd: labels.${key} has an invalid value`);
|
|
1816
|
+
}
|
|
1817
|
+
}
|
|
1818
|
+
}
|
|
1819
|
+
function utf8Bytes(value) {
|
|
1820
|
+
return new TextEncoder().encode(value).length;
|
|
1821
|
+
}
|
|
1822
|
+
export function validateBrowserEvent(event) {
|
|
1823
|
+
const missing = [];
|
|
1824
|
+
if (!event.eventUuid)
|
|
1825
|
+
missing.push("eventUuid");
|
|
1826
|
+
if (!event.eventTypeSlug)
|
|
1827
|
+
missing.push("eventTypeSlug");
|
|
1828
|
+
if (!event.schemaVersion)
|
|
1829
|
+
missing.push("schemaVersion");
|
|
1830
|
+
if (!event.timestamp)
|
|
1831
|
+
missing.push("timestamp");
|
|
1832
|
+
if (!event.context)
|
|
1833
|
+
missing.push("context");
|
|
1834
|
+
if (!event.payload)
|
|
1835
|
+
missing.push("payload");
|
|
1836
|
+
if (!event.payload?.siteUuid)
|
|
1837
|
+
missing.push("payload.siteUuid");
|
|
1838
|
+
const deviceType = event.context?.device?.type;
|
|
1839
|
+
if (!deviceType)
|
|
1840
|
+
missing.push("context.device.type");
|
|
1841
|
+
if (missing.length > 0) {
|
|
1842
|
+
throw new Error(`custd: missing required browser fields: ${missing.join(", ")}`);
|
|
1843
|
+
}
|
|
1844
|
+
validateEnvironmentValue(event.environment ?? "");
|
|
1845
|
+
validateProducerLabels(event);
|
|
1846
|
+
}
|
|
1847
|
+
export function createDogfoodEvent(input) {
|
|
1848
|
+
const missing = [];
|
|
1849
|
+
if (!input.eventTypeSlug)
|
|
1850
|
+
missing.push("eventTypeSlug");
|
|
1851
|
+
if (!input.schemaVersion)
|
|
1852
|
+
missing.push("schemaVersion");
|
|
1853
|
+
if (!input.companySlug)
|
|
1854
|
+
missing.push("companySlug");
|
|
1855
|
+
if (!input.sourceSystem)
|
|
1856
|
+
missing.push("sourceSystem");
|
|
1857
|
+
if (!input.sourceCompany)
|
|
1858
|
+
missing.push("sourceCompany");
|
|
1859
|
+
if (!input.environment)
|
|
1860
|
+
missing.push("environment");
|
|
1861
|
+
if (missing.length > 0) {
|
|
1862
|
+
throw new Error(`custd: missing dogfood fields: ${missing.join(", ")}`);
|
|
1863
|
+
}
|
|
1864
|
+
const sanitized = sanitizeDogfoodPayload(input.payload ?? {});
|
|
1865
|
+
if (input.strictPayloadKeys && sanitized.droppedKeys.length > 0) {
|
|
1866
|
+
throw new Error(`custd: dropped dogfood payload keys: ${sanitized.droppedKeys.join(", ")}`);
|
|
1867
|
+
}
|
|
1868
|
+
const payload = sanitized.payload;
|
|
1869
|
+
payload.sourceSystem = input.sourceSystem;
|
|
1870
|
+
payload.sourceCompany = input.sourceCompany;
|
|
1871
|
+
payload.environment = input.environment;
|
|
1872
|
+
payload.schemaVersion = input.schemaVersion;
|
|
1873
|
+
if (input.correlationId) {
|
|
1874
|
+
payload.correlationId = input.correlationId;
|
|
1875
|
+
}
|
|
1876
|
+
return prepareEvent({
|
|
1877
|
+
eventTypeSlug: input.eventTypeSlug,
|
|
1878
|
+
schemaVersion: input.schemaVersion,
|
|
1879
|
+
timestamp: new Date().toISOString(),
|
|
1880
|
+
companySlug: input.companySlug,
|
|
1881
|
+
context: { device: { type: "server" } },
|
|
1882
|
+
payload,
|
|
1883
|
+
});
|
|
1884
|
+
}
|
|
1885
|
+
export function prepareEvent(event, options = {}) {
|
|
1886
|
+
if (options.mode === "browser-cookieless") {
|
|
1887
|
+
return {
|
|
1888
|
+
...event,
|
|
1889
|
+
eventUuid: event.eventUuid || randomUUID(),
|
|
1890
|
+
sessionId: event.sessionId ?? "",
|
|
1891
|
+
anonymousId: event.anonymousId ?? "",
|
|
1892
|
+
};
|
|
1893
|
+
}
|
|
1894
|
+
return {
|
|
1895
|
+
...event,
|
|
1896
|
+
eventUuid: event.eventUuid || randomUUID(),
|
|
1897
|
+
sessionId: event.sessionId || randomUUID(),
|
|
1898
|
+
anonymousId: event.anonymousId || randomUUID(),
|
|
1899
|
+
};
|
|
1900
|
+
}
|
|
1901
|
+
const RAW_PARSER_UUID_PATTERN = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
|
|
1902
|
+
// assertRawParserUuid rejects a missing or malformed parser UUID before a
|
|
1903
|
+
// request is sent. It is a cheap shape check; the backend still verifies the
|
|
1904
|
+
// parser exists and is enabled.
|
|
1905
|
+
function assertRawParserUuid(value) {
|
|
1906
|
+
if (typeof value !== "string" || !RAW_PARSER_UUID_PATTERN.test(value)) {
|
|
1907
|
+
throw new RangeError("custd: raw ingest requires a parser UUID");
|
|
1908
|
+
}
|
|
1909
|
+
return value;
|
|
1910
|
+
}
|
|
1911
|
+
// assertRawSourceTarget rejects a partial or malformed target before a request
|
|
1912
|
+
// is sent. Both codes must be present and well-formed; the backend remains the
|
|
1913
|
+
// authority on whether they are registered.
|
|
1914
|
+
function assertRawSourceTarget(target) {
|
|
1915
|
+
if (typeof target.subClient !== "string" ||
|
|
1916
|
+
typeof target.resource !== "string" ||
|
|
1917
|
+
!validDataScopeCode(target.subClient) ||
|
|
1918
|
+
!validDataScopeCode(target.resource)) {
|
|
1919
|
+
throw new RangeError("custd: raw source target requires subClient and resource as a pair of valid codes");
|
|
1920
|
+
}
|
|
1921
|
+
}
|
|
1922
|
+
// validateRawIngestResult requires an actual object carrying a boolean success
|
|
1923
|
+
// and non-negative integer processed and failed. A missing field, a null, a
|
|
1924
|
+
// wrong type, or a negative count is rejected rather than defaulted or coerced.
|
|
1925
|
+
// Legitimate partial counts are returned unchanged.
|
|
1926
|
+
function validateRawIngestResult(value, operationKey) {
|
|
1927
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
1928
|
+
throw new CustdRawAcceptanceUnknownError({ operationKey });
|
|
1929
|
+
}
|
|
1930
|
+
const record = value;
|
|
1931
|
+
if (typeof record.success !== "boolean") {
|
|
1932
|
+
throw new CustdRawAcceptanceUnknownError({ operationKey });
|
|
1933
|
+
}
|
|
1934
|
+
return {
|
|
1935
|
+
success: record.success,
|
|
1936
|
+
processed: requireNonNegativeInteger(record.processed, operationKey),
|
|
1937
|
+
failed: requireNonNegativeInteger(record.failed, operationKey),
|
|
1938
|
+
};
|
|
1939
|
+
}
|
|
1940
|
+
function requireNonNegativeInteger(value, operationKey) {
|
|
1941
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
|
|
1942
|
+
throw new CustdRawAcceptanceUnknownError({ operationKey });
|
|
1943
|
+
}
|
|
1944
|
+
return value;
|
|
1945
|
+
}
|
|
1946
|
+
export class RetryableError extends Error {
|
|
1947
|
+
}
|
|
1948
|
+
function transportRequestError(error) {
|
|
1949
|
+
if (error instanceof Error && error.name === "AbortError")
|
|
1950
|
+
return error;
|
|
1951
|
+
return new CustdRequestError(null, "transport_unavailable", "bounded", { action: "retry", maxRetries: 1 }, undefined, { cause: error });
|
|
1952
|
+
}
|
|
1953
|
+
async function responseRequestError(response, fallbackCode, fallbackMessage, responseText) {
|
|
1954
|
+
const text = responseText ??
|
|
1955
|
+
(await response
|
|
1956
|
+
.clone()
|
|
1957
|
+
.text()
|
|
1958
|
+
.catch(() => ""));
|
|
1959
|
+
let problem;
|
|
1960
|
+
try {
|
|
1961
|
+
const parsed = JSON.parse(text);
|
|
1962
|
+
if (parsed && typeof parsed === "object" && parsed.status === response.status)
|
|
1963
|
+
problem = parsed;
|
|
1964
|
+
}
|
|
1965
|
+
catch {
|
|
1966
|
+
problem = undefined;
|
|
1967
|
+
}
|
|
1968
|
+
const retryability = problem?.retryability ?? (response.status === 429 || response.status >= 500 ? "bounded" : "none");
|
|
1969
|
+
const nextAction = problem?.nextAction ??
|
|
1970
|
+
(retryability === "bounded" ? { action: "retry", maxRetries: 1 } : { action: "none" });
|
|
1971
|
+
const code = problem?.code || fallbackCode;
|
|
1972
|
+
const requestError = new CustdRequestError(response.status, code, retryability, nextAction, problem);
|
|
1973
|
+
if (fallbackMessage)
|
|
1974
|
+
requestError.message = fallbackMessage;
|
|
1975
|
+
return requestError;
|
|
1976
|
+
}
|
|
1977
|
+
// CustdProblemError carries the decoded RFC 9457 problem document (when the
|
|
1978
|
+
// server sent one) and, for batch sends, the failed per-event results so a
|
|
1979
|
+
// caller can inspect every rejection without re-probing the API.
|
|
1980
|
+
export class CustdProblemError extends Error {
|
|
1981
|
+
constructor(message, problem, failures = []) {
|
|
1982
|
+
super(message);
|
|
1983
|
+
this.name = "CustdProblemError";
|
|
1984
|
+
this.problem = problem;
|
|
1985
|
+
this.failures = failures;
|
|
1986
|
+
}
|
|
1987
|
+
}
|
|
1988
|
+
// problemError decodes an RFC 9457 problem document from an error response and
|
|
1989
|
+
// wraps it in a CustdProblemError. When the body is missing or unparseable it
|
|
1990
|
+
// falls back to the supplied status-only message so callers still get an error.
|
|
1991
|
+
async function problemError(response, fallbackMessage) {
|
|
1992
|
+
const text = await response.text().catch(() => "");
|
|
1993
|
+
if (text === "") {
|
|
1994
|
+
return new CustdProblemError(fallbackMessage);
|
|
1995
|
+
}
|
|
1996
|
+
let problem;
|
|
1997
|
+
try {
|
|
1998
|
+
problem = JSON.parse(text);
|
|
1999
|
+
}
|
|
2000
|
+
catch {
|
|
2001
|
+
return new CustdProblemError(fallbackMessage);
|
|
2002
|
+
}
|
|
2003
|
+
const message = problem.detail || problem.title || fallbackMessage;
|
|
2004
|
+
return new CustdProblemError(`custd: ${message}`, problem);
|
|
2005
|
+
}
|
|
2006
|
+
const dogfoodProtectedPayloadFields = new Set([
|
|
2007
|
+
"sourcesystem",
|
|
2008
|
+
"sourcecompany",
|
|
2009
|
+
"environment",
|
|
2010
|
+
"schemaversion",
|
|
2011
|
+
"correlationid",
|
|
2012
|
+
]);
|
|
2013
|
+
const dogfoodForbiddenPayloadFields = new Set([
|
|
2014
|
+
"apikey",
|
|
2015
|
+
"authorization",
|
|
2016
|
+
"password",
|
|
2017
|
+
"rawapiresponse",
|
|
2018
|
+
"token",
|
|
2019
|
+
"signedurl",
|
|
2020
|
+
"rawprompt",
|
|
2021
|
+
"oauthcode",
|
|
2022
|
+
"devicesecret",
|
|
2023
|
+
"providercredential",
|
|
2024
|
+
]);
|
|
2025
|
+
const forbiddenReportingTrustKeys = new Set([
|
|
2026
|
+
"rawpayload",
|
|
2027
|
+
"sql",
|
|
2028
|
+
"token",
|
|
2029
|
+
"secret",
|
|
2030
|
+
"stack",
|
|
2031
|
+
"email",
|
|
2032
|
+
"ipaddress",
|
|
2033
|
+
"hostname",
|
|
2034
|
+
"orderid",
|
|
2035
|
+
"carttoken",
|
|
2036
|
+
]);
|
|
2037
|
+
function containsForbiddenReportingTrustKey(value) {
|
|
2038
|
+
if (Array.isArray(value)) {
|
|
2039
|
+
return value.some(containsForbiddenReportingTrustKey);
|
|
2040
|
+
}
|
|
2041
|
+
if (!value || typeof value !== "object") {
|
|
2042
|
+
return false;
|
|
2043
|
+
}
|
|
2044
|
+
return Object.entries(value).some(([key, child]) => forbiddenReportingTrustKeys.has(key.toLowerCase()) || containsForbiddenReportingTrustKey(child));
|
|
2045
|
+
}
|
|
2046
|
+
function sanitizeDogfoodPayload(payload, prefix = "") {
|
|
2047
|
+
const cleaned = {};
|
|
2048
|
+
const droppedKeys = [];
|
|
2049
|
+
for (const [key, value] of Object.entries(payload)) {
|
|
2050
|
+
if (!dogfoodPayloadFieldAllowed(key)) {
|
|
2051
|
+
droppedKeys.push(`${prefix}${key}`);
|
|
2052
|
+
continue;
|
|
2053
|
+
}
|
|
2054
|
+
if (value != null && typeof value === "object" && !Array.isArray(value)) {
|
|
2055
|
+
const nested = sanitizeDogfoodPayload(value, `${prefix}${key}.`);
|
|
2056
|
+
cleaned[key] = nested.payload;
|
|
2057
|
+
droppedKeys.push(...nested.droppedKeys);
|
|
2058
|
+
}
|
|
2059
|
+
else {
|
|
2060
|
+
cleaned[key] = value;
|
|
2061
|
+
}
|
|
2062
|
+
}
|
|
2063
|
+
return { payload: cleaned, droppedKeys };
|
|
2064
|
+
}
|
|
2065
|
+
function dogfoodPayloadFieldAllowed(key) {
|
|
2066
|
+
const normalized = key.toLowerCase().replace(/_/g, "");
|
|
2067
|
+
return !dogfoodProtectedPayloadFields.has(normalized) && !dogfoodForbiddenPayloadFields.has(normalized);
|
|
2068
|
+
}
|
|
2069
|
+
function brokerBaseUrl(env) {
|
|
2070
|
+
const explicit = brokerEnvValue(env, "CUSTD_BASE_URL", "CUSTD_API_BASE_URL");
|
|
2071
|
+
if (explicit) {
|
|
2072
|
+
return normalizeCustdBaseUrl(explicit);
|
|
2073
|
+
}
|
|
2074
|
+
const endpoint = brokerEnvValue(env, "CUSTD_PROVISIONING_ENDPOINT", "PROVISIONING_ENDPOINT", "CUSTD_TENANT_ADMIN_ENDPOINT", "TENANT_ADMIN_ENDPOINT");
|
|
2075
|
+
if (!endpoint) {
|
|
2076
|
+
throw new Error("custd: broker env missing CUSTD_BASE_URL or CUSTD_PROVISIONING_ENDPOINT");
|
|
2077
|
+
}
|
|
2078
|
+
return normalizeCustdBaseUrl(endpoint);
|
|
2079
|
+
}
|
|
2080
|
+
function normalizeCustdBaseUrl(rawUrl) {
|
|
2081
|
+
const url = new URL(rawUrl);
|
|
2082
|
+
const suffixes = [
|
|
2083
|
+
"/api/v1/managed-audit/provision",
|
|
2084
|
+
"/api/v1/producer-provisioning",
|
|
2085
|
+
"/api/v1/admin/tenants",
|
|
2086
|
+
"/api/v1",
|
|
2087
|
+
];
|
|
2088
|
+
for (const suffix of suffixes) {
|
|
2089
|
+
if (url.pathname.endsWith(suffix)) {
|
|
2090
|
+
url.pathname = url.pathname.slice(0, -suffix.length) || "/";
|
|
2091
|
+
break;
|
|
2092
|
+
}
|
|
2093
|
+
}
|
|
2094
|
+
url.search = "";
|
|
2095
|
+
url.hash = "";
|
|
2096
|
+
return url.toString().replace(/\/$/, "");
|
|
2097
|
+
}
|
|
2098
|
+
function requireBrokerEnv(env, ...keys) {
|
|
2099
|
+
const value = brokerEnvValue(env, ...keys);
|
|
2100
|
+
if (!value) {
|
|
2101
|
+
throw new Error(`custd: broker env missing ${keys[0]}`);
|
|
2102
|
+
}
|
|
2103
|
+
return value;
|
|
2104
|
+
}
|
|
2105
|
+
function brokerEnvValue(env, ...keys) {
|
|
2106
|
+
for (const key of keys) {
|
|
2107
|
+
const value = env[key];
|
|
2108
|
+
if (typeof value === "string" && value.trim() !== "") {
|
|
2109
|
+
return value;
|
|
2110
|
+
}
|
|
2111
|
+
}
|
|
2112
|
+
return undefined;
|
|
2113
|
+
}
|
|
2114
|
+
function assertSecureOrLocalHTTP(rawUrl, field) {
|
|
2115
|
+
const parsed = new URL(rawUrl);
|
|
2116
|
+
if (parsed.protocol === "https:") {
|
|
2117
|
+
return;
|
|
2118
|
+
}
|
|
2119
|
+
if (parsed.protocol === "http:" && isLocalHostname(parsed.hostname)) {
|
|
2120
|
+
return;
|
|
2121
|
+
}
|
|
2122
|
+
throw new Error(`custd: ${field} must use https unless it targets localhost`);
|
|
2123
|
+
}
|
|
2124
|
+
export function normalizeRetryOptions(options) {
|
|
2125
|
+
return {
|
|
2126
|
+
maxAttempts: options?.maxAttempts ?? 3,
|
|
2127
|
+
baseDelayMs: options?.baseDelayMs ?? 200,
|
|
2128
|
+
maxDelayMs: options?.maxDelayMs ?? 2000,
|
|
2129
|
+
jitter: options?.jitter ?? 0.2,
|
|
2130
|
+
retryOnStatuses: options?.retryOnStatuses ?? [408, 429, 500, 502, 503, 504],
|
|
2131
|
+
};
|
|
2132
|
+
}
|
|
2133
|
+
export async function withRetry(options, op) {
|
|
2134
|
+
let attempt = 0;
|
|
2135
|
+
for (;;) {
|
|
2136
|
+
attempt++;
|
|
2137
|
+
try {
|
|
2138
|
+
return await op();
|
|
2139
|
+
}
|
|
2140
|
+
catch (err) {
|
|
2141
|
+
const retryable = err instanceof RetryableError || err instanceof TypeError;
|
|
2142
|
+
if (!retryable || attempt >= options.maxAttempts) {
|
|
2143
|
+
throw err;
|
|
2144
|
+
}
|
|
2145
|
+
const delay = backoffDelay(options, attempt);
|
|
2146
|
+
await sleep(delay);
|
|
2147
|
+
}
|
|
2148
|
+
}
|
|
2149
|
+
}
|
|
2150
|
+
function backoffDelay(options, attempt) {
|
|
2151
|
+
const exp = options.baseDelayMs * 2 ** (attempt - 1);
|
|
2152
|
+
const capped = Math.min(exp, options.maxDelayMs);
|
|
2153
|
+
const jitter = capped * options.jitter * (Math.random() * 2 - 1);
|
|
2154
|
+
return Math.max(0, capped + jitter);
|
|
2155
|
+
}
|
|
2156
|
+
function sleep(ms) {
|
|
2157
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
2158
|
+
}
|
|
2159
|
+
function isOnline() {
|
|
2160
|
+
if (typeof navigator === "undefined") {
|
|
2161
|
+
return true;
|
|
2162
|
+
}
|
|
2163
|
+
if (typeof navigator.onLine !== "boolean") {
|
|
2164
|
+
return true;
|
|
2165
|
+
}
|
|
2166
|
+
return navigator.onLine;
|
|
2167
|
+
}
|
|
2168
|
+
// uuidv7 returns a canonical RFC 9562 version 7 UUID. Custd requires one as the
|
|
2169
|
+
// Idempotency-Key of an OAuth client mutation.
|
|
2170
|
+
function uuidv7() {
|
|
2171
|
+
const bytes = new Uint8Array(16);
|
|
2172
|
+
if (typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function") {
|
|
2173
|
+
crypto.getRandomValues(bytes);
|
|
2174
|
+
}
|
|
2175
|
+
else {
|
|
2176
|
+
for (let index = 0; index < bytes.length; index += 1) {
|
|
2177
|
+
bytes[index] = Math.floor(Math.random() * 256);
|
|
2178
|
+
}
|
|
2179
|
+
}
|
|
2180
|
+
let timestamp = Date.now();
|
|
2181
|
+
for (let index = 5; index >= 0; index -= 1) {
|
|
2182
|
+
bytes[index] = timestamp % 256;
|
|
2183
|
+
timestamp = Math.floor(timestamp / 256);
|
|
2184
|
+
}
|
|
2185
|
+
bytes[6] = (bytes[6] & 0x0f) | 0x70;
|
|
2186
|
+
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
|
2187
|
+
const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
2188
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
2189
|
+
}
|
|
2190
|
+
/** Opaque per-event identity, including runtimes without Web Crypto. Not an authentication token. */
|
|
2191
|
+
export function createEventId() {
|
|
2192
|
+
return randomUUID();
|
|
2193
|
+
}
|
|
2194
|
+
function randomUUID() {
|
|
2195
|
+
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
|
|
2196
|
+
return crypto.randomUUID();
|
|
2197
|
+
}
|
|
2198
|
+
return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) => (Number(c) ^ ((Math.random() * 16) >> (Number(c) / 4))).toString(16));
|
|
2199
|
+
}
|
|
2200
|
+
export * from "./admin-accounting-evidence.js";
|
|
2201
|
+
export * from "./admin-campaign-email.js";
|
|
2202
|
+
export * from "./admin-email-relay.js";
|
|
2203
|
+
export * from "./admin-environment-policy.js";
|
|
2204
|
+
export * from "./admin-error-issues.js";
|
|
2205
|
+
export * from "./admin-event-types.js";
|
|
2206
|
+
export * from "./admin-impersonation.js";
|
|
2207
|
+
export * from "./admin-ingest-claims.js";
|
|
2208
|
+
export * from "./admin-managed-audit.js";
|
|
2209
|
+
export * from "./admin-measurement-projects.js";
|
|
2210
|
+
export * from "./admin-notification-destinations.js";
|
|
2211
|
+
export * from "./admin-notification-webhooks.js";
|
|
2212
|
+
export * from "./admin-oauth-client-admissions.js";
|
|
2213
|
+
export * from "./admin-rls.js";
|
|
2214
|
+
export * from "./admin-sdk-usage.js";
|
|
2215
|
+
export * from "./admin-support-access.js";
|
|
2216
|
+
export * from "./admin-system.js";
|
|
2217
|
+
export * from "./admin-uncertainty-models.js";
|
|
2218
|
+
export * from "./analytics-reads.js";
|
|
2219
|
+
export * from "./app-account.js";
|
|
2220
|
+
export { createErrorCaptureEvent, ErrorCaptureClient, installBrowserErrorCapture, installNativeErrorCapture, } from "./error-capture.js";
|
|
2221
|
+
export * from "./ingest-operations.js";
|
|
2222
|
+
export * from "./measurement.js";
|
|
2223
|
+
export * from "./public-reads.js";
|
|
2224
|
+
export * from "./reporting-catalogue.js";
|
|
2225
|
+
export { SiteAIOwnerSession } from "./site-ai-owner.js";
|
|
2226
|
+
export * from "./site-monitor-reports.js";
|