DecCF./ˈdɛk.ɛf/

Embedded Calculator App reference

Embed a published Calculator App in your own website with the snippet from Embed. It contains a unique script URL and a deccf-… element name for that service, application and published version. Copy both exactly. Publishing another version or renaming a draft does not update an existing component. Generate a new snippet to change versions. Existing div-based snippets must be replaced with the new snippet.

This reference describes host website integration code, not code for the DECCF model editor. The model and its presentation still execute on DECCF servers. The component renders the same input controls and reports from their public metadata; it does not receive model source or execute authored model code.

Load and initialize

The copied snippet has this shape; replace the example element, URL and key together with the values copied from your app:

<deccf-example-0123456789abcdef id="analysis" embed-key="COPIED_EMBED_KEY"><span role="status">Loading Calculator App…</span></deccf-example-0123456789abcdef>
<script>
  const app = document.querySelector('#analysis');
  app.addEventListener('deccf-error', ({detail}) => {
    console.error(detail.code, detail.operation, detail.message);
  });
</script>
<script defer crossorigin="anonymous" src="https://YOUR-DECCF-SERVICE/api/embed/components/APP_ID/VERSION_ID.js?elementName=deccf-example-0123456789abcdef"></script>
<script type="module">
  const app = document.querySelector('#analysis');
  try {
    await customElements.whenDefined(app.localName);
    await app.ready;
    console.log(await app.getRequest());
  } catch (error) {
    console.error(error.code, error.message);
  }
</script>

The readable element name is at most 63 characters. Its suffix distinguishes the service, app and release; the elementName parameter lets an unavailable pinned version report a safe error on the right element. The loading text is a fallback if the browser cannot fetch or execute the component script. It disappears when the component loads. If the runtime or component cannot initialize, the element is still registered with a rejected ready promise and a deccf-error event. Loading the same script twice is safe. Several apps, versions or instances can coexist. Elements already on the page upgrade when their script loads; later elements initialize when connected.

embedKey is the JavaScript equivalent of embed-key. Set it before connecting an element, or use the copied attribute. Changing it reinitializes authorization. ready: Promise<void> resolves after authorized input discovery and rendering, and rejects with a safe coded error on failure. Wait for registration before calling methods; asynchronous methods then wait for ready themselves. Synchronous getResult() and getNavigation() return their empty state before initialization. Set inputsVisible and caseProvider before upgrade if needed; their values survive upgrade.

Disconnecting an element aborts local pending work and disposes its UI. Reconnecting initializes a fresh surface and a new ready promise, retains the last accepted request/result, and does not calculate automatically. A promise obtained during an abandoned initialization rejects. Attach event listeners to the element or its ancestor once, rather than adding another listener on every ready event.

The dedicated embed key is intentionally public and permits input discovery and runs only. It is locked to the exact allowed website origin and published app version, expires after 90 days, and can be revoked. Use HTTPS outside local testing. Installation, ownership, credit charging and server authorization still apply. A script URL contains no key. Never substitute a private Personal Access Token (PAT) or put credentials in URLs, logs or model code. A key for another app/version cannot be used with this element.

Request and result

await app.setRequest(payload): Promise<void> atomically replaces the request using the Web API envelope {input, scenarios, run}. input is an object of the app's declared names, scenarios is an array of {name, input}, and run uses the normal run settings. Omitted top-level input names take the published app's defaults; nested objects and arrays replace that value rather than merging individual rows. Omitted scenarios and run settings use the published defaults. Unknown envelope properties, invalid run/scenario structure, non-JSON values, cycles, excessive nesting or requests over 1 MiB are rejected without replacing the accepted request. Authoritative model validation also runs on the server.

await app.getRequest(): Promise<{input, scenarios, run}> reads the same typed controls the user edits and returns a detached JSON copy. It waits for pending reads and setters. Invalid or incomplete controls reject instead of silently returning older values. Use the app's actual money, array and time-series formats, just as in its Web API; the component does not introduce a second input schema.

<script type="module">
  const app = document.querySelector('#analysis');
  await customElements.whenDefined(app.localName);
  const request = await app.getRequest();
  await app.setRequest({
    input: request.input,
    scenarios: request.scenarios,
    run: {mode: 'deterministic', currency: 'SEK'}
  });
  const result = await app.run();
  console.log(result.data, result.requestRevision, result.credits);
  console.log(app.getResult()); // Detached copy of this successful run.
</script>

