@datadog/apps-frontend 0.0.3 → 0.0.5

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.
@@ -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 R(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 x=new WeakSet,h=/^[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"||!h.test(e.identifier))throw new Error(`Datadog App input contract identifier "${String(d(e)?e.identifier:void 0)}" must match ${String(h)}.`);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=R(t,...o),r=Object.freeze({...a,surfaces:Object.freeze([...n.surfaces??F])});return x.add(r),r}function K(e){if(typeof e!="object"||e===null||!x.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-NCWC7QOQ.js.map
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
@@ -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 inputs schema that\n * surface provides -- see `../inputs/schemas`. Sent host-to-app as part of\n * 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\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 PublishedDatadogAppInputsDefinition<AnyDatadogAppInputsSchema> {\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": "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",
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
+ }
@@ -0,0 +1,46 @@
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 { DruidsEnvironment } from '@datadog/druids/layout/DruidsEnvironment';
7
+ import type { ComponentProps, ReactElement } from 'react';
8
+ import type { DatadogAppTheme } from '../../inputs/schemas/index.js';
9
+ type DruidsEnvironmentProps = ComponentProps<typeof DruidsEnvironment>;
10
+ /**
11
+ * Everything {@link DruidsEnvironment} accepts, except the two
12
+ * theme-preference props this component owns: the initial preference arrives
13
+ * as a plain `'light' | 'dark'` and the live one comes from the
14
+ * `datadog.theme` input, so neither can be forwarded by callers.
15
+ */
16
+ export type DruidsEnvironmentWithThemeInputProps = Omit<DruidsEnvironmentProps, 'defaultThemePreference' | 'fallbackThemePreference'> & {
17
+ /**
18
+ * Theme rendered until the `datadog.theme` input claims -- and whenever it
19
+ * cannot (the claim is pending, the host offers no such input, or the
20
+ * claim failed). The host's live theme replaces it the moment it arrives.
21
+ */
22
+ defaultThemePreference: DatadogAppTheme;
23
+ };
24
+ /**
25
+ * `DruidsEnvironment` driven by the host's live `datadog.theme` input.
26
+ *
27
+ * A drop-in for `@datadog/druids/layout/DruidsEnvironment`: every other prop
28
+ * is forwarded unchanged. The first render applies `defaultThemePreference`,
29
+ * and as soon as the `datadog.theme` input claims, the host's actual theme
30
+ * takes over and live-updates whenever the user switches it. Until then --
31
+ * and whenever the input never resolves -- your initial preference stays
32
+ * applied. That keeps the app deterministic instead of falling back to
33
+ * DRUIDS' own cookie and iframe detection, which forces light mode inside the
34
+ * iframe every Datadog App runs in, and means the worst case is a brief
35
+ * initial paint in your default theme.
36
+ *
37
+ * Must be rendered below `DatadogAppProvider`
38
+ * (`@datadog/apps-frontend/embedding/react`), like every Datadog App hook.
39
+ *
40
+ * To opt out of the input -- for example to keep DRUIDS' own cookie-based
41
+ * preference handling -- render `DruidsEnvironment` directly instead. This
42
+ * subpath is the only entry that requires `@datadog/druids` (an optional peer
43
+ * dependency): apps that do not import it do not bundle DRUIDS.
44
+ */
45
+ export declare function DruidsEnvironmentWithThemeInput(props: DruidsEnvironmentWithThemeInputProps): ReactElement;
46
+ export {};
@@ -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
+ export { DruidsEnvironmentWithThemeInput } from './druids-environment-with-theme-input.js';
7
+ export type { DruidsEnvironmentWithThemeInputProps } from './druids-environment-with-theme-input.js';
@@ -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 r}from"../../_chunks/chunk-O6R7PFZZ.js";import"../../_chunks/chunk-2V2HASKF.js";import{a as t}from"../../_chunks/chunk-IM4AWPJX.js";import"../../_chunks/chunk-T34NWJ7R.js";import"../../_chunks/chunk-X34MSTJH.js";import{DruidsEnvironment as i}from"@datadog/druids/layout/DruidsEnvironment";import{createElement as s}from"react";function u(n){let{defaultThemePreference:m,...o}=n,e=r(t),p=e.status==="ready"?e.fields.theme:m;return s(i,{...o,defaultThemePreference:p})}export{u as DruidsEnvironmentWithThemeInput};
7
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/druids/react/druids-environment-with-theme-input.ts"],
4
+ "sourcesContent": ["import { DruidsEnvironment } from '@datadog/druids/layout/DruidsEnvironment';\nimport { createElement } from 'react';\nimport type { ComponentProps, ReactElement } from 'react';\n\nimport { useDatadogAppInput } from '../../inputs/react/index';\nimport { datadogTheme } from '../../inputs/schemas/index';\nimport type { DatadogAppTheme } from '../../inputs/schemas/index';\n\ntype DruidsEnvironmentProps = ComponentProps<typeof DruidsEnvironment>;\n\n/**\n * `SavedThemes` is the type `DruidsEnvironment` expects for its preference\n * props, but `@datadog/druids` does not export it. Recover it structurally --\n * its runtime values are exactly `'light' | 'dark' | 'system'`, so accepting\n * the cast below is only teaching the compiler that correspondence.\n */\ntype DruidsThemePreference = DruidsEnvironmentProps['defaultThemePreference'];\n\n/**\n * Everything {@link DruidsEnvironment} accepts, except the two\n * theme-preference props this component owns: the initial preference arrives\n * as a plain `'light' | 'dark'` and the live one comes from the\n * `datadog.theme` input, so neither can be forwarded by callers.\n */\nexport type DruidsEnvironmentWithThemeInputProps = Omit<\n DruidsEnvironmentProps,\n 'defaultThemePreference' | 'fallbackThemePreference'\n> & {\n /**\n * Theme rendered until the `datadog.theme` input claims -- and whenever it\n * cannot (the claim is pending, the host offers no such input, or the\n * claim failed). The host's live theme replaces it the moment it arrives.\n */\n defaultThemePreference: DatadogAppTheme;\n};\n\n/**\n * `DruidsEnvironment` driven by the host's live `datadog.theme` input.\n *\n * A drop-in for `@datadog/druids/layout/DruidsEnvironment`: every other prop\n * is forwarded unchanged. The first render applies `defaultThemePreference`,\n * and as soon as the `datadog.theme` input claims, the host's actual theme\n * takes over and live-updates whenever the user switches it. Until then --\n * and whenever the input never resolves -- your initial preference stays\n * applied. That keeps the app deterministic instead of falling back to\n * DRUIDS' own cookie and iframe detection, which forces light mode inside the\n * iframe every Datadog App runs in, and means the worst case is a brief\n * initial paint in your default theme.\n *\n * Must be rendered below `DatadogAppProvider`\n * (`@datadog/apps-frontend/embedding/react`), like every Datadog App hook.\n *\n * To opt out of the input -- for example to keep DRUIDS' own cookie-based\n * preference handling -- render `DruidsEnvironment` directly instead. This\n * subpath is the only entry that requires `@datadog/druids` (an optional peer\n * dependency): apps that do not import it do not bundle DRUIDS.\n */\nexport function DruidsEnvironmentWithThemeInput(\n props: DruidsEnvironmentWithThemeInputProps,\n): ReactElement {\n const { defaultThemePreference, ...druidsEnvironmentProps } = props;\n const themeInput = useDatadogAppInput(datadogTheme);\n const preference: DatadogAppTheme =\n themeInput.status === 'ready'\n ? themeInput.fields.theme\n : defaultThemePreference;\n\n return createElement(DruidsEnvironment, {\n ...druidsEnvironmentProps,\n // `preference` is `'light' | 'dark'`; only the enum wrapper differs.\n defaultThemePreference: preference as DruidsThemePreference,\n });\n}\n"],
5
+ "mappings": "gOAAA,OAAS,qBAAAA,MAAyB,2CAClC,OAAS,iBAAAC,MAAqB,QAwDvB,SAASC,EACZC,EACY,CACZ,GAAM,CAAE,uBAAAC,EAAwB,GAAGC,CAAuB,EAAIF,EACxDG,EAAaC,EAAmBC,CAAY,EAC5CC,EACFH,EAAW,SAAW,QAChBA,EAAW,OAAO,MAClBF,EAEV,OAAOM,EAAcC,EAAmB,CACpC,GAAGN,EAEH,uBAAwBI,CAC5B,CAAC,CACL",
6
+ "names": ["DruidsEnvironment", "createElement", "DruidsEnvironmentWithThemeInput", "props", "defaultThemePreference", "druidsEnvironmentProps", "themeInput", "useDatadogAppInput", "datadogTheme", "preference", "createElement", "DruidsEnvironment"]
7
+ }
@@ -211,11 +211,18 @@ export declare const EVERY_SURFACE: readonly [
211
211
  'datadog.dashboard'
212
212
  ];
