:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): visual manifest builder for Custom REST source (#59387)
Marcus Hofea8d45854c2f
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 020d330dc4d1..47a6835858f8 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -4059,17 +4059,17 @@ snapshots:scenes-app-ai-observability-sentiment--tag-positive--light:hash: v1.k794b7964.815de3d9207328cf5219021229f699cbcc1953137668b1896f387e7f862a2ee2.XpkSjMjcHgKuQphgeNThN63CIWAhCsa3s-KxHiwDbL8scenes-app-ai-observability-skills--skill-detail-side-by-side-above-2-xl-breakpoint--superwide--dark:- hash: v1.k794b7964.be417603652100c79c46974d9b5b51b29be7f52cd42ed27c97952e204e44f455.Hl-jGfGhs5V_C7j3Kvp1bUoXrSoKGnWQDoCl3QpiK1U+ hash: v1.k794b7964.b13a52a161099a8052efa37f4b5ca3d2c9118e96691c2f6899c2f74e92bf8df4.ZqELZsV9yyZ282G4gT1qiuEpZOLSrw2Nskq7rShEzZYscenes-app-ai-observability-skills--skill-detail-side-by-side-above-2-xl-breakpoint--superwide--light:- hash: v1.k794b7964.aed846c40da509fdd657b5e7e4f47b9a1799b7f194e52809ceeebf96f7a803cb.4yNfhSYbMDfLtjDPcYPzUeEPCK-0Ucmhcj1nTP-wqUk+ hash: v1.k794b7964.bd2376d6eb06eb3e6e1b34e173937d917d7354d0fa83469629cf06bccda75b85.TJXGm4v8NV5jMLMkwuCZjz1XZJIHO5QYcVqVI3nzeNoscenes-app-ai-observability-skills--skill-detail-stacked-below-2-xl-breakpoint--medium--dark:- hash: v1.k794b7964.42bdb593a7f35590ce116e5602aa7b231b4f0890de50a9eceef3ba83c4d9f936.aYh94nQqyvrzfd7mSuA0BKtb-gJRYPZ8vuvEQldrgxU+ hash: v1.k794b7964.9b8eaf652698b582fc17886bee4219a007e730d3a9ff35bed1e17ff9d631b460.GaSoHxkJ-WRHk3ux5JTGaPNkRPepZSTbCe_dI7ItYPkscenes-app-ai-observability-skills--skill-detail-stacked-below-2-xl-breakpoint--medium--light:- hash: v1.k794b7964.0da54b12763b72d9f3f8a7b7b3c19260b5902949b362a45868140a7763e800fc.PT9BBrQ4UY6sYNVOW8zxMBvP6YkXEin5RqC4G3wIPZs+ hash: v1.k794b7964.cbe208ce2aca8a7727e59261a5a293b79607e1358c8b0b8402314879dc74ef92.mquv2HsDgbxkiJzLtih2YgUAe4aL0LJwzXeR_JH0bPcscenes-app-ai-observability-skills--skill-detail-stacked-below-2-xl-breakpoint--wide--dark:- hash: v1.k794b7964.8e04beb5d0eaf101479d3dcea9e50665a5c77ba49f77e03e155911b3d6476cb6.EOF-AMwbHaG0pbqwiRnj5RrQZX_0mjSWBRIYd93GuD0+ hash: v1.k794b7964.99e742a702d21b1be689d06448a6cb45cad2e42969f1db9c3e6134c6b5fe3ddd.xkVzJ7il6FUCFjKIVxHF89wfrAhLKFNd-wv4cT--Ch0scenes-app-ai-observability-skills--skill-detail-stacked-below-2-xl-breakpoint--wide--light:- hash: v1.k794b7964.0f3afd38b8ac79bfb5452749ad76d3956413fb933d01587fdf4ba7280e980399.TFYIuwcCCTYOUBpVU40LPGbbNbhPxLOMV3UkBa9yuGw+ hash: v1.k794b7964.01aa0b288121d9e5e338b641e2d4c1e9f619eacb5948923cc2c5a6f7a1b1ff63.7g3UKVhP2XBzYsvKcTX2mzudF6trs6WzQt3--m2Mq3cscenes-app-ai-observability-trace--full--dark:hash: v1.k794b7964.284878f1c3dd48212cfcbb472b45b9dc3381383d5908eb61521f601ee6310f75.nReNoI5hzUZbSfIpwcKW06bGdCyphRtbId5MiGFRgKEscenes-app-ai-observability-trace--full--light:@@ -4143,9 +4143,9 @@ snapshots:scenes-app-customer-analytics-accounts--row-expanded-empty--light:hash: v1.k794b7964.021a1c353b9538e92b53522c2f9f0ce54edfe2128a8d73d2db5a1c18300fd521.ue3Cheto6fAr6I55Hn41DRJ8Ki0uSQydijiiDYjJpJYscenes-app-customer-analytics-accounts--row-expanded-with-note--dark:- hash: v1.k794b7964.5766de93c835a93b824169b0d68674fdda0f2370094692ddcf7c7b182a3cfe89.wVjuimww9AOH7VBoaI7Ji07pOrxrW6PmWexYN23lRQc+ hash: v1.k794b7964.d0789930ec3aa1a4952996f5b6e9260fb0403c64085259c10c4f6f703d66fad6.9Cb3M77BJTkzTmZbZUIVvrYbz-6rOas9qfCBnXvGc20scenes-app-customer-analytics-accounts--row-expanded-with-note--light:- hash: v1.k794b7964.ddac5516ff9df120ea18a456cf3a3a648dc5b32cb6672a962c73273f384e4ded.J7Gn0iZoA4IIpF7iidcgsnhSuGPe7YssglzpxegJQl0+ hash: v1.k794b7964.6cdedf3bdb1962c2971d4c812f46c301ac195e74059bdee07122ed9b2d88b7f4.r5ZRQD_sHB0qgXtliu1uj5aPVttOg4cuL_rOhP20ngwscenes-app-customer-analytics-dashboard--b-2-b-mode-with-groups-enabled--dark:hash: v1.k794b7964.b1e7b3b4db44122983952ce49cdcb2721216d6e09cdda2e03d88250a66f9531d.XEmKGVDBb7ph1xN1zMKNGWDQAkJPR509WPM2orhsrZoscenes-app-customer-analytics-dashboard--b-2-b-mode-with-groups-enabled--light:@@ -6031,13 +6031,13 @@ snapshots:scenes-app-user-research-topics--search-no-results--light:hash: v1.k794b7964.ff0bc9fb718908b9bd7aec82c9fdfff3d1beacd788bb3ed3721245ee7af9fae3.8_bm5mLUjc3uTKstx8eTREoruP53hFu8KO7wAs3VKMYscenes-app-user-research-topics--search-with-results--dark:- hash: v1.k794b7964.eb87efdfd040d41204e1d4cd2af3e5c8a31616c4c75b8597ffdbcf2c218e87e6.yArNJAeAczj4qkuAI7V9KR3CEXwe_LkSgmlapsXpOi8+ hash: v1.k794b7964.acde76a9ee773175787045e01d0d425f239635b413b414238e891d1acfe63de1.KwNCdI_JPiXSOqUuyEiqFNnK_guIO7DB3MuMtM_26k8scenes-app-user-research-topics--search-with-results--light:- hash: v1.k794b7964.3813435da13a613c0cf9855f40c89ed46a2d38a2408f933e60fb8d79f2126cd9.KBq9Fk2Jf7uSN_j7SPoji-vu5FwJuy2lMv4V_c__UwA+ hash: v1.k794b7964.e5cc683d2837f19e71fcdf52b5741b14ec965394f7c0778750aaf85c23f9e2f0.lhvklKb_H289D1632iKUZXFWrYIRPXIWksDkolSC9aQscenes-app-user-research-topics--topics-list--dark:- hash: v1.k794b7964.d69d7670abb2a83ae34f5fd1d5207f21e5b1ef14e0116997b55b6854f77564a5.BuxfmZGhUt3c9qQw3T27cYFr9cnafBjOJXLbAke8Sx4+ hash: v1.k794b7964.8826fc78d609b42cbda952e0e847c9c95c956b66232831ce90aa299d18020871.OSbhkXqvyEXBVRCILSsqw7e1sFKs4vuwrfiYy5k1dMoscenes-app-user-research-topics--topics-list--light:- hash: v1.k794b7964.c4ee7785c554f517bcaf7013daa0277ccb038faf2883d1ddb3ccb6f3ac7c7e00.apAT1Kl9oDw_AAmV8akOA9zvcF0mOUCUjtrEwJ1wA54+ hash: v1.k794b7964.53fba46a547b51c181a50c02d97b063d687a551e74865b07532cf1b7ff9e0894.f4gOdNsOQk_mHlPYTQFQhfq0IrTE2MIDA6dTKk5oZEoscenes-app-web-analytics--web-analytics-dashboard--dark:hash: v1.k794b7964.d729142b01b803dbcfffd430343e1176225e4f58cdf02aa407cc00c55d6c33d0.kk553-OF0ph-irS6_xeghO1Cqq3Iw7oWwvB153DNJuoscenes-app-web-analytics--web-analytics-dashboard--light:diff --git a/products/data_warehouse/frontend/shared/components/forms/CustomSourceManifestBuilder.tsx b/products/data_warehouse/frontend/shared/components/forms/CustomSourceManifestBuilder.tsxnew file mode 100644index 000000000000..fe26c35e222f--- /dev/null+++ b/products/data_warehouse/frontend/shared/components/forms/CustomSourceManifestBuilder.tsx@@ -0,0 +1,558 @@+import { useActions, useValues } from 'kea'++import { IconPlus, IconTrash } from '@posthog/icons'+import { LemonButton, LemonCheckbox, LemonDivider, LemonInput, LemonSelect } from '@posthog/lemon-ui'++import { CodeSnippet, Language } from 'lib/components/CodeSnippet/CodeSnippet'+import { LemonField } from 'lib/lemon-ui/LemonField'++import {+ API_KEY_LOCATIONS,+ type ApiKeyLocation,+ AUTH_TYPES,+ type AuthType,+ CURSOR_TYPES,+ type CursorType,+ type HeaderEntry,+ type ManifestState,+ type Paginator,+ PAGINATOR_DEFAULTS,+ PAGINATOR_TYPES,+ type PaginatorType,+ SORT_MODES,+ type SortMode,+ type StreamForm,+} from './customSourceManifest'+import {+ customSourceManifestBuilderLogic,+ type CustomSourceManifestBuilderLogicProps,+} from './customSourceManifestBuilderLogic'++// Option lists derive their value set from the single-source `as const` tuples in+// customSourceManifest.ts; only the labels live here, so the allowed values can't+// drift between the type, the parser, and these selects.+const PAGINATOR_LABELS: Record<PaginatorType, string> = {+ auto: 'Auto-detect',+ single_page: 'Single page (no pagination)',+ json_response: 'JSON body next-URL',+ cursor: 'Cursor in JSON body',+ offset: 'Offset / limit query params',+ page_number: 'Page number query param',+ header_link: 'Link header (RFC 5988)',+}+const PAGINATOR_OPTIONS = PAGINATOR_TYPES.map((value) => ({ value, label: PAGINATOR_LABELS[value] }))++const AUTH_LABELS: Record<AuthType, string> = {+ none: 'No auth',+ bearer: 'Bearer token',+ api_key: 'API key',+ http_basic: 'HTTP basic auth',+}+const AUTH_OPTIONS = AUTH_TYPES.map((value) => ({ value, label: AUTH_LABELS[value] }))++const API_KEY_LOCATION_LABELS: Record<ApiKeyLocation, string> = {+ header: 'Header',+ query: 'Query parameter',+ cookie: 'Cookie',+}+const API_KEY_LOCATION_OPTIONS = API_KEY_LOCATIONS.map((value) => ({ value, label: API_KEY_LOCATION_LABELS[value] }))++const CURSOR_TYPE_LABELS: Record<CursorType, string> = {+ datetime: 'Datetime',+ date: 'Date',+ timestamp: 'Timestamp (epoch)',+ integer: 'Integer',+}+const CURSOR_TYPE_OPTIONS = CURSOR_TYPES.map((value) => ({ value, label: CURSOR_TYPE_LABELS[value] }))++const SORT_MODE_LABELS: Record<SortMode, string> = {+ asc: 'Ascending (oldest first)',+ desc: 'Descending (newest first)',+}+const SORT_MODE_OPTIONS = SORT_MODES.map((value) => ({ value, label: SORT_MODE_LABELS[value] }))++/**+ * Visual builder for the Custom REST source's manifest. State and the+ * outer-form sync live in `customSourceManifestBuilderLogic`; this component+ * only renders the form and dispatches actions.+ */+export function CustomSourceManifestBuilder({+ initialManifestJson,+ setValue,+}: CustomSourceManifestBuilderLogicProps): JSX.Element {+ const logic = customSourceManifestBuilderLogic({ initialManifestJson, setValue })+ const { manifestState, manifestJson, manifestPreviewOpen } = useValues(logic)+ const {+ updateState,+ updateStream,+ updatePaginator,+ addStream,+ removeStream,+ addHeader,+ removeHeader,+ updateHeader,+ setManifestPreviewOpen,+ } = useActions(logic)++ return (+ <div className="space-y-6">+ <LemonField.Pure label="Base URL" htmlFor="custom-source-base-url">+ <LemonInput+ id="custom-source-base-url"+ placeholder="https://api.example.com"+ value={manifestState.base_url}+ onChange={(value) => updateState({ base_url: value })}+ />+ </LemonField.Pure>++ <AuthSection state={manifestState} update={updateState} />++ <HeadersSection+ headers={manifestState.headers}+ onAdd={addHeader}+ onRemove={removeHeader}+ onUpdate={updateHeader}+ />++ <LemonDivider />++ <div className="space-y-4">+ <div className="flex items-center justify-between">+ <div>+ <h4 className="mb-0">Streams</h4>+ <p className="m-0 text-xs text-secondary">+ Each stream becomes a table. PostHog fetches the endpoint, paginates, and writes rows.+ </p>+ </div>+ <LemonButton type="secondary" icon={<IconPlus />} onClick={addStream}>+ Add stream+ </LemonButton>+ </div>+ {manifestState.streams.map((stream, index) => (+ <StreamCard+ key={stream.id}+ index={index}+ stream={stream}+ canRemove={manifestState.streams.length > 1}+ onUpdate={(patch) => updateStream(index, patch)}+ onUpdatePaginator={(paginator) => updatePaginator(index, paginator)}+ onRemove={() => removeStream(index)}+ />+ ))}+ </div>++ <details+ className="rounded border border-border p-3"+ open={manifestPreviewOpen}+ onToggle={(e) => setManifestPreviewOpen((e.target as HTMLDetailsElement).open)}+ >+ <summary className="cursor-pointer text-xs text-secondary">Show generated manifest</summary>+ {/* Only render (and syntax-highlight) the snippet while expanded — otherwise+ lowlight re-runs over the whole manifest on every keystroke even when collapsed. */}+ {manifestPreviewOpen && (+ <CodeSnippet language={Language.JSON} className="mt-2 text-xs" wrap maxLinesWithoutExpansion={20}>+ {manifestJson}+ </CodeSnippet>+ )}+ </details>+ </div>+ )+}++function AuthSection({+ state,+ update,+}: {+ state: ManifestState+ update: (patch: Partial<ManifestState>) => void+}): JSX.Element {+ return (+ <div className="space-y-2">+ <LemonField.Pure label="Authentication">+ <LemonSelect+ value={state.auth_type}+ onChange={(value) => update({ auth_type: value as AuthType })}+ options={AUTH_OPTIONS}+ />+ </LemonField.Pure>+ {state.auth_type === 'bearer' && (+ <LemonField.Pure label="Bearer token">+ <LemonInput+ type="password"+ autoComplete="off"+ placeholder="ya29...."+ value={state.auth_token}+ onChange={(value) => update({ auth_token: value })}+ />+ </LemonField.Pure>+ )}+ {state.auth_type === 'api_key' && (+ <div className="grid grid-cols-3 gap-2">+ <LemonField.Pure label="Location">+ <LemonSelect+ value={state.auth_api_key_location}+ onChange={(value) => update({ auth_api_key_location: value as ApiKeyLocation })}+ options={API_KEY_LOCATION_OPTIONS}+ />+ </LemonField.Pure>+ <LemonField.Pure+ label={state.auth_api_key_location === 'header' ? 'Header name' : 'Parameter name'}+ >+ <LemonInput+ placeholder={state.auth_api_key_location === 'header' ? 'Authorization' : 'api_key'}+ value={state.auth_api_key_name}+ onChange={(value) => update({ auth_api_key_name: value })}+ />+ </LemonField.Pure>+ <LemonField.Pure label="API key">+ <LemonInput+ type="password"+ autoComplete="off"+ placeholder="sk_live_…"+ value={state.auth_api_key}+ onChange={(value) => update({ auth_api_key: value })}+ />+ </LemonField.Pure>+ </div>+ )}+ {state.auth_type === 'http_basic' && (+ <div className="grid grid-cols-2 gap-2">+ <LemonField.Pure label="Username">+ <LemonInput+ autoComplete="off"+ value={state.auth_username}+ onChange={(value) => update({ auth_username: value })}+ />+ </LemonField.Pure>+ <LemonField.Pure label="Password">+ <LemonInput+ type="password"+ autoComplete="off"+ value={state.auth_password}+ onChange={(value) => update({ auth_password: value })}+ />+ </LemonField.Pure>+ </div>+ )}+ </div>+ )+}++function HeadersSection({+ headers,+ onAdd,+ onRemove,+ onUpdate,+}: {+ headers: HeaderEntry[]+ onAdd: () => void+ onRemove: (index: number) => void+ onUpdate: (index: number, patch: Partial<HeaderEntry>) => void+}): JSX.Element {+ return (+ <div className="space-y-2">+ <div className="flex items-center justify-between">+ <span className="text-sm font-medium">Default headers</span>+ <LemonButton type="tertiary" size="small" icon={<IconPlus />} onClick={onAdd}>+ Add header+ </LemonButton>+ </div>+ {headers.length === 0 ? (+ <p className="m-0 text-xs text-secondary">+ No extra headers. Auth headers above are added automatically.+ </p>+ ) : (+ <div className="space-y-2">+ {headers.map((header, index) => (+ <div key={header.id} className="flex items-center gap-2">+ <LemonInput+ placeholder="Header name"+ value={header.key}+ onChange={(value) => onUpdate(index, { key: value })}+ />+ <LemonInput+ placeholder="Header value"+ value={header.value}+ onChange={(value) => onUpdate(index, { value })}+ />+ <LemonButton+ type="tertiary"+ icon={<IconTrash />}+ tooltip="Remove header"+ onClick={() => onRemove(index)}+ />+ </div>+ ))}+ </div>+ )}+ </div>+ )+}++function StreamCard({+ index,+ stream,+ canRemove,+ onUpdate,+ onUpdatePaginator,+ onRemove,+}: {+ index: number+ stream: StreamForm+ canRemove: boolean+ onUpdate: (patch: Partial<StreamForm>) => void+ onUpdatePaginator: (paginator: Paginator) => void+ onRemove: () => void+}): JSX.Element {+ return (+ <div className="rounded border border-border p-3 space-y-3">+ <div className="flex items-center justify-between">+ <h5 className="mb-0">Stream {index + 1}</h5>+ {canRemove && (+ <LemonButton type="tertiary" size="small" icon={<IconTrash />} onClick={onRemove}>+ Remove+ </LemonButton>+ )}+ </div>+ <div className="grid grid-cols-2 gap-2">+ <LemonField.Pure label="Stream name">+ <LemonInput+ placeholder="users"+ value={stream.name}+ onChange={(value) => onUpdate({ name: value })}+ />+ </LemonField.Pure>+ <LemonField.Pure label="Primary key">+ <LemonInput+ placeholder="id"+ value={stream.primary_key}+ onChange={(value) => onUpdate({ primary_key: value })}+ />+ </LemonField.Pure>+ </div>+ <div className="grid grid-cols-2 gap-2">+ <LemonField.Pure label="Path">+ <LemonInput+ placeholder="/v1/users"+ value={stream.path}+ onChange={(value) => onUpdate({ path: value })}+ />+ </LemonField.Pure>+ <LemonField.Pure label="HTTP method">+ <LemonSelect+ value={stream.method}+ onChange={(value) => onUpdate({ method: value as 'GET' | 'POST' })}+ options={[+ { value: 'GET', label: 'GET' },+ { value: 'POST', label: 'POST' },+ ]}+ />+ </LemonField.Pure>+ </div>+ <LemonField.Pure label="Records JSONPath">+ <LemonInput+ placeholder="data"+ value={stream.data_selector}+ onChange={(value) => onUpdate({ data_selector: value })}+ />+ <p className="m-0 mt-1 text-xs text-secondary">+ JSONPath that points at the array of rows in each response (e.g. <code>data</code>,{' '}+ <code>items</code>, <code>results.data</code>).+ </p>+ </LemonField.Pure>+ <PaginatorSection paginator={stream.paginator} onUpdate={onUpdatePaginator} />+ <IncrementalSection stream={stream} onUpdate={onUpdate} />+ </div>+ )+}++function PaginatorSection({+ paginator,+ onUpdate,+}: {+ paginator: Paginator+ onUpdate: (paginator: Paginator) => void+}): JSX.Element {+ const switchType = (type: Paginator['type']): void => {+ switch (type) {+ case 'auto':+ case 'single_page':+ onUpdate({ type })+ return+ case 'json_response':+ onUpdate({ type, ...PAGINATOR_DEFAULTS.json_response })+ return+ case 'cursor':+ onUpdate({ type, ...PAGINATOR_DEFAULTS.cursor })+ return+ case 'offset':+ onUpdate({ type, ...PAGINATOR_DEFAULTS.offset })+ return+ case 'page_number':+ onUpdate({ type, ...PAGINATOR_DEFAULTS.page_number })+ return+ case 'header_link':+ onUpdate({ type, ...PAGINATOR_DEFAULTS.header_link })+ return+ }+ }++ return (+ <div className="space-y-2">+ <LemonField.Pure label="Paginator">+ <LemonSelect+ value={paginator.type}+ onChange={(value) => switchType(value)}+ options={PAGINATOR_OPTIONS}+ />+ </LemonField.Pure>+ {paginator.type === 'json_response' && (+ <LemonField.Pure label="Next-URL JSONPath">+ <LemonInput+ placeholder={PAGINATOR_DEFAULTS.json_response.next_url_path}+ value={paginator.next_url_path ?? ''}+ onChange={(value) => onUpdate({ ...paginator, next_url_path: value })}+ />+ </LemonField.Pure>+ )}+ {paginator.type === 'cursor' && (+ <div className="grid grid-cols-2 gap-2">+ <LemonField.Pure label="Cursor JSONPath">+ <LemonInput+ placeholder={PAGINATOR_DEFAULTS.cursor.cursor_path}+ value={paginator.cursor_path ?? ''}+ onChange={(value) => onUpdate({ ...paginator, cursor_path: value })}+ />+ </LemonField.Pure>+ <LemonField.Pure label="Cursor query param">+ <LemonInput+ placeholder={PAGINATOR_DEFAULTS.cursor.cursor_param}+ value={paginator.cursor_param ?? ''}+ onChange={(value) => onUpdate({ ...paginator, cursor_param: value })}+ />+ </LemonField.Pure>+ </div>+ )}+ {paginator.type === 'offset' && (+ <div className="grid grid-cols-3 gap-2">+ <LemonField.Pure label="Page size">+ <LemonInput+ type="number"+ value={paginator.limit ?? PAGINATOR_DEFAULTS.offset.limit}+ onChange={(value) =>+ onUpdate({ ...paginator, limit: value ?? PAGINATOR_DEFAULTS.offset.limit })+ }+ />+ </LemonField.Pure>+ <LemonField.Pure label="Offset param">+ <LemonInput+ placeholder={PAGINATOR_DEFAULTS.offset.offset_param}+ value={paginator.offset_param ?? ''}+ onChange={(value) => onUpdate({ ...paginator, offset_param: value })}+ />+ </LemonField.Pure>+ <LemonField.Pure label="Limit param">+ <LemonInput+ placeholder={PAGINATOR_DEFAULTS.offset.limit_param}+ value={paginator.limit_param ?? ''}+ onChange={(value) => onUpdate({ ...paginator, limit_param: value })}+ />+ </LemonField.Pure>+ </div>+ )}+ {paginator.type === 'page_number' && (+ <div className="grid grid-cols-2 gap-2">+ <LemonField.Pure label="Page query param">+ <LemonInput+ placeholder={PAGINATOR_DEFAULTS.page_number.page_param}+ value={paginator.page_param ?? ''}+ onChange={(value) => onUpdate({ ...paginator, page_param: value })}+ />+ </LemonField.Pure>+ <LemonField.Pure label="Initial page">+ <LemonInput+ type="number"+ value={paginator.base_page ?? PAGINATOR_DEFAULTS.page_number.base_page}+ onChange={(value) =>+ onUpdate({ ...paginator, base_page: value ?? PAGINATOR_DEFAULTS.page_number.base_page })+ }+ />+ </LemonField.Pure>+ </div>+ )}+ {paginator.type === 'header_link' && (+ <LemonField.Pure label="rel= key in Link header">+ <LemonInput+ placeholder={PAGINATOR_DEFAULTS.header_link.links_next_key}+ value={paginator.links_next_key ?? ''}+ onChange={(value) => onUpdate({ ...paginator, links_next_key: value })}+ />+ </LemonField.Pure>+ )}+ </div>+ )+}++function IncrementalSection({+ stream,+ onUpdate,+}: {+ stream: StreamForm+ onUpdate: (patch: Partial<StreamForm>) => void+}): JSX.Element {+ return (+ <div className="rounded border border-border p-3 space-y-2">+ <LemonCheckbox+ checked={stream.incremental_enabled}+ onChange={(checked) => onUpdate({ incremental_enabled: checked })}+ label="Enable incremental sync"+ />+ {stream.incremental_enabled && (+ <>+ <div className="grid grid-cols-2 gap-2">+ <LemonField.Pure label="Cursor JSONPath">+ <LemonInput+ placeholder="updated_at"+ value={stream.cursor_path}+ onChange={(value) => onUpdate({ cursor_path: value })}+ />+ </LemonField.Pure>+ <LemonField.Pure label="Cursor query param">+ <LemonInput+ placeholder="since"+ value={stream.start_param}+ onChange={(value) => onUpdate({ start_param: value })}+ />+ </LemonField.Pure>+ </div>+ {!stream.cursor_path.trim() && (+ <p className="m-0 text-xs text-danger">+ Set a cursor JSONPath — otherwise incremental sync is ignored and the stream does a full+ refresh every run.+ </p>+ )}+ <div className="grid grid-cols-2 gap-2">+ <LemonField.Pure label="Cursor type">+ <LemonSelect+ value={stream.cursor_type}+ onChange={(value) => onUpdate({ cursor_type: value as CursorType })}+ options={CURSOR_TYPE_OPTIONS}+ />+ </LemonField.Pure>+ <LemonField.Pure label="Upstream row order">+ <LemonSelect+ value={stream.sort_mode}+ onChange={(value) => onUpdate({ sort_mode: value as SortMode })}+ options={SORT_MODE_OPTIONS}+ />+ </LemonField.Pure>+ </div>+ <p className="m-0 text-xs text-secondary">+ Pick "Descending" when the API returns newest rows first — otherwise a resumed sync may skip+ rows.+ </p>+ </>+ )}+ </div>+ )+}diff --git a/products/data_warehouse/frontend/shared/components/forms/SourceForm.tsx b/products/data_warehouse/frontend/shared/components/forms/SourceForm.tsxindex 30b841468b13..260fa35beb60 100644--- a/products/data_warehouse/frontend/shared/components/forms/SourceForm.tsx+++ b/products/data_warehouse/frontend/shared/components/forms/SourceForm.tsx@@ -30,6 +30,7 @@ import {type SourceWizardLogicProps,sourceWizardLogic,} from '../../../scenes/NewSourceScene/sourceWizardLogic'+import { CustomSourceManifestBuilder } from './CustomSourceManifestBuilder'import { GitHubRepositorySelector } from './GitHubRepositorySelector'import { SourceIntegrationChoice } from './IntegrationChoice'import { parseConnectionStringForSource } from './parsers'@@ -743,17 +744,36 @@ export function SourceFormComponent({</LemonField>)}<Group name="payload">- {availableSources[sourceConfig.name].fields- .filter((field) => !(isPostgresDirectQuery && field.type === 'ssh-tunnel'))- .map((field) =>- sourceFieldToElement(- field,- sourceConfig,- jobInputs?.[field.name],- isUpdateMode,- setSourceConnectionDetailsValue+ {sourceConfig.name === 'Custom' ? (+ setSourceConfigValue ? (+ <CustomSourceManifestBuilder+ initialManifestJson={jobInputs?.manifest_json}+ setValue={setSourceConfigValue}+ />+ ) : setSourceConnectionDetailsValue ? (+ <CustomSourceManifestBuilder+ initialManifestJson={jobInputs?.manifest_json}+ setValue={setSourceConnectionDetailsValue}+ />+ ) : (+ <LemonBanner type="error">+ Custom source form is misconfigured: neither setSourceConfigValue nor sourceWizardLogicProps+ was provided to SourceForm.+ </LemonBanner>+ )+ ) : (+ availableSources[sourceConfig.name].fields+ .filter((field) => !(isPostgresDirectQuery && field.type === 'ssh-tunnel'))+ .map((field) =>+ sourceFieldToElement(+ field,+ sourceConfig,+ jobInputs?.[field.name],+ isUpdateMode,+ setSourceConnectionDetailsValue+ ))- )}+ )}</Group>{!isUpdateMode &&sourceConfig.name === 'Postgres' &&diff --git a/products/data_warehouse/frontend/shared/components/forms/__tests__/customSourceManifest.test.ts b/products/data_warehouse/frontend/shared/components/forms/__tests__/customSourceManifest.test.tsnew file mode 100644index 000000000000..6ca3cb9fc3a6--- /dev/null+++ b/products/data_warehouse/frontend/shared/components/forms/__tests__/customSourceManifest.test.ts@@ -0,0 +1,446 @@+import { buildManifest, extractAuthSecrets, ManifestState, parseManifestIntoState } from '../customSourceManifest'++const baseState = (): ManifestState => ({+ base_url: 'https://api.example.com',+ auth_type: 'bearer',+ auth_token: 'tok_123',+ auth_api_key: '',+ auth_api_key_name: 'Authorization',+ auth_api_key_location: 'header',+ auth_username: '',+ auth_password: '',+ headers: [],+ streams: [+ {+ id: 'stream-base',+ name: 'users',+ path: '/v1/users',+ method: 'GET',+ data_selector: 'data',+ primary_key: 'id',+ paginator: { type: 'single_page' },+ sort_mode: 'asc',+ incremental_enabled: false,+ cursor_path: '',+ cursor_type: 'datetime',+ start_param: '',+ },+ ],+})++describe('buildManifest', () => {+ it('emits client.auth for bearer with no inline credential', () => {+ const manifest = buildManifest(baseState()) as any+ expect(manifest.client.auth).toEqual({ type: 'bearer' })+ expect(manifest.client.auth.token).toBeUndefined()+ })++ it('emits client.auth with api_key header location but no key value', () => {+ const state = baseState()+ state.auth_type = 'api_key'+ state.auth_api_key = 'sk_test'+ state.auth_api_key_name = 'X-API-Key'+ const manifest = buildManifest(state) as any+ expect(manifest.client.auth).toEqual({ type: 'api_key', name: 'X-API-Key', location: 'header' })+ expect(manifest.client.auth.api_key).toBeUndefined()+ })++ it.each(['header', 'query', 'cookie'] as const)('threads api_key location=%s into client.auth', (location) => {+ const state = baseState()+ state.auth_type = 'api_key'+ state.auth_api_key_location = location+ state.auth_api_key_name = 'key'+ const manifest = buildManifest(state) as any+ expect(manifest.client.auth.location).toBe(location)+ })++ it('emits http_basic auth with username but no password', () => {+ const state = baseState()+ state.auth_type = 'http_basic'+ state.auth_username = 'alice'+ state.auth_password = 'hunter2'+ const manifest = buildManifest(state) as any+ expect(manifest.client.auth).toEqual({ type: 'http_basic', username: 'alice' })+ expect(manifest.client.auth.password).toBeUndefined()+ })++ it("omits client.auth when 'none' is selected", () => {+ const state = baseState()+ state.auth_type = 'none'+ const manifest = buildManifest(state) as any+ expect(manifest.client.auth).toBeUndefined()+ })++ it('serializes non-empty headers into client.headers as a map', () => {+ const state = baseState()+ state.headers = [+ { id: 'h1', key: 'X-Workspace', value: 'acme' },+ { id: 'h2', key: '', value: 'ignored' },+ { id: 'h3', key: ' ', value: 'also ignored' },+ ]+ const manifest = buildManifest(state) as any+ expect(manifest.client.headers).toEqual({ 'X-Workspace': 'acme' })+ })++ it('omits client.headers entirely when no real entries are present', () => {+ const state = baseState()+ state.headers = [{ id: 'h1', key: '', value: 'whatever' }]+ const manifest = buildManifest(state) as any+ expect('headers' in manifest.client).toBe(false)+ })++ it('splits a comma-separated primary_key into a list when multi-column', () => {+ const state = baseState()+ state.streams[0].primary_key = 'user_id, page_url, day'+ const manifest = buildManifest(state) as any+ expect(manifest.resources[0].primary_key).toEqual(['user_id', 'page_url', 'day'])+ })++ it('keeps a single primary_key as a string', () => {+ const manifest = buildManifest(baseState()) as any+ expect(manifest.resources[0].primary_key).toEqual('id')+ })++ it.each(['', ' ', ' , '])('falls back to id when primary_key is cleared (%p)', (cleared) => {+ const state = baseState()+ state.streams[0].primary_key = cleared+ const manifest = buildManifest(state) as any+ expect(manifest.resources[0].primary_key).toEqual('id')+ })++ it("only sets endpoint.method when the stream isn't GET", () => {+ const get = buildManifest(baseState()) as any+ expect('method' in get.resources[0].endpoint).toBe(false)++ const state = baseState()+ state.streams[0].method = 'POST'+ const post = buildManifest(state) as any+ expect(post.resources[0].endpoint.method).toBe('POST')+ })++ it('serializes paginator-specific fields per paginator type', () => {+ const offsetState = baseState()+ offsetState.streams[0].paginator = { type: 'offset', limit: 50, offset_param: 'o', limit_param: 'l' }+ const offsetManifest = buildManifest(offsetState) as any+ expect(offsetManifest.resources[0].endpoint.paginator).toEqual({+ type: 'offset',+ limit: 50,+ offset_param: 'o',+ limit_param: 'l',+ })++ const pageState = baseState()+ pageState.streams[0].paginator = { type: 'page_number', page_param: 'p', base_page: 0 }+ const pageManifest = buildManifest(pageState) as any+ expect(pageManifest.resources[0].endpoint.paginator).toEqual({+ type: 'page_number',+ page_param: 'p',+ base_page: 0,+ })+ })++ it('fills paginator defaults when fields are left blank', () => {+ const state = baseState()+ state.streams[0].paginator = { type: 'cursor' }+ const manifest = buildManifest(state) as any+ expect(manifest.resources[0].endpoint.paginator).toEqual({+ type: 'cursor',+ cursor_path: 'meta.next_cursor',+ cursor_param: 'cursor',+ })+ })++ it('serializes json_response with an explicit and a default next_url_path', () => {+ const explicit = baseState()+ explicit.streams[0].paginator = { type: 'json_response', next_url_path: 'paging.next' }+ expect((buildManifest(explicit) as any).resources[0].endpoint.paginator).toEqual({+ type: 'json_response',+ next_url_path: 'paging.next',+ })++ const blank = baseState()+ blank.streams[0].paginator = { type: 'json_response' }+ expect((buildManifest(blank) as any).resources[0].endpoint.paginator).toEqual({+ type: 'json_response',+ next_url_path: 'links.next',+ })+ })++ it('serializes header_link with an explicit and a default links_next_key', () => {+ const explicit = baseState()+ explicit.streams[0].paginator = { type: 'header_link', links_next_key: 'successor' }+ expect((buildManifest(explicit) as any).resources[0].endpoint.paginator).toEqual({+ type: 'header_link',+ links_next_key: 'successor',+ })++ const blank = baseState()+ blank.streams[0].paginator = { type: 'header_link' }+ expect((buildManifest(blank) as any).resources[0].endpoint.paginator).toEqual({+ type: 'header_link',+ links_next_key: 'next',+ })+ })++ it('emits endpoint.incremental only when enabled AND cursor_path is set', () => {+ const state = baseState()+ state.streams[0].incremental_enabled = true+ state.streams[0].cursor_path = 'updated_at'+ const manifest = buildManifest(state) as any+ expect(manifest.resources[0].endpoint.incremental).toEqual({+ cursor_path: 'updated_at',+ start_param: 'updated_at',+ })++ state.streams[0].start_param = 'since'+ const overriddenStart = buildManifest(state) as any+ expect(overriddenStart.resources[0].endpoint.incremental.start_param).toBe('since')++ state.streams[0].cursor_path = ''+ const noCursor = buildManifest(state) as any+ expect('incremental' in noCursor.resources[0].endpoint).toBe(false)+ })++ it('omits cursor_type when it equals the backend default (datetime)', () => {+ const state = baseState()+ state.streams[0].incremental_enabled = true+ state.streams[0].cursor_path = 'updated_at'+ const manifest = buildManifest(state) as any+ expect('cursor_type' in manifest.resources[0].endpoint.incremental).toBe(false)+ })++ it.each(['date', 'timestamp', 'integer'] as const)('emits cursor_type=%s when non-default', (cursorType) => {+ const state = baseState()+ state.streams[0].incremental_enabled = true+ state.streams[0].cursor_path = 'updated_at'+ state.streams[0].cursor_type = cursorType+ const manifest = buildManifest(state) as any+ expect(manifest.resources[0].endpoint.incremental.cursor_type).toBe(cursorType)+ })++ it('emits sort_mode only when explicitly descending', () => {+ const asc = buildManifest(baseState()) as any+ expect('sort_mode' in asc.resources[0]).toBe(false)++ const descState = baseState()+ descState.streams[0].sort_mode = 'desc'+ const desc = buildManifest(descState) as any+ expect(desc.resources[0].sort_mode).toBe('desc')+ })++ it('serializes the auto paginator to type-only', () => {+ const state = baseState()+ state.streams[0].paginator = { type: 'auto' }+ const manifest = buildManifest(state) as any+ expect(manifest.resources[0].endpoint.paginator).toEqual({ type: 'auto' })+ })+})++describe('parseManifestIntoState', () => {+ it('returns defaults for undefined/empty input', () => {+ const state = parseManifestIntoState(undefined)+ expect(state.base_url).toBe('')+ expect(state.auth_type).toBe('bearer')+ expect(state.streams).toHaveLength(1)+ })++ it('returns defaults for invalid JSON', () => {+ const state = parseManifestIntoState('{not json}')+ expect(state.streams).toHaveLength(1)+ })++ it('round-trips a manifest through build → parse → build without drift', () => {+ const original = baseState()+ original.headers = [{ id: 'h1', key: 'X-Workspace', value: 'acme' }]+ original.streams = [+ {+ id: 'stream-orders',+ name: 'orders',+ path: '/orders',+ method: 'POST',+ data_selector: 'records',+ primary_key: 'order_id, line_no',+ paginator: { type: 'cursor', cursor_path: 'meta.next', cursor_param: 'after' },+ sort_mode: 'asc',+ incremental_enabled: true,+ cursor_path: 'updated_at',+ cursor_type: 'datetime',+ start_param: 'since',+ },+ ]++ const firstJson = JSON.stringify(buildManifest(original))+ const reparsed = parseManifestIntoState(firstJson)+ const secondJson = JSON.stringify(buildManifest(reparsed))+ expect(secondJson).toBe(firstJson)+ })++ it.each([+ ['offset', { type: 'offset', limit: 50, offset_param: 'o', limit_param: 'l' }],+ ['page_number (base_page 0)', { type: 'page_number', page_param: 'p', base_page: 0 }],+ ['json_response', { type: 'json_response', next_url_path: 'paging.next' }],+ ['header_link', { type: 'header_link', links_next_key: 'successor' }],+ ] as const)('round-trips the %s paginator without drift', (_name, paginator) => {+ const original = baseState()+ original.streams[0].paginator = { ...paginator }+ const firstJson = JSON.stringify(buildManifest(original))+ const secondJson = JSON.stringify(buildManifest(parseManifestIntoState(firstJson)))+ expect(secondJson).toBe(firstJson)+ })++ it('flattens a single-element primary_key array back to a string-ish form on parse', () => {+ const manifestJson = JSON.stringify({+ client: { base_url: 'https://x' },+ resources: [{ name: 'r', primary_key: ['id'], endpoint: { path: '/r' } }],+ })+ const state = parseManifestIntoState(manifestJson)+ expect(state.streams[0].primary_key).toBe('id')+ })++ it('falls back to single_page paginator when type is unknown', () => {+ const manifestJson = JSON.stringify({+ client: { base_url: 'https://x' },+ resources: [{ name: 'r', endpoint: { path: '/r', paginator: { type: 'wat' } } }],+ })+ const state = parseManifestIntoState(manifestJson)+ expect(state.streams[0].paginator.type).toBe('single_page')+ })++ it("recognizes 'none' auth when type isn't one of the supported set", () => {+ const manifestJson = JSON.stringify({+ client: { base_url: 'https://x', auth: { type: 'oauth' } },+ resources: [{ name: 'r', endpoint: { path: '/r' } }],+ })+ const state = parseManifestIntoState(manifestJson)+ expect(state.auth_type).toBe('none')+ })++ it.each(['query', 'cookie'] as const)('parses api_key location=%s out of the manifest', (location) => {+ const manifestJson = JSON.stringify({+ client: { base_url: 'https://x', auth: { type: 'api_key', name: 'k', location } },+ resources: [{ name: 'r', endpoint: { path: '/r' } }],+ })+ const state = parseManifestIntoState(manifestJson)+ expect(state.auth_api_key_location).toBe(location)+ })++ it("folds the dead 'param' alias to 'query' on parse", () => {+ // Backend treats both as the same (auth.py:41), so the UI never has to+ // distinguish them. A manifest authored elsewhere should still parse.+ const manifestJson = JSON.stringify({+ client: { base_url: 'https://x', auth: { type: 'api_key', name: 'k', location: 'param' } },+ resources: [{ name: 'r', endpoint: { path: '/r' } }],+ })+ const state = parseManifestIntoState(manifestJson)+ expect(state.auth_api_key_location).toBe('query')+ })++ it('parses the auto paginator type when the manifest declares it', () => {+ const manifestJson = JSON.stringify({+ client: { base_url: 'https://x' },+ resources: [{ name: 'r', endpoint: { path: '/r', paginator: { type: 'auto' } } }],+ })+ const state = parseManifestIntoState(manifestJson)+ expect(state.streams[0].paginator.type).toBe('auto')+ })++ it.each(['date', 'timestamp', 'integer'] as const)(+ 'parses cursor_type=%s from incremental config',+ (cursorType) => {+ const manifestJson = JSON.stringify({+ client: { base_url: 'https://x' },+ resources: [+ {+ name: 'r',+ endpoint: { path: '/r', incremental: { cursor_path: 'c', cursor_type: cursorType } },+ },+ ],+ })+ const state = parseManifestIntoState(manifestJson)+ expect(state.streams[0].cursor_type).toBe(cursorType)+ }+ )++ it('falls back to datetime cursor_type for an unknown value', () => {+ const manifestJson = JSON.stringify({+ client: { base_url: 'https://x' },+ resources: [+ {+ name: 'r',+ endpoint: { path: '/r', incremental: { cursor_path: 'c', cursor_type: 'bogus' } },+ },+ ],+ })+ const state = parseManifestIntoState(manifestJson)+ expect(state.streams[0].cursor_type).toBe('datetime')+ })++ it.each(['asc', 'desc'] as const)('parses sort_mode=%s from the resource', (mode) => {+ const manifestJson = JSON.stringify({+ client: { base_url: 'https://x' },+ resources: [{ name: 'r', endpoint: { path: '/r' }, sort_mode: mode }],+ })+ const state = parseManifestIntoState(manifestJson)+ expect(state.streams[0].sort_mode).toBe(mode)+ })++ it('round-trips all new fields without drift', () => {+ const original = baseState()+ original.auth_type = 'api_key'+ original.auth_api_key_name = 'X-Key'+ original.auth_api_key_location = 'query'+ original.streams = [+ {+ id: 'stream-events',+ name: 'events',+ path: '/events',+ method: 'GET',+ data_selector: 'data',+ primary_key: 'id',+ paginator: { type: 'auto' },+ sort_mode: 'desc',+ incremental_enabled: true,+ cursor_path: 'updated_at',+ cursor_type: 'timestamp',+ start_param: 'since',+ },+ ]++ const firstJson = JSON.stringify(buildManifest(original))+ const secondJson = JSON.stringify(buildManifest(parseManifestIntoState(firstJson)))+ expect(secondJson).toBe(firstJson)+ })+})++describe('extractAuthSecrets', () => {+ it('returns only the bearer token for bearer auth', () => {+ const state = baseState()+ state.auth_type = 'bearer'+ state.auth_token = 'tok_123'+ expect(extractAuthSecrets(state)).toEqual({ auth_token: 'tok_123', auth_api_key: '', auth_password: '' })+ })++ it('returns only the api key for api_key auth', () => {+ const state = baseState()+ state.auth_type = 'api_key'+ state.auth_api_key = 'sk_test'+ expect(extractAuthSecrets(state)).toEqual({ auth_token: '', auth_api_key: 'sk_test', auth_password: '' })+ })++ it('returns only the password for http_basic auth', () => {+ const state = baseState()+ state.auth_type = 'http_basic'+ state.auth_password = 'hunter2'+ expect(extractAuthSecrets(state)).toEqual({ auth_token: '', auth_api_key: '', auth_password: 'hunter2' })+ })++ it('returns all-empty for none auth, ignoring stale credential state', () => {+ const state = baseState()+ state.auth_type = 'none'+ // All three stale so each ternary's false-arm is genuinely exercised.+ state.auth_token = 'tok_123'+ state.auth_api_key = 'sk_test'+ state.auth_password = 'hunter2'+ expect(extractAuthSecrets(state)).toEqual({ auth_token: '', auth_api_key: '', auth_password: '' })+ })+})diff --git a/products/data_warehouse/frontend/shared/components/forms/__tests__/customSourceManifestBuilderLogic.test.ts b/products/data_warehouse/frontend/shared/components/forms/__tests__/customSourceManifestBuilderLogic.test.tsnew file mode 100644index 000000000000..065dfe9ca606--- /dev/null+++ b/products/data_warehouse/frontend/shared/components/forms/__tests__/customSourceManifestBuilderLogic.test.ts@@ -0,0 +1,160 @@+import { expectLogic } from 'kea-test-utils'++import { initKeaTests } from '~/test/init'++import { parseManifestIntoState } from '../customSourceManifest'+import { customSourceManifestBuilderLogic } from '../customSourceManifestBuilderLogic'++const savedManifest = JSON.stringify({+ client: { base_url: 'https://saved.example.com', auth: { type: 'bearer' } },+ resources: [{ name: 'users', primary_key: 'id', endpoint: { path: '/users', data_selector: 'data' } }],+})++const pushedFields = (setValue: jest.Mock): Record<string, unknown> =>+ Object.fromEntries(setValue.mock.calls.map(([path, value]) => [(path as (string | number)[]).join('.'), value]))++describe('customSourceManifestBuilderLogic', () => {+ let logic: ReturnType<typeof customSourceManifestBuilderLogic.build>+ let setValue: jest.Mock++ beforeEach(() => {+ initKeaTests()+ setValue = jest.fn()+ })++ afterEach(() => {+ logic?.unmount()+ })++ describe('wizard mode (no initial manifest)', () => {+ beforeEach(() => {+ logic = customSourceManifestBuilderLogic({ setValue })+ logic.mount()+ })++ it('does not touch the outer form before the user edits', () => {+ expect(setValue).not.toHaveBeenCalled()+ expect(logic.values.hasContent).toBe(false)+ })++ it('pushes the manifest and secret fields once the user edits', async () => {+ await expectLogic(logic, () => {+ logic.actions.updateState({ base_url: 'https://api.example.com' })+ })+ .toDispatchActions(['updateState'])+ .toMatchValues({ hasContent: true })++ const pushed = pushedFields(setValue)+ expect(JSON.parse(pushed['payload.manifest_json'] as string).client.base_url).toBe(+ 'https://api.example.com'+ )+ expect(pushed['payload.auth_token']).toBe('')+ expect(pushed['payload.auth_api_key']).toBe('')+ expect(pushed['payload.auth_password']).toBe('')+ })++ it('routes a bearer token to the secret field, never into the manifest', () => {+ logic.actions.updateState({ auth_type: 'bearer', auth_token: 'tok_secret' })++ const pushed = pushedFields(setValue)+ expect(pushed['payload.auth_token']).toBe('tok_secret')+ expect(pushed['payload.manifest_json']).not.toContain('tok_secret')+ })++ it('clears the bearer token in the outer form after switching auth away from bearer', () => {+ logic.actions.updateState({ auth_type: 'bearer', auth_token: 'tok_secret' })+ expect(pushedFields(setValue)['payload.auth_token']).toBe('tok_secret')++ logic.actions.updateState({ auth_type: 'api_key' })+ expect(pushedFields(setValue)['payload.auth_token']).toBe('')+ })+ })++ describe('configuration page (initial manifest present)', () => {+ beforeEach(() => {+ logic = customSourceManifestBuilderLogic({ setValue, initialManifestJson: savedManifest })+ logic.mount()+ })++ it('parses the saved manifest into form state on mount', () => {+ expect(logic.values.hasContent).toBe(true)+ expect(logic.values.manifestState.base_url).toBe('https://saved.example.com')+ expect(logic.values.manifestState.streams[0].name).toBe('users')+ })++ it('mirrors the saved manifest into the outer form on mount', () => {+ const pushed = pushedFields(setValue)+ expect(JSON.parse(pushed['payload.manifest_json'] as string).client.base_url).toBe(+ 'https://saved.example.com'+ )+ })+ })++ describe('manifest re-parse (the propsChanged path)', () => {+ beforeEach(() => {+ logic = customSourceManifestBuilderLogic({ setValue })+ logic.mount()+ })++ it('replaces form state and unblocks the outer-form sync', () => {+ expect(logic.values.manifestState.base_url).toBe('')++ logic.actions.setManifestState(parseManifestIntoState(savedManifest))++ expect(logic.values.manifestState.base_url).toBe('https://saved.example.com')+ expect(logic.values.hasContent).toBe(true)+ expect(Object.keys(pushedFields(setValue))).toContain('payload.manifest_json')+ })++ it('does not clobber in-progress user edits when initialManifestJson arrives late', () => {+ // User types something before the job_inputs poll lands.+ logic.actions.updateState({ base_url: 'https://user-typed.example.com' })+ expect(logic.values.userHasEdited).toBe(true)++ // Poll lands — the props update should be ignored because the user has edits.+ customSourceManifestBuilderLogic({ setValue, initialManifestJson: savedManifest })++ expect(logic.values.manifestState.base_url).toBe('https://user-typed.example.com')+ })++ it('hydrates from a late-arriving initialManifestJson when the user has not edited yet', () => {+ expect(logic.values.userHasEdited).toBe(false)+ customSourceManifestBuilderLogic({ setValue, initialManifestJson: savedManifest })++ expect(logic.values.manifestState.base_url).toBe('https://saved.example.com')+ })+ })++ describe('stream and header mutations', () => {+ beforeEach(() => {+ logic = customSourceManifestBuilderLogic({ setValue })+ logic.mount()+ })++ it('adds and removes streams', () => {+ expect(logic.values.manifestState.streams).toHaveLength(1)+ logic.actions.addStream()+ expect(logic.values.manifestState.streams).toHaveLength(2)+ logic.actions.removeStream(0)+ expect(logic.values.manifestState.streams).toHaveLength(1)+ })++ it('updates a stream paginator by index', () => {+ logic.actions.updatePaginator(0, { type: 'cursor', cursor_path: 'meta.next', cursor_param: 'after' })+ expect(logic.values.manifestState.streams[0].paginator).toEqual({+ type: 'cursor',+ cursor_path: 'meta.next',+ cursor_param: 'after',+ })+ })++ it('adds, edits, and removes headers', () => {+ logic.actions.addHeader()+ logic.actions.updateHeader(0, { key: 'X-Workspace', value: 'acme' })+ expect(logic.values.manifestState.headers).toMatchObject([{ key: 'X-Workspace', value: 'acme' }])+ expect(logic.values.manifestState.headers[0].id).toBeTruthy()+ logic.actions.removeHeader(0)+ expect(logic.values.manifestState.headers).toEqual([])+ })+ })+})diff --git a/products/data_warehouse/frontend/shared/components/forms/customSourceManifest.ts b/products/data_warehouse/frontend/shared/components/forms/customSourceManifest.tsnew file mode 100644index 000000000000..90f427e85675--- /dev/null+++ b/products/data_warehouse/frontend/shared/components/forms/customSourceManifest.ts@@ -0,0 +1,365 @@+// Pure serialization layer for the Custom REST source manifest builder. Holds no+// React or kea state — `customSourceManifestBuilderLogic` owns the form state and+// `CustomSourceManifestBuilder` renders it. Keeping these functions pure makes the+// build ⇄ parse round-trip directly unit-testable.++// Each enum-like value set is declared once as an `as const` tuple; the union type+// and the runtime guard (via `isMember`) are derived from it, so the allowed values+// can't drift between the type, the parser, and the component's select options.+export const AUTH_TYPES = ['none', 'bearer', 'api_key', 'http_basic'] as const+export type AuthType = (typeof AUTH_TYPES)[number]++// The backend treats 'query' and 'param' as synonymous (auth.py:41), so we+// only surface 'query' in the UI — the parser still accepts 'param' for+// manifests authored elsewhere.+export const API_KEY_LOCATIONS = ['header', 'query', 'cookie'] as const+export type ApiKeyLocation = (typeof API_KEY_LOCATIONS)[number]++export const PAGINATOR_TYPES = [+ 'auto',+ 'single_page',+ 'json_response',+ 'cursor',+ 'offset',+ 'page_number',+ 'header_link',+] as const+export type PaginatorType = (typeof PAGINATOR_TYPES)[number]++export type Paginator =+ | { type: 'auto' }+ | { type: 'single_page' }+ | { type: 'json_response'; next_url_path?: string }+ | { type: 'cursor'; cursor_path?: string; cursor_param?: string }+ | { type: 'offset'; limit?: number; offset_param?: string; limit_param?: string }+ | { type: 'page_number'; page_param?: string; base_page?: number }+ | { type: 'header_link'; links_next_key?: string }++// Backend IncrementalFieldType values that make sense for REST cursors.+// numeric/objectid are warehouse-specific and intentionally omitted.+export const CURSOR_TYPES = ['datetime', 'date', 'timestamp', 'integer'] as const+export type CursorType = (typeof CURSOR_TYPES)[number]++export const SORT_MODES = ['asc', 'desc'] as const+export type SortMode = (typeof SORT_MODES)[number]++// Default field values per paginator type — the single source shared by+// `serializePaginator` (build-time fallbacks), the form's paginator type-switch,+// and the input placeholders, so a default can't drift between them.+export const PAGINATOR_DEFAULTS = {+ json_response: { next_url_path: 'links.next' },+ cursor: { cursor_path: 'meta.next_cursor', cursor_param: 'cursor' },+ offset: { limit: 100, offset_param: 'offset', limit_param: 'limit' },+ page_number: { page_param: 'page', base_page: 1 },+ header_link: { links_next_key: 'next' },+} as const++function isMember<T extends string>(values: readonly T[], value: string): value is T {+ return (values as readonly string[]).includes(value)+}++// Stable client-only ids so React lists keep input/focus state attached to the+// right row across mid-list removals. Never serialized into the manifest.+let streamIdSeq = 0+let headerIdSeq = 0+export function nextStreamId(): string {+ return `stream-${streamIdSeq++}`+}+export function nextHeaderId(): string {+ return `header-${headerIdSeq++}`+}++export interface HeaderEntry {+ id: string+ key: string+ value: string+}++export interface StreamForm {+ id: string+ name: string+ path: string+ method: 'GET' | 'POST'+ data_selector: string+ primary_key: string+ paginator: Paginator+ sort_mode: SortMode+ incremental_enabled: boolean+ cursor_path: string+ cursor_type: CursorType+ start_param: string+}++export interface ManifestState {+ base_url: string+ auth_type: AuthType+ auth_token: string+ auth_api_key: string+ auth_api_key_name: string+ auth_api_key_location: ApiKeyLocation+ auth_username: string+ auth_password: string+ headers: HeaderEntry[]+ streams: StreamForm[]+}++export interface AuthSecrets {+ auth_token: string+ auth_api_key: string+ auth_password: string+}++export function emptyHeader(): HeaderEntry {+ return { id: nextHeaderId(), key: '', value: '' }+}++export function emptyStream(): StreamForm {+ return {+ id: nextStreamId(),+ name: '',+ path: '',+ method: 'GET',+ data_selector: 'data',+ primary_key: 'id',+ paginator: { type: 'single_page' },+ sort_mode: 'asc',+ incremental_enabled: false,+ cursor_path: '',+ cursor_type: 'datetime',+ start_param: '',+ }+}++export function defaultState(): ManifestState {+ return {+ base_url: '',+ auth_type: 'bearer',+ auth_token: '',+ auth_api_key: '',+ auth_api_key_name: 'Authorization',+ auth_api_key_location: 'header',+ auth_username: '',+ auth_password: '',+ headers: [],+ streams: [emptyStream()],+ }+}++export function buildManifest(state: ManifestState): Record<string, unknown> {+ const headerEntries = state.headers.filter((h) => h.key.trim().length > 0)+ const headerMap: Record<string, string> = {}+ for (const entry of headerEntries) {+ headerMap[entry.key.trim()] = entry.value+ }++ // Auth carries only NON-secret fields. The credential values (token /+ // api_key / password) are written to separate secret form fields by+ // `extractAuthSecrets` so the backend can redact them generically.+ const auth: Record<string, unknown> | undefined = (() => {+ switch (state.auth_type) {+ case 'bearer':+ return { type: 'bearer' }+ case 'api_key':+ return {+ type: 'api_key',+ name: state.auth_api_key_name,+ location: state.auth_api_key_location,+ }+ case 'http_basic':+ return { type: 'http_basic', username: state.auth_username }+ default:+ return undefined+ }+ })()++ const client: Record<string, unknown> = { base_url: state.base_url }+ if (auth) {+ client.auth = auth+ }+ if (Object.keys(headerMap).length > 0) {+ client.headers = headerMap+ }++ const resources = state.streams.map((stream) => {+ const endpoint: Record<string, unknown> = {+ path: stream.path,+ data_selector: stream.data_selector || 'data',+ }+ if (stream.method !== 'GET') {+ endpoint.method = stream.method+ }+ endpoint.paginator = serializePaginator(stream.paginator)+ if (stream.incremental_enabled && stream.cursor_path.trim()) {+ const incremental: Record<string, unknown> = {+ cursor_path: stream.cursor_path.trim(),+ start_param: stream.start_param.trim() || stream.cursor_path.trim(),+ }+ // Only emit cursor_type when it differs from the backend default+ // (datetime) — keeps round-tripped manifests minimal. The Custom+ // source reads it for incremental-field typing and strips it before+ // the REST engine builds its Incremental tracker.+ if (stream.cursor_type !== 'datetime') {+ incremental.cursor_type = stream.cursor_type+ }+ endpoint.incremental = incremental+ }+ const primaryKeys = stream.primary_key+ .split(',')+ .map((part) => part.trim())+ .filter(Boolean)+ const resource: Record<string, unknown> = {+ name: stream.name,+ // Fall back to 'id' when the field is cleared — an empty primary_key+ // array produces a broken resource downstream.+ primary_key: primaryKeys.length === 0 ? 'id' : primaryKeys.length === 1 ? primaryKeys[0] : primaryKeys,+ endpoint,+ }+ // sort_mode only affects incremental resume safety. Emit only when the+ // user explicitly opts into descending order — backend default is asc.+ if (stream.sort_mode === 'desc') {+ resource.sort_mode = 'desc'+ }+ return resource+ })++ return { client, resources }+}++/**+ * The credential values for the currently selected auth type. These are+ * written to separate secret form fields (`payload.auth_*`), never inlined+ * into the manifest — so the backend redacts them with the generic+ * sensitive-field machinery. Non-active auth types yield empty strings.+ */+export function extractAuthSecrets(state: ManifestState): AuthSecrets {+ return {+ auth_token: state.auth_type === 'bearer' ? state.auth_token : '',+ auth_api_key: state.auth_type === 'api_key' ? state.auth_api_key : '',+ auth_password: state.auth_type === 'http_basic' ? state.auth_password : '',+ }+}++function serializePaginator(paginator: Paginator): Record<string, unknown> {+ switch (paginator.type) {+ case 'auto':+ return { type: 'auto' }+ case 'json_response':+ return {+ type: 'json_response',+ next_url_path: paginator.next_url_path || PAGINATOR_DEFAULTS.json_response.next_url_path,+ }+ case 'cursor':+ return {+ type: 'cursor',+ cursor_path: paginator.cursor_path || PAGINATOR_DEFAULTS.cursor.cursor_path,+ cursor_param: paginator.cursor_param || PAGINATOR_DEFAULTS.cursor.cursor_param,+ }+ case 'offset':+ return {+ type: 'offset',+ limit: paginator.limit ?? PAGINATOR_DEFAULTS.offset.limit,+ offset_param: paginator.offset_param || PAGINATOR_DEFAULTS.offset.offset_param,+ limit_param: paginator.limit_param || PAGINATOR_DEFAULTS.offset.limit_param,+ }+ case 'page_number':+ return {+ type: 'page_number',+ page_param: paginator.page_param || PAGINATOR_DEFAULTS.page_number.page_param,+ // base_page is the PageNumberPaginator constructor arg the REST+ // engine expects — initial_page would raise an unexpected-kwarg error.+ base_page: paginator.base_page ?? PAGINATOR_DEFAULTS.page_number.base_page,+ }+ case 'header_link':+ return {+ type: 'header_link',+ links_next_key: paginator.links_next_key || PAGINATOR_DEFAULTS.header_link.links_next_key,+ }+ case 'single_page':+ default:+ return { type: 'single_page' }+ }+}++type RawObject = Record<string, unknown>++function asObject(value: unknown): RawObject {+ return typeof value === 'object' && value !== null ? (value as RawObject) : {}+}++function asString(value: unknown, fallback = ''): string {+ return typeof value === 'string' ? value : fallback+}++export function parseManifestIntoState(rawJson: string | undefined): ManifestState {+ if (!rawJson) {+ return defaultState()+ }+ let parsed: unknown+ try {+ parsed = JSON.parse(rawJson)+ } catch {+ return defaultState()+ }+ const manifest = asObject(parsed)+ const client = asObject(manifest.client)+ const auth = asObject(client.auth)+ const authTypeRaw = asString(auth.type)+ // 'none' is the fallback for any unsupported auth type; it carries no+ // credential fields so the token/api_key/password reads below stay empty.+ const authType: AuthType = isMember(AUTH_TYPES, authTypeRaw) ? authTypeRaw : 'none'+ // Backend treats 'param' as a synonym for 'query' — fold it back so the+ // UI never has to surface the dead alias.+ const rawLocation = asString(auth.location, 'header')+ const normalizedLocation = rawLocation === 'param' ? 'query' : rawLocation+ const apiKeyLocation: ApiKeyLocation = isMember(API_KEY_LOCATIONS, normalizedLocation)+ ? normalizedLocation+ : 'header'+ const headerObj = asObject(client.headers)+ const headers: HeaderEntry[] = Object.entries(headerObj).map(([key, value]) => ({+ id: nextHeaderId(),+ key,+ value: String(value),+ }))+ const resources: unknown[] = Array.isArray(manifest.resources) ? manifest.resources : []+ const streams: StreamForm[] = resources.length > 0 ? resources.map(parseStream) : [emptyStream()]+ return {+ base_url: asString(client.base_url),+ auth_type: authType,+ auth_token: asString(auth.token),+ auth_api_key: asString(auth.api_key),+ auth_api_key_name: asString(auth.name, 'Authorization'),+ auth_api_key_location: apiKeyLocation,+ auth_username: asString(auth.username),+ auth_password: asString(auth.password),+ headers,+ streams,+ }+}++function parseStream(resource: unknown): StreamForm {+ const r = asObject(resource)+ const endpoint = asObject(r.endpoint)+ const paginatorRaw = asObject(endpoint.paginator)+ const paginatorType = asString(paginatorRaw.type)+ const paginator: Paginator = isMember(PAGINATOR_TYPES, paginatorType)+ ? (paginatorRaw as Paginator)+ : { type: 'single_page' }+ const incremental = asObject(endpoint.incremental)+ const cursorTypeRaw = asString(incremental.cursor_type, 'datetime')+ const cursorType: CursorType = isMember(CURSOR_TYPES, cursorTypeRaw) ? cursorTypeRaw : 'datetime'+ const primaryKey = r.primary_key+ return {+ id: nextStreamId(),+ name: asString(r.name),+ path: asString(endpoint.path),+ method: asString(endpoint.method) === 'POST' ? 'POST' : 'GET',+ data_selector: asString(endpoint.data_selector, 'data'),+ primary_key: Array.isArray(primaryKey) ? primaryKey.join(', ') : asString(primaryKey, 'id'),+ paginator,+ sort_mode: asString(r.sort_mode) === 'desc' ? 'desc' : 'asc',+ incremental_enabled: !!endpoint.incremental,+ cursor_path: asString(incremental.cursor_path),+ cursor_type: cursorType,+ start_param: asString(incremental.start_param),+ }+}diff --git a/products/data_warehouse/frontend/shared/components/forms/customSourceManifestBuilderLogic.ts b/products/data_warehouse/frontend/shared/components/forms/customSourceManifestBuilderLogic.tsnew file mode 100644index 000000000000..3ac90dc02f89--- /dev/null+++ b/products/data_warehouse/frontend/shared/components/forms/customSourceManifestBuilderLogic.ts@@ -0,0 +1,202 @@+import {+ actions,+ afterMount,+ kea,+ listeners,+ path,+ props,+ propsChanged,+ reducers,+ selectors,+ sharedListeners,+} from 'kea'+import type { FieldName } from 'kea-forms'++import {+ buildManifest,+ emptyHeader,+ emptyStream,+ extractAuthSecrets,+ type HeaderEntry,+ type ManifestState,+ type Paginator,+ parseManifestIntoState,+ type StreamForm,+} from './customSourceManifest'+import type { customSourceManifestBuilderLogicType } from './customSourceManifestBuilderLogicType'++export interface CustomSourceManifestBuilderLogicProps {+ /** Saved manifest JSON, supplied on the configuration page; undefined in the wizard. */+ initialManifestJson?: string+ /**+ * Writes a value into the outer source form. The mount site differs: the+ * wizard passes `sourceWizardLogic.actions.setSourceConnectionDetailsValue`,+ * the configuration page passes `sourceSettingsLogic.actions.setSourceConfigValue`.+ * Both accept a `(path, value)` signature.+ */+ setValue: (path: FieldName, value: unknown) => void+}++/**+ * Owns the Custom REST source's manifest-builder form state (base URL, auth,+ * headers, streams) and mirrors it into the outer source form as+ * `payload.manifest_json` (the non-secret RESTAPIConfig structure) plus separate+ * `payload.auth_*` secret fields for the credentials.+ *+ * The backend rejoins the two before handing the config to `rest_api_resource()`.+ * Keeping credentials out of the manifest lets the generic API layer redact them+ * with no Custom-source-specific serializer code.+ */+// Intentionally keyless (singleton): the wizard and the configuration tab are+// separate scenes and never mounted at the same time, so kea's mount refcount+// drops to zero between them and `manifestState` / `userHasEdited` reset from+// props on the next mount. If a future caller keeps this logic mounted across+// that transition (e.g. a persistent parent or a second consumer), add a `key()`+// — otherwise the latched `userHasEdited` would make `propsChanged` skip+// re-parsing the new manifest.+export const customSourceManifestBuilderLogic = kea<customSourceManifestBuilderLogicType>([+ props({} as CustomSourceManifestBuilderLogicProps),+ path(['products', 'dataWarehouse', 'customSourceManifestBuilderLogic']),+ actions({+ setManifestState: (state: ManifestState) => ({ state }),+ updateState: (patch: Partial<ManifestState>) => ({ patch }),+ updateStream: (index: number, patch: Partial<StreamForm>) => ({ index, patch }),+ updatePaginator: (index: number, paginator: Paginator) => ({ index, paginator }),+ addStream: true,+ removeStream: (index: number) => ({ index }),+ addHeader: true,+ removeHeader: (index: number) => ({ index }),+ updateHeader: (index: number, patch: Partial<HeaderEntry>) => ({ index, patch }),+ // Fires the push listener without changing state — used on mount to mirror the+ // already-parsed initial manifest into the outer form without re-parsing.+ syncToOuterForm: true,+ // UI-only: tracks the generated-manifest <details> disclosure so the+ // CodeSnippet (and its syntax highlighting) only renders while expanded.+ setManifestPreviewOpen: (open: boolean) => ({ open }),+ }),+ reducers(({ props }) => ({+ manifestState: [+ parseManifestIntoState(props.initialManifestJson),+ {+ setManifestState: (_, { state }) => state,+ updateState: (state, { patch }) => ({ ...state, ...patch }),+ updateStream: (state, { index, patch }) => ({+ ...state,+ streams: state.streams.map((stream, i) => (i === index ? { ...stream, ...patch } : stream)),+ }),+ updatePaginator: (state, { index, paginator }) => ({+ ...state,+ streams: state.streams.map((stream, i) => (i === index ? { ...stream, paginator } : stream)),+ }),+ addStream: (state) => ({ ...state, streams: [...state.streams, emptyStream()] }),+ removeStream: (state, { index }) => ({+ ...state,+ streams: state.streams.filter((_, i) => i !== index),+ }),+ addHeader: (state) => ({ ...state, headers: [...state.headers, emptyHeader()] }),+ removeHeader: (state, { index }) => ({+ ...state,+ headers: state.headers.filter((_, i) => i !== index),+ }),+ updateHeader: (state, { index, patch }) => ({+ ...state,+ headers: state.headers.map((header, i) => (i === index ? { ...header, ...patch } : header)),+ }),+ },+ ],+ // Gates `pushManifestToOuterForm`: stays false until either an initial+ // manifest arrives or the user edits. Without it the configuration page+ // would clobber the saved manifest with empty defaults on the render+ // between mount and the `job_inputs` poll landing.+ hasContent: [+ Boolean(props.initialManifestJson),+ {+ setManifestState: () => true,+ updateState: () => true,+ updateStream: () => true,+ updatePaginator: () => true,+ addStream: () => true,+ removeStream: () => true,+ addHeader: () => true,+ removeHeader: () => true,+ updateHeader: () => true,+ },+ ],+ // Flips true the moment the user touches any field. Distinct from `hasContent`+ // because we need `propsChanged` to know "was this state edited by the user, or+ // just hydrated from props?" — without it, a late-arriving `job_inputs` poll+ // would silently overwrite in-progress edits.+ userHasEdited: [+ false,+ {+ updateState: () => true,+ updateStream: () => true,+ updatePaginator: () => true,+ addStream: () => true,+ removeStream: () => true,+ addHeader: () => true,+ removeHeader: () => true,+ updateHeader: () => true,+ },+ ],+ manifestPreviewOpen: [+ false,+ {+ setManifestPreviewOpen: (_, { open }) => open,+ },+ ],+ })),+ selectors({+ manifestJson: [(s) => [s.manifestState], (state): string => JSON.stringify(buildManifest(state), null, 2)],+ authSecrets: [(s) => [s.manifestState], (state) => extractAuthSecrets(state)],+ }),+ sharedListeners(({ values, props }) => ({+ pushManifestToOuterForm: () => {+ if (!values.hasContent) {+ return+ }+ props.setValue(['payload', 'manifest_json'] as FieldName, values.manifestJson)+ // Secrets go to their own fields so the backend redacts them generically;+ // the manifest itself stays non-secret and round-trips to the config tab.+ props.setValue(['payload', 'auth_token'] as FieldName, values.authSecrets.auth_token)+ props.setValue(['payload', 'auth_api_key'] as FieldName, values.authSecrets.auth_api_key)+ props.setValue(['payload', 'auth_password'] as FieldName, values.authSecrets.auth_password)+ },+ })),+ // Every state mutation re-pushes the serialized manifest + secrets to the+ // outer form — this replaces the effect that watched the derived values.+ listeners(({ sharedListeners }) => ({+ setManifestState: sharedListeners.pushManifestToOuterForm,+ updateState: sharedListeners.pushManifestToOuterForm,+ updateStream: sharedListeners.pushManifestToOuterForm,+ updatePaginator: sharedListeners.pushManifestToOuterForm,+ addStream: sharedListeners.pushManifestToOuterForm,+ removeStream: sharedListeners.pushManifestToOuterForm,+ addHeader: sharedListeners.pushManifestToOuterForm,+ removeHeader: sharedListeners.pushManifestToOuterForm,+ updateHeader: sharedListeners.pushManifestToOuterForm,+ syncToOuterForm: sharedListeners.pushManifestToOuterForm,+ })),+ afterMount(({ actions, props }) => {+ // The reducer already parsed `initialManifestJson` at mount, but the listeners+ // that push to the outer form only fire on actions. Dispatch a no-op sync so+ // the configuration page reflects the saved manifest even before the user edits.+ // The wizard mounts with no manifest — a no-op there.+ if (props.initialManifestJson) {+ actions.syncToOuterForm()+ }+ }),+ propsChanged(({ actions, values, props }, oldProps) => {+ // The configuration page loads `source.job_inputs` via a poll, so the+ // manifest typically arrives a beat after mount. Re-parse on a real value+ // change — but only when the user hasn't started editing yet, so a+ // late-arriving poll doesn't wipe in-progress edits.+ if (+ !values.userHasEdited &&+ props.initialManifestJson !== oldProps.initialManifestJson &&+ props.initialManifestJson+ ) {+ actions.setManifestState(parseManifestIntoState(props.initialManifestJson))+ }+ }),+])