await app.run({signal}?): Promise<EmbeddedResult> explicitly starts a server calculation, using the current request and the normal UI calculation price. The user's Update results action does the same. Setting inputs, navigating, showing inputs or loading a case never starts a calculation. signal is an optional AbortSignal; cancellation stops waiting locally but cannot guarantee a refund for server work already performed.

The result wrapper is {data, credits, requestRevision, correlationId, stale}. data is the same filtered consumer response as a calculation API call, including the presentation result. credits is the response's reported credit amount or null when unavailable. requestRevision identifies accepted input state; correlationId identifies that run. getResult(): EmbeddedResult | null synchronously returns a detached copy of the last successful result, or null before any success. Its stale becomes true after an input change or invalid control. The previous report remains visible during another run. Superseded or cancelled runs cannot publish a successful current result or overwrite a later run.

Input visibility and navigation

inputsVisible: boolean and setInputsVisible(visible: boolean): void show or hide the input surface without discarding its values or bypassing validation. They reflect the boolean hide-inputs attribute: any presence hides, including hide-inputs="false"; remove the attribute to show inputs. Passing a non-boolean to the method/property throws TypeError.

getNavigation(): EmbeddedNavigation synchronously returns a detached snapshot:

  • input.pages: available {id, label} pages; input.pageId: the selected page ID or null.
  • input.aspects and presentation: available groups {id, selected, options: [{id, label}]}. Groups can change when an outer tab changes. Presentation groups become available after a successful run.

await setNavigation({input?, presentation?}): Promise<void> selects stable IDs from that snapshot. input accepts pageId and aspects: [{id, selected}]; presentation accepts [{id, selected}]. For nested tabs, select an outer group first and then read the newly available inner groups, or provide them in outer-to-inner order. A bad or unavailable selection rejects with INVALID_NAVIGATION and rolls back the batch. Labels and DOM selectors are not identifiers.

<script type="module">
  const app = document.querySelector('#analysis');
  await customElements.whenDefined(app.localName);
  await app.ready;
  const navigation = app.getNavigation();
  if (navigation.input.pages.length > 1) {
    await app.setNavigation({input: {pageId: navigation.input.pages[1].id}});
  }
  app.setInputsVisible(false);
  console.log(await app.getRequest()); // Hidden values remain available.
  app.inputsVisible = true;
</script>

Events and errors

All events are CustomEvents dispatched on the element with bubbles: true, composed: true, and detached JSON detail containing apiVersion: 1:

EventAdditional detail
deccf-readyappId, versionId; emitted after each successful initialization.
deccf-input-change`origin: 'user'
deccf-run-startcorrelationId, requestRevision.
deccf-resultThe same result wrapper returned by run() and getResult().
deccf-navigation-change`origin: 'user'
deccf-app-language-changelanguage, the app instance’s selected supported language. The portal preference is unchanged.
deccf-errorcode, safe message, operation, optional correlationId, for component loading, input discovery, execution and case loading failures.
<script type="module">
  const app = document.querySelector('#analysis');
  app.addEventListener('deccf-input-change', ({detail}) => {
    if (detail.origin === 'user' && detail.valid) {
      console.log('User request revision', detail.requestRevision);
    }
  });
  app.addEventListener('deccf-result', ({detail}) => {
    console.log('Completed run', detail.correlationId, detail.data);
  });
  app.addEventListener('deccf-error', ({detail}) => {
    console.error(detail.code, detail.message);
  });
</script>

Rejected methods expose a stable code and safe message; catch the promise as well as observing events. Codes include INVALID_REQUEST, INVALID_NAVIGATION, INVALID_RESPONSE, INVALID_EMBED_KEY, ACCESS_DENIED, NO_CREDITS, APP_SERVICE_FAILED, APP_OPERATION_FAILED, APP_VERSION_MISMATCH, APP_VERSION_UNAVAILABLE, APP_RUNTIME_UNAVAILABLE, APP_COMPONENT_UNAVAILABLE, CASE_ACCESS_UNAVAILABLE, CASE_ACCESS_DENIED, CASE_NOT_FOUND, CASE_VERSION_MISMATCH, CASE_SERVICE_FAILED, CANCELLED, SUPERSEDED, and DISCONNECTED. Transport errors map HTTP authorization, credit, validation, network and service failures to these stable codes. operation identifies the phase: load-component, load-runtime, register-component, load-inputs, run, cases, or load-case. An unavailable pinned release tells the owner to generate a fresh snippet; runtime and registration errors are reported separately from input discovery and calculation failures. Cancellation, disconnection and supersession are expected lifecycle rejections and do not emit deccf-error. No server stack, embed key, PAT, authorization header or model source is exposed.