213
213
  /**
214
- * Where an app is running. Derived from `EVERY_SURFACE`, so there is one
215
- * list, but widened to arbitrary strings: it is inert metadata forwarded to
216
- * `listen()`, never used to gate whether embedding connects, so a host is
217
- * free to pass a value with no matching surface (e.g. an unmapped view
218
- * context) rather than going without one.
214
+ * The static category of surface where an embedding session is running.
215
+ * It is chosen when the connection is established and does not change in
216
+ * place. Dynamic placement or parent/child relationships (for example, a
217
+ * pinned app moving between containers) belong in separately versioned
218
+ * module inputs rather than mutations to `surfaceId`.
219
+ *
220
+ * Derived from `EVERY_SURFACE`, so there is one list, but widened to arbitrary
221
+ * strings: it is metadata forwarded to `listen()` and may be used by the host
222
+ * to gate which input schemas are offered on a given surface, but it never
223
+ * gates whether embedding connects — a host is free to pass a value with
224
+ * no matching surface (e.g. an unmapped view context) rather than going
225
+ * without one.
219
226
  */
220
227
  export type SurfaceId = (typeof EVERY_SURFACE)[number] | (string & {});
221
228
  export type AppConnectionState = Readonly<{
@@ -283,6 +290,7 @@ export interface HostListenOptions {
283
290
  allowOpaqueOrigin?: boolean;
284
291
  }>;
285
292
  readonly modules: readonly HostModule[];
293
+ /** Static surface category for the lifetime of the established connection. */
286
294
  readonly surfaceId?: SurfaceId;
287
295
  /**
288
296
  * Local compatibility and establishment deadline for each phase. Must be
@@ -11,11 +11,10 @@ declare const publishedDefinitionBrand: unique symbol;
11
11
  * One published inputs definition: every version it serves, and the surfaces
12
12
  * it is offered on.
13
13
  *
14
- * `surfaces` exists for development ergonomics only -- discovery while writing
15
- * code, and type errors when a host forgets an input its surface offers.
16
- * Nothing reads it at runtime, and inputs and surfaces are otherwise unrelated:
17
- * an input is a complete thing without any surface, which is why declaring them
18
- * is optional. Omitted resolves to every `SurfaceId`, so the hint reads as
14
+ * `surfaces` is read at runtime by `datadogAppHostInputsFor` to gate which
15
+ * schemas a host offers on a given surface — a dashboard-only schema is not
16
+ * offered on IDP even if a synthetic `dashboard` field is present in the
17
+ * inputs bag. Omitted resolves to every `SurfaceId`, so the hint reads as
19
18
  * "available everywhere" rather than as an empty list.
20
19
  */
21
20
  export type DatadogAppInputsSchema<TLatest extends AnyContract, TSurfaces extends readonly SurfaceId[] = typeof EVERY_SURFACE, TOlderVersions extends readonly AnyOlderContractVersion<TLatest>[] = readonly []> = VersionedContract<TLatest, TOlderVersions> & Readonly<{
@@ -95,7 +94,7 @@ export declare function datadogAppInputsDefinition<const TIdentifier extends str
95
94
  identifier: TIdentifier;
96
95
  version: TVersion;
97
96
  fields: ValidationOnlyFields<TFields>;
98
- /** Surfaces this input is offered on -- a development-time hint, read by nothing at runtime. */
97
+ /** Surfaces this input is offered on — read at runtime by the host to gate which schemas are offered per surface. */
99
98
  surfaces?: TSurfaces;
100
99
  }>): PublishedDatadogAppInputsDefinition<DatadogAppInputsSchema<PortableContract<TIdentifier, TVersion, TFields>, TSurfaces>>;
