@datadog/apps-frontend 0.0.4 → 0.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +38 -5
  2. package/dist/src/_chunks/chunk-3UFPUAWY.js +7 -0
  3. package/dist/src/_chunks/chunk-3UFPUAWY.js.map +7 -0
  4. package/dist/src/_chunks/chunk-627KNBXP.js +7 -0
  5. package/dist/src/_chunks/chunk-627KNBXP.js.map +7 -0
  6. package/dist/src/_chunks/{chunk-T34NWJ7R.js → chunk-G2SXTUX4.js} +2 -2
  7. package/dist/src/_chunks/chunk-G2SXTUX4.js.map +7 -0
  8. package/dist/src/_chunks/{chunk-X34MSTJH.js → chunk-LEEYMNMO.js} +2 -2
  9. package/dist/src/_chunks/{chunk-X34MSTJH.js.map → chunk-LEEYMNMO.js.map} +3 -3
  10. package/dist/src/_chunks/chunk-MF7HCOXQ.js +7 -0
  11. package/dist/src/_chunks/chunk-MF7HCOXQ.js.map +7 -0
  12. package/dist/src/_chunks/chunk-PA4Z7DNH.js +7 -0
  13. package/dist/src/_chunks/chunk-PA4Z7DNH.js.map +7 -0
  14. package/dist/src/_chunks/chunk-QOXXZE7D.js +7 -0
  15. package/dist/src/_chunks/chunk-QOXXZE7D.js.map +7 -0
  16. package/dist/src/_chunks/chunk-VVRISDII.js +7 -0
  17. package/dist/src/_chunks/chunk-VVRISDII.js.map +7 -0
  18. package/dist/src/apps-provider.d.ts +51 -0
  19. package/dist/src/deep-links/react/index.d.ts +18 -0
  20. package/dist/src/deep-links/react/index.js +7 -0
  21. package/dist/src/deep-links/react/index.js.map +7 -0
  22. package/dist/src/druids/react/druids-environment-with-theme-input.d.ts +46 -0
  23. package/dist/src/druids/react/index.d.ts +7 -0
  24. package/dist/src/druids/react/index.js +7 -0
  25. package/dist/src/druids/react/index.js.map +7 -0
  26. package/dist/src/embedding/react/config.d.ts +62 -0
  27. package/dist/src/embedding/react/index.d.ts +2 -0
  28. package/dist/src/embedding/react/index.js +1 -1
  29. package/dist/src/embedding/react/index.js.map +4 -4
  30. package/dist/src/embedding/react/provider.d.ts +36 -2
  31. package/dist/src/embedding/types.d.ts +2 -3
  32. package/dist/src/index.d.ts +2 -1
  33. package/dist/src/index.js +1 -0
  34. package/dist/src/index.js.map +4 -4
  35. package/dist/src/inputs/published-definition.d.ts +5 -1
  36. package/dist/src/inputs/react/index.js +1 -1
  37. package/dist/src/inputs/react/index.js.map +4 -4
  38. package/dist/src/inputs/schemas/index.js +1 -1
  39. package/dist/src/inputs/schemas/index.js.map +4 -4
  40. package/package.json +24 -1
  41. package/dist/src/_chunks/chunk-T34NWJ7R.js.map +0 -7
package/README.md CHANGED
@@ -6,17 +6,50 @@ Frontend capabilities for Datadog Apps.
6
6
  npm install @datadog/apps-frontend
