Read page as text

NIB / DOCUMENTATION

API reference — NibGenUI

Pick the core, Flutter renderer, or optional HTTP adapter deliberately.

Open interactive view

Choose the smallest layer that solves the task

Use nib_genui_core when you need to validate or replay data without Flutter. Add nib_genui when the accepted surface should become native widgets. Add nib_genui_http only when an existing host endpoint will deliver JSONL or receive approved action envelopes. Each layer has a separate owner: the runtime owns surface state, the renderer owns widget subscriptions, and your host owns the HTTP client and session.

The custom Badge example below is an advanced extension, after the Basic fixture works. Give the custom catalog its own ID, create the surface with that same ID, then send Badge with a label. Register both the schema and the builder. A schema-only Badge is valid data but has no custom visual implementation; a builder-only Badge is rejected before rendering because the catalog never permitted it.

The upper callback is a registered string function. The schema specifies its argument names and types, while functions supplies trusted executable code. A wire value can request that known function but cannot define new Dart. Keep callbacks deterministic and free of I/O: resolving a label may happen repeatedly, and a formatting operation must not trigger a payment, fetch or mutation.

Core: data and policy

nib_genui_core is pure Dart. NibCatalog defines allowed component and function schemas. NibRuntime validates envelopes, owns surfaces and bindings, and decides whether a registered action may dispatch. NibA2uiV091Adapter and NibJsonlAdapter sit at the untrusted input boundary.

Use allowedSurfaceIds on adapters when a stream should control only particular surfaces. Calling runtime.applyJson directly does not add stream ownership policy for you.

Local string computation also needs two registrations: a NibFunctionSchema in the catalog and a same-named pure callback in NibRuntime.functions. A dynamic-string field may request {"call":"upper","args":{"value":{"path":"/name"}},"returnType":"string"}; the wire cannot define the function itself.

final catalog = NibCatalog(
  'https://example.test/catalog/v1',
  [
    NibComponentSchema('Badge', {
      'label': const NibPropertySchema(
        NibPropertyKind.dynamicString,
        required: true,
      ),
    }),
  ],
  functions: [
    NibFunctionSchema('upper', {
      'value': NibFunctionArgumentKind.string,
    }),
  ],
);
final runtime = NibRuntime(
  catalogs: [catalog],
  functions: {
    'upper': (args) => (args['value'] as String).toUpperCase(),
  },
);
APITypeDefaultBehavior
NibCatalog.basic()NibCatalogfour componentsRegistered Basic subset with its exact catalog ID.
NibA2uiV091Adapter(..., allowedSurfaceIds: ...)adapternullEnvelope parser with optional surface ownership allowlist.
NibJsonlAdapter.maxFramesint1024Physical JSONL lines per adapter, including blank or malformed lines.
NibRuntime.resolve(surfaceId, value)Object?null if unresolvedResolves literal, binding, or registered string function.

Renderer: trusted Flutter builders

nib_genui exports the core API and adds NibGeneratedSurface. It uses Nib components for controls and NibMotion for structural changes. The host may register a map of NibComponentBuilder callbacks, but untrusted JSON cannot provide Dart builders.

A schema without a renderer builder shows an unsupported-component fallback. The host owns the runtime; the widget owns its node subscription. The surrounding Theme and Directionality apply to the rendered controls.

NibGeneratedSurface(
  runtime: runtime,
  surfaceId: 'main',
  builders: {
    'Badge': (context, node, runtime, surfaceId) {
      final value = runtime.resolve(
        surfaceId,
        node.properties['label']!,
      );
      return Text(value as String? ?? '');
    },
  },
)
APITypeDefaultBehavior
runtime / surfaceIdNibRuntime / StringrequiredRuntime and surface selected for rendering.
motionEnabledbooltrueAllows structural motion unless reduced motion is active.
buildersMap<String, NibComponentBuilder>{}Host-registered renderers for custom catalog components.
labelsNibGeneratedSurfaceLabelsEnglish fallbacksLocalized empty, loading, error, tree, component, action, and field text.
errorNibDiagnostic?nullInitial error label when no valid surface exists.

HTTP: optional transport

nib_genui_http adds NibHttpTransport. The host supplies an http.Client, endpoint, headers, surface allowlist, and reconnect policy. connect consumes JSONL; sendAction posts one approved action envelope. It does not choose a backend or authorize an account.

A successful action POST only means the endpoint returned a 2xx status. It is not a business-operation receipt. Handle failure and duplicate delivery in the host and backend.

import 'package:http/http.dart' as http;
import 'package:nib_genui_core/nib_genui_core.dart';
import 'package:nib_genui_http/nib_genui_http.dart';

Future<void> readUi(Uri endpoint, NibRuntime runtime) async {
  final client = http.Client();
  final transport = NibHttpTransport(client: client, runtime: runtime);
  try {
    await for (final result in transport.connect(
      endpoint,
      allowedSurfaceIds: {'main'},
    )) {
      if (!result.accepted) {
        for (final diagnostic in result.diagnostics) {
          print(diagnostic.code);
        }
      }
    }
  } finally {
    client.close();
  }
}
APITypeDefaultBehavior
connect(endpoint, allowedSurfaceIds: ...)Stream<NibApplyResult>surface IDs requiredGET JSONL stream into one runtime.
sendAction(endpoint, event)Future<void>host callPOST a versioned action envelope after local policy.
maxStreamBytes / maxFramesint8 MiB / 1024Per-connection byte and frame ceilings.

Give a stream an explicit owner

The readUi function is a finite-stream example. Supply a real endpoint that your host already controls and a runtime whose allowed surface is main. connect performs GET and yields one NibApplyResult per processed frame. A malformed frame can produce a rejected result; connection failures are stream errors. Handle both paths. The allowedSurfaceIds set limits which surface this connection may mutate; it does not authenticate the caller or endpoint.

For an interactive page that can close before the response ends, keep the StreamSubscription and cancel it when leaving. Cancellation aborts the request. Close the client only if that owner created it, and stop the stream before disposing the runtime. If several sessions share a client, one session must not close the client while the others still use it.

The runtime action handler type is synchronous void. If it starts sendAction, catch that Future’s errors in host code and update a separate busy/result state. An accepted dispatch means local policy permitted the handler; it does not mean an asynchronous server operation succeeded. Start transport integration with a bounded fixture endpoint, verify cancellation and failures, then add authentication and your application’s action contract.