101
100
  export declare function datadogAppInputsDefinition<TLatest extends AnyContract, const TSurfaces extends readonly SurfaceId[] = typeof EVERY_SURFACE, const TOlderVersions extends readonly AnyOlderContractVersion<TLatest>[] = readonly []>(definition: Readonly<{
@@ -105,6 +104,13 @@ export declare function datadogAppInputsDefinition<TLatest extends AnyContract,
105
104
  }>): PublishedDatadogAppInputsDefinition<DatadogAppInputsSchema<TLatest, TSurfaces, TOlderVersions>>;
106
105
  /** Rejects copied or user-authored definitions at the public React boundary. */
107
106
  export declare function assertPublishedDatadogAppInputsDefinition(definition: unknown): asserts definition is PublishedDatadogAppInputsDefinition<AnyDatadogAppInputsSchema>;
107
+ /**
108
+ * Reports whether a value is a definition created by `datadogAppInputsDefinition()`
109
+ * (i.e. published through `@datadog/apps-frontend/inputs/schema`). Backed by the
110
+ * same `WeakSet` brand as `assertPublishedDatadogAppInputsDefinition`, so it
111
+ * cannot be spoofed by a duck-typed lookalike.
112
+ */
113
+ export declare function isPublishedDatadogAppInputsDefinition(definition: unknown): definition is PublishedDatadogAppInputsDefinition<AnyDatadogAppInputsSchema>;
108
114
  /**
109
115
  * Turns one plain value into the field descriptor that carries it: a function
110
116
  * becomes a callable field with validated inputs and result, anything else a
@@ -3,5 +3,5 @@
3
3
  * Copyright 2019-Present Datadog, Inc.
4
4
  */