7
7
  ```
8
8
 
9
- The package root intentionally exposes no runtime API; capabilities are reached
10
- through its subpath entries:
9
+ The package root exposes `DatadogAppsProvider` (see [Usage](#usage)); further
10
+ capabilities are reached through its subpath entries:
11
11
 
12
- - `@datadog/apps-frontend/embedding/react` — `DatadogAppProvider` connects an
13
- app to its host, and `useDatadogAppEmbedding` reads that connection's state.
12
+ - `@datadog/apps-frontend/embedding/react` — `DatadogAppProvider`
13
+ connects an app to its host, and `useDatadogAppEmbedding` reads that
14
+ connection's state.
14
15
  - `@datadog/apps-frontend/inputs/react` — `useDatadogAppInput` reads a typed
15
16
  input the host provides.
16
17
  - `@datadog/apps-frontend/inputs/schema` — the input schemas themselves, such
17
18
  as `datadogTheme` and `datadogDashboard`, passed to `useDatadogAppInput`.
18
19
 
19
- React 18 and 19 are supported as peer dependencies.
20
+ ## Usage
21
+
22
+ Mount the composite provider near your app root; it installs this package's
23
+ default modules and shares one embedding connection with every module hook
24
+ beneath it:
25
+
26
+ ```tsx
27
+ import { DatadogAppsProvider } from '@datadog/apps-frontend';
28
+
29
+ export function App() {
30
+ return <DatadogAppsProvider>{/* app UI */}</DatadogAppsProvider>;
31
+ }
32
+ ```
33
+
34
+ Additional modules are installed by passing them in `modules`. A module is a
35
+ startup capability, not a UI layer: on mount the provider runs each one's
36
+ `install` with the shared connection and a dispose signal, and the app's UI
37
+ renders untouched:
38
+
39
+ ```tsx
40
+ <DatadogAppsProvider modules={[someModule({ option: true })]}>
41
+ {/* app UI */}
42
+ </DatadogAppsProvider>
43
+ ```
44
+
45
+ `disabledModules` accepts exactly the ids of this package's default modules —
46
+ type-checked and autocompleted from the default set, so a misspelled id is a
47
+ compile error. Deep links (`'datadog.deep-links'`) is installed by default and
48
+ can be excluded when an app must opt out. At runtime an unknown id only warns,
49
+ so a frozen app compiled against an older default set keeps rendering.
50
+
51
+ React 18 and 19 are supported as peer dependencies; `@datadog/druids` is an
52
+ optional peer, needed only by the `druids/react` entry.
20
53
 
21
54
  ## Development
22
55
 
@@ -0,0 +1,7 @@
1
+ /* Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0.
2
+ * This product includes software developed at Datadog (https://www.datadoghq.com/).
3
+ * Copyright 2019-Present Datadog, Inc.
4
+ */
5
+
6
+ import{a as m}from"./chunk-MF7HCOXQ.js";import{a as u,d as y,g as v}from"./chunk-PA4Z7DNH.js";import{J as g,K as f}from"./chunk-LEEYMNMO.js";var S=u(),L=y(),D=f({identifier:"datadog.deep-links",version:2,fields:{setDeepLinkState:g.readOnly({inputs:{search:S,fragment:S},result:L})}}),A=v(u(),u()),M=f({identifier:"datadog.deep-links",version:1,fields:{setDeepLinkVariables:g.readOnly({inputs:{variables:A,fragment:S},result:L})}});var k=Object.freeze({search:"",fragment:""});function C(){return typeof globalThis.location>"u"?k:Object.freeze({search:globalThis.location.search,fragment:globalThis.location.hash})}function T(a,e){console.error(`[datadog-apps:deep-links] ${a}`,e??"")}var i=null;function s(){b()}function E({search:a,fragment:e}){return JSON.stringify([a,e])}function b(a=!1){let e=i;if(e===null)return;let t=C(),n=E(t);!a&&e.lastPublishedFingerprint===n||(e.lastPublishedFingerprint=n,R(t))}function R(a){let e=i?.publishers;if(e===void 0)return;let t=e.values().next();t.done===!1&&t.value(a)}function V(a){let e=i?.publishers;if(e===void 0)return!1;let t=e.values().next();return t.done===!1&&t.value===a}function F(a){if(i!==null)return i.publishers.add(a),i;let e=globalThis.history,t=e.pushState,n=e.replaceState,c=new Set([a]),l=()=>{b()},o=function(r,d,h){t.call(e,r,d,h),l()},p=function(r,d,h){n.call(e,r,d,h),l()};try{e.pushState=o,e.replaceState=p,globalThis.addEventListener("popstate",s),globalThis.addEventListener("hashchange",s)}catch(r){throw e.replaceState===p&&(e.replaceState=n),e.pushState===o&&(e.pushState=t),globalThis.removeEventListener("popstate",s),globalThis.removeEventListener("hashchange",s),r}return i={pushState:o,replaceState:p,originalPushState:t,originalReplaceState:n,publishers:c,lastPublishedFingerprint:null},i}function x(a){let e=i;if(e===null||(e.publishers.delete(a),e.publishers.size>0))return;let t=globalThis.history;t.pushState===e.pushState&&(t.pushState=e.originalPushState),t.replaceState===e.replaceState&&(t.replaceState=e.originalReplaceState),globalThis.removeEventListener("popstate",s),globalThis.removeEventListener("hashchange",s),i=null}function P({embedding:a,disposeSignal:e}){if(e.aborted)return;let t=a.getClaim(D),n=({search:o,fragment:p})=>{let r=t.getSnapshot();r.status==="ready"&&r.fields.setDeepLinkState({search:o,fragment:p}).catch(d=>T("The app URL state could not be synchronized to the embedding host.",d))},c=o=>{o.status==="ready"&&V(n)&&b(!0)},l=t.subscribe(()=>{c(t.getSnapshot())});try{F(n)}catch(o){throw l(),o}c(t.getSnapshot()),e.addEventListener("abort",()=>{l(),x(n)},{once:!0})}var z=Object.freeze({});function Y(){return m("datadog.deep-links",z,{install({embedding:a,disposeSignal:e}){P({embedding:a,disposeSignal:e})}})}export{Y as a};
7
+ //# sourceMappingURL=chunk-3UFPUAWY.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/deep-links/internal/protocol.ts", "../../../src/deep-links/react/module-install.ts", "../../../src/deep-links/react/index.ts"],
4
+ "sourcesContent": ["import * as z from 'zod/mini';\n\nimport { defineContract, fn } from '../../embedding/contract';\nimport type {\n Contract,\n FunctionField,\n ValueSchema,\n} from '../../embedding/types';\n\nconst stringSchema: ValueSchema<string> = z.string();\nconst undefinedSchema: ValueSchema<undefined> = z.undefined();\n\n/**\n * A one-way mirror of the embedded app's query string and fragment. The host\n * stores the snapshot under `app-links-${id}` and seeds the iframe's starting\n * URL before first navigation. There is no host-to-app value field or ongoing\n * inbound synchronization.\n *\n * V2 carries `location.search` verbatim rather than a dictionary, preserving\n * repeated parameters, ordering, empty values, and encoding.\n */\nexport const datadogAppDeepLinksContract: Contract<{\n setDeepLinkState: FunctionField<\n Readonly<{\n search: ValueSchema<string>;\n fragment: ValueSchema<string>;\n }>,\n ValueSchema<undefined>\n >;\n}> = defineContract({\n identifier: 'datadog.deep-links',\n version: 2,\n fields: {\n setDeepLinkState: fn.readOnly({\n inputs: {\n search: stringSchema,\n fragment: stringSchema,\n },\n result: undefinedSchema,\n }),\n },\n});\n\nconst variablesSchema: ValueSchema<Readonly<Record<string, string>>> = z.record(\n z.string(),\n z.string(),\n);\n\n/** Retained for apps built with the original scalar-query guest runtime. */\nexport const datadogAppDeepLinksV1Contract: Contract<{\n setDeepLinkVariables: FunctionField<\n Readonly<{\n variables: ValueSchema<Readonly<Record<string, string>>>;\n fragment: ValueSchema<string>;\n }>,\n ValueSchema<undefined>\n >;\n}> = defineContract({\n identifier: 'datadog.deep-links',\n version: 1,\n fields: {\n setDeepLinkVariables: fn.readOnly({\n inputs: {\n variables: variablesSchema,\n fragment: stringSchema,\n },\n result: undefinedSchema,\n }),\n },\n});\n", "import type { AppEmbedding, ClaimState } from '../../embedding/types';\nimport { datadogAppDeepLinksContract } from '../internal/protocol';\n\ninterface AppLocationState {\n readonly search: string;\n readonly fragment: string;\n}\n\nconst EMPTY_LOCATION_STATE: AppLocationState = Object.freeze({\n search: '',\n fragment: '',\n});\n\n/**\n * There is no ambient `location` outside a browser (or this guest's iframe\n * realm), so reading it unconditionally would throw. Install only ever runs\n * from a provider effect in a browser, but a non-browser embedding\n * implementation is not forbidden from calling in, so the read stays guarded.\n */\nfunction currentLocationState(): AppLocationState {\n if (typeof globalThis.location === 'undefined') {\n return EMPTY_LOCATION_STATE;\n }\n return Object.freeze({\n search: globalThis.location.search,\n fragment: globalThis.location.hash,\n });\n}\n\nfunction reportDeepLinksError(message: string, error?: unknown): void {\n console.error(`[datadog-apps:deep-links] ${message}`, error ?? '');\n}\n\ntype Publish = (state: AppLocationState) => void;\n\n/**\n * Ref-counted, per-realm history patch. Sibling provider mounts share one\n * embedding connection but each installs this runtime; without coordination,\n * two patches would publish twice and an out-of-order unmount could restore\n * a stale method. One patch is installed on the first install and torn down\n * on the last dispose; every live install's publisher is kept in an ordered\n * set, so a navigation uses the first live claim and disposing that claim\n * falls back to the next remaining one rather than going silent.\n */\ninterface PatchState {\n readonly pushState: History['pushState'];\n readonly replaceState: History['replaceState'];\n readonly originalPushState: History['pushState'];\n readonly originalReplaceState: History['replaceState'];\n /** Live publishers in install order; the first is the active publisher. */\n readonly publishers: Set<Publish>;\n lastPublishedFingerprint: string | null;\n}\nlet patchState: PatchState | null = null;\n\n/**\n * One stable handler, registered once, that publishes through one claim.\n * Fragment-changing history traversal can emit both `popstate` and\n * `hashchange`; the shared location fingerprint suppresses the second event.\n */\nfunction onLocationChange(): void {\n publishCurrentLocation();\n}\n\nfunction locationStateFingerprint({\n search,\n fragment,\n}: AppLocationState): string {\n return JSON.stringify([search, fragment]);\n}\n\nfunction publishCurrentLocation(force = false): void {\n const state = patchState;\n if (state === null) {\n return;\n }\n const locationState = currentLocationState();\n const fingerprint = locationStateFingerprint(locationState);\n if (!force && state.lastPublishedFingerprint === fingerprint) {\n return;\n }\n state.lastPublishedFingerprint = fingerprint;\n publishToActivePublisher(locationState);\n}\n\n/**\n * Publish to the first live publisher only. Sibling provider mounts share\n * one embedding connection and therefore one claim store, so every live\n * publisher holds the same callable -- invoking more than one would publish\n * the same navigation twice. Deleting the active publisher (on its dispose)\n * lets `Set` iteration fall back to the next remaining one, so a navigation\n * is never dropped and never duplicated.\n */\nfunction publishToActivePublisher(state: AppLocationState): void {\n const publishers = patchState?.publishers;\n if (publishers === undefined) {\n return;\n }\n const next = publishers.values().next();\n if (next.done === false) {\n (next.value as Publish)(state);\n }\n}\n\n/**\n * True when `publish` is the active (first) live publisher. Used to gate the\n * per-install ready publication so a startup publication goes out once across\n * siblings, not once per sibling -- the same single-publisher rule the\n * singleton applies to navigation.\n */\nfunction isActivePublisher(publish: Publish): boolean {\n const publishers = patchState?.publishers;\n if (publishers === undefined) {\n return false;\n }\n const next = publishers.values().next();\n return next.done === false && next.value === publish;\n}\n\nfunction acquireHistoryPatch(publish: Publish): PatchState {\n if (patchState !== null) {\n patchState.publishers.add(publish);\n return patchState;\n }\n const history = globalThis.history;\n const originalPushState = history.pushState;\n const originalReplaceState = history.replaceState;\n const publishers = new Set<Publish>([publish]);\n const publishLocalState = (): void => {\n publishCurrentLocation();\n };\n const patchedPushState: History['pushState'] = function (\n data,\n unused,\n url,\n ): void {\n originalPushState.call(history, data, unused, url);\n publishLocalState();\n };\n const patchedReplaceState: History['replaceState'] = function (\n data,\n unused,\n url,\n ): void {\n originalReplaceState.call(history, data, unused, url);\n publishLocalState();\n };\n try {\n history.pushState = patchedPushState;\n history.replaceState = patchedReplaceState;\n globalThis.addEventListener('popstate', onLocationChange);\n globalThis.addEventListener('hashchange', onLocationChange);\n } catch (error) {\n // Acquisition is all-or-nothing. If a hardened realm rejects one of\n // the method assignments after the other succeeded, restore whatever\n // this attempt installed before surfacing the failure.\n if (history.replaceState === patchedReplaceState) {\n history.replaceState = originalReplaceState;\n }\n if (history.pushState === patchedPushState) {\n history.pushState = originalPushState;\n }\n globalThis.removeEventListener('popstate', onLocationChange);\n globalThis.removeEventListener('hashchange', onLocationChange);\n throw error;\n }\n patchState = {\n pushState: patchedPushState,\n replaceState: patchedReplaceState,\n originalPushState,\n originalReplaceState,\n publishers,\n lastPublishedFingerprint: null,\n };\n return patchState;\n}\n\nfunction releaseHistoryPatch(publish: Publish): void {\n const state = patchState;\n if (state === null) {\n return;\n }\n state.publishers.delete(publish);\n if (state.publishers.size > 0) {\n return;\n }\n const history = globalThis.history;\n // Restore only our own still-installed methods: an out-of-order dispose\n // of a sibling that patched later would have overwritten these, and\n // blindly restoring the originals would drop that sibling's patch. The\n // identity check guarantees we only undo our own installation.\n if (history.pushState === state.pushState) {\n history.pushState = state.originalPushState;\n }\n if (history.replaceState === state.replaceState) {\n history.replaceState = state.originalReplaceState;\n }\n globalThis.removeEventListener('popstate', onLocationChange);\n globalThis.removeEventListener('hashchange', onLocationChange);\n patchState = null;\n}\n\nexport interface InstallDatadogAppDeepLinksOptions {\n /** The embedding connection shared by every mount of this package. */\n readonly embedding: AppEmbedding;\n /** Aborted when this mount disposes; all cleanup keys off it. */\n readonly disposeSignal: AbortSignal;\n}\n\n/**\n * Installs the deep-links guest runtime for one provider mount.\n *\n * A one-way mirror the app drives onto the host page URL. The app owns its\n * query string and fragment; this runtime watches them -- patching `history`\n * once per realm and listening for `popstate` and `hashchange` -- and, whenever\n * they change, calls the host's `setDeepLinkState` with the current\n * snapshot. On each transition of the deep-links claim to `ready`, including\n * after an embedding reconnect, it publishes the current snapshot immediately.\n * The host's outer URL therefore reflects the app's state even before the app\n * navigates. There is no inbound apply and no remembered baseline: the host\n * seeded the iframe's starting URL before first navigation, and after that the\n * app's URL is its own state -- this runtime only reports it outward.\n *\n * When the claim is not `ready` (no host-side deep-links counterpart, or the\n * handshake still in flight) publishing is a no-op, so a default install is\n * inert rather than broken. Re-runnable: `install -> dispose -> install` on\n * the same mount is legal (StrictMode double-invokes provider effects), so\n * the patch acquisition, claim subscription, and abort listener all clean up\n * on `disposeSignal` and tolerate a second install.\n */\nexport function installDatadogAppDeepLinks({\n embedding,\n disposeSignal,\n}: InstallDatadogAppDeepLinksOptions): void {\n if (disposeSignal.aborted) {\n return;\n }\n\n const store = embedding.getClaim(datadogAppDeepLinksContract);\n\n const publish: Publish = ({ search, fragment }) => {\n const claim = store.getSnapshot();\n if (claim.status !== 'ready') {\n return;\n }\n claim.fields\n .setDeepLinkState({ search, fragment })\n .catch((error: unknown) =>\n reportDeepLinksError(\n 'The app URL state could not be synchronized to the embedding host.',\n error,\n ),\n );\n };\n\n // Publish the current snapshot on each transition of the claim to\n // `ready`. A reconnect produces a fresh claim (new callable), so\n // publishing per-ready (rather than once per install) keeps the host in\n // sync after a reconnect and reconciles the one-shot overlay with the\n // app's effective URL even when it never navigates. An unseeded app also\n // publishes any authored params so the outer URL gains a shareable link.\n const publishIfReady = (\n claim: ClaimState<typeof datadogAppDeepLinksContract>,\n ): void => {\n if (claim.status === 'ready' && isActivePublisher(publish)) {\n // Force each ready transition through even when its URL state is\n // unchanged: a reconnect supplies a fresh host callable that has\n // not received the current snapshot yet.\n publishCurrentLocation(true);\n }\n };\n const unsubscribe = store.subscribe(() => {\n publishIfReady(store.getSnapshot());\n });\n\n try {\n acquireHistoryPatch(publish);\n } catch (error) {\n unsubscribe();\n throw error;\n }\n\n // The claim may already be `ready` when this install runs (a sibling\n // mount claimed the same contract, or a reconnect raced the install\n // effect), so check once up front in addition to listening for changes.\n publishIfReady(store.getSnapshot());\n\n disposeSignal.addEventListener(\n 'abort',\n () => {\n unsubscribe();\n releaseHistoryPatch(publish);\n },\n { once: true },\n );\n}\n", "/**\n * The npm-facing React entry point for deep links. The provider module is a\n * startup capability: the provider installs it by id and knows nothing about\n * what it does. Nothing is rendered on the module's behalf -- the guest\n * runtime is framework-neutral install code over the shared embedding\n * connection.\n */\nimport { createDatadogAppProviderModule } from '../../embedding/react/config';\nimport type {\n DatadogAppProviderModule,\n DatadogAppProviderModuleHandle,\n} from '../../embedding/react/config';\n\nimport { installDatadogAppDeepLinks } from './module-install';\n\n/** Deep links take no module configuration today. */\nexport type DatadogAppDeepLinksConfig = Readonly<Record<string, never>>;\n\nexport type DatadogAppDeepLinksProviderModule = DatadogAppProviderModule<\n 'datadog.deep-links',\n DatadogAppDeepLinksConfig\n>;\n\nconst EMPTY_DEEP_LINKS_CONFIG: DatadogAppDeepLinksConfig = Object.freeze({});\n\n/**\n * Starts deep links with the provider. Installing this module mirrors the\n * app's query and fragment state onto the embedding host's page URL (under\n * the host's opaque id), so an app's navigations become shareable links. App\n * authors pass it through the composite provider's `modules` list (or get it\n * as a default); with no host-side deep-links counterpart the claim stays\n * pending and the module is inert.\n */\nexport function datadogAppDeepLinks(): DatadogAppDeepLinksProviderModule {\n return createDatadogAppProviderModule(\n 'datadog.deep-links',\n EMPTY_DEEP_LINKS_CONFIG,\n {\n install({\n embedding,\n disposeSignal,\n }: DatadogAppProviderModuleHandle): undefined {\n installDatadogAppDeepLinks({ embedding, disposeSignal });\n },\n },\n );\n}\n"],
5
+ "mappings": "6IASA,IAAMA,EAAsCC,EAAO,EAC7CC,EAA4CC,EAAU,EAW/CC,EAQRC,EAAe,CAChB,WAAY,qBACZ,QAAS,EACT,OAAQ,CACJ,iBAAkBC,EAAG,SAAS,CAC1B,OAAQ,CACJ,OAAQN,EACR,SAAUA,CACd,EACA,OAAQE,CACZ,CAAC,CACL,CACJ,CAAC,EAEKK,EAAmEC,EACnEP,EAAO,EACPA,EAAO,CACb,EAGaQ,EAQRJ,EAAe,CAChB,WAAY,qBACZ,QAAS,EACT,OAAQ,CACJ,qBAAsBC,EAAG,SAAS,CAC9B,OAAQ,CACJ,UAAWC,EACX,SAAUP,CACd,EACA,OAAQE,CACZ,CAAC,CACL,CACJ,CAAC,EC7DD,IAAMQ,EAAyC,OAAO,OAAO,CACzD,OAAQ,GACR,SAAU,EACd,CAAC,EAQD,SAASC,GAAyC,CAC9C,OAAI,OAAO,WAAW,SAAa,IACxBD,EAEJ,OAAO,OAAO,CACjB,OAAQ,WAAW,SAAS,OAC5B,SAAU,WAAW,SAAS,IAClC,CAAC,CACL,CAEA,SAASE,EAAqBC,EAAiBC,EAAuB,CAClE,QAAQ,MAAM,6BAA6BD,CAAO,GAA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,SAAWlB,EAAkBC,CAAO,GAIrDZ,EAAuB,EAAI,CAEnC,EACM+B,EAAcJ,EAAM,UAAU,IAAM,CACtCG,EAAeH,EAAM,YAAY,CAAC,CACtC,CAAC,EAED,GAAI,CACAd,EAAoBD,CAAO,CAC/B,OAASf,EAAO,CACZ,MAAAkC,EAAY,EACNlC,CACV,CAKAiC,EAAeH,EAAM,YAAY,CAAC,EAElCD,EAAc,iBACV,QACA,IAAM,CACFK,EAAY,EACZR,EAAoBX,CAAO,CAC/B,EACA,CAAE,KAAM,EAAK,CACjB,CACJ,CChRA,IAAMoB,EAAqD,OAAO,OAAO,CAAC,CAAC,EAUpE,SAASC,GAAyD,CACrE,OAAOC,EACH,qBACAF,EACA,CACI,QAAQ,CACJ,UAAAG,EACA,cAAAC,CACJ,EAA8C,CAC1CC,EAA2B,CAAE,UAAAF,EAAW,cAAAC,CAAc,CAAC,CAC3D,CACJ,CACJ,CACJ",
6
+ "names": ["stringSchema", "string", "undefinedSchema", "_undefined", "datadogAppDeepLinksContract", "defineContract", "fn", "variablesSchema", "record", "datadogAppDeepLinksV1Contract", "EMPTY_LOCATION_STATE", "currentLocationState", "reportDeepLinksError", "message", "error", "patchState", "onLocationChange", "publishCurrentLocation", "locationStateFingerprint", "search", "fragment", "force", "state", "locationState", "fingerprint", "publishToActivePublisher", "publishers", "next", "isActivePublisher", "publish", "acquireHistoryPatch", "history", "originalPushState", "originalReplaceState", "publishLocalState", "patchedPushState", "data", "unused", "url", "patchedReplaceState", "releaseHistoryPatch", "installDatadogAppDeepLinks", "embedding", "disposeSignal", "store", "datadogAppDeepLinksContract", "claim", "publishIfReady", "unsubscribe", "EMPTY_DEEP_LINKS_CONFIG", "datadogAppDeepLinks", "createDatadogAppProviderModule", "embedding", "disposeSignal", "installDatadogAppDeepLinks"]
7
+ }
@@ -0,0 +1,7 @@
1
+ /* Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0.
2
+ * This product includes software developed at Datadog (https://www.datadoghq.com/).
3
+ * Copyright 2019-Present Datadog, Inc.
4
+ */
5
+
6
+ import{d as i}from"./chunk-2V2HASKF.js";import{c as n}from"./chunk-G2SXTUX4.js";import{useSyncExternalStore as a}from"react";function o(t){let p=i();n(t);let e=p.getClaim(t.latest);return a(e.subscribe,e.getSnapshot,e.getSnapshot)}function d(t){return o(t)}export{d as a};
7
+ //# sourceMappingURL=chunk-627KNBXP.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/inputs/react/use-package-datadog-app-input.ts", "../../../src/inputs/react/use-datadog-app-input.ts"],
4
+ "sourcesContent": ["import { useSyncExternalStore } from 'react';\n\nimport { useAppEmbedding } from '../../embedding/react/context';\nimport type { ClaimState } from '../../embedding/types';\nimport type { AnyPublishedDatadogAppInputsDefinition } from '../published-definition';\nimport { assertPublishedDatadogAppInputsDefinition } from '../published-definition';\n\n/** Claims a package-owned definition that is absent from the public schema barrel. */\nexport function usePackageDatadogAppInput<\n TDefinition extends AnyPublishedDatadogAppInputsDefinition,\n>(definition: TDefinition): ClaimState<TDefinition['latest']> {\n const embedding = useAppEmbedding();\n assertPublishedDatadogAppInputsDefinition(definition);\n const store = embedding.getClaim<TDefinition['latest']>(definition.latest);\n return useSyncExternalStore(\n store.subscribe,\n store.getSnapshot,\n store.getSnapshot,\n );\n}\n", "import type { ClaimState } from '../../embedding/types';\nimport type { DatadogAppInputDefinition } from '../schemas/index';\n\nimport { usePackageDatadogAppInput } from './use-package-datadog-app-input';\n\n/**\n * What {@link useDatadogAppInput} gives back for one input: `pending` while the\n * connection or claim is in flight, `ready` with validated `fields`, `unavailable`\n * when this host does not provide the input, or `failed` with an actionable\n * `error`. `fields` exists only on `ready`, so stale values can never be read as\n * live.\n *\n * Named in terms of the input rather than the contract behind it -- which\n * version is being served is not a caller's concern.\n */\nexport type DatadogAppInputState<\n TDefinition extends DatadogAppInputDefinition,\n> = ClaimState<TDefinition['latest']>;\n\n/**\n * A type that refuses to match while saying why.\n *\n * A compiler error is the one piece of documentation a caller cannot skip, so\n * rejections here resolve to a sentence rather than to a bare `never` -- the\n * message becomes the error text, at the call site, in the editor.\n */\ntype Rejected<TMessage extends string> = Readonly<{\n __datadogAppInputsError: TMessage;\n}>;\n\ntype PublishedDefinitionFor<TDefinition extends DatadogAppInputDefinition> =\n Extract<\n DatadogAppInputDefinition,\n Readonly<{ identifier: TDefinition['identifier'] }>\n >;\n\ntype NoExtraFields<TDefinition extends DatadogAppInputDefinition> =\n Exclude<\n keyof TDefinition['latest']['fields'],\n keyof PublishedDefinitionFor<TDefinition>['latest']['fields']\n > extends never\n ? unknown\n : Rejected<'This definition has fields the published one does not. Pass a definition exported from @datadog/apps-frontend/inputs/schema, unmodified.'>;\n\n/**\n * Claims one Datadog App input and tracks its state across renders. Call it\n * below {@link DatadogAppProvider}.\n *\n * Pass a definition exported from `@datadog/apps-frontend/inputs/schema` --\n * {@link datadogTheme} is one. Hovering a definition shows the surfaces it is\n * offered on; the returned {@link ClaimState} says whether its values are usable\n * yet, and carries `fields` only while they are.\n *\n * Versions are not a caller's concern: this claims whichever version the\n * installed copy of the package treats as latest. An older copy asks for an\n * older version and keeps working for as long as the host still converts to it.\n * Past that the claim fails with `APP_MAJOR_TOO_OLD` -- update this package and\n * re-upload the app -- rather than silently degrading.\n *\n * @param definition An input definition from `@datadog/apps-frontend/inputs/schema`.\n * @returns The claim's current state: `pending`, `ready` (with `fields`),\n * `unavailable` when this host does not provide the input, or `failed` with an\n * actionable `error`.\n */\nexport function useDatadogAppInput<\n const TDefinition extends DatadogAppInputDefinition,\n>(\n definition: TDefinition & NoExtraFields<TDefinition>,\n): DatadogAppInputState<TDefinition> {\n return usePackageDatadogAppInput<TDefinition>(definition);\n}\n"],
5
+ "mappings": "gFAAA,OAAS,wBAAAA,MAA4B,QAQ9B,SAASC,EAEdC,EAA4D,CAC1D,IAAMC,EAAYC,EAAgB,EAClCC,EAA0CH,CAAU,EACpD,IAAMI,EAAQH,EAAU,SAAgCD,EAAW,MAAM,EACzE,OAAOK,EACHD,EAAM,UACNA,EAAM,YACNA,EAAM,WACV,CACJ,CC6CO,SAASE,EAGZC,EACiC,CACjC,OAAOC,EAAuCD,CAAU,CAC5D",
6
+ "names": ["useSyncExternalStore", "usePackageDatadogAppInput", "definition", "embedding", "useAppEmbedding", "assertPublishedDatadogAppInputsDefinition", "store", "useSyncExternalStore", "useDatadogAppInput", "definition", "usePackageDatadogAppInput"]
7
+ }
@@ -3,5 +3,5 @@
3
3
  * Copyright 2019-Present Datadog, Inc.
4
4
  */
5
5
 
6
- import{A as d,E as s,F as O,G as p,H as C,I as A,J as I,r as u,s as l}from"./chunk-X34MSTJH.js";var F=["datadog.idp.homepage","datadog.idp.service-panel","datadog.idp.self-service","datadog.app-builder","datadog.appsec","datadog.notebook","datadog.dashboard"];function S(e,n,t){let o=Object.create(null),a=n;for(let[r,i]of Object.entries(e.fields))o[r]=i.kind==="value"?a[r]:Object.freeze({invoke:a[r]});return O(e,Object.freeze(o),t)}function V(e,n){let t=Object.create(null);for(let o of n)t[o]=e[o];return t}function E(e,n){if(e.kind!==n.kind)return!1;if(e.kind==="value"&&n.kind==="value")return e.schema===n.schema;if(e.kind==="function"&&n.kind==="function"){let t=Object.keys(e.inputs),o=Object.keys(n.inputs);return!(t.length!==o.length||e.result!==n.result||t.some(a=>!Object.prototype.hasOwnProperty.call(n.inputs,a)||e.inputs[a]!==n.inputs[a]))}return!1}function L(e,n){let t=Object.create(null);for(let[o,a]of Object.entries(e.fields))t[o]=a;for(let o of n)for(let[a,r]of Object.entries(o.extraInputs)){if(Object.prototype.hasOwnProperty.call(e.fields,a))throw new Error(`"${e.identifier}" v${o.contract.version} declares extra input "${a}", which already names a field of v${e.version}.`);let i=Object.prototype.hasOwnProperty.call(t,a)?t[a]:void 0;if(i&&!E(i,r))throw new Error(`"${e.identifier}" extra input "${a}" is declared with conflicting schemas by more than one older version.`);t[a]=r}return Object.freeze(t)}function h(e,...n){let t=new Set([e.version]);for(let r of n){if(r.contract.identifier!==e.identifier)throw new Error(`Older version "${r.contract.identifier}" v${r.contract.version} must share identifier "${e.identifier}" with its latest contract.`);if(r.contract.version>=e.version)throw new Error(`Older version "${e.identifier}" v${r.contract.version} must be older than latest v${e.version}.`);if(t.has(r.contract.version))throw new Error(`"${e.identifier}" declares version ${r.contract.version} more than once.`);t.add(r.contract.version)}let o=L(e,n),a=Object.keys(e.fields);return Object.freeze({identifier:e.identifier,latest:e,olderVersions:Object.freeze([...n]),fields:o,buildModules(r,i){let y=r,f=V(y,a),m=[S(e,f,i)];for(let c of n){let g=c.convert(f,V(y,Object.keys(c.extraInputs)));m.push(S(c.contract,g,i))}return Object.freeze(m)}})}var R=new WeakSet,x=/^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$/;function b(e,n,t){if(!s.test(n)||n.length>l||!p(t))throw new Error(`Datadog App input field "${e}.${n}" must have a name matching ${String(s)} of at most ${l} characters and be a read-only value or function whose schemas implement Standard Schema V1.`);if(t.kind==="function"){for(let o of Object.keys(t.inputs))if(!s.test(o))throw new Error(`Datadog App input function parameter "${e}.${n}.${o}" must have a name matching ${String(s)}.`);if(!C(t))throw new Error(`Datadog App input function field "${e}.${n}" declares a timeoutMs no call could meet. It must be greater than 0 and at most ${2147483647}.`)}}function T(e){if(!d(e)||typeof e.identifier!="string"||!x.test(e.identifier))throw new Error(`Datadog App input contract identifier "${String(d(e)?e.identifier:void 0)}" must match ${String(x)}.`);if(typeof e.version!="number"||!Number.isSafeInteger(e.version)||e.version<1)throw new Error(`Datadog App input contract "${e.identifier}" must have a positive integer version.`);if(!d(e.fields)||Object.keys(e.fields).length===0||Object.keys(e.fields).length>u)throw new Error(`Datadog App input contract "${e.identifier}" must define between 1 and ${u} fields.`);for(let[n,t]of Object.entries(e.fields))b(e.identifier,n,t)}function N(e,n){if(!d(n))throw new Error(`Older Datadog App input contract "${e}" must declare its extra inputs as an object.`);for(let[t,o]of Object.entries(n))b(e,t,o)}var J=Object.freeze({readOnly(e){return A.readOnly(e)}});function D(e){let n=I(e);return T(n),n}function Y(e){let n=e,t="latest"in n?n.latest:D(n),o=n.olderVersions??[];T(t);for(let i of o)T(i.contract),N(t.identifier,i.extraInputs);let a=h(t,...o),r=Object.freeze({...a,surfaces:Object.freeze([...n.surfaces??F])});return R.add(r),r}function K(e){if(typeof e!="object"||e===null||!R.has(e))throw new Error("useDatadogAppInput() requires a definition exported by @datadog/apps-frontend/inputs/schema.")}export{J as a,Y as b,K as c};
7
- //# sourceMappingURL=chunk-T34NWJ7R.js.map
6
+ import{A as d,E as s,F as O,G as p,H as C,I as A,K as I,r as u,s as l}from"./chunk-LEEYMNMO.js";var F=["datadog.idp.homepage","datadog.idp.service-panel","datadog.idp.self-service","datadog.app-builder","datadog.appsec","datadog.notebook","datadog.dashboard"];function S(e,n,t){let o=Object.create(null),a=n;for(let[r,i]of Object.entries(e.fields))o[r]=i.kind==="value"?a[r]:Object.freeze({invoke:a[r]});return O(e,Object.freeze(o),t)}function h(e,n){let t=Object.create(null);for(let o of n)t[o]=e[o];return t}function E(e,n){if(e.kind!==n.kind)return!1;if(e.kind==="value"&&n.kind==="value")return e.schema===n.schema;if(e.kind==="function"&&n.kind==="function"){let t=Object.keys(e.inputs),o=Object.keys(n.inputs);return!(t.length!==o.length||e.result!==n.result||t.some(a=>!Object.prototype.hasOwnProperty.call(n.inputs,a)||e.inputs[a]!==n.inputs[a]))}return!1}function L(e,n){let t=Object.create(null);for(let[o,a]of Object.entries(e.fields))t[o]=a;for(let o of n)for(let[a,r]of Object.entries(o.extraInputs)){if(Object.prototype.hasOwnProperty.call(e.fields,a))throw new Error(`"${e.identifier}" v${o.contract.version} declares extra input "${a}", which already names a field of v${e.version}.`);let i=Object.prototype.hasOwnProperty.call(t,a)?t[a]:void 0;if(i&&!E(i,r))throw new Error(`"${e.identifier}" extra input "${a}" is declared with conflicting schemas by more than one older version.`);t[a]=r}return Object.freeze(t)}function V(e,...n){let t=new Set([e.version]);for(let r of n){if(r.contract.identifier!==e.identifier)throw new Error(`Older version "${r.contract.identifier}" v${r.contract.version} must share identifier "${e.identifier}" with its latest contract.`);if(r.contract.version>=e.version)throw new Error(`Older version "${e.identifier}" v${r.contract.version} must be older than latest v${e.version}.`);if(t.has(r.contract.version))throw new Error(`"${e.identifier}" declares version ${r.contract.version} more than once.`);t.add(r.contract.version)}let o=L(e,n),a=Object.keys(e.fields);return Object.freeze({identifier:e.identifier,latest:e,olderVersions:Object.freeze([...n]),fields:o,buildModules(r,i){let y=r,f=h(y,a),m=[S(e,f,i)];for(let c of n){let g=c.convert(f,h(y,Object.keys(c.extraInputs)));m.push(S(c.contract,g,i))}return Object.freeze(m)}})}var R=new WeakSet,x=/^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$/;function b(e,n,t){if(!s.test(n)||n.length>l||!p(t))throw new Error(`Datadog App input field "${e}.${n}" must have a name matching ${String(s)} of at most ${l} characters and be a read-only value or function whose schemas implement Standard Schema V1.`);if(t.kind==="function"){for(let o of Object.keys(t.inputs))if(!s.test(o))throw new Error(`Datadog App input function parameter "${e}.${n}.${o}" must have a name matching ${String(s)}.`);if(!C(t))throw new Error(`Datadog App input function field "${e}.${n}" declares a timeoutMs no call could meet. It must be greater than 0 and at most ${2147483647}.`)}}function T(e){if(!d(e)||typeof e.identifier!="string"||!x.test(e.identifier))throw new Error(`Datadog App input contract identifier "${String(d(e)?e.identifier:void 0)}" must match ${String(x)}.`);if(typeof e.version!="number"||!Number.isSafeInteger(e.version)||e.version<1)throw new Error(`Datadog App input contract "${e.identifier}" must have a positive integer version.`);if(!d(e.fields)||Object.keys(e.fields).length===0||Object.keys(e.fields).length>u)throw new Error(`Datadog App input contract "${e.identifier}" must define between 1 and ${u} fields.`);for(let[n,t]of Object.entries(e.fields))b(e.identifier,n,t)}function D(e,n){if(!d(n))throw new Error(`Older Datadog App input contract "${e}" must declare its extra inputs as an object.`);for(let[t,o]of Object.entries(n))b(e,t,o)}var J=Object.freeze({readOnly(e){return A.readOnly(e)}});function N(e){let n=I(e);return T(n),n}function Y(e){let n=e,t="latest"in n?n.latest:N(n),o=n.olderVersions??[];T(t);for(let i of o)T(i.contract),D(t.identifier,i.extraInputs);let a=V(t,...o),r=Object.freeze({...a,surfaces:Object.freeze([...n.surfaces??F])});return R.add(r),r}function K(e){if(typeof e!="object"||e===null||!R.has(e))throw new Error("useDatadogAppInput() requires a definition exported by @datadog/apps-frontend/inputs/schema.")}export{J as a,Y as b,K as c};
7
+ //# sourceMappingURL=chunk-G2SXTUX4.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/embedding/types.ts", "../../../src/embedding/versioning.ts", "../../../src/inputs/published-definition.ts"],
4
+ "sourcesContent": ["import type { StandardSchemaV1 } from '@standard-schema/spec';\n\nexport type Unsubscribe = () => void;\n\nexport type Result<TValue, TError> =\n | Readonly<{ ok: true; value: TValue }>\n | Readonly<{ ok: false; error: TError }>;\n\n/**\n * A synchronous, deterministic, validation-only Standard Schema.\n *\n * Both embedding peers validate independently. Schemas must therefore have\n * identical input/output types and must not coerce or transform accepted\n * values.\n */\nexport type ValueSchema<TValue> = StandardSchemaV1<TValue, TValue>;\n\nexport type AnySchema = StandardSchemaV1;\n\nexport type InferOf<TSchema extends AnySchema> =\n StandardSchemaV1.InferOutput<TSchema>;\n\nexport type ValidationOnlySchema<TSchema extends AnySchema> =\n StandardSchemaV1.InferInput<TSchema> extends StandardSchemaV1.InferOutput<TSchema>\n ? StandardSchemaV1.InferOutput<TSchema> extends StandardSchemaV1.InferInput<TSchema>\n ? TSchema\n : never\n : never;\n\nexport type ContractVersion = number;\n\nexport interface ValueField<TSchema extends AnySchema> {\n readonly kind: 'value';\n readonly schema: ValidationOnlySchema<TSchema>;\n}\n\nexport interface FunctionField<\n TInputs extends Readonly<Record<string, AnySchema>>,\n TResult extends AnySchema,\n> {\n readonly kind: 'function';\n readonly inputs: {\n readonly [TName in keyof TInputs]: ValidationOnlySchema<TInputs[TName]>;\n };\n readonly result: ValidationOnlySchema<TResult>;\n /**\n * How long this function may run before it times out, overriding the\n * default `FUNCTION_CALL_TIMEOUT_MS`. A fast lookup can ask for seconds\n * instead of inheriting a ten-minute budget.\n *\n * Never sent over the wire. The app arms its wait from the contract it\n * claims and the host arms its watchdog from the contract it registers, so\n * two peers on different contract revisions may use different numbers.\n * That needs no reconciling: whichever watchdog fires first wins through\n * the normal `TIMED_OUT` path, as it already did with the default alone.\n *\n * Must be positive and no larger than `MAX_TIMER_DELAY_MS`. Outside that\n * range no call could ever meet it -- at `0` the host's deadline checks are\n * already past, and beyond the timer ceiling `setTimeout` overflows and\n * fires almost at once -- so `defineContract()` rejects it outright.\n */\n readonly timeoutMs?: number;\n}\n\nexport type AnyFunctionField = FunctionField<\n Readonly<Record<string, AnySchema>>,\n AnySchema\n>;\n\nexport type AnyField = ValueField<AnySchema> | AnyFunctionField;\n\nexport interface Contract<TFields extends Record<string, AnyField>> {\n readonly identifier: string;\n readonly version: ContractVersion;\n readonly fields: TFields;\n}\n\nexport type AnyContract = Contract<Record<string, AnyField>>;\n\nexport interface LiveValue<TValue> {\n get(): TValue;\n subscribe(onChange: () => void): Unsubscribe;\n}\n\nexport interface HostFunctionContext {\n /**\n * Aborts once the call is cancelled or its deadline passes. An async\n * implementation should check or listen for this to stop early. A\n * *synchronous* implementation has no way to observe it mid-call: JS\n * can't preempt a running function, so a synchronous handler that blocks\n * past the deadline still runs to completion and produces its value --\n * the caller is simply told the call timed out and never sees that\n * value, rather than the value being prevented from being computed.\n */\n readonly signal: AbortSignal;\n}\n\nexport interface HostFunction {\n invoke(\n inputs: Readonly<Record<string, unknown>>,\n context: HostFunctionContext,\n ): unknown;\n}\n\nexport type FunctionInputs<\n TInputs extends Readonly<Record<string, AnySchema>>,\n> = {\n readonly [TName in keyof TInputs as undefined extends InferOf<\n TInputs[TName]\n >\n ? TName\n : never]?: InferOf<TInputs[TName]>;\n} & {\n readonly [TName in keyof TInputs as undefined extends InferOf<\n TInputs[TName]\n >\n ? never\n : TName]: InferOf<TInputs[TName]>;\n};\n\n/** Resolves a contract field to the plain value/callable shape a claimant receives, ignoring subscription. */\ntype FieldValue<TField extends AnyField> =\n TField extends ValueField<infer TSchema>\n ? InferOf<TSchema>\n : TField extends FunctionField<infer TInputs, infer TResult>\n ? (inputs: FunctionInputs<TInputs>) => Promise<InferOf<TResult>>\n : never;\n\ntype ClaimedField<TField extends AnyField> =\n TField extends ValueField<infer TSchema>\n ? LiveValue<InferOf<TSchema>>\n : FieldValue<TField>;\n\n/** The live, per-field view of a claim: subscribable `LiveValue`s for value fields, callables for function fields. */\nexport type ClaimedFields<TContract extends AnyContract> = {\n readonly [TKey in keyof TContract['fields']]: ClaimedField<\n TContract['fields'][TKey]\n >;\n};\n\ndeclare const hostModuleBrand: unique symbol;\n\n/**\n * One contract version, live and ready to serve claims. Nominally branded --\n * `hostModuleBrand` is declared but never exported, so only this package can\n * produce a `HostModule`, and only through `createHostModule()`. That is what\n * keeps a host from assembling a module for one hand-picked version: the\n * single supported way in is to provide an inputs definition, which mints a\n * module for *every* version that definition still converts to. The brand has\n * no runtime representation.\n */\nexport interface HostModule {\n readonly [hostModuleBrand]: true;\n readonly contract: AnyContract;\n readonly implementation: Readonly<\n Record<string, LiveValue<unknown> | HostFunction>\n >;\n readonly signal?: AbortSignal;\n}\n\nexport interface Issue {\n readonly message: string;\n readonly path: readonly (string | number)[];\n}\n\nexport type AnyError =\n | Readonly<{ code: 'ORIGIN_REJECTED'; origin: string }>\n | Readonly<{\n code: 'APP_PROTOCOL_TOO_OLD';\n appProtocols: readonly number[];\n hostProtocols: readonly number[];\n }>\n | Readonly<{\n code: 'HOST_PROTOCOL_TOO_OLD';\n appProtocols: readonly number[];\n hostProtocols: readonly number[];\n }>\n | Readonly<{\n code: 'PROTOCOL_INCOMPATIBLE';\n appProtocols: readonly number[];\n hostProtocols: readonly number[];\n }>\n | Readonly<{ code: 'PEER_LACKS_MODULE'; identifier: string }>\n | Readonly<{\n code: 'APP_MAJOR_TOO_OLD';\n wanted: ContractVersion;\n hostVersions: readonly ContractVersion[];\n }>\n | Readonly<{\n code: 'HOST_MAJOR_TOO_OLD';\n wanted: ContractVersion;\n hostVersions: readonly ContractVersion[];\n }>\n | Readonly<{ code: 'CONTRACT_INCOMPATIBLE'; field: string }>\n | Readonly<{ code: 'INVALID_ARGUMENT'; issues: readonly Issue[] }>\n | Readonly<{ code: 'FUNCTION_FAILED'; field: string }>\n | Readonly<{ code: 'INVALID_RESULT'; issues: readonly Issue[] }>\n | Readonly<{ code: 'TIMED_OUT'; timeoutMs: number }>\n | Readonly<{ code: 'TRANSPORT_FAILED'; cause: unknown }>\n | Readonly<{ code: 'ABORTED' }>\n | Readonly<{ code: 'DISCONNECTED' }>\n | Readonly<{ code: 'UNRECOGNIZED'; rawCode: string; raw: unknown }>;\n\nexport type ErrorOf<TCode extends AnyError['code']> = Extract<\n AnyError,\n { code: TCode }\n>;\n\nexport type ConnectError = ErrorOf<\n | 'ORIGIN_REJECTED'\n | 'APP_PROTOCOL_TOO_OLD'\n | 'HOST_PROTOCOL_TOO_OLD'\n | 'PROTOCOL_INCOMPATIBLE'\n | 'TIMED_OUT'\n | 'TRANSPORT_FAILED'\n | 'ABORTED'\n | 'DISCONNECTED'\n | 'UNRECOGNIZED'\n>;\n\nexport type WireClaimError = ErrorOf<\n | 'PEER_LACKS_MODULE'\n | 'APP_MAJOR_TOO_OLD'\n | 'HOST_MAJOR_TOO_OLD'\n | 'CONTRACT_INCOMPATIBLE'\n | 'INVALID_RESULT'\n | 'TIMED_OUT'\n | 'ABORTED'\n | 'DISCONNECTED'\n | 'UNRECOGNIZED'\n>;\n\nexport type WireFunctionError = ErrorOf<\n | 'CONTRACT_INCOMPATIBLE'\n | 'INVALID_ARGUMENT'\n | 'FUNCTION_FAILED'\n | 'INVALID_RESULT'\n | 'TIMED_OUT'\n | 'ABORTED'\n | 'DISCONNECTED'\n | 'UNRECOGNIZED'\n>;\n\nexport type ClaimInvalidationError = ErrorOf<\n 'INVALID_RESULT' | 'DISCONNECTED' | 'UNRECOGNIZED'\n>;\n\nexport interface Claimed<TContract extends AnyContract> {\n readonly fields: ClaimedFields<TContract>;\n release(): void;\n onValuesChanged(listener: () => void): Unsubscribe;\n onInvalidated(\n listener: (error: ClaimInvalidationError) => void,\n ): Unsubscribe;\n}\n\nexport interface ClaimOptions {\n /**\n * Local claim deadline. Must be finite, non-negative, and no larger than\n * the platform timer ceiling (`2_147_483_647`).\n */\n readonly timeoutMs?: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface AppConnection {\n claim<TContract extends AnyContract>(\n contract: TContract,\n options?: ClaimOptions,\n ): Promise<Result<Claimed<TContract>, WireClaimError>>;\n}\n\n/**\n * Identifies which product surface a Datadog App is embedded into (e.g. the\n * Service Catalog side panel vs. IDP), so an app can render surface-specific\n * content. Each value matches the identifier of the schema that surface\n * provides. Sent host-to-app as part of the embedding connection handshake.\n */\n/**\n * Every surface, as a tuple rather than a bare union so it can also serve as a\n * type: `DatadogAppInputsSchema` defaults its `surfaces` to this, which makes\n * an IDE print the members in full on hover instead of collapsing them to the\n * `SurfaceId` alias.\n */\nexport const EVERY_SURFACE: readonly [\n 'datadog.idp.homepage',\n 'datadog.idp.service-panel',\n 'datadog.idp.self-service',\n 'datadog.app-builder',\n 'datadog.appsec',\n 'datadog.notebook',\n 'datadog.dashboard',\n] = [\n 'datadog.idp.homepage',\n 'datadog.idp.service-panel',\n 'datadog.idp.self-service',\n 'datadog.app-builder',\n 'datadog.appsec',\n 'datadog.notebook',\n 'datadog.dashboard',\n];\n\n/**\n * The static category of surface where an embedding session is running.\n * It is chosen when the connection is established and does not change in\n * place. Dynamic placement or parent/child relationships (for example, a\n * pinned app moving between containers) belong in separately versioned\n * module inputs rather than mutations to `surfaceId`.\n *\n * Derived from `EVERY_SURFACE`, so there is one list, but widened to arbitrary\n * strings: it is metadata forwarded to `listen()` and may be used by the host\n * to gate which input schemas are offered on a given surface, but it never\n * gates whether embedding connects \u2014 a host is free to pass a value with\n * no matching surface (e.g. an unmapped view context) rather than going\n * without one.\n */\nexport type SurfaceId = (typeof EVERY_SURFACE)[number] | (string & {});\n\nexport type AppConnectionState =\n | Readonly<{ state: 'connecting'; error?: ConnectError }>\n | Readonly<{\n state: 'connected';\n connection: AppConnection;\n surfaceId?: SurfaceId;\n }>\n | Readonly<{ state: 'reconnecting'; lastError: ConnectError }>\n | Readonly<{ state: 'rejected'; error: ConnectError }>\n | Readonly<{ state: 'not-embedded' }>\n | Readonly<{ state: 'closed' }>;\n\n/**\n * Public-safe view of `AppConnectionState`: the same lifecycle cases, minus\n * the raw `AppConnection` a consumer would otherwise have no use for outside\n * of claiming a contract.\n */\nexport type EmbeddingMetadata =\n | Readonly<{ state: 'connecting'; error?: ConnectError }>\n | Readonly<{ state: 'connected'; surfaceId?: SurfaceId }>\n | Readonly<{ state: 'reconnecting'; lastError: ConnectError }>\n | Readonly<{ state: 'rejected'; error: ConnectError }>\n | Readonly<{ state: 'not-embedded' }>\n | Readonly<{ state: 'closed' }>;\n\nexport interface EmbeddingMetadataStore {\n readonly getSnapshot: () => EmbeddingMetadata;\n readonly subscribe: (onChange: () => void) => Unsubscribe;\n}\n\nexport interface AppConnectionHandle {\n getSnapshot(): AppConnectionState;\n subscribe(onChange: () => void): Unsubscribe;\n close(): void;\n}\n\nexport interface AppConnectionFactory {\n connect(): AppConnectionHandle;\n}\n\nexport interface HostListenOptions {\n /** Security boundary for the app-created bootstrap port. */\n readonly peer: Readonly<{\n frame: HTMLIFrameElement;\n appOrigin: string;\n /**\n * Set when the iframe is intentionally configured with an opaque\n * sandboxed origin, so the host should accept a `\"null\"` origin from\n * it in place of an exact match against `appOrigin`.\n */\n allowOpaqueOrigin?: boolean;\n }>;\n readonly modules: readonly HostModule[];\n /** Static surface category for the lifetime of the established connection. */\n readonly surfaceId?: SurfaceId;\n /**\n * Local compatibility and establishment deadline for each phase. Must be\n * finite, non-negative, and no larger than the platform timer ceiling\n * (`2_147_483_647`).\n */\n readonly timeoutMs?: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface HostListener {\n onError(listener: (error: ConnectError) => void): Unsubscribe;\n /**\n * Fires exactly once per successful operational session: after permanent\n * bootstrap and compatibility negotiation complete, before any\n * per-module claim resolves. Not a one-shot for the listener's whole\n * lifetime -- if this session is later superseded (a new bootstrap\n * replaces it, see `close()`'s effect on an active connection) and a new\n * session establishes, this fires again for that new session. Never\n * fires for an attempt that fails, or after `close()`. A subscriber that\n * calls `onReady` while a session is already active is notified\n * immediately upon subscribing, so a late subscriber cannot miss an\n * already-established session.\n */\n onReady(listener: () => void): Unsubscribe;\n close(): void;\n}\n\nexport type EmbeddingError =\n | Readonly<{ code: 'TIMED_OUT'; message: string; action: 'retry' }>\n | Readonly<{\n code: 'ORIGIN_REJECTED';\n message: string;\n action: 'contact-support';\n }>\n | Readonly<{\n code: 'APP_PROTOCOL_TOO_OLD';\n message: string;\n action: 'update-app';\n }>\n | Readonly<{\n code: 'HOST_PROTOCOL_TOO_OLD' | 'PROTOCOL_INCOMPATIBLE';\n message: string;\n action: 'contact-support';\n }>\n | Readonly<{\n code: 'CONNECTION_LOST';\n message: string;\n action: 'retry';\n }>\n | Readonly<{\n code: 'UNKNOWN';\n message: string;\n action: 'contact-support';\n }>;\n\nexport type ClaimError =\n | EmbeddingError\n | Readonly<{\n code: 'APP_MAJOR_TOO_OLD';\n action: 'update-app';\n requestedVersion: ContractVersion;\n availableVersions: readonly ContractVersion[];\n message: string;\n }>\n | Readonly<{\n code: 'HOST_MAJOR_TOO_OLD';\n action: 'contact-support';\n requestedVersion: ContractVersion;\n availableVersions: readonly ContractVersion[];\n message: string;\n }>;\n\nexport type ClaimedValues<TContract extends AnyContract> = Readonly<{\n [TKey in keyof TContract['fields']]: FieldValue<TContract['fields'][TKey]>;\n}>;\n\nexport type ClaimState<TContract extends AnyContract> =\n | Readonly<{ status: 'pending' }>\n | Readonly<{\n status: 'ready';\n fields: ClaimedValues<TContract>;\n }>\n | Readonly<{ status: 'unavailable' }>\n | Readonly<{ status: 'failed'; error: ClaimError }>;\n\nexport interface ClaimStore<TContract extends AnyContract> {\n readonly getSnapshot: () => ClaimState<TContract>;\n readonly subscribe: (onChange: () => void) => Unsubscribe;\n}\n\n/** Framework-neutral claim capability consumed by feature modules. */\nexport interface AppClaims {\n getClaim<TContract extends AnyContract>(\n contract: TContract,\n ): ClaimStore<TContract>;\n}\n\n/** Owns the lifecycle of one concrete embedding implementation. */\nexport interface AppEmbedding extends AppClaims {\n start(): Unsubscribe;\n getEmbeddingMetadata(): EmbeddingMetadataStore;\n}\n\n/**\n * One established connection, owned by the caller that opened it. These say\n * nothing about which operational protocol produced them, so the connection\n * lifecycle does not change when a protocol is added or retired.\n */\nexport type ManagedAppConnection = Readonly<{\n connection: AppConnection;\n surfaceId?: SurfaceId;\n closeSignal: AbortSignal;\n close(): void;\n}>;\n\nexport type ManagedHostConnection = Readonly<{\n closeSignal: AbortSignal;\n close(): void;\n}>;\n", "import { MAX_CLAIM_FIELD_NAME_LENGTH } from './config';\nimport {\n createHostModule,\n isAnyFieldShape,\n VALID_FIELD_NAME,\n} from './contract';\nimport { teardown } from './shared';\nimport type {\n AnyContract,\n AnyField,\n ContractVersion,\n FunctionField,\n FunctionInputs,\n HostFunction,\n HostFunctionContext,\n HostModule,\n InferOf,\n LiveValue,\n Unsubscribe,\n ValueField,\n} from './types';\n\ntype HostFieldImplementation<TField extends AnyField> =\n TField extends ValueField<infer TSchema>\n ? LiveValue<InferOf<TSchema>>\n : TField extends FunctionField<infer TInputs, infer TResult>\n ? (\n inputs: FunctionInputs<TInputs>,\n context: HostFunctionContext,\n ) => InferOf<TResult> | Promise<InferOf<TResult>>\n : never;\n\n/** The live host-side implementation of a raw field map: `LiveValue`s for value fields, plain callables for function fields. */\nexport type HostFieldsFor<TFields extends Record<string, AnyField>> = Readonly<{\n [TName in keyof TFields]: HostFieldImplementation<TFields[TName]>;\n}>;\n\n/** The live host-side implementation of a whole contract's fields. */\nexport type HostFields<TContract extends AnyContract> = HostFieldsFor<\n TContract['fields']\n>;\n\n/**\n * A `LiveValue` that recomputes from `sources` on every `get()` rather than\n * caching, so it always reflects whichever of `sources` last changed without\n * needing its own dedupe or disposal bookkeeping -- that already lives on\n * `sources` themselves.\n */\nexport function deriveLiveValue<TValue>(\n sources: readonly LiveValue<unknown>[],\n compute: () => TValue,\n): LiveValue<TValue> {\n return Object.freeze({\n get: compute,\n subscribe(onChange: () => void): Unsubscribe {\n // Acquired sequentially (not via `sources.map()`) so a later\n // source throwing rolls back every subscription already made.\n const unsubscribes: Unsubscribe[] = [];\n try {\n for (const source of sources) {\n unsubscribes.push(source.subscribe(onChange));\n }\n } catch (error) {\n for (const unsubscribe of unsubscribes) {\n teardown(\n 'deriveLiveValue subscription rollback',\n unsubscribe,\n );\n }\n throw error;\n }\n // Routed through `teardown()` so one throwing unsubscribe can't\n // skip the rest.\n return () => {\n for (const unsubscribe of unsubscribes) {\n teardown('deriveLiveValue unsubscribe', unsubscribe);\n }\n };\n },\n });\n}\n\n/**\n * One older version of `TLatest`: its own frozen contract, the extra live\n * inputs its `convert` needs beyond what `TLatest` already carries, and the\n * function that derives its fields from `TLatest` plus those extras. Runs\n * once, at `buildModules()` time, and must return live fields -- typically\n * built with `deriveLiveValue()` -- so the older version stays exactly as\n * reactive as `TLatest`, with `TLatest`'s own implementation untouched.\n */\nexport interface OlderContractVersion<\n TLatest extends AnyContract,\n TOlder extends AnyContract,\n TExtraInputs extends Record<string, AnyField>,\n> {\n readonly contract: TOlder;\n readonly extraInputs: TExtraInputs;\n convert(\n latest: HostFields<TLatest>,\n extra: HostFieldsFor<TExtraInputs>,\n ): HostFields<TOlder>;\n}\n\nexport type AnyOlderContractVersion<TLatest extends AnyContract> =\n OlderContractVersion<TLatest, AnyContract, Record<string, AnyField>>;\n\n/**\n * Declares and validates one `OlderContractVersion`. Takes `latest` as its\n * own argument -- rather than only through `definition.convert`'s parameter\n * type -- so `TLatest` can be inferred directly from a value in covariant\n * position; inference can't otherwise recover it from `convert`'s parameter,\n * a contravariant position, and silently falls back to `AnyContract`.\n */\nexport function olderVersion<\n TLatest extends AnyContract,\n TOlder extends AnyContract,\n const TExtraInputs extends Record<string, AnyField>,\n>(\n _latest: TLatest,\n definition: OlderContractVersion<TLatest, TOlder, TExtraInputs>,\n): OlderContractVersion<TLatest, TOlder, TExtraInputs> {\n for (const [name, field] of Object.entries(definition.extraInputs)) {\n if (\n !VALID_FIELD_NAME.test(name) ||\n name.length > MAX_CLAIM_FIELD_NAME_LENGTH ||\n !isAnyFieldShape(field)\n ) {\n throw new Error(\n `Older-version extra input \"${definition.contract.identifier}.${name}\" must be a named read-only value or function whose schemas implement Standard Schema V1.`,\n );\n }\n }\n return Object.freeze({\n contract: definition.contract,\n extraInputs: Object.freeze({ ...definition.extraInputs }),\n convert: definition.convert,\n });\n}\n\nexport interface VersionedContract<\n TLatest extends AnyContract,\n TOlderVersions extends readonly AnyOlderContractVersion<TLatest>[],\n> {\n readonly identifier: TLatest['identifier'];\n /**\n * The version an up-to-date peer claims. Read by the claiming side to\n * know what it is asking for; never a way to *provide* one version alone,\n * since `buildModules()` is all-or-nothing.\n */\n readonly latest: TLatest;\n readonly olderVersions: TOlderVersions;\n /**\n * `X`: every field needed to serve every version, in one flat namespace.\n * A provider populates exactly this and learns nothing about how many\n * versions sit behind it.\n */\n readonly fields: VersionedContractFields<TLatest, TOlderVersions>;\n /**\n * Mints one live module per version -- latest plus every version that\n * still has a converter -- from one flat field record. There is\n * deliberately no way to ask for a subset: supporting a version and\n * serving it are the same act.\n */\n buildModules(\n fields: HostFieldsFor<VersionedContractFields<TLatest, TOlderVersions>>,\n signal?: AbortSignal,\n ): readonly HostModule[];\n}\n\n/**\n * Structural bound for \"some versioned contract\", used where generic code\n * needs to accept any of them. Deliberately forgetful about `buildModules`'s\n * parameter and about `olderVersions`' element type: both are contravariant,\n * so naming them would make every concrete contract fail to satisfy this.\n * Callers recover the precise field types from the generic parameter itself\n * (see `DatadogAppInputImplementations`), not from this bound.\n */\nexport type AnyVersionedContract = Readonly<{\n identifier: string;\n latest: AnyContract;\n olderVersions: readonly unknown[];\n fields: Readonly<Record<string, AnyField>>;\n buildModules: (\n fields: never,\n signal?: AbortSignal,\n ) => readonly HostModule[];\n}>;\n\nexport type UnionToIntersection<TUnion> = (\n TUnion extends unknown ? (key: TUnion) => void : never\n) extends (key: infer TIntersection) => void\n ? TIntersection\n : never;\n\ntype OlderVersionsExtraFieldsUnion<\n TLatest extends AnyContract,\n TOlderVersions extends readonly AnyOlderContractVersion<TLatest>[],\n> = {\n [TIndex in keyof TOlderVersions]: TOlderVersions[TIndex] extends OlderContractVersion<\n TLatest,\n AnyContract,\n infer TExtraInputs\n >\n ? TExtraInputs\n : never;\n}[number];\n\n/**\n * Every field needed to construct every version this contract declares,\n * flattened into one namespace: `latest`'s own fields plus each older\n * version's `extraInputs`. This is `giving` values' whole contract with\n * versioning -- a caller populates this one flat record with no notion that\n * more than one version exists behind it. Field names must therefore be\n * unique across `latest` and every older version's `extraInputs`; two older\n * versions may reuse the same name only when it means the same schema, since\n * flattening gives it exactly one slot.\n */\nexport type VersionedContractFields<\n TLatest extends AnyContract,\n TOlderVersions extends readonly AnyOlderContractVersion<TLatest>[],\n> =\n OlderVersionsExtraFieldsUnion<TLatest, TOlderVersions> extends never\n ? TLatest['fields']\n : TLatest['fields'] &\n UnionToIntersection<\n OlderVersionsExtraFieldsUnion<TLatest, TOlderVersions>\n >;\n\nfunction toHostModule<TContract extends AnyContract>(\n contract: TContract,\n fields: HostFields<TContract>,\n signal: AbortSignal | undefined,\n): HostModule {\n // Null-prototype as defence in depth. `olderVersion` already rejects an\n // extra input named \"__proto__\" via `VALID_FIELD_NAME`, so no such name\n // should reach here; a plain `{}` would silently drop it through the\n // legacy setter rather than defining an own property if one ever did.\n const implementation: Record<string, LiveValue<unknown> | HostFunction> =\n Object.create(null);\n const rawFields: Record<string, unknown> = fields;\n for (const [name, field] of Object.entries(contract.fields)) {\n implementation[name] =\n field.kind === 'value'\n ? (rawFields[name] as LiveValue<unknown>)\n : Object.freeze({\n invoke: rawFields[name] as HostFunction['invoke'],\n });\n }\n return createHostModule(contract, Object.freeze(implementation), signal);\n}\n\n/** Narrows a flat field record to the names one version actually reads. */\nfunction pickFields(\n fields: Readonly<Record<string, unknown>>,\n names: readonly string[],\n): Readonly<Record<string, unknown>> {\n // Null-prototype for the same defence-in-depth reason as `toHostModule`\n // above: `names` can include an older version's extra-input name, which\n // `olderVersion` already shape-checks with `VALID_FIELD_NAME`.\n const picked: Record<string, unknown> = Object.create(null);\n for (const name of names) {\n picked[name] = fields[name];\n }\n return picked;\n}\n\n/**\n * Whether two versions asking for the same field name mean the same thing.\n * Flattening gives a name exactly one slot, so a disagreement has to be an\n * authoring error rather than something a provider could satisfy twice.\n */\nfunction isSameField(left: AnyField, right: AnyField): boolean {\n if (left.kind !== right.kind) {\n return false;\n }\n if (left.kind === 'value' && right.kind === 'value') {\n return left.schema === right.schema;\n }\n if (left.kind === 'function' && right.kind === 'function') {\n const leftNames = Object.keys(left.inputs);\n const rightNames = Object.keys(right.inputs);\n // Deliberately does not compare `timeoutMs`. This check exists so one\n // provider implementation can serve every version sharing a flattened\n // slot, which a mismatched schema or input name would prevent. A\n // deadline cannot prevent it: the flattened descriptor is only used to\n // type the provider record and to slice it by name, and `buildModules`\n // hands each version `toHostModule(older.contract, ...)`, so every\n // deadline is resolved from that version's own contract field. Two\n // versions reusing one extra-input name may declare different\n // deadlines with no runtime consequence whatsoever.\n return !(\n leftNames.length !== rightNames.length ||\n left.result !== right.result ||\n leftNames.some(\n (name) =>\n !Object.prototype.hasOwnProperty.call(right.inputs, name) ||\n left.inputs[name] !== right.inputs[name],\n )\n );\n }\n return false;\n}\n\n/**\n * Flattens `latest`'s own fields together with every older version's extra\n * inputs into the one namespace a provider populates, rejecting the two ways\n * that flattening can go wrong: an extra input that shadows a real field of\n * `latest`, and two older versions claiming one name for different schemas.\n */\nfunction mergeVersionedFields<TLatest extends AnyContract>(\n latest: TLatest,\n olderVersions: readonly AnyOlderContractVersion<TLatest>[],\n): Readonly<Record<string, AnyField>> {\n // Null-prototype as defence in depth: `VALID_FIELD_NAME` already excludes\n // an extra input named \"__proto__\", but were one to reach here it must\n // become an own property rather than invoke the inherited legacy setter\n // and silently repoint `merged`'s prototype.\n const merged: Record<string, AnyField> = Object.create(null);\n for (const [name, field] of Object.entries(latest.fields)) {\n merged[name] = field;\n }\n for (const older of olderVersions) {\n for (const [name, field] of Object.entries(older.extraInputs)) {\n if (Object.prototype.hasOwnProperty.call(latest.fields, name)) {\n throw new Error(\n `\"${latest.identifier}\" v${older.contract.version} declares extra input \"${name}\", which already names a field of v${latest.version}.`,\n );\n }\n const existing = Object.prototype.hasOwnProperty.call(merged, name)\n ? merged[name]\n : undefined;\n if (existing && !isSameField(existing, field)) {\n throw new Error(\n `\"${latest.identifier}\" extra input \"${name}\" is declared with conflicting schemas by more than one older version.`,\n );\n }\n merged[name] = field;\n }\n }\n return Object.freeze(merged);\n}\n\n/**\n * Ties a latest contract to any number of older versions it stays willing to\n * serve. `buildModules()` derives each older version's fields from the\n * latest implementation plus that version's own extra inputs and returns one\n * independent, fully live `HostModule` per version -- ready to hand to a\n * host listener alongside modules for any other contract.\n */\nexport function defineVersionedContract<\n TLatest extends AnyContract,\n const TOlderVersions extends readonly AnyOlderContractVersion<TLatest>[],\n>(\n latest: TLatest,\n ...olderVersions: TOlderVersions\n): VersionedContract<TLatest, TOlderVersions> {\n const versions = new Set<ContractVersion>([latest.version]);\n for (const older of olderVersions) {\n if (older.contract.identifier !== latest.identifier) {\n throw new Error(\n `Older version \"${older.contract.identifier}\" v${older.contract.version} must share identifier \"${latest.identifier}\" with its latest contract.`,\n );\n }\n if (older.contract.version >= latest.version) {\n throw new Error(\n `Older version \"${latest.identifier}\" v${older.contract.version} must be older than latest v${latest.version}.`,\n );\n }\n if (versions.has(older.contract.version)) {\n throw new Error(\n `\"${latest.identifier}\" declares version ${older.contract.version} more than once.`,\n );\n }\n versions.add(older.contract.version);\n }\n\n const fields = mergeVersionedFields(latest, olderVersions);\n const latestNames = Object.keys(latest.fields);\n\n return Object.freeze({\n identifier: latest.identifier,\n latest,\n // `Object.freeze` on the returned object is shallow: exposing the\n // validated array by reference would let a caller mutate it (push,\n // sort, splice) after the fact despite the wrapper looking frozen.\n olderVersions: Object.freeze([...olderVersions]) as TOlderVersions,\n fields: fields as VersionedContractFields<TLatest, TOlderVersions>,\n buildModules(\n allFields: HostFieldsFor<\n VersionedContractFields<TLatest, TOlderVersions>\n >,\n signal?: AbortSignal,\n ): readonly HostModule[] {\n const flat: Readonly<Record<string, unknown>> = allFields;\n // Slicing by each version's own field names is what lets two\n // versions share one slot: both reads hit the same live value.\n const latestImplementation = pickFields(\n flat,\n latestNames,\n ) as HostFields<TLatest>;\n const modules: HostModule[] = [\n toHostModule(latest, latestImplementation, signal),\n ];\n for (const older of olderVersions) {\n const derived = older.convert(\n latestImplementation,\n pickFields(\n flat,\n Object.keys(older.extraInputs),\n ) as HostFieldsFor<Record<string, AnyField>>,\n );\n modules.push(toHostModule(older.contract, derived, signal));\n }\n return Object.freeze(modules);\n },\n });\n}\n", "import {\n MAX_CLAIM_FIELD_NAME_LENGTH,\n MAX_CLAIM_FIELDS,\n MAX_TIMER_DELAY_MS,\n} from '../embedding/config';\nimport {\n defineContract,\n fn as defineFunctionField,\n hasUsableFunctionTimeout,\n isAnyFieldShape,\n VALID_FIELD_NAME,\n value as defineValueField,\n} from '../embedding/contract';\nimport { isRecord } from '../embedding/shared';\nimport { EVERY_SURFACE } from '../embedding/types';\nimport type {\n AnyContract,\n AnyField,\n AnySchema,\n Contract,\n ContractVersion,\n FunctionField,\n InferOf,\n SurfaceId,\n ValidationOnlySchema,\n ValueField,\n ValueSchema,\n} from '../embedding/types';\nimport { defineVersionedContract } from '../embedding/versioning';\nimport type {\n AnyOlderContractVersion,\n AnyVersionedContract,\n VersionedContract,\n} from '../embedding/versioning';\n\ndeclare const publishedDefinitionBrand: unique symbol;\n\n/**\n * One published inputs definition: every version it serves, and the surfaces\n * it is offered on.\n *\n * `surfaces` is read at runtime by `datadogAppHostInputsFor` to gate which\n * schemas a host offers on a given surface \u2014 a dashboard-only schema is not\n * offered on IDP even if a synthetic `dashboard` field is present in the\n * inputs bag. Omitted resolves to every `SurfaceId`, so the hint reads as\n * \"available everywhere\" rather than as an empty list.\n */\nexport type DatadogAppInputsSchema<\n TLatest extends AnyContract,\n TSurfaces extends readonly SurfaceId[] = typeof EVERY_SURFACE,\n TOlderVersions extends readonly AnyOlderContractVersion<TLatest>[] =\n readonly [],\n> = VersionedContract<TLatest, TOlderVersions> &\n Readonly<{ surfaces: TSurfaces }>;\n\nexport type AnyDatadogAppInputsSchema = AnyVersionedContract &\n Readonly<{ surfaces: readonly SurfaceId[] }>;\n\nexport type PublishedDatadogAppInputsDefinition<\n TSchema extends AnyDatadogAppInputsSchema,\n> = TSchema &\n Readonly<{\n [publishedDefinitionBrand]: (\n fields: TSchema['latest']['fields'],\n ) => TSchema['latest']['fields'];\n }>;\n\n/** A package-owned definition whose concrete, deliberately invariant fields are unknown. */\nexport type AnyPublishedDatadogAppInputsDefinition = AnyDatadogAppInputsSchema &\n Readonly<{ [publishedDefinitionBrand]: unknown }>;\n\nconst publishedDefinitions = new WeakSet<object>();\n\ntype PortableSchema<TSchema extends AnySchema> = ValueSchema<InferOf<TSchema>>;\n\nconst CONTRACT_IDENTIFIER_PATTERN = /^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$/;\n\nfunction assertValidField(\n contractIdentifier: string,\n name: string,\n field: unknown,\n): asserts field is AnyField {\n if (\n !VALID_FIELD_NAME.test(name) ||\n name.length > MAX_CLAIM_FIELD_NAME_LENGTH ||\n !isAnyFieldShape(field)\n ) {\n throw new Error(\n `Datadog App input field \"${contractIdentifier}.${name}\" must have a name matching ${String(VALID_FIELD_NAME)} of at most ${MAX_CLAIM_FIELD_NAME_LENGTH} characters and be a read-only value or function whose schemas implement Standard Schema V1.`,\n );\n }\n if (field.kind === 'function') {\n for (const inputName of Object.keys(field.inputs)) {\n if (!VALID_FIELD_NAME.test(inputName)) {\n throw new Error(\n `Datadog App input function parameter \"${contractIdentifier}.${name}.${inputName}\" must have a name matching ${String(VALID_FIELD_NAME)}.`,\n );\n }\n }\n if (!hasUsableFunctionTimeout(field)) {\n throw new Error(\n `Datadog App input function field \"${contractIdentifier}.${name}\" declares a timeoutMs no call could meet. It must be greater than 0 and at most ${MAX_TIMER_DELAY_MS}.`,\n );\n }\n }\n}\n\nfunction assertValidContract(\n contract: unknown,\n): asserts contract is AnyContract {\n if (\n !isRecord(contract) ||\n typeof contract.identifier !== 'string' ||\n !CONTRACT_IDENTIFIER_PATTERN.test(contract.identifier)\n ) {\n throw new Error(\n `Datadog App input contract identifier \"${String(isRecord(contract) ? contract.identifier : undefined)}\" must match ${String(CONTRACT_IDENTIFIER_PATTERN)}.`,\n );\n }\n if (\n typeof contract.version !== 'number' ||\n !Number.isSafeInteger(contract.version) ||\n contract.version < 1\n ) {\n throw new Error(\n `Datadog App input contract \"${contract.identifier}\" must have a positive integer version.`,\n );\n }\n if (\n !isRecord(contract.fields) ||\n Object.keys(contract.fields).length === 0 ||\n Object.keys(contract.fields).length > MAX_CLAIM_FIELDS\n ) {\n throw new Error(\n `Datadog App input contract \"${contract.identifier}\" must define between 1 and ${MAX_CLAIM_FIELDS} fields.`,\n );\n }\n for (const [name, field] of Object.entries(contract.fields)) {\n assertValidField(contract.identifier, name, field);\n }\n}\n\nfunction assertValidExtraInputs(\n contractIdentifier: string,\n extraInputs: unknown,\n): void {\n if (!isRecord(extraInputs)) {\n throw new Error(\n `Older Datadog App input contract \"${contractIdentifier}\" must declare its extra inputs as an object.`,\n );\n }\n for (const [name, field] of Object.entries(extraInputs)) {\n assertValidField(contractIdentifier, name, field);\n }\n}\n\ninterface PortableValueBuilder {\n readOnly<TSchema extends AnySchema>(\n schema: ValidationOnlySchema<TSchema>,\n ): ValueField<PortableSchema<TSchema>>;\n}\n\ninterface PortableFunctionBuilder {\n readOnly<\n const TInputs extends Readonly<Record<string, AnySchema>>,\n TResult extends AnySchema,\n >(\n definition: Readonly<{\n inputs: {\n readonly [TName in keyof TInputs]: ValidationOnlySchema<\n TInputs[TName]\n >;\n };\n result: ValidationOnlySchema<TResult>;\n /**\n * Optional per-function override of `FUNCTION_CALL_TIMEOUT_MS`.\n * See `FunctionField.timeoutMs`.\n */\n timeoutMs?: number;\n }>,\n ): FunctionField<\n {\n readonly [TName in keyof TInputs]: PortableSchema<TInputs[TName]>;\n },\n PortableSchema<TResult>\n >;\n}\n\n/** Builds an input value field while hiding its concrete validator type. */\nexport const value: PortableValueBuilder = /* @__PURE__ */ Object.freeze({\n readOnly<TSchema extends AnySchema>(\n schema: ValidationOnlySchema<TSchema>,\n ): ValueField<PortableSchema<TSchema>> {\n return defineValueField.readOnly(schema) as unknown as ValueField<\n PortableSchema<TSchema>\n >;\n },\n});\n\n/** Builds an input function field while hiding its concrete validator types. */\nexport const fn: PortableFunctionBuilder = /* @__PURE__ */ Object.freeze({\n readOnly<\n const TInputs extends Readonly<Record<string, AnySchema>>,\n TResult extends AnySchema,\n >(\n definition: Readonly<{\n inputs: {\n readonly [TName in keyof TInputs]: ValidationOnlySchema<\n TInputs[TName]\n >;\n };\n result: ValidationOnlySchema<TResult>;\n timeoutMs?: number;\n }>,\n ): FunctionField<\n {\n readonly [TName in keyof TInputs]: PortableSchema<TInputs[TName]>;\n },\n PortableSchema<TResult>\n > {\n return defineFunctionField.readOnly(\n definition,\n ) as unknown as FunctionField<\n {\n readonly [TName in keyof TInputs]: PortableSchema<\n TInputs[TName]\n >;\n },\n PortableSchema<TResult>\n >;\n },\n});\n\ntype ValidationOnlyFields<TFields extends Record<string, AnyField>> = {\n readonly [TName in keyof TFields]: TFields[TName] extends ValueField<\n infer TSchema\n >\n ? ValueField<ValidationOnlySchema<TSchema>>\n : TFields[TName] extends FunctionField<infer TInputs, infer TResult>\n ? FunctionField<\n {\n readonly [TInputName in keyof TInputs]: ValidationOnlySchema<\n TInputs[TInputName]\n >;\n },\n ValidationOnlySchema<TResult>\n >\n : never;\n};\n\ntype PortableFields<TFields extends Record<string, AnyField>> = {\n readonly [TName in keyof TFields]: TFields[TName] extends ValueField<\n infer TSchema\n >\n ? ValueField<PortableSchema<TSchema>>\n : TFields[TName] extends FunctionField<infer TInputs, infer TResult>\n ? FunctionField<\n {\n readonly [TInputName in keyof TInputs]: PortableSchema<\n TInputs[TInputName]\n >;\n },\n PortableSchema<TResult>\n >\n : never;\n};\n\nexport type PortableContract<\n TIdentifier extends string,\n TVersion extends ContractVersion,\n TFields extends Record<string, AnyField>,\n> = Contract<PortableFields<TFields>> &\n Readonly<{ identifier: TIdentifier; version: TVersion }>;\n\n/**\n * Defines one version of a package-owned input contract. Concrete validator\n * types are deliberately erased at this boundary: schema authors keep full\n * inference while public declarations expose only Standard Schema.\n *\n * A contract on its own cannot be provided to an app -- only\n * `datadogAppInputsDefinition()`'s output can -- so declaring a version is\n * never the same as offering to serve it.\n */\nexport function datadogAppInputsVersion<\n const TIdentifier extends string,\n const TVersion extends ContractVersion,\n const TFields extends Record<string, AnyField>,\n>(\n definition: Contract<TFields> &\n Readonly<{\n identifier: TIdentifier;\n version: TVersion;\n fields: ValidationOnlyFields<TFields>;\n }>,\n): PortableContract<TIdentifier, TVersion, TFields> {\n const contract = defineContract<TIdentifier, TVersion, TFields>(\n definition as unknown as Parameters<\n typeof defineContract<TIdentifier, TVersion, TFields>\n >[0],\n ) as unknown as PortableContract<TIdentifier, TVersion, TFields>;\n assertValidContract(contract);\n return contract;\n}\n\n/**\n * Publishes one package-owned inputs definition.\n *\n * The common case is one version, declared inline -- `identifier`, `version`,\n * `fields`, and optionally the `surfaces` it is offered on. A schema that has\n * to keep serving older versions instead passes `latest` plus `olderVersions`,\n * so the extra step is paid only where extra versions exist.\n *\n * Either way the result is the single unit both sides deal in: an app claims it\n * without naming a version, and a host provides it without learning that more\n * than one exists. Dropping an `olderVersion()` is how support for that version\n * ends, and simultaneously how the fields a host must supply get smaller.\n */\nexport function datadogAppInputsDefinition<\n const TIdentifier extends string,\n const TVersion extends ContractVersion,\n const TFields extends Record<string, AnyField>,\n const TSurfaces extends readonly SurfaceId[] = typeof EVERY_SURFACE,\n>(\n // `Contract<TFields> &` is the inference site for `TFields`: TS cannot\n // recover it from the mapped `ValidationOnlyFields<TFields>` alone, and\n // silently widens to `Record<string, AnyField>` without this.\n definition: Contract<TFields> &\n Readonly<{\n identifier: TIdentifier;\n version: TVersion;\n fields: ValidationOnlyFields<TFields>;\n /** Surfaces this input is offered on \u2014 read at runtime by the host to gate which schemas are offered per surface. */\n surfaces?: TSurfaces;\n }>,\n): PublishedDatadogAppInputsDefinition<\n DatadogAppInputsSchema<\n PortableContract<TIdentifier, TVersion, TFields>,\n TSurfaces\n >\n>;\nexport function datadogAppInputsDefinition<\n TLatest extends AnyContract,\n const TSurfaces extends readonly SurfaceId[] = typeof EVERY_SURFACE,\n const TOlderVersions extends readonly AnyOlderContractVersion<TLatest>[] =\n readonly [],\n>(\n definition: Readonly<{\n latest: TLatest;\n surfaces?: TSurfaces;\n olderVersions?: TOlderVersions;\n }>,\n): PublishedDatadogAppInputsDefinition<\n DatadogAppInputsSchema<TLatest, TSurfaces, TOlderVersions>\n>;\nexport function datadogAppInputsDefinition(definitionInput: object): unknown {\n const definition = definitionInput as Readonly<Record<string, unknown>>;\n const latest =\n 'latest' in definition\n ? (definition.latest as AnyContract)\n : datadogAppInputsVersion(\n definition as unknown as Parameters<\n typeof datadogAppInputsVersion\n >[0],\n );\n const olderVersions = (definition.olderVersions ??\n []) as readonly AnyOlderContractVersion<AnyContract>[];\n assertValidContract(latest);\n for (const olderVersion of olderVersions) {\n assertValidContract(olderVersion.contract);\n assertValidExtraInputs(latest.identifier, olderVersion.extraInputs);\n }\n const schema = defineVersionedContract(latest, ...olderVersions);\n const published = Object.freeze({\n ...schema,\n surfaces: Object.freeze([\n ...((definition.surfaces as readonly SurfaceId[] | undefined) ??\n EVERY_SURFACE),\n ]),\n });\n publishedDefinitions.add(published);\n return published;\n}\n\n/** Rejects copied or user-authored definitions at the public React boundary. */\nexport function assertPublishedDatadogAppInputsDefinition(\n definition: unknown,\n): asserts definition is AnyPublishedDatadogAppInputsDefinition {\n if (\n typeof definition !== 'object' ||\n definition === null ||\n !publishedDefinitions.has(definition)\n ) {\n throw new Error(\n 'useDatadogAppInput() requires a definition exported by @datadog/apps-frontend/inputs/schema.',\n );\n }\n}\n\n/**\n * Reports whether a value is a definition created by `datadogAppInputsDefinition()`\n * (i.e. published through `@datadog/apps-frontend/inputs/schema`). Backed by the\n * same `WeakSet` brand as `assertPublishedDatadogAppInputsDefinition`, so it\n * cannot be spoofed by a duck-typed lookalike.\n */\nexport function isPublishedDatadogAppInputsDefinition(\n definition: unknown,\n): definition is PublishedDatadogAppInputsDefinition<AnyDatadogAppInputsSchema> {\n return (\n typeof definition === 'object' &&\n definition !== null &&\n publishedDefinitions.has(definition)\n );\n}\n\n/**\n * Turns one plain value into the field descriptor that carries it: a function\n * becomes a callable field with validated inputs and result, anything else a\n * read-only value field. This is the inverse of the erasure `value.readOnly()`\n * and `fn.readOnly()` perform, which is what lets a schema be *declared* in the\n * terms a consumer thinks in while being *built* from real validators.\n */\n// `[TValue] extends [...]` rather than a naked parameter: a naked one\n// distributes, so a union value like `'light' | 'dark'` would become a *union of\n// fields* instead of one field carrying a union.\ntype FieldFor<TValue> = [TValue] extends [\n (inputs: infer TInputs) => infer TResult,\n]\n ? FunctionField<\n { readonly [TName in keyof TInputs]: ValueSchema<TInputs[TName]> },\n ValueSchema<Awaited<TResult>>\n >\n : ValueField<ValueSchema<TValue>>;\n\ntype FieldsFor<TShape extends Readonly<Record<string, unknown>>> = {\n readonly [TName in keyof TShape]: FieldFor<TShape[TName]>;\n};\n\n/**\n * One Datadog App input, described the way it is used rather than the way it is\n * built: its identifier, the values a claim hands you, and the surfaces it is\n * offered on.\n *\n * This is the type a schema annotates itself with, so it is also what an editor\n * shows on hover. Versions are deliberately absent -- how many exist, and which\n * one a given peer gets, is settled by the package and is not a caller's\n * concern.\n *\n * @example\n * ```ts\n * DatadogAppInput<\n * 'datadog.idp.homepage',\n * { position: number; move: (inputs: { delta: number }) => number },\n * readonly ['datadog.idp.homepage']\n * >\n * ```\n */\nexport type DatadogAppInput<\n TIdentifier extends string,\n TShape extends Readonly<Record<string, unknown>>,\n TSurfaces extends readonly SurfaceId[] = typeof EVERY_SURFACE,\n> = PublishedDatadogAppInputsDefinition<\n DatadogAppInputsSchema<\n Contract<FieldsFor<TShape>> &\n Readonly<{ identifier: TIdentifier; version: ContractVersion }>,\n TSurfaces\n >\n>;\n"],
5
+ "mappings": "gGA4RO,IAAMA,EAQT,CACA,uBACA,4BACA,2BACA,sBACA,iBACA,mBACA,mBACJ,ECxEA,SAASC,EACLC,EACAC,EACAC,EACU,CAKV,IAAMC,EACF,OAAO,OAAO,IAAI,EAChBC,EAAqCH,EAC3C,OAAW,CAACI,EAAMC,CAAK,IAAK,OAAO,QAAQN,EAAS,MAAM,EACtDG,EAAeE,CAAI,EACfC,EAAM,OAAS,QACRF,EAAUC,CAAI,EACf,OAAO,OAAO,CACV,OAAQD,EAAUC,CAAI,CAC1B,CAAC,EAEf,OAAOE,EAAiBP,EAAU,OAAO,OAAOG,CAAc,EAAGD,CAAM,CAC3E,CAGA,SAASM,EACLP,EACAQ,EACiC,CAIjC,IAAMC,EAAkC,OAAO,OAAO,IAAI,EAC1D,QAAWL,KAAQI,EACfC,EAAOL,CAAI,EAAIJ,EAAOI,CAAI,EAE9B,OAAOK,CACX,CAOA,SAASC,EAAYC,EAAgBC,EAA0B,CAC3D,GAAID,EAAK,OAASC,EAAM,KACpB,MAAO,GAEX,GAAID,EAAK,OAAS,SAAWC,EAAM,OAAS,QACxC,OAAOD,EAAK,SAAWC,EAAM,OAEjC,GAAID,EAAK,OAAS,YAAcC,EAAM,OAAS,WAAY,CACvD,IAAMC,EAAY,OAAO,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AAOD,EAAiB,SAASC,CAAM,CAG3C,CACJ,CAAC,EAsFM,SAASC,EAKZC,EAMgD,CAChD,IAAMC,EAAWC,EACbF,CAGJ,EACA,OAAAG,EAAoBF,CAAQ,EACrBA,CACX,CAoDO,SAASG,EAA2BC,EAAkC,CACzE,IAAML,EAAaK,EACbC,EACF,WAAYN,EACLA,EAAW,OACZD,EACIC,CAGJ,EACJO,EAAiBP,EAAW,eAC9B,CAAC,EACLG,EAAoBG,CAAM,EAC1B,QAAWE,KAAgBD,EACvBJ,EAAoBK,EAAa,QAAQ,EACzCC,EAAuBH,EAAO,WAAYE,EAAa,WAAW,EAEtE,IAAME,EAASC,EAAwBL,EAAQ,GAAGC,CAAa,EACzDK,EAAY,OAAO,OAAO,CAC5B,GAAGF,EACH,SAAU,OAAO,OAAO,CACpB,GAAKV,EAAW,UACZa,CACR,CAAC,CACL,CAAC,EACD,OAAAC,EAAqB,IAAIF,CAAS,EAC3BA,CACX,CAGO,SAASG,EACZf,EAC4D,CAC5D,GACI,OAAOA,GAAe,UACtBA,IAAe,MACf,CAACc,EAAqB,IAAId,CAAU,EAEpC,MAAM,IAAI,MACN,8FACJ,CAER",
6
+ "names": ["EVERY_SURFACE", "toHostModule", "contract", "fields", "signal", "implementation", "rawFields", "name", "field", "createHostModule", "pickFields", "names", "picked", "isSameField", "left", "right", "leftNames", "rightNames", "mergeVersionedFields", "latest", "olderVersions", "merged", "older", "existing", "defineVersionedContract", "versions", "latestNames", "allFields", "flat", "latestImplementation", "modules", "derived", "publishedDefinitions", "CONTRACT_IDENTIFIER_PATTERN", "assertValidField", "contractIdentifier", "name", "field", "VALID_FIELD_NAME", "MAX_CLAIM_FIELD_NAME_LENGTH", "isAnyFieldShape", "inputName", "hasUsableFunctionTimeout", "assertValidContract", "contract", "isRecord", "MAX_CLAIM_FIELDS", "assertValidExtraInputs", "extraInputs", "value", "schema", "datadogAppInputsVersion", "definition", "contract", "defineContract", "assertValidContract", "datadogAppInputsDefinition", "definitionInput", "latest", "olderVersions", "olderVersion", "assertValidExtraInputs", "schema", "defineVersionedContract", "published", "EVERY_SURFACE", "publishedDefinitions", "assertPublishedDatadogAppInputsDefinition"]
7
+ }
@@ -3,5 +3,5 @@
3
3
  * Copyright 2019-Present Datadog, Inc.