Read-only case integration

Case access is optional and separate from the run-only embed key. Without caseProvider, ordinary calculations work; listCases/loadCase reject with CASE_ACCESS_UNAVAILABLE. No private case list is fetched. Case storage must be enabled for the app and its Web API, and the authenticated user's PAT must permit the existing list and get operations for that app and storage.

Assign caseProvider an object with:

  • list({limit, cursor?, signal?}) returning Promise<{items, nextCursor?}>.
  • load(caseId, {signal?}) returning Promise<{id, name, appId, versionId, version?, updatedAt?, request}>.

Metadata is {id, name, appId, versionId, version?, updatedAt?}. request uses the same JSON envelope as setRequest. The exact app and release must match the component; legacy cases without an exact release ID or incompatible cases cannot be loaded automatically. Model/package snapshots, source and private fields are excluded.

await app.listCases({limit=25, cursor?, signal?}?) returns a detached page of metadata. Limits are integers from 1 to 100; cursors are opaque strings at most 2,048 characters. Continue with nextCursor until null. await app.loadCase(caseId, {signal?}?) replaces the request, emits origin case, and does not run. Case IDs are non-empty strings at most 200 characters. An older load cannot overwrite a newer load, edit or provider. Setting a provider also enables the component's Open case picker.

The browser helper createHttpCaseProvider(url, {baseUrl?, fetch?}?) uses your authenticated, same-origin host endpoint. baseUrl defaults to the current page and fetch to browser fetch. The URL must have no credentials, query or fragment. Requests include same-origin cookies and reject redirects. Neither a DECCF PAT nor an account ID is sent from the browser.

<script type="module">
  import {createHttpCaseProvider} from 'https://YOUR-DECCF-SERVICE/api/embed/runtime.js';
  const app = document.querySelector('#analysis');
  await customElements.whenDefined(app.localName);
  app.caseProvider = createHttpCaseProvider('/deccf-cases');
  const page = await app.listCases({limit: 25});
  if (page.items.length) await app.loadCase(page.items[0].id);
</script>

Download the reference host adapter and its types for your authenticated host backend, never for the browser. createCaseProviderHandler({authenticate, resolveConnection, fetch?}) returns a Fetch-compatible (Request) => Promise<Response> handler. Both callbacks run for every request. authenticate(request) returns your verified principal or null; resolveConnection(principal) returns that user's server-held {apiUrl, appId, versionId, version, token} or null. apiUrl is the app's published Web API URL, token is that user's appropriately scoped PAT, and the identity must match the embedded release. The adapter reuses the existing DECCF case authorization instead of granting extra access.

Here sessions and connections are your own authenticated session and per-user connection services. Keep their credentials on the backend. Never select a privileged shared account from a browser-supplied user ID. The adapter permits GET only, delegates only list/get, disables caching/redirects and filters output to allowed metadata/request fields. Every guessed case ID is checked by the existing API against the actual user, app and storage. It filters list items to the exact release and paginates the authorized list; the upstream response is limited to 8 MiB. Unknown/duplicate query parameters, inaccessible storage, revoked PATs, foreign cases and release mismatches are rejected. There is no case save, update or delete method.

Styling and types

Each instance has its own open Shadow Root, including dialogs and dropdowns. Component CSS stays inside it. The host does not need a global DECCF stylesheet. Normal host selectors do not style internal controls. The intentional customization contract is --deccf-app-ink, --deccf-app-background, --deccf-app-accent on the element, plus ::part(surface) and ::part(title). Keyboard focus and reduced-motion preferences remain supported. Input layout responds to the available component width; allow the host element to grow vertically. Shadow DOM is not an authorization boundary.

Download the component API type declarations. The public integration/event contract has apiVersion: 1. These host methods are not functions in deccf or modules and must not be inserted into model code.

Versioned appearance

The component uses its pinned app version's optional content.ui theme, including Compact and Ultra compact density. The same theme applies in the portal and Run preview. See App themes for the eight stable IDs, metadata save/transfer example, touch targets and compatibility defaults. A host cannot change the saved theme through request inputs. The documented host variables remain deliberate overrides; choose accessible colors when overriding them.

App language changes

An app declares its supported languages and default in its own language resource. A fresh launch uses the portal preference when supported and otherwise uses that default. The app’s Language menu changes only its live instance, preserving input drafts, scenarios and navigation. Hosts can observe that change:

The event bubbles, crosses the component boundary and includes apiVersion: 1. Observing it does not run a calculation or update the portal language.