5
5
 
6
- import{d as i}from"../../_chunks/chunk-2V2HASKF.js";import{c as n}from"../../_chunks/chunk-NCWC7QOQ.js";import"../../_chunks/chunk-X34MSTJH.js";import{useSyncExternalStore as p}from"react";function a(e){let o=i();n(e);let t=o.getClaim(e.latest);return p(t.subscribe,t.getSnapshot,t.getSnapshot)}export{a as useDatadogAppInput};
6
+ import{a}from"../../_chunks/chunk-O6R7PFZZ.js";import"../../_chunks/chunk-2V2HASKF.js";import"../../_chunks/chunk-T34NWJ7R.js";import"../../_chunks/chunk-X34MSTJH.js";export{a as useDatadogAppInput};
7
7
  //# sourceMappingURL=index.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../../../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 { assertPublishedDatadogAppInputsDefinition } from '../published-definition';\nimport type { DatadogAppInputDefinition } from '../schemas/index';\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 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"],
5
- "mappings": "gJAAA,OAAS,wBAAAA,MAA4B,QAkE9B,SAASC,EAGZC,EACiC,CACjC,IAAMC,EAAYC,EAAgB,EAClCC,EAA0CH,CAAU,EACpD,IAAMI,EAAQH,EAAU,SAAgCD,EAAW,MAAM,EACzE,OAAOK,EACHD,EAAM,UACNA,EAAM,YACNA,EAAM,WACV,CACJ",
6
- "names": ["useSyncExternalStore", "useDatadogAppInput", "definition", "embedding", "useAppEmbedding", "assertPublishedDatadogAppInputsDefinition", "store", "useSyncExternalStore"]
3
+ "sources": [],
4
+ "sourcesContent": [],
5
+ "mappings": "",
6
+ "names": []
7
7
  }
@@ -3,5 +3,5 @@
3
3
  * Copyright 2019-Present Datadog, Inc.
4
4
  */
5
5
 