4
4
  */
5
5
 
6
- var _=Object.defineProperty;var u=e=>{throw TypeError(e)};var A=(e,n,t)=>n in e?_(e,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[n]=t;var I=(e,n,t)=>A(e,typeof n!="symbol"?n+"":n,t),s=(e,n,t)=>n.has(e)||u("Cannot "+t);var w=(e,n,t)=>(s(e,n,"read from private field"),t?t.call(e):n.get(e)),v=(e,n,t)=>n.has(e)?u("Cannot add the same private member more than once"):n instanceof WeakSet?n.add(e):n.set(e,t),V=(e,n,t,r)=>(s(e,n,"write to private field"),r?r.call(e,t):n.set(e,t),t),L=(e,n,t)=>(s(e,n,"access private method"),t);function k(e,n){if(!Number.isFinite(n)||n<0||n>2147483647)throw new RangeError(`${e} must be a finite number between 0 and 2147483647.`)}var C=1e4,D=5e3,j=250,H=1e3,$=1e4,X=45e3,z=128,U=256,P=256,B=128,Y=32,a=128,f=256;var g="[Datadog Apps embedding]";function o(e,n=0){if(!(e instanceof Error))return e;try{let t={name:e.name,message:e.message};return typeof e.stack=="string"&&(t.stack=e.stack),e.cause!==void 0&&(t.cause=n<3?o(e.cause,n+1):"(cause chain truncated)"),t}catch{return"(cause could not be described)"}}function W(e){return"cause"in e?{...e,cause:o(e.cause)}:e}function p(e,n,t){try{globalThis.console?.[e](`${g} ${n}`,t)}catch{}}function Z(e,n={}){p("warn",e,n)}function c(e,n={}){p("error",e,n)}var m=0;function K(e){return m+=1,`${e}:${S()}:${m.toString(36)}`}function S(){let e=new Uint8Array(8);globalThis.crypto.getRandomValues(e);let n="";for(let t of e)n+=t.toString(16).padStart(2,"0");return n}function Q(e){return{ok:!0,value:e}}function ee(e){return{ok:!1,error:e}}function i(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function y(e,n){return typeof e=="string"&&e.length>0&&(n===void 0||e.length<=n)}function ne(e,n){try{n()}catch(t){c("a teardown step failed",{description:e,cause:o(t)})}}function te(e,...n){for(let t of[...e])try{t(...n)}catch(r){c("an embedding listener threw",{cause:o(r)}),globalThis.queueMicrotask(()=>{throw r})}}var O=/^[A-Za-z][A-Za-z0-9_]*$/,b=new WeakSet;function se(e,n,t){let r=Object.create(null);for(let[h,E]of Object.entries(n))r[h]=E;Object.freeze(r);let l=Object.freeze(t===void 0?{contract:e,implementation:r}:{contract:e,implementation:r,signal:t});return b.add(l),l}function d(e){if(!(typeof e=="object"&&e!==null||typeof e=="function"))return!1;let n=e["~standard"];return i(n)&&n.version===1&&typeof n.validate=="function"}function M(e){return i(e)&&e.kind==="value"&&d(e.schema)}function R(e){return i(e)&&e.kind==="function"&&i(e.inputs)&&Object.entries(e.inputs).every(([n,t])=>n.length>0&&d(t))&&d(e.result)}function x(e){return M(e)||R(e)}function F(e){return e.kind!=="function"||e.timeoutMs===void 0||typeof e.timeoutMs=="number"&&Number.isFinite(e.timeoutMs)&&e.timeoutMs>0&&e.timeoutMs<=2147483647}var ae=Object.freeze({readOnly(e){return Object.freeze({kind:"value",schema:e})}});function ce(e){if(!y(e.identifier))throw new Error(`Invalid embedding contract identifier "${String(e.identifier)}".`);if(!Number.isSafeInteger(e.version)||e.version<1)throw new Error(`Embedding contract "${e.identifier}" must have a positive integer version.`);let n=Object.entries(e.fields);if(n.length===0||n.length>a)throw new Error(`Embedding contract "${e.identifier}" must define between 1 and ${a} fields.`);for(let[t,r]of n){if(!O.test(t)||t.length>f||!x(r))throw new Error(`Embedding contract field "${e.identifier}.${t}" must be a named read-only value or function whose schemas implement Standard Schema V1.`);if(!F(r))throw new Error(`Embedding contract field "${e.identifier}.${t}" declares a timeoutMs no call could meet. It must be greater than 0 and at most ${2147483647}.`)}return Object.freeze({identifier:e.identifier,version:e.version,fields:Object.freeze(Object.fromEntries(n.map(([t,r])=>[t,r.kind==="value"?Object.freeze({...r,schema:r.schema}):Object.freeze({...r,inputs:Object.freeze({...r.inputs}),result:r.result})])))})}export{I as a,w as b,v as c,V as d,L as e,k as f,C as g,D as h,j as i,H as j,$ as k,X as l,z as m,U as n,P as o,B as p,Y as q,a as r,f as s,o as t,W as u,Z as v,c as w,K as x,Q as y,ee as z,i as A,y as B,ne as C,te as D,O as E,se as F,x as G,F as H,ae as I,ce as J};
7
- //# sourceMappingURL=chunk-X34MSTJH.js.map
6
+ var _=Object.defineProperty;var u=e=>{throw TypeError(e)};var A=(e,n,t)=>n in e?_(e,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[n]=t;var I=(e,n,t)=>A(e,typeof n!="symbol"?n+"":n,t),s=(e,n,t)=>n.has(e)||u("Cannot "+t);var v=(e,n,t)=>(s(e,n,"read from private field"),t?t.call(e):n.get(e)),w=(e,n,t)=>n.has(e)?u("Cannot add the same private member more than once"):n instanceof WeakSet?n.add(e):n.set(e,t),V=(e,n,t,r)=>(s(e,n,"write to private field"),r?r.call(e,t):n.set(e,t),t),L=(e,n,t)=>(s(e,n,"access private method"),t);function k(e,n){if(!Number.isFinite(n)||n<0||n>2147483647)throw new RangeError(`${e} must be a finite number between 0 and 2147483647.`)}var C=1e4,D=5e3,j=250,H=1e3,$=1e4,X=45e3,z=128,U=256,P=256,B=128,Y=32,a=128,f=256;var g="[Datadog Apps embedding]";function o(e,n=0){if(!(e instanceof Error))return e;try{let t={name:e.name,message:e.message};return typeof e.stack=="string"&&(t.stack=e.stack),e.cause!==void 0&&(t.cause=n<3?o(e.cause,n+1):"(cause chain truncated)"),t}catch{return"(cause could not be described)"}}function W(e){return"cause"in e?{...e,cause:o(e.cause)}:e}function m(e,n,t){try{globalThis.console?.[e](`${g} ${n}`,t)}catch{}}function Z(e,n={}){m("warn",e,n)}function c(e,n={}){m("error",e,n)}var p=0;function K(e){return p+=1,`${e}:${S()}:${p.toString(36)}`}function S(){let e=new Uint8Array(8);globalThis.crypto.getRandomValues(e);let n="";for(let t of e)n+=t.toString(16).padStart(2,"0");return n}function Q(e){return{ok:!0,value:e}}function ee(e){return{ok:!1,error:e}}function i(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function y(e,n){return typeof e=="string"&&e.length>0&&(n===void 0||e.length<=n)}function ne(e,n){try{n()}catch(t){c("a teardown step failed",{description:e,cause:o(t)})}}function te(e,...n){for(let t of[...e])try{t(...n)}catch(r){c("an embedding listener threw",{cause:o(r)}),globalThis.queueMicrotask(()=>{throw r})}}var O=/^[A-Za-z][A-Za-z0-9_]*$/,b=new WeakSet;function se(e,n,t){let r=Object.create(null);for(let[h,E]of Object.entries(n))r[h]=E;Object.freeze(r);let l=Object.freeze(t===void 0?{contract:e,implementation:r}:{contract:e,implementation:r,signal:t});return b.add(l),l}function d(e){if(!(typeof e=="object"&&e!==null||typeof e=="function"))return!1;let n=e["~standard"];return i(n)&&n.version===1&&typeof n.validate=="function"}function M(e){return i(e)&&e.kind==="value"&&d(e.schema)}function R(e){return i(e)&&e.kind==="function"&&i(e.inputs)&&Object.entries(e.inputs).every(([n,t])=>n.length>0&&d(t))&&d(e.result)}function x(e){return M(e)||R(e)}function F(e){return e.kind!=="function"||e.timeoutMs===void 0||typeof e.timeoutMs=="number"&&Number.isFinite(e.timeoutMs)&&e.timeoutMs>0&&e.timeoutMs<=2147483647}var ae=Object.freeze({readOnly(e){return Object.freeze({kind:"value",schema:e})}}),ce=Object.freeze({readOnly({inputs:e,result:n,timeoutMs:t}){return Object.freeze(t===void 0?{kind:"function",inputs:e,result:n}:{kind:"function",inputs:e,result:n,timeoutMs:t})}});function de(e){if(!y(e.identifier))throw new Error(`Invalid embedding contract identifier "${String(e.identifier)}".`);if(!Number.isSafeInteger(e.version)||e.version<1)throw new Error(`Embedding contract "${e.identifier}" must have a positive integer version.`);let n=Object.entries(e.fields);if(n.length===0||n.length>a)throw new Error(`Embedding contract "${e.identifier}" must define between 1 and ${a} fields.`);for(let[t,r]of n){if(!O.test(t)||t.length>f||!x(r))throw new Error(`Embedding contract field "${e.identifier}.${t}" must be a named read-only value or function whose schemas implement Standard Schema V1.`);if(!F(r))throw new Error(`Embedding contract field "${e.identifier}.${t}" declares a timeoutMs no call could meet. It must be greater than 0 and at most ${2147483647}.`)}return Object.freeze({identifier:e.identifier,version:e.version,fields:Object.freeze(Object.fromEntries(n.map(([t,r])=>[t,r.kind==="value"?Object.freeze({...r,schema:r.schema}):Object.freeze({...r,inputs:Object.freeze({...r.inputs}),result:r.result})])))})}export{I as a,v as b,w as c,V as d,L as e,k as f,C as g,D as h,j as i,H as j,$ as k,X as l,z as m,U as n,P as o,B as p,Y as q,a as r,f as s,o as t,W as u,Z as v,c as w,K as x,Q as y,ee as z,i as A,y as B,ne as C,te as D,O as E,se as F,x as G,F as H,ae as I,ce as J,de as K};
7
+ //# sourceMappingURL=chunk-LEEYMNMO.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/embedding/config.ts", "../../../src/embedding/diagnostics.ts", "../../../src/embedding/shared.ts", "../../../src/embedding/contract.ts"],
4
- "sourcesContent": ["/**\n * Every tunable the embedding protocol uses -- timeouts and the limits that\n * bound peer-influenced state -- together in one place with an obvious name\n * each, instead of scattered as same-looking magic numbers across unrelated\n * files.\n */\n\nexport const PROTOCOL_VERSION = 1;\n\n// --- Timeouts -----------------------------------------------------------\n//\n// Each one is a local decision made independently by whichever side enforces\n// it -- none of these are negotiated with, or need to match, the peer's own\n// value for the same phase.\n\n/** Phase 1: transferring the private control port across the window boundary. */\nexport const BOOTSTRAP_TIMEOUT_MS = 10_000;\n\n/** Phases 2 and 3: protocol compatibility negotiation and bringing up the\n * operational protocol on the transferred port. Each phase receives this\n * full deadline independently. */\nexport const CONNECT_TIMEOUT_MS = 10_000;\n\n/** How long the app waits for the host to answer its claim of a module. */\nexport const CLAIM_TIMEOUT_MS = 5_000;\n\n/** How long a function call is allowed to run (host side) or be waited on\n * (app side). Each side enforces this purely locally -- it is never sent\n * over the wire, and one side never needs to know the other's value: the\n * watchdog that fires first just wins through the normal error path, the\n * same way any other host/app-independent failure already does. */\nexport const FUNCTION_CALL_TIMEOUT_MS = 600_000;\n\n/**\n * Ceiling for a `FunctionField.timeoutMs` override: the largest delay\n * `setTimeout` accepts. Anything above it silently overflows the 32-bit\n * signed timer and fires almost immediately, inverting the longest deadline\n * an author can ask for into the shortest one they could get.\n */\nexport const MAX_TIMER_DELAY_MS = 2_147_483_647;\n\n/** Reject a public timeout override that `setTimeout` cannot represent. */\nexport function assertValidTimerDelay(name: string, timeoutMs: number): void {\n if (\n !Number.isFinite(timeoutMs) ||\n timeoutMs < 0 ||\n timeoutMs > MAX_TIMER_DELAY_MS\n ) {\n throw new RangeError(\n `${name} must be a finite number between 0 and ${MAX_TIMER_DELAY_MS}.`,\n );\n }\n}\n\n/** How often a heartbeat ping is sent, and how long a reply is awaited\n * before it counts as a miss. */\nexport const HEARTBEAT_INTERVAL_MS = 10_000;\nexport const HEARTBEAT_DEADLINE_MS = 5_000;\n\n/** Grace period between posting a close envelope and actually tearing down\n * the transport, so the envelope isn't truncated in flight. */\nexport const CLOSE_DELIVERY_TIMEOUT_MS = 250;\n\n/** Reconnection backoff: starting delay, cap, and how long to keep retrying\n * before giving up on the whole recovery attempt. */\nexport const RECONNECT_RETRY_MS = 1_000;\nexport const RECONNECT_MAX_RETRY_MS = 10_000;\nexport const RECONNECT_GIVE_UP_AFTER_MS = 45_000;\n\n// --- Limits ---------------------------------------------------------------\n//\n// These bound state retained at the request of iframe code, so an\n// adversarial or malformed peer can't grow it without limit. Both peers\n// validate against them independently.\n\nexport const MAX_LIVE_HOST_CLAIMS = 128;\nexport const MAX_CLAIM_ID_LENGTH = 256;\nexport const MAX_CALL_ID_LENGTH = 256;\nexport const MAX_LIVE_HOST_FUNCTION_CALLS = 128;\nexport const MAX_PENDING_ENDPOINT_OPERATIONS = 32;\nexport const MAX_CLAIM_FIELDS = 128;\nexport const MAX_CLAIM_FIELD_NAME_LENGTH = 256;\n", "/**\n * Console diagnostics for every embedding outcome that is not\n * starting -> connecting -> connected.\n *\n * Debugging an embedding failure means reasoning about two documents that each\n * see half of the connection: the Datadog page owns the host listener, the app\n * iframe owns the connection handle, and neither observes why the other gave\n * up. Every failure, rejection, timeout, and lost connection therefore reports\n * itself locally, naming the side that produced it and carrying the detail the\n * wire deliberately does not: raw causes, validation issues, claim and call\n * identifiers, attempt counts, and the deadline that expired.\n *\n * This module never throws. It runs on paths that are already failing, in\n * browsers we do not control, so a missing or hostile `console` must not\n * replace the failure being reported.\n */\n\nimport type { AnyError } from './types';\n\nconst PREFIX = '[Datadog Apps embedding]';\n\n/** How deep an `Error.cause` chain is described before it is truncated. */\nconst MAX_CAUSE_DEPTH = 3;\n\n/** Which peer produced a log line; both peers run this code. */\nexport type DiagnosticSide = 'app' | 'host';\n\nexport type DiagnosticDetail = Readonly<Record<string, unknown>>;\n\n/**\n * Renders an arbitrary thrown value as inspectable data. Errors lose their\n * `name`, `message`, `stack`, and `cause` when a console is handed a bare\n * `Error` inside an object in some environments, so those are spread out\n * explicitly; anything else is passed through for the console to format.\n */\nexport function describeCause(cause: unknown, depth = 0): unknown {\n if (!(cause instanceof Error)) {\n return cause;\n }\n // A peer-influenced Error may have hostile name/message/stack/cause\n // accessors; this module's \"never throws\" guarantee must hold even then.\n try {\n const described: Record<string, unknown> = {\n name: cause.name,\n message: cause.message,\n };\n if (typeof cause.stack === 'string') {\n described.stack = cause.stack;\n }\n if (cause.cause !== undefined) {\n described.cause =\n depth < MAX_CAUSE_DEPTH\n ? describeCause(cause.cause, depth + 1)\n : '(cause chain truncated)';\n }\n return described;\n } catch {\n return '(cause could not be described)';\n }\n}\n\n/**\n * Renders a wire error for logging. Every code carries structured-clone-safe\n * data already, except the local-only `cause` of `TRANSPORT_FAILED`, which is\n * where the actual explanation usually lives.\n */\nexport function describeError(error: AnyError): DiagnosticDetail {\n return 'cause' in error\n ? { ...error, cause: describeCause(error.cause) }\n : error;\n}\n\nfunction log(\n level: 'warn' | 'error',\n event: string,\n detail: DiagnosticDetail,\n): void {\n try {\n globalThis.console?.[level](`${PREFIX} ${event}`, detail);\n } catch {\n // A console that cannot be used is not a reason to lose the outcome\n // this call was reporting.\n }\n}\n\n/** A failure the connection expects to recover from, or a degraded outcome. */\nexport function logWarning(event: string, detail: DiagnosticDetail = {}): void {\n log('warn', event, detail);\n}\n\n/** A failure a consumer observes: terminal, unrecoverable, or data-losing. */\nexport function logFailure(event: string, detail: DiagnosticDetail = {}): void {\n log('error', event, detail);\n}\n", "import { describeCause, logFailure } from './diagnostics';\nimport type { Result } from './types';\n\nlet nextId = 0;\n\n/**\n * The counter prevents local reuse if randomness repeats; the random segment\n * makes heartbeat nonces difficult for the peer to predict.\n */\nexport function createId(prefix: string): string {\n nextId += 1;\n return `${prefix}:${randomSegment()}:${nextId.toString(36)}`;\n}\n\nfunction randomSegment(): string {\n const bytes = new Uint8Array(8);\n globalThis.crypto.getRandomValues(bytes);\n let segment = '';\n for (const byte of bytes) {\n segment += byte.toString(16).padStart(2, '0');\n }\n return segment;\n}\n\nexport function success<TValue>(value: TValue): Result<TValue, never> {\n return { ok: true, value };\n}\n\nexport function err<TError>(value: TError): Result<never, TError> {\n return { ok: false, error: value };\n}\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * True when `value` is a well-formed identifier: a non-empty string. Bounds\n * its length to at most `limit` characters only when a limit is supplied.\n */\nexport function isValidIdentifier(\n value: unknown,\n limit?: number,\n): value is string {\n return (\n typeof value === 'string' &&\n value.length > 0 &&\n (limit === undefined || value.length <= limit)\n );\n}\n\n/**\n * Runs a cleanup action that must not throw into its caller. Teardown runs on\n * paths that are already failing, so a secondary failure is reported and\n * swallowed instead of replacing the outcome the caller is about to return.\n */\nexport function teardown(description: string, action: () => void): void {\n try {\n action();\n } catch (error) {\n logFailure('a teardown step failed', {\n description,\n cause: describeCause(error),\n });\n }\n}\n\n/**\n * Calls every listener, isolating exceptions so one listener throwing doesn't\n * stop the rest from being notified or propagate into the caller that\n * triggered the notification.\n */\nexport function notifyListeners<TArgs extends readonly unknown[] = []>(\n listeners: Iterable<(...args: TArgs) => void>,\n ...args: TArgs\n): void {\n for (const listener of [...listeners]) {\n try {\n listener(...args);\n } catch (error) {\n // Rethrown out of band, where the stack no longer shows that\n // embedding was notifying a listener.\n logFailure('an embedding listener threw', {\n cause: describeCause(error),\n });\n globalThis.queueMicrotask(() => {\n throw error;\n });\n }\n }\n}\n", "import {\n MAX_CLAIM_FIELDS,\n MAX_CLAIM_FIELD_NAME_LENGTH,\n MAX_TIMER_DELAY_MS,\n} from './config';\nimport { isRecord, isValidIdentifier } from './shared';\nimport type {\n AnyContract,\n AnyField,\n AnyFunctionField,\n AnySchema,\n Contract,\n ContractVersion,\n FunctionField,\n HostFunction,\n HostModule,\n LiveValue,\n ValidationOnlySchema,\n ValueField,\n} from './types';\n\n/**\n * A field name must be a valid own-property identifier the wire protocol\n * will actually carry: excludes \"__proto__\" and other names that a plain\n * object assignment would resolve against the prototype chain instead of\n * creating an own property. Exported so every place a contract-shaped field\n * name is declared (e.g. an older version's `extraInputs`) enforces the same\n * shape, not just `defineContract` itself.\n */\nexport const VALID_FIELD_NAME: RegExp = /^[A-Za-z][A-Za-z0-9_]*$/;\n\n/**\n * Every module this package has minted. Backs the runtime half of\n * `HostModule`'s brand, so a structurally-identical object built elsewhere is\n * rejected at `listen()` even where types were bypassed.\n */\nconst mintedHostModules = new WeakSet<object>();\n\n/**\n * The only way a `HostModule` comes into existence. Kept here, beside the\n * validation it has to satisfy, and deliberately not re-exported from\n * `@datadog/apps-frontend/embedding/internal` -- a host reaches modules only\n * as the output of providing an inputs definition, never by naming a version\n * and building one itself.\n */\nexport function createHostModule(\n contract: AnyContract,\n implementation: Readonly<Record<string, LiveValue<unknown> | HostFunction>>,\n signal?: AbortSignal,\n): HostModule {\n // A null-prototype snapshot means a wire-supplied field name (e.g.\n // \"__proto__\" or \"constructor\") can never resolve to an inherited\n // Object.prototype member when this dict is later indexed by that name.\n const snapshot: Record<string, LiveValue<unknown> | HostFunction> =\n Object.create(null);\n for (const [name, provider] of Object.entries(implementation)) {\n snapshot[name] = provider;\n }\n Object.freeze(snapshot);\n const module = Object.freeze(\n signal === undefined\n ? { contract, implementation: snapshot }\n : { contract, implementation: snapshot, signal },\n ) as unknown as HostModule;\n mintedHostModules.add(module);\n return module;\n}\n\nfunction isSchemaShape(value: unknown): value is AnySchema {\n if (\n !(\n (typeof value === 'object' && value !== null) ||\n typeof value === 'function'\n )\n ) {\n return false;\n }\n const standard = (value as AnySchema)['~standard'];\n return (\n isRecord(standard) &&\n standard.version === 1 &&\n typeof standard.validate === 'function'\n );\n}\n\n/**\n * True when `field` has the generic shape of a read-only value field.\n * Ignores identifier-name rules and implementation matching, which are\n * caller-specific (e.g. host modules also validate against a provider).\n */\nexport function isValueFieldShape(\n field: unknown,\n): field is ValueField<AnySchema> {\n return (\n isRecord(field) && field.kind === 'value' && isSchemaShape(field.schema)\n );\n}\n\n/**\n * True when `field` has the generic shape of a callable function field.\n * Ignores identifier-name rules and implementation matching, which are\n * caller-specific (e.g. host modules also validate against a provider).\n */\nexport function isFunctionFieldShape(\n field: unknown,\n): field is AnyFunctionField {\n return (\n isRecord(field) &&\n field.kind === 'function' &&\n isRecord(field.inputs) &&\n Object.entries(field.inputs).every(\n ([name, schema]) => name.length > 0 && isSchemaShape(schema),\n ) &&\n isSchemaShape(field.result)\n );\n}\n\n/** True when `field` has the generic shape of any well-formed contract field. */\nexport function isAnyFieldShape(field: unknown): field is AnyField {\n return isValueFieldShape(field) || isFunctionFieldShape(field);\n}\n\n/**\n * True when a function field's optional `timeoutMs` is a deadline a call could\n * actually meet -- see `FunctionField.timeoutMs` for why each end is not.\n *\n * Deliberately separate from `isFunctionFieldShape`: this is about a value being\n * sensible, not about the field being a function, so folding it in would make an\n * out-of-range deadline report as a malformed shape or a mismatched provider.\n */\nexport function hasUsableFunctionTimeout(field: AnyField): boolean {\n return (\n field.kind !== 'function' ||\n field.timeoutMs === undefined ||\n (typeof field.timeoutMs === 'number' &&\n Number.isFinite(field.timeoutMs) &&\n field.timeoutMs > 0 &&\n field.timeoutMs <= MAX_TIMER_DELAY_MS)\n );\n}\n\ninterface ReadOnlyValueBuilder {\n readOnly<TSchema extends AnySchema>(\n schema: ValidationOnlySchema<TSchema>,\n ): ValueField<TSchema>;\n}\n\ninterface ReadOnlyFunctionBuilder {\n readOnly<\n const TInputs extends Readonly<Record<string, AnySchema>>,\n TResult extends AnySchema,\n >(\n definition: Readonly<{\n inputs: {\n readonly [TName in keyof TInputs]: ValidationOnlySchema<\n TInputs[TName]\n >;\n };\n result: ValidationOnlySchema<TResult>;\n /**\n * Optional per-function override of `FUNCTION_CALL_TIMEOUT_MS`.\n * See `FunctionField.timeoutMs`.\n */\n timeoutMs?: number;\n }>,\n ): FunctionField<TInputs, TResult>;\n}\n\n/**\n * Builds a value field for any embedding contract. `readOnly` is the only\n * builder today because no transport exists for an app to write a value\n * back to the host; the name leaves room for a future writable builder\n * without implying one exists yet.\n */\nexport const value: ReadOnlyValueBuilder = /* @__PURE__ */ Object.freeze({\n readOnly<TSchema extends AnySchema>(\n schema: ValidationOnlySchema<TSchema>,\n ): ValueField<TSchema> {\n return Object.freeze({ kind: 'value', schema });\n },\n});\n\n/** Builds a callable function field for any embedding contract. */\nexport const fn: ReadOnlyFunctionBuilder = /* @__PURE__ */ Object.freeze({\n readOnly<\n const TInputs extends Readonly<Record<string, AnySchema>>,\n TResult extends AnySchema,\n >({\n inputs,\n result,\n timeoutMs,\n }: Readonly<{\n inputs: {\n readonly [TName in keyof TInputs]: ValidationOnlySchema<\n TInputs[TName]\n >;\n };\n result: ValidationOnlySchema<TResult>;\n timeoutMs?: number;\n }>): FunctionField<TInputs, TResult> {\n // Omitted entirely rather than stored as an explicit `undefined`, so\n // `'timeoutMs' in field` answers whether an override was declared.\n return Object.freeze(\n timeoutMs === undefined\n ? { kind: 'function', inputs, result }\n : { kind: 'function', inputs, result, timeoutMs },\n );\n },\n});\n\ntype ValidationOnlyField<TField extends AnyField> =\n TField extends Readonly<{\n kind: 'value';\n schema: infer TSchema extends AnySchema;\n }>\n ? TField & Readonly<{ schema: ValidationOnlySchema<TSchema> }>\n : TField extends Readonly<{\n kind: 'function';\n inputs: infer TInputs extends Readonly<\n Record<string, AnySchema>\n >;\n result: infer TResult extends AnySchema;\n }>\n ? TField &\n Readonly<{\n inputs: {\n readonly [TName in keyof TInputs]: ValidationOnlySchema<\n TInputs[TName]\n >;\n };\n result: ValidationOnlySchema<TResult>;\n }>\n : never;\n\ntype ValidationOnlyFields<TFields extends Record<string, AnyField>> = {\n readonly [TName in keyof TFields]: ValidationOnlyField<TFields[TName]>;\n};\n\n/**\n * Assembles and validates a well-formed `Contract`: the one place any\n * claim-defining module builds an identifier, version, and fields into the\n * shape the embedding protocol requires. Field-shape correctness reuses\n * `isAnyFieldShape` so there is a single source of truth for what a\n * contract field looks like, shared with the host-registration gate above.\n */\nexport function defineContract<\n const TIdentifier extends string,\n const TVersion extends ContractVersion,\n const TFields extends Record<string, AnyField>,\n>(\n definition: Contract<TFields> &\n Readonly<{\n identifier: TIdentifier;\n version: TVersion;\n fields: ValidationOnlyFields<TFields>;\n }>,\n): Contract<TFields> &\n Readonly<{ identifier: TIdentifier; version: TVersion }> {\n if (!isValidIdentifier(definition.identifier)) {\n throw new Error(\n `Invalid embedding contract identifier \"${String(definition.identifier)}\".`,\n );\n }\n if (!Number.isSafeInteger(definition.version) || definition.version < 1) {\n throw new Error(\n `Embedding contract \"${definition.identifier}\" must have a positive integer version.`,\n );\n }\n\n const entries = Object.entries(definition.fields);\n if (entries.length === 0 || entries.length > MAX_CLAIM_FIELDS) {\n throw new Error(\n `Embedding contract \"${definition.identifier}\" must define between 1 and ${MAX_CLAIM_FIELDS} fields.`,\n );\n }\n for (const [name, field] of entries) {\n if (\n !VALID_FIELD_NAME.test(name) ||\n name.length > MAX_CLAIM_FIELD_NAME_LENGTH ||\n !isAnyFieldShape(field)\n ) {\n throw new Error(\n `Embedding contract field \"${definition.identifier}.${name}\" must be a named read-only value or function whose schemas implement Standard Schema V1.`,\n );\n }\n if (!hasUsableFunctionTimeout(field)) {\n throw new Error(\n `Embedding contract field \"${definition.identifier}.${name}\" declares a timeoutMs no call could meet. It must be greater than 0 and at most ${MAX_TIMER_DELAY_MS}.`,\n );\n }\n }\n\n return Object.freeze({\n identifier: definition.identifier,\n version: definition.version,\n fields: Object.freeze(\n Object.fromEntries(\n entries.map(([name, field]) => [\n name,\n field.kind === 'value'\n ? Object.freeze({ ...field, schema: field.schema })\n : Object.freeze({\n ...field,\n inputs: Object.freeze({ ...field.inputs }),\n result: field.result,\n }),\n ]),\n ),\n ) as unknown as TFields,\n });\n}\n\n/**\n * The host-side registration gate. Runs when a host registers its modules, so\n * a contract that does not match its implementation fails loudly at `listen()`\n * instead of as a confusing claim failure later.\n */\nexport function assertHostModule(module: HostModule): void {\n if (!isRecord(module) || !mintedHostModules.has(module)) {\n throw new Error(\n 'A host module must come from provideDatadogAppInputs(), which serves every version an inputs definition still converts to.',\n );\n }\n if (\n !isRecord(module.contract) ||\n !isValidIdentifier(module.contract.identifier) ||\n typeof module.contract.version !== 'number' ||\n !Number.isSafeInteger(module.contract.version) ||\n module.contract.version < 1 ||\n !isRecord(module.contract.fields) ||\n Object.keys(module.contract.fields).length === 0 ||\n !isRecord(module.implementation) ||\n (module.signal !== undefined &&\n (typeof module.signal.aborted !== 'boolean' ||\n typeof module.signal.addEventListener !== 'function' ||\n typeof module.signal.removeEventListener !== 'function'))\n ) {\n throw new Error('The host module has an invalid contract.');\n }\n\n for (const [name, field] of Object.entries(module.contract.fields)) {\n const provider = Object.hasOwn(module.implementation, name)\n ? module.implementation[name]\n : undefined;\n if (\n !VALID_FIELD_NAME.test(name) ||\n name.length > MAX_CLAIM_FIELD_NAME_LENGTH\n ) {\n throw new Error(\n `A host module field name \"${name}\" is not a valid claim field name.`,\n );\n }\n const isValue =\n isValueFieldShape(field) &&\n isRecord(provider) &&\n typeof provider.get === 'function' &&\n typeof provider.subscribe === 'function';\n const isFunction =\n isFunctionFieldShape(field) &&\n isRecord(provider) &&\n typeof provider.invoke === 'function';\n if (!isValue && !isFunction) {\n throw new Error(\n `The implementation of \"${module.contract.identifier}.${name}\" does not match its field contract.`,\n );\n }\n }\n}\n\n/**\n * Validates a whole registration: every module well-formed and no duplicate\n * `(identifier, version)`. Returns the failure rather than throwing so a\n * caller can report it over the connection.\n */\nexport function invalidHostModule(\n modules: readonly HostModule[],\n): Error | undefined {\n try {\n const versions = new Set<string>();\n for (const module of modules) {\n assertHostModule(module);\n const key = JSON.stringify([\n module.contract.identifier,\n module.contract.version,\n ]);\n if (versions.has(key)) {\n throw new Error(\n `The host registered \"${module.contract.identifier}\" v${module.contract.version} more than once.`,\n );\n }\n versions.add(key);\n }\n return undefined;\n } catch (error) {\n return error instanceof Error\n ? error\n : new Error('The host module is invalid.', { cause: error });\n }\n}\n"],
5
- "mappings": "yhBA0CO,SAASA,EAAsBC,EAAcC,EAAyB,CACzE,GACI,CAAC,OAAO,SAASA,CAAS,GAC1BA,EAAY,GACZA,EAAY,WAEZ,MAAM,IAAI,WACN,GAAGD,CAAI,oDACX,CAER,CAIO,IAAME,EAAwB,IACxBC,EAAwB,IAIxBC,EAA4B,IAI5BC,EAAqB,IACrBC,EAAyB,IACzBC,EAA6B,KAQ7BC,EAAuB,IACvBC,EAAsB,IACtBC,EAAqB,IACrBC,EAA+B,IAC/BC,EAAkC,GAClCC,EAAmB,IACnBC,EAA8B,IC9D3C,IAAMC,EAAS,2BAgBR,SAASC,EAAcC,EAAgBC,EAAQ,EAAY,CAC9D,GAAI,EAAED,aAAiB,OACnB,OAAOA,EAIX,GAAI,CACA,IAAME,EAAqC,CACvC,KAAMF,EAAM,KACZ,QAASA,EAAM,OACnB,EACA,OAAI,OAAOA,EAAM,OAAU,WACvBE,EAAU,MAAQF,EA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IAAI,MACN,6BAA6BL,EAAW,UAAU,IAAII,CAAI,oFAAoF,UAAkB,GACpK,CAER,CAEA,OAAO,OAAO,OAAO,CACjB,WAAYJ,EAAW,WACvB,QAASA,EAAW,QACpB,OAAQ,OAAO,OACX,OAAO,YACHE,EAAQ,IAAI,CAAC,CAACE,EAAMC,CAAK,IAAM,CAC3BD,EACAC,EAAM,OAAS,QACT,OAAO,OAAO,CAAE,GAAGA,EAAO,OAAQA,EAAM,MAAO,CAAC,EAChD,OAAO,OAAO,CACV,GAAGA,EACH,OAAQ,OAAO,OAAO,CAAE,GAAGA,EAAM,MAAO,CAAC,EACzC,OAAQA,EAAM,MAClB,CAAC,CACX,CAAC,CACL,CACJ,CACJ,CAAC,CACL",
6
- "names": ["assertValidTimerDelay", "name", "timeoutMs", "HEARTBEAT_INTERVAL_MS", "HEARTBEAT_DEADLINE_MS", "CLOSE_DELIVERY_TIMEOUT_MS", "RECONNECT_RETRY_MS", "RECONNECT_MAX_RETRY_MS", "RECONNECT_GIVE_UP_AFTER_MS", "MAX_LIVE_HOST_CLAIMS", "MAX_CLAIM_ID_LENGTH", "MAX_CALL_ID_LENGTH", "MAX_LIVE_HOST_FUNCTION_CALLS", "MAX_PENDING_ENDPOINT_OPERATIONS", "MAX_CLAIM_FIELDS", "MAX_CLAIM_FIELD_NAME_LENGTH", "PREFIX", "describeCause", "cause", "depth", "described", "describeError", "error", "log", "level", "event", "detail", "PREFIX", "logWarning", "logFailure", "nextId", "createId", "prefix", "randomSegment", "bytes", "segment", "byte", "success", "value", "err", "isRecord", "isValidIdentifier", "limit", "teardown", "description", "action", "error", "logFailure", "describeCause", "notifyListeners", "listeners", "args", "listener", "VALID_FIELD_NAME", "mintedHostModules", "createHostModule", "contract", "implementation", "signal", "snapshot", "name", "provider", "module", "isSchemaShape", "value", "standard", "isRecord", "isValueFieldShape", "field", "isFunctionFieldShape", "schema", "isAnyFieldShape", "hasUsableFunctionTimeout", "defineContract", "definition", "isValidIdentifier", "entries", "MAX_CLAIM_FIELDS", "name", "field", "VALID_FIELD_NAME", "MAX_CLAIM_FIELD_NAME_LENGTH", "isAnyFieldShape", "hasUsableFunctionTimeout"]
4
+ "sourcesContent": ["/**\n * Every tunable the embedding protocol uses -- timeouts and the limits that\n * bound peer-influenced state -- together in one place with an obvious name\n * each, instead of scattered as same-looking magic numbers across unrelated\n * files.\n */\n\nexport const PROTOCOL_VERSION = 1;\n\n// --- Timeouts -----------------------------------------------------------\n//\n// Each one is a local decision made independently by whichever side enforces\n// it -- none of these are negotiated with, or need to match, the peer's own\n// value for the same phase.\n\n/** Phase 1: transferring the private control port across the window boundary. */\nexport const BOOTSTRAP_TIMEOUT_MS = 10_000;\n\n/** Phases 2 and 3: protocol compatibility negotiation and bringing up the\n * operational protocol on the transferred port. Each phase receives this\n * full deadline independently. */\nexport const CONNECT_TIMEOUT_MS = 10_000;\n\n/** How long the app waits for the host to answer its claim of a module. */\nexport const CLAIM_TIMEOUT_MS = 5_000;\n\n/** How long a function call is allowed to run (host side) or be waited on\n * (app side). Each side enforces this purely locally -- it is never sent\n * over the wire, and one side never needs to know the other's value: the\n * watchdog that fires first just wins through the normal error path, the\n * same way any other host/app-independent failure already does. */\nexport const FUNCTION_CALL_TIMEOUT_MS = 600_000;\n\n/**\n * Ceiling for a `FunctionField.timeoutMs` override: the largest delay\n * `setTimeout` accepts. Anything above it silently overflows the 32-bit\n * signed timer and fires almost immediately, inverting the longest deadline\n * an author can ask for into the shortest one they could get.\n */\nexport const MAX_TIMER_DELAY_MS = 2_147_483_647;\n\n/** Reject a public timeout override that `setTimeout` cannot represent. */\nexport function assertValidTimerDelay(name: string, timeoutMs: number): void {\n if (\n !Number.isFinite(timeoutMs) ||\n timeoutMs < 0 ||\n timeoutMs > MAX_TIMER_DELAY_MS\n ) {\n throw new RangeError(\n `${name} must be a finite number between 0 and ${MAX_TIMER_DELAY_MS}.`,\n );\n }\n}\n\n/** How often a heartbeat ping is sent, and how long a reply is awaited\n * before it counts as a miss. */\nexport const HEARTBEAT_INTERVAL_MS = 10_000;\nexport const HEARTBEAT_DEADLINE_MS = 5_000;\n\n/** Grace period between posting a close envelope and actually tearing down\n * the transport, so the envelope isn't truncated in flight. */\nexport const CLOSE_DELIVERY_TIMEOUT_MS = 250;\n\n/** Reconnection backoff: starting delay, cap, and how long to keep retrying\n * before giving up on the whole recovery attempt. */\nexport const RECONNECT_RETRY_MS = 1_000;\nexport const RECONNECT_MAX_RETRY_MS = 10_000;\nexport const RECONNECT_GIVE_UP_AFTER_MS = 45_000;\n\n// --- Limits ---------------------------------------------------------------\n//\n// These bound state retained at the request of iframe code, so an\n// adversarial or malformed peer can't grow it without limit. Both peers\n// validate against them independently.\n\nexport const MAX_LIVE_HOST_CLAIMS = 128;\nexport const MAX_CLAIM_ID_LENGTH = 256;\nexport const MAX_CALL_ID_LENGTH = 256;\nexport const MAX_LIVE_HOST_FUNCTION_CALLS = 128;\nexport const MAX_PENDING_ENDPOINT_OPERATIONS = 32;\nexport const MAX_CLAIM_FIELDS = 128;\nexport const MAX_CLAIM_FIELD_NAME_LENGTH = 256;\n", "/**\n * Console diagnostics for every embedding outcome that is not\n * starting -> connecting -> connected.\n *\n * Debugging an embedding failure means reasoning about two documents that each\n * see half of the connection: the Datadog page owns the host listener, the app\n * iframe owns the connection handle, and neither observes why the other gave\n * up. Every failure, rejection, timeout, and lost connection therefore reports\n * itself locally, naming the side that produced it and carrying the detail the\n * wire deliberately does not: raw causes, validation issues, claim and call\n * identifiers, attempt counts, and the deadline that expired.\n *\n * This module never throws. It runs on paths that are already failing, in\n * browsers we do not control, so a missing or hostile `console` must not\n * replace the failure being reported.\n */\n\nimport type { AnyError } from './types';\n\nconst PREFIX = '[Datadog Apps embedding]';\n\n/** How deep an `Error.cause` chain is described before it is truncated. */\nconst MAX_CAUSE_DEPTH = 3;\n\n/** Which peer produced a log line; both peers run this code. */\nexport type DiagnosticSide = 'app' | 'host';\n\nexport type DiagnosticDetail = Readonly<Record<string, unknown>>;\n\n/**\n * Renders an arbitrary thrown value as inspectable data. Errors lose their\n * `name`, `message`, `stack`, and `cause` when a console is handed a bare\n * `Error` inside an object in some environments, so those are spread out\n * explicitly; anything else is passed through for the console to format.\n */\nexport function describeCause(cause: unknown, depth = 0): unknown {\n if (!(cause instanceof Error)) {\n return cause;\n }\n // A peer-influenced Error may have hostile name/message/stack/cause\n // accessors; this module's \"never throws\" guarantee must hold even then.\n try {\n const described: Record<string, unknown> = {\n name: cause.name,\n message: cause.message,\n };\n if (typeof cause.stack === 'string') {\n described.stack = cause.stack;\n }\n if (cause.cause !== undefined) {\n described.cause =\n depth < MAX_CAUSE_DEPTH\n ? describeCause(cause.cause, depth + 1)\n : '(cause chain truncated)';\n }\n return described;\n } catch {\n return '(cause could not be described)';\n }\n}\n\n/**\n * Renders a wire error for logging. Every code carries structured-clone-safe\n * data already, except the local-only `cause` of `TRANSPORT_FAILED`, which is\n * where the actual explanation usually lives.\n */\nexport function describeError(error: AnyError): DiagnosticDetail {\n return 'cause' in error\n ? { ...error, cause: describeCause(error.cause) }\n : error;\n}\n\nfunction log(\n level: 'warn' | 'error',\n event: string,\n detail: DiagnosticDetail,\n): void {\n try {\n globalThis.console?.[level](`${PREFIX} ${event}`, detail);\n } catch {\n // A console that cannot be used is not a reason to lose the outcome\n // this call was reporting.\n }\n}\n\n/** A failure the connection expects to recover from, or a degraded outcome. */\nexport function logWarning(event: string, detail: DiagnosticDetail = {}): void {\n log('warn', event, detail);\n}\n\n/** A failure a consumer observes: terminal, unrecoverable, or data-losing. */\nexport function logFailure(event: string, detail: DiagnosticDetail = {}): void {\n log('error', event, detail);\n}\n", "import { describeCause, logFailure } from './diagnostics';\nimport type { Result } from './types';\n\nlet nextId = 0;\n\n/**\n * The counter prevents local reuse if randomness repeats; the random segment\n * makes heartbeat nonces difficult for the peer to predict.\n */\nexport function createId(prefix: string): string {\n nextId += 1;\n return `${prefix}:${randomSegment()}:${nextId.toString(36)}`;\n}\n\nfunction randomSegment(): string {\n const bytes = new Uint8Array(8);\n globalThis.crypto.getRandomValues(bytes);\n let segment = '';\n for (const byte of bytes) {\n segment += byte.toString(16).padStart(2, '0');\n }\n return segment;\n}\n\nexport function success<TValue>(value: TValue): Result<TValue, never> {\n return { ok: true, value };\n}\n\nexport function err<TError>(value: TError): Result<never, TError> {\n return { ok: false, error: value };\n}\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * True when `value` is a well-formed identifier: a non-empty string. Bounds\n * its length to at most `limit` characters only when a limit is supplied.\n */\nexport function isValidIdentifier(\n value: unknown,\n limit?: number,\n): value is string {\n return (\n typeof value === 'string' &&\n value.length > 0 &&\n (limit === undefined || value.length <= limit)\n );\n}\n\n/**\n * Runs a cleanup action that must not throw into its caller. Teardown runs on\n * paths that are already failing, so a secondary failure is reported and\n * swallowed instead of replacing the outcome the caller is about to return.\n */\nexport function teardown(description: string, action: () => void): void {\n try {\n action();\n } catch (error) {\n logFailure('a teardown step failed', {\n description,\n cause: describeCause(error),\n });\n }\n}\n\n/**\n * Calls every listener, isolating exceptions so one listener throwing doesn't\n * stop the rest from being notified or propagate into the caller that\n * triggered the notification.\n */\nexport function notifyListeners<TArgs extends readonly unknown[] = []>(\n listeners: Iterable<(...args: TArgs) => void>,\n ...args: TArgs\n): void {\n for (const listener of [...listeners]) {\n try {\n listener(...args);\n } catch (error) {\n // Rethrown out of band, where the stack no longer shows that\n // embedding was notifying a listener.\n logFailure('an embedding listener threw', {\n cause: describeCause(error),\n });\n globalThis.queueMicrotask(() => {\n throw error;\n });\n }\n }\n}\n", "import {\n MAX_CLAIM_FIELDS,\n MAX_CLAIM_FIELD_NAME_LENGTH,\n MAX_TIMER_DELAY_MS,\n} from './config';\nimport { isRecord, isValidIdentifier } from './shared';\nimport type {\n AnyContract,\n AnyField,\n AnyFunctionField,\n AnySchema,\n Contract,\n ContractVersion,\n FunctionField,\n HostFunction,\n HostModule,\n LiveValue,\n ValidationOnlySchema,\n ValueField,\n} from './types';\n\n/**\n * A field name must be a valid own-property identifier the wire protocol\n * will actually carry: excludes \"__proto__\" and other names that a plain\n * object assignment would resolve against the prototype chain instead of\n * creating an own property. Exported so every place a contract-shaped field\n * name is declared (e.g. an older version's `extraInputs`) enforces the same\n * shape, not just `defineContract` itself.\n */\nexport const VALID_FIELD_NAME: RegExp = /^[A-Za-z][A-Za-z0-9_]*$/;\n\n/**\n * Every module this package has minted. Backs the runtime half of\n * `HostModule`'s brand, so a structurally-identical object built elsewhere is\n * rejected at `listen()` even where types were bypassed.\n */\nconst mintedHostModules = new WeakSet<object>();\n\n/**\n * The only way a `HostModule` comes into existence. Kept here, beside the\n * validation it has to satisfy, and deliberately not re-exported from\n * `@datadog/apps-frontend/embedding/internal` -- a host reaches modules only\n * as the output of providing an inputs definition, never by naming a version\n * and building one itself.\n */\nexport function createHostModule(\n contract: AnyContract,\n implementation: Readonly<Record<string, LiveValue<unknown> | HostFunction>>,\n signal?: AbortSignal,\n): HostModule {\n // A null-prototype snapshot means a wire-supplied field name (e.g.\n // \"__proto__\" or \"constructor\") can never resolve to an inherited\n // Object.prototype member when this dict is later indexed by that name.\n const snapshot: Record<string, LiveValue<unknown> | HostFunction> =\n Object.create(null);\n for (const [name, provider] of Object.entries(implementation)) {\n snapshot[name] = provider;\n }\n Object.freeze(snapshot);\n const module = Object.freeze(\n signal === undefined\n ? { contract, implementation: snapshot }\n : { contract, implementation: snapshot, signal },\n ) as unknown as HostModule;\n mintedHostModules.add(module);\n return module;\n}\n\nfunction isSchemaShape(value: unknown): value is AnySchema {\n if (\n !(\n (typeof value === 'object' && value !== null) ||\n typeof value === 'function'\n )\n ) {\n return false;\n }\n const standard = (value as AnySchema)['~standard'];\n return (\n isRecord(standard) &&\n standard.version === 1 &&\n typeof standard.validate === 'function'\n );\n}\n\n/**\n * True when `field` has the generic shape of a read-only value field.\n * Ignores identifier-name rules and implementation matching, which are\n * caller-specific (e.g. host modules also validate against a provider).\n */\nexport function isValueFieldShape(\n field: unknown,\n): field is ValueField<AnySchema> {\n return (\n isRecord(field) && field.kind === 'value' && isSchemaShape(field.schema)\n );\n}\n\n/**\n * True when `field` has the generic shape of a callable function field.\n * Ignores identifier-name rules and implementation matching, which are\n * caller-specific (e.g. host modules also validate against a provider).\n */\nexport function isFunctionFieldShape(\n field: unknown,\n): field is AnyFunctionField {\n return (\n isRecord(field) &&\n field.kind === 'function' &&\n isRecord(field.inputs) &&\n Object.entries(field.inputs).every(\n ([name, schema]) => name.length > 0 && isSchemaShape(schema),\n ) &&\n isSchemaShape(field.result)\n );\n}\n\n/** True when `field` has the generic shape of any well-formed contract field. */\nexport function isAnyFieldShape(field: unknown): field is AnyField {\n return isValueFieldShape(field) || isFunctionFieldShape(field);\n}\n\n/**\n * True when a function field's optional `timeoutMs` is a deadline a call could\n * actually meet -- see `FunctionField.timeoutMs` for why each end is not.\n *\n * Deliberately separate from `isFunctionFieldShape`: this is about a value being\n * sensible, not about the field being a function, so folding it in would make an\n * out-of-range deadline report as a malformed shape or a mismatched provider.\n */\nexport function hasUsableFunctionTimeout(field: AnyField): boolean {\n return (\n field.kind !== 'function' ||\n field.timeoutMs === undefined ||\n (typeof field.timeoutMs === 'number' &&\n Number.isFinite(field.timeoutMs) &&\n field.timeoutMs > 0 &&\n field.timeoutMs <= MAX_TIMER_DELAY_MS)\n );\n}\n\ninterface ReadOnlyValueBuilder {\n readOnly<TSchema extends AnySchema>(\n schema: ValidationOnlySchema<TSchema>,\n ): ValueField<TSchema>;\n}\n\ninterface ReadOnlyFunctionBuilder {\n readOnly<\n const TInputs extends Readonly<Record<string, AnySchema>>,\n TResult extends AnySchema,\n >(\n definition: Readonly<{\n inputs: {\n readonly [TName in keyof TInputs]: ValidationOnlySchema<\n TInputs[TName]\n >;\n };\n result: ValidationOnlySchema<TResult>;\n /**\n * Optional per-function override of `FUNCTION_CALL_TIMEOUT_MS`.\n * See `FunctionField.timeoutMs`.\n */\n timeoutMs?: number;\n }>,\n ): FunctionField<TInputs, TResult>;\n}\n\n/**\n * Builds a value field for any embedding contract. `readOnly` is the only\n * builder today because no transport exists for an app to write a value\n * back to the host; the name leaves room for a future writable builder\n * without implying one exists yet.\n */\nexport const value: ReadOnlyValueBuilder = /* @__PURE__ */ Object.freeze({\n readOnly<TSchema extends AnySchema>(\n schema: ValidationOnlySchema<TSchema>,\n ): ValueField<TSchema> {\n return Object.freeze({ kind: 'value', schema });\n },\n});\n\n/** Builds a callable function field for any embedding contract. */\nexport const fn: ReadOnlyFunctionBuilder = /* @__PURE__ */ Object.freeze({\n readOnly<\n const TInputs extends Readonly<Record<string, AnySchema>>,\n TResult extends AnySchema,\n >({\n inputs,\n result,\n timeoutMs,\n }: Readonly<{\n inputs: {\n readonly [TName in keyof TInputs]: ValidationOnlySchema<\n TInputs[TName]\n >;\n };\n result: ValidationOnlySchema<TResult>;\n timeoutMs?: number;\n }>): FunctionField<TInputs, TResult> {\n // Omitted entirely rather than stored as an explicit `undefined`, so\n // `'timeoutMs' in field` answers whether an override was declared.\n return Object.freeze(\n timeoutMs === undefined\n ? { kind: 'function', inputs, result }\n : { kind: 'function', inputs, result, timeoutMs },\n );\n },\n});\n\ntype ValidationOnlyField<TField extends AnyField> =\n TField extends Readonly<{\n kind: 'value';\n schema: infer TSchema extends AnySchema;\n }>\n ? TField & Readonly<{ schema: ValidationOnlySchema<TSchema> }>\n : TField extends Readonly<{\n kind: 'function';\n inputs: infer TInputs extends Readonly<\n Record<string, AnySchema>\n >;\n result: infer TResult extends AnySchema;\n }>\n ? TField &\n Readonly<{\n inputs: {\n readonly [TName in keyof TInputs]: ValidationOnlySchema<\n TInputs[TName]\n >;\n };\n result: ValidationOnlySchema<TResult>;\n }>\n : never;\n\ntype ValidationOnlyFields<TFields extends Record<string, AnyField>> = {\n readonly [TName in keyof TFields]: ValidationOnlyField<TFields[TName]>;\n};\n\n/**\n * Assembles and validates a well-formed `Contract`: the one place any\n * claim-defining module builds an identifier, version, and fields into the\n * shape the embedding protocol requires. Field-shape correctness reuses\n * `isAnyFieldShape` so there is a single source of truth for what a\n * contract field looks like, shared with the host-registration gate above.\n */\nexport function defineContract<\n const TIdentifier extends string,\n const TVersion extends ContractVersion,\n const TFields extends Record<string, AnyField>,\n>(\n definition: Contract<TFields> &\n Readonly<{\n identifier: TIdentifier;\n version: TVersion;\n fields: ValidationOnlyFields<TFields>;\n }>,\n): Contract<TFields> &\n Readonly<{ identifier: TIdentifier; version: TVersion }> {\n if (!isValidIdentifier(definition.identifier)) {\n throw new Error(\n `Invalid embedding contract identifier \"${String(definition.identifier)}\".`,\n );\n }\n if (!Number.isSafeInteger(definition.version) || definition.version < 1) {\n throw new Error(\n `Embedding contract \"${definition.identifier}\" must have a positive integer version.`,\n );\n }\n\n const entries = Object.entries(definition.fields);\n if (entries.length === 0 || entries.length > MAX_CLAIM_FIELDS) {\n throw new Error(\n `Embedding contract \"${definition.identifier}\" must define between 1 and ${MAX_CLAIM_FIELDS} fields.`,\n );\n }\n for (const [name, field] of entries) {\n if (\n !VALID_FIELD_NAME.test(name) ||\n name.length > MAX_CLAIM_FIELD_NAME_LENGTH ||\n !isAnyFieldShape(field)\n ) {\n throw new Error(\n `Embedding contract field \"${definition.identifier}.${name}\" must be a named read-only value or function whose schemas implement Standard Schema V1.`,\n );\n }\n if (!hasUsableFunctionTimeout(field)) {\n throw new Error(\n `Embedding contract field \"${definition.identifier}.${name}\" declares a timeoutMs no call could meet. It must be greater than 0 and at most ${MAX_TIMER_DELAY_MS}.`,\n );\n }\n }\n\n return Object.freeze({\n identifier: definition.identifier,\n version: definition.version,\n fields: Object.freeze(\n Object.fromEntries(\n entries.map(([name, field]) => [\n name,\n field.kind === 'value'\n ? Object.freeze({ ...field, schema: field.schema })\n : Object.freeze({\n ...field,\n inputs: Object.freeze({ ...field.inputs }),\n result: field.result,\n }),\n ]),\n ),\n ) as unknown as TFields,\n });\n}\n\n/**\n * The host-side registration gate. Runs when a host registers its modules, so\n * a contract that does not match its implementation fails loudly at `listen()`\n * instead of as a confusing claim failure later.\n */\nexport function assertHostModule(module: HostModule): void {\n if (!isRecord(module) || !mintedHostModules.has(module)) {\n throw new Error(\n 'A host module must come from its module provider -- the host-side helper that serves every contract version its definition still converts to.',\n );\n }\n if (\n !isRecord(module.contract) ||\n !isValidIdentifier(module.contract.identifier) ||\n typeof module.contract.version !== 'number' ||\n !Number.isSafeInteger(module.contract.version) ||\n module.contract.version < 1 ||\n !isRecord(module.contract.fields) ||\n Object.keys(module.contract.fields).length === 0 ||\n !isRecord(module.implementation) ||\n (module.signal !== undefined &&\n (typeof module.signal.aborted !== 'boolean' ||\n typeof module.signal.addEventListener !== 'function' ||\n typeof module.signal.removeEventListener !== 'function'))\n ) {\n throw new Error('The host module has an invalid contract.');\n }\n\n for (const [name, field] of Object.entries(module.contract.fields)) {\n const provider = Object.hasOwn(module.implementation, name)\n ? module.implementation[name]\n : undefined;\n if (\n !VALID_FIELD_NAME.test(name) ||\n name.length > MAX_CLAIM_FIELD_NAME_LENGTH\n ) {\n throw new Error(\n `A host module field name \"${name}\" is not a valid claim field name.`,\n );\n }\n const isValue =\n isValueFieldShape(field) &&\n isRecord(provider) &&\n typeof provider.get === 'function' &&\n typeof provider.subscribe === 'function';\n const isFunction =\n isFunctionFieldShape(field) &&\n isRecord(provider) &&\n typeof provider.invoke === 'function';\n if (!isValue && !isFunction) {\n throw new Error(\n `The implementation of \"${module.contract.identifier}.${name}\" does not match its field contract.`,\n );\n }\n }\n}\n\n/**\n * Validates a whole registration: every module well-formed and no duplicate\n * `(identifier, version)`. Returns the failure rather than throwing so a\n * caller can report it over the connection.\n */\nexport function invalidHostModule(\n modules: readonly HostModule[],\n): Error | undefined {\n try {\n const versions = new Set<string>();\n for (const module of modules) {\n assertHostModule(module);\n const key = JSON.stringify([\n module.contract.identifier,\n module.contract.version,\n ]);\n if (versions.has(key)) {\n throw new Error(\n `The host registered \"${module.contract.identifier}\" v${module.contract.version} more than once.`,\n );\n }\n versions.add(key);\n }\n return undefined;\n } catch (error) {\n return error instanceof Error\n ? error\n : new Error('The host module is invalid.', { cause: error });\n }\n}\n"],
5
+ "mappings": "yhBA0CO,SAASA,EAAsBC,EAAcC,EAAyB,CACzE,GACI,CAAC,OAAO,SAASA,CAAS,GAC1BA,EAAY,GACZA,EAAY,WAEZ,MAAM,IAAI,WACN,GAAGD,CAAI,oDACX,CAER,CAIO,IAAME,EAAwB,IACxBC,EAAwB,IAIxBC,EAA4B,IAI5BC,EAAqB,IACrBC,EAAyB,IACzBC,EAA6B,KAQ7BC,EAAuB,IACvBC,EAAsB,IACtBC,EAAqB,IACrBC,EAA+B,IAC/BC,EAAkC,GAClCC,EAAmB,IACnBC,EAA8B,IC9D3C,IAAMC,EAAS,2BAgBR,SAASC,EAAcC,EAAgBC,EAAQ,EAAY,CAC9D,GAAI,EAAED,aAAiB,OACnB,OAAOA,EAIX,GAAI,CACA,IAAME,EAAqC,CACvC,KAAMF,EAAM,KACZ,QAASA,EAAM,OACnB,EACA,OAAI,OAAOA,EAAM,OAAU,WACvBE,EAAU,MAAQF,EAAM,OAExBA,EAAM,QAAU,SAChBE,EAAU,MACND,EAAQ,EACFF,EAAcC,EAAM,MAAOC,EAAQ,CAAC,EACpC,2BAEPC,CACX,MAAQ,CACJ,MAAO,gCACX,CACJ,CAOO,SAASC,EAAcC,EAAmC,CAC7D,MAAO,UAAWA,EACZ,CAAE,GAAGA,EAAO,MAAOL,EAAcK,EAAM,KAAK,CAAE,EAC9CA,CACV,CAEA,SAASC,EACLC,EACAC,EACAC,EACI,CACJ,GAAI,CACA,WAAW,UAAUF,CAAK,EAAE,GAAGG,CAAM,IAAIF,CAAK,GAAIC,CAAM,CAC5D,MAAQ,CAGR,CACJ,CAGO,SAASE,EAAWH,EAAeC,EAA2B,CAAC,EAAS,CAC3EH,EAAI,OAAQE,EAAOC,CAAM,CAC7B,CAGO,SAASG,EAAWJ,EAAeC,EAA2B,CAAC,EAAS,CAC3EH,EAAI,QAASE,EAAOC,CAAM,CAC9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AC,EAChD,OAAO,OAAO,CACV,GAAGA,EACH,OAAQ,OAAO,OAAO,CAAE,GAAGA,EAAM,MAAO,CAAC,EACzC,OAAQA,EAAM,MAClB,CAAC,CACX,CAAC,CACL,CACJ,CACJ,CAAC,CACL",
6
+ "names": ["assertValidTimerDelay", "name", "timeoutMs", "HEARTBEAT_INTERVAL_MS", "HEARTBEAT_DEADLINE_MS", "CLOSE_DELIVERY_TIMEOUT_MS", "RECONNECT_RETRY_MS", "RECONNECT_MAX_RETRY_MS", "RECONNECT_GIVE_UP_AFTER_MS", "MAX_LIVE_HOST_CLAIMS", "MAX_CLAIM_ID_LENGTH", "MAX_CALL_ID_LENGTH", "MAX_LIVE_HOST_FUNCTION_CALLS", "MAX_PENDING_ENDPOINT_OPERATIONS", "MAX_CLAIM_FIELDS", "MAX_CLAIM_FIELD_NAME_LENGTH", "PREFIX", "describeCause", "cause", "depth", "described", "describeError", "error", "log", "level", "event", "detail", "PREFIX", "logWarning", "logFailure", "nextId", "createId", "prefix", "randomSegment", "bytes", "segment", "byte", "success", "value", "err", "isRecord", "isValidIdentifier", "limit", "teardown", "description", "action", "error", "logFailure", "describeCause", "notifyListeners", "listeners", "args", "listener", "VALID_FIELD_NAME", "mintedHostModules", "createHostModule", "contract", "implementation", "signal", "snapshot", "name", "provider", "module", "isSchemaShape", "value", "standard", "isRecord", "isValueFieldShape", "field", "isFunctionFieldShape", "schema", "isAnyFieldShape", "hasUsableFunctionTimeout", "fn", "inputs", "result", "timeoutMs", "defineContract", "definition", "isValidIdentifier", "entries", "MAX_CLAIM_FIELDS", "MAX_CLAIM_FIELD_NAME_LENGTH"]
7
7
  }
@@ -0,0 +1,7 @@
1
+ /* Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0.
2
+ * This product includes software developed at Datadog (https://www.datadoghq.com/).
3
+ * Copyright 2019-Present Datadog, Inc.
4
+ */
5
+
6
+ var t=Symbol("DatadogAppProviderModule");function p(e,d,n){if(e.length===0)throw new Error("A Datadog App provider module requires an id.");return Object.freeze({id:e,config:Object.freeze({...d}),[t]:n})}function l(e,d){try{console.error(`Installing the "${e}" Datadog App provider module failed; the remaining modules and the app still run.`,d)}catch{}}function g(e,d,n){let r=new Set;for(let o of e){if(r.has(o.id))throw new Error(`DatadogAppProvider received duplicate module "${o.id}".`);r.add(o.id)}let i=Object.freeze({embedding:d,disposeSignal:n});for(let o of e)try{o[t].install(i)}catch(a){l(o.id,a)}}export{p as a,g as b};
7
+ //# sourceMappingURL=chunk-MF7HCOXQ.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/embedding/react/config.ts"],
4
+ "sourcesContent": ["import type { AppEmbedding } from '../types';\n\nconst providerModuleImplementation: unique symbol = Symbol(\n 'DatadogAppProviderModule',\n);\n\nexport interface DatadogAppProviderModule<\n TId extends string = string,\n TConfig extends Readonly<Record<string, unknown>> = Readonly<\n Record<string, unknown>\n >,\n> {\n readonly id: TId;\n /** This module's readonly settings, as passed to its factory. */\n readonly config: TConfig;\n readonly [providerModuleImplementation]: DatadogAppProviderModuleImplementation;\n}\n\n/**\n * Everything a module receives when the provider installs it on a mount.\n *\n * Deliberately neutral plumbing, made only of things the provider already\n * owns: the shared embedding connection and this mount's dispose signal. The\n * core knows nothing else about modules -- no module-specific fields, and no\n * DOM knowledge at all.\n */\nexport interface DatadogAppProviderModuleHandle {\n /**\n * The embedding connection shared by every mount of this package. A\n * module claims its contracts and subscribes to claim stores from here.\n */\n readonly embedding: AppEmbedding;\n /**\n * Aborted when this mount unmounts, or when React re-runs the provider's\n * effects (StrictMode double-invokes them in development). Modules clean\n * up by listening for this signal.\n */\n readonly disposeSignal: AbortSignal;\n}\n\nexport interface DatadogAppProviderModuleImplementation {\n /**\n * Installs this module's capability for one provider mount.\n *\n * Synchronous: `install` returns once the module's synchronous setup is\n * done. A module owns any async work it starts and must end it when\n * `disposeSignal` aborts.\n *\n * Re-runnable: `install -> dispose -> install` on the same mount is legal\n * and does happen (StrictMode), so a module's install must work again\n * after its dispose path has run.\n */\n install(handle: DatadogAppProviderModuleHandle): undefined;\n}\n\n/** Creates one opaque, configured provider module for package capabilities. */\nexport function createDatadogAppProviderModule<\n const TId extends string,\n const TConfig extends Readonly<Record<string, unknown>>,\n>(\n id: TId,\n config: TConfig,\n implementation: DatadogAppProviderModuleImplementation,\n): DatadogAppProviderModule<TId, TConfig> {\n if (id.length === 0) {\n throw new Error('A Datadog App provider module requires an id.');\n }\n return Object.freeze({\n id,\n config: Object.freeze({ ...config }) as TConfig,\n [providerModuleImplementation]: implementation,\n });\n}\n\n/** Reports an isolated install failure. Guarded like the composite's warn():\n * a hostile console implementation must never break the isolation promise. */\nfunction reportInstallFailure(moduleId: string, error: unknown): void {\n try {\n console.error(\n `Installing the \"${moduleId}\" Datadog App provider module failed; the remaining modules and the app still run.`,\n error,\n );\n } catch {\n // Nothing more can be done here; the remaining modules still install.\n }\n}\n\n/**\n * Installs modules on one provider mount, in list order, and nothing more.\n *\n * Duplicate ids are a wiring bug, not a runtime condition: they throw before\n * anything is installed. Individual install failures are the opposite -- they\n * are isolated and reported, and the remaining modules still install. That\n * asymmetry is deliberate: duplicates mean the author wired the same\n * capability twice and must hear about it immediately, while a failing\n * default module must not take down the app or its sibling modules.\n */\nexport function installDatadogAppProviderModules(\n modules: readonly DatadogAppProviderModule[],\n embedding: AppEmbedding,\n disposeSignal: AbortSignal,\n): void {\n const moduleIds = new Set<string>();\n for (const module of modules) {\n if (moduleIds.has(module.id)) {\n throw new Error(\n `DatadogAppProvider received duplicate module \"${module.id}\".`,\n );\n }\n moduleIds.add(module.id);\n }\n const handle: DatadogAppProviderModuleHandle = Object.freeze({\n embedding,\n disposeSignal,\n });\n for (const module of modules) {\n try {\n module[providerModuleImplementation].install(handle);\n } catch (error: unknown) {\n reportInstallFailure(module.id, error);\n }\n }\n}\n"],
5
+ "mappings": "AAEA,IAAMA,EAA8C,OAChD,0BACJ,EAoDO,SAASC,EAIZC,EACAC,EACAC,EACsC,CACtC,GAAIF,EAAG,SAAW,EACd,MAAM,IAAI,MAAM,+CAA+C,EAEnE,OAAO,OAAO,OAAO,CACjB,GAAAA,EACA,OAAQ,OAAO,OAAO,CAAE,GAAGC,CAAO,CAAC,EACnC,CAACH,CAA4B,EAAGI,CACpC,CAAC,CACL,CAIA,SAASC,EAAqBC,EAAkBC,EAAsB,CAClE,GAAI,CACA,QAAQ,MACJ,mBAAmBD,CAAQ,qFAC3BC,CACJ,CACJ,MAAQ,CAER,CACJ,CAYO,SAASC,EACZC,EACAC,EACAC,EACI,CACJ,IAAMC,EAAY,IAAI,IACtB,QAAWC,KAAUJ,EAAS,CAC1B,GAAIG,EAAU,IAAIC,EAAO,EAAE,EACvB,MAAM,IAAI,MACN,iDAAiDA,EAAO,EAAE,IAC9D,EAEJD,EAAU,IAAIC,EAAO,EAAE,CAC3B,CACA,IAAMC,EAAyC,OAAO,OAAO,CACzD,UAAAJ,EACA,cAAAC,CACJ,CAAC,EACD,QAAWE,KAAUJ,EACjB,GAAI,CACAI,EAAOb,CAA4B,EAAE,QAAQc,CAAM,CACvD,OAASP,EAAgB,CACrBF,EAAqBQ,EAAO,GAAIN,CAAK,CACzC,CAER",
6
+ "names": ["providerModuleImplementation", "createDatadogAppProviderModule", "id", "config", "implementation", "reportInstallFailure", "moduleId", "error", "installDatadogAppProviderModules", "modules", "embedding", "disposeSignal", "moduleIds", "module", "handle"]
7
+ }