6
- import{a as O,b as T}from"../../_chunks/chunk-NCWC7QOQ.js";import"../../_chunks/chunk-X34MSTJH.js";var Me=Object.freeze({status:"aborted"});function g(e,t,r){function n(u,m){if(u._zod||Object.defineProperty(u,"_zod",{value:{def:m,constr:o,traits:new Set},enumerable:!1}),u._zod.traits.has(e))return;u._zod.traits.add(e),t(u,m);let p=o.prototype,f=Object.keys(p);for(let v=0;v<f.length;v++){let $=f[v];$ in u||(u[$]=p[$].bind(u))}}let i=r?.Parent??Object;class d extends i{}Object.defineProperty(d,"name",{value:e});function o(u){var m;let p=r?.Parent?new d:this;n(p,u),(m=p._zod).deferred??(m.deferred=[]);for(let f of p._zod.deferred)f();return p}return Object.defineProperty(o,"init",{value:n}),Object.defineProperty(o,Symbol.hasInstance,{value:u=>r?.Parent&&u instanceof r.Parent?!0:u?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}var _=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};var K={};function b(e){return e&&Object.assign(K,e),K}function B(e){let t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,i])=>t.indexOf(+n)===-1).map(([n,i])=>i)}function ie(e,t){return typeof t=="bigint"?t.toString():t}function X(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function oe(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}var ne=Symbol("evaluating");function z(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==ne)return n===void 0&&(n=ne,n=r()),n},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}var q="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function ae(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Le=X(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});var ue=new Set(["string","number","symbol"]);function E(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function A(e,t,r){let n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function y(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function ce(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Re={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function j(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function M(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function N(e){return typeof e=="string"?e:e?.message}function I(e,t,r){let n={...e,path:e.path??[]};if(!e.message){let i=N(e.inst?._zod.def?.error?.(e))??N(t?.error?.(e))??N(r.customError?.(e))??N(r.localeError?.(e))??"Invalid input";n.message=i}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}var le=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,ie,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},se=g("$ZodError",le),U=g("$ZodError",le,{Parent:Error});var Fe=e=>(t,r,n,i)=>{let d=n?Object.assign(n,{async:!1}):{async:!1},o=t._zod.run({value:r,issues:[]},d);if(o instanceof Promise)throw new _;if(o.issues.length){let u=new(i?.Err??e)(o.issues.map(m=>I(m,d,b())));throw q(u,i?.callee),u}return o.value},L=Fe(U),Ve=e=>async(t,r,n,i)=>{let d=n?Object.assign(n,{async:!0}):{async:!0},o=t._zod.run({value:r,issues:[]},d);if(o instanceof Promise&&(o=await o),o.issues.length){let u=new(i?.Err??e)(o.issues.map(m=>I(m,d,b())));throw q(u,i?.callee),u}return o.value},R=Ve(U),Je=e=>(t,r,n)=>{let i=n?{...n,async:!1}:{async:!1},d=t._zod.run({value:r,issues:[]},i);if(d instanceof Promise)throw new _;return d.issues.length?{success:!1,error:new(e??se)(d.issues.map(o=>I(o,i,b())))}:{success:!0,data:d.value}},Z=Je(U),Ge=e=>async(t,r,n)=>{let i=n?Object.assign(n,{async:!0}):{async:!0},d=t._zod.run({value:r,issues:[]},i);return d instanceof Promise&&(d=await d),d.issues.length?{success:!1,error:new e(d.issues.map(o=>I(o,i,b())))}:{success:!0,data:d.value}},P=Ge(U);var Ke="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",We=new RegExp(`^${Ke}$`);var de=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var me=/^-?\d+(?:\.\d+)?$/,pe=/^(?:true|false)$/i;var ge={major:4,minor:3,patch:6};var h=g("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=ge;let n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(let i of n)for(let d of i._zod.onattach)d(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let i=(o,u,m)=>{let p=j(o),f;for(let v of u){if(v._zod.def.when){if(!v._zod.def.when(o))continue}else if(p)continue;let $=o.issues.length,x=v._zod.check(o);if(x instanceof Promise&&m?.async===!1)throw new _;if(f||x instanceof Promise)f=(f??Promise.resolve()).then(async()=>{await x,o.issues.length!==$&&(p||(p=j(o,$)))});else{if(o.issues.length===$)continue;p||(p=j(o,$))}}return f?f.then(()=>o):o},d=(o,u,m)=>{if(j(o))return o.aborted=!0,o;let p=i(u,n,m);if(p instanceof Promise){if(m.async===!1)throw new _;return p.then(f=>e._zod.parse(f,m))}return e._zod.parse(p,m)};e._zod.run=(o,u)=>{if(u.skipChecks)return e._zod.parse(o,u);if(u.direction==="backward"){let p=e._zod.parse({value:o.value,issues:[]},{...u,skipChecks:!0});return p instanceof Promise?p.then(f=>d(f,o,u)):d(p,o,u)}let m=e._zod.parse(o,u);if(m instanceof Promise){if(u.async===!1)throw new _;return m.then(p=>i(p,n,u))}return i(m,n,u)}}z(e,"~standard",()=>({validate:i=>{try{let d=Z(e,i);return d.success?{value:d.data}:{issues:d.error?.issues}}catch{return P(e,i).then(o=>o.success?{value:o.data}:{issues:o.error?.issues})}},vendor:"zod",version:1}))}),Y=g("$ZodString",(e,t)=>{h.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??de(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}});var _e=g("$ZodNumber",(e,t)=>{h.init(e,t),e._zod.pattern=e._zod.bag.pattern??me,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}let i=r.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return r;let d=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...d?{received:d}:{}}),r}});var H=g("$ZodBoolean",(e,t)=>{h.init(e,t),e._zod.pattern=pe,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=!!r.value}catch{}let i=r.value;return typeof i=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),r}});function ve(e,t,r){e.issues.length&&t.issues.push(...M(r,e.issues)),t.value[r]=e.value}var xe=g("$ZodArray",(e,t)=>{h.init(e,t),e._zod.parse=(r,n)=>{let i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),r;r.value=Array(i.length);let d=[];for(let o=0;o<i.length;o++){let u=i[o],m=t.element._zod.run({value:u,issues:[]},n);m instanceof Promise?d.push(m.then(p=>ve(p,r,o))):ve(m,r,o)}return d.length?Promise.all(d).then(()=>r):r}});function C(e,t,r,n,i){if(e.issues.length){if(i&&!(r in n))return;t.issues.push(...M(r,e.issues))}e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}function Xe(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);let r=ce(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function qe(e,t,r,n,i,d){let o=[],u=i.keySet,m=i.catchall._zod,p=m.def.type,f=m.optout==="optional";for(let v in t){if(u.has(v))continue;if(p==="never"){o.push(v);continue}let $=m.run({value:t[v],issues:[]},n);$ instanceof Promise?e.push($.then(x=>C(x,r,v,t,f))):C($,r,v,t,f)}return o.length&&r.issues.push({code:"unrecognized_keys",keys:o,input:t,inst:d}),e.length?Promise.all(e).then(()=>r):r}var ye=g("$ZodObject",(e,t)=>{if(h.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let u=t.shape;Object.defineProperty(t,"shape",{get:()=>{let m={...u};return Object.defineProperty(t,"shape",{value:m}),m}})}let n=X(()=>Xe(t));z(e._zod,"propValues",()=>{let u=t.shape,m={};for(let p in u){let f=u[p]._zod;if(f.values){m[p]??(m[p]=new Set);for(let v of f.values)m[p].add(v)}}return m});let i=ae,d=t.catchall,o;e._zod.parse=(u,m)=>{o??(o=n.value);let p=u.value;if(!i(p))return u.issues.push({expected:"object",code:"invalid_type",input:p,inst:e}),u;u.value={};let f=[],v=o.shape;for(let $ of o.keys){let x=v[$],w=x._zod.optout==="optional",G=x._zod.run({value:p[$],issues:[]},m);G instanceof Promise?f.push(G.then(Ae=>C(Ae,u,$,p,w))):C(G,u,$,p,w)}return d?qe(f,p,u,m,n.value,e):f.length?Promise.all(f).then(()=>u):u}});var be=g("$ZodEnum",(e,t)=>{h.init(e,t);let r=B(t.entries),n=new Set(r);e._zod.values=n,e._zod.pattern=new RegExp(`^(${r.filter(i=>ue.has(typeof i)).map(i=>typeof i=="string"?E(i):i.toString()).join("|")})$`),e._zod.parse=(i,d)=>{let o=i.value;return n.has(o)||i.issues.push({code:"invalid_value",values:r,input:o,inst:e}),i}});function $e(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}var ze=g("$ZodOptional",(e,t)=>{h.init(e,t),e._zod.optin="optional",e._zod.optout="optional",z(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),z(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${oe(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>{if(t.innerType._zod.optin==="optional"){let i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(d=>$e(d,r.value)):$e(i,r.value)}return r.value===void 0?r:t.innerType._zod.run(r,n)}});var Ie;var Q=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...r){let n=r[0];return this._map.set(t,n),n&&typeof n=="object"&&"id"in n&&this._idmap.set(n.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){let r=this._map.get(t);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){let r=t._zod.parent;if(r){let n={...this.get(r)??{}};delete n.id;let i={...n,...this._map.get(t)};return Object.keys(i).length?i:void 0}return this._map.get(t)}has(t){return this._map.has(t)}};function Se(){return new Q}(Ie=globalThis).__zod_globalRegistry??(Ie.__zod_globalRegistry=Se());var ee=globalThis.__zod_globalRegistry;function we(e,t){return new e({type:"string",...y(t)})}function je(e,t){return new e({type:"number",checks:[],...y(t)})}function Ue(e,t){return new e({type:"boolean",...y(t)})}var k=g("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");h.init(e,t),e.def=t,e.type=t.type,e.parse=(r,n)=>L(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>Z(e,r,n),e.parseAsync=async(r,n)=>R(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>P(e,r,n),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]},{parent:!0}),e.with=e.check,e.clone=(r,n)=>A(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.apply=r=>r(e)}),Ze=g("ZodMiniString",(e,t)=>{Y.init(e,t),k.init(e,t)});function S(e){return we(Ze,e)}var Pe=g("ZodMiniNumber",(e,t)=>{_e.init(e,t),k.init(e,t)});function te(e){return je(Pe,e)}var De=g("ZodMiniBoolean",(e,t)=>{H.init(e,t),k.init(e,t)});function Oe(e){return Ue(De,e)}var lt=g("ZodMiniArray",(e,t)=>{xe.init(e,t),k.init(e,t)});function re(e,t){return new lt({type:"array",element:e,...y(t)})}var st=g("ZodMiniObject",(e,t)=>{ye.init(e,t),k.init(e,t),z(e,"shape",()=>t.shape)});function V(e,t){let r={type:"object",shape:e??{},...y(t)};return new st(r)}var dt=g("ZodMiniEnum",(e,t)=>{be.init(e,t),k.init(e,t),e.options=Object.values(t.entries)});function Te(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new dt({type:"enum",entries:r,...y(t)})}var mt=g("ZodMiniOptional",(e,t)=>{ze.init(e,t),k.init(e,t)});function J(e){return new mt({type:"optional",innerType:e})}var ht=T({identifier:"datadog.theme",version:1,fields:{theme:O.readOnly(Te(["light","dark"]))}});var _t=V({name:S(),value:S(),values:J(re(S())),prefix:J(S()),default:J(S())}),xt=V({start:te(),end:te(),isLive:Oe()}),yt=V({timeframe:xt,templateVariables:re(_t)}),bt=T({identifier:"datadog.dashboard",version:1,surfaces:["datadog.dashboard"],fields:{dashboard:O.readOnly(yt)}});export{bt as datadogDashboard,ht as datadogTheme};
6
+ import{a,b}from"../../_chunks/chunk-IM4AWPJX.js";import"../../_chunks/chunk-T34NWJ7R.js";import"../../_chunks/chunk-X34MSTJH.js";export{b as datadogDashboard,a as datadogTheme};
7
7
  //# sourceMappingURL=index.js.map