Rspack Build API

The /rspack entry point is build-time code for Node.js. Import it from Rsbuild or Rslib configuration and package assembly scripts, never from a target runtime module.

Compile a Target

tapLib returns an Rslib configuration for one independently compiled target. pluginTap provides the equivalent Rsbuild plugin behavior. Both accept the build-manifest path, target, output root, and Module Federation settings.

import { defineConfig } from '@rslib/core';
import { tapLib } from '@theaiplatform/miniapp-sdk/rspack';

const desktop = tapLib({
  manifest: './tap-miniapp.build.json',
  packageTarget: 'desktop',
  packageOutputRoot: '.tap-build/desktop',
  federation: {
    name: 'example_desktop',
    filename: 'remoteEntry.mjs',
    manifest: true,
    library: { type: 'module' },
    dts: false,
    exposes: { './ui/desktop': './src/surface.ts' },
  },
});

export default defineConfig({ lib: [desktop] });

TapPackageTarget is the supported target union: desktop, mobile, QuickJS, worker, Node.js, and workflow host. Compile each declared target into a separate staging root.

Package-runtime mcp.server contributions use a dedicated ./mcp/<server-contribution-id> expose. The build rejects a package-wide ./tap/mcp alias or any other expose that does not match the exact server contribution ID. Stdio and Streamable HTTP MCP servers are host-declarative; they do not add a Federation expose or a package-side registration call. The desktop host reconstructs an immutable desired registration from verified installations and swaps complete generations atomically. For a QuickJS package-runtime server, the expose's named mcpServer export may define descriptor-declared tools through defineMcpServer; the host validates the exact live catalog before making it privately discoverable to an authorized specialist and revalidates its access lease immediately before invocation. This tools-only ABI supports API version 1 and pure QuickJS functions: any declared MCP authorization action or runtime effect fails package activation, and MCP execution receives no miniapp host-action context. Human-approved exact consumer selections are persisted with audit metadata, and package consumer classes are re-derived from verified descriptors while the complete installation graph is projected. Package tools never enter the global tool registry or user MCP store. This MVP does not activate stdio/HTTP servers, prompts, resources, resource templates, or MCP Apps; schema/build acceptance for those declarations is not runtime support. The live consumer path is limited to selected specialists. On desktop, an operator grants one from Apps → Marketplace → Installed → package details. On mobile, use Workspace Settings → Miniapps → Installed → package details. Use the canonical slug, such as chloe, rather than a versioned manifest ID. Chat, workflow, miniapp, and platform-service consumer classes remain non-live. Mobile and other non-desktop hosts currently fail package activation closed for any nonempty MCP projection instead of silently omitting those declarations.

Customize Rspack

tapLib returns a patch-stable TapLibConfig rather than exposing the dependency-private Rslib configuration type. Its tools.rspack field accepts a TapRspackTool: a partial TapRspackConfig, a TapRspackConfigMutator, or an array of those values.

Preserve the configuration produced by tapLib when adding a mutator. The callback receives a TapRspackNormalizedConfig and can return a partial patch, mutate the supplied configuration, complete asynchronously, or combine those patterns.

import {
  tapLib,
  type TapRspackConfigMutator,
} from '@theaiplatform/miniapp-sdk/rspack';

const addSharedAlias: TapRspackConfigMutator = (config) => {
  const aliases =
    config.resolve.alias && config.resolve.alias !== false
      ? config.resolve.alias
      : {};

  return {
    resolve: {
      alias: { ...aliases, '@miniapp/shared': './src/shared.ts' },
    },
  };
};

const desktop = tapLib({
  manifest: './tap-miniapp.build.json',
  packageTarget: 'desktop',
});

desktop.tools.rspack = [desktop.tools.rspack ?? {}, addSharedAlias];

These structural types intentionally keep third-party extension fields open across compatible Rslib and Rspack patches. A thrown or rejected mutator, or an invalid returned patch, stops the build.

Assemble the Package

assembleTapPackage accepts TapPackageAssemblyOptions: the build manifest, final output directory, and exact map of TapPackageTarget values to staging directories.

import { assembleTapPackage } from '@theaiplatform/miniapp-sdk/rspack';

await assembleTapPackage({
  buildManifest: './tap-miniapp.build.json',
  output: './dist',
  targets: { desktop: './.tap-build/desktop' },
});

Assembly validates the build manifest and target graphs, computes integrity metadata and the content digest, and swaps the complete output into place. Missing, extra, overlapping, or incompatible targets fail the operation without publishing a partial package.

Validate and Verify a Package

assertValidTapMiniappBuildManifest validates staged build metadata before target compilation. verifyTapPackage accepts TapPackageVerificationOptions and verifies the assembled source manifest, target locks, integrity graph, Federation metadata, exposed modules, specialist manifests, runtime bootstrap, and release content digest.

import {
  assertValidTapMiniappBuildManifest,
  verifyTapPackage,
  type TapPackageVerificationOptions,
} from '@theaiplatform/miniapp-sdk/rspack';

await assertValidTapMiniappBuildManifest('./.tap-build/tap-miniapp.build.json');

const verification: TapPackageVerificationOptions = { output: './dist' };
await verifyTapPackage(verification);

Verification is read-only. It rejects placeholder values, unlocked files, path escapes, malformed package contracts, or bytes that do not match their locks.

Build a Lifecycle Target

tapLifecycleTarget creates the Rslib target selected by tap-miniapp build, check, or publish. It reads the staged descriptor, target definition, and output root from the lifecycle environment supplied to the project-owned builder.

import { defineConfig } from '@rslib/core';
import { tapLifecycleTarget } from '@theaiplatform/miniapp-sdk/rspack';

const target = tapLifecycleTarget();
target.output = { ...target.output, sourceMap: false, minify: true };

export default defineConfig({ lib: [target] });

Do not invoke this helper outside an SDK lifecycle command. Missing or malformed lifecycle environment values stop configuration before compilation.

Scan Portability

assertPortableTapPackageArtifacts accepts TapPackageArtifactPortabilityOptions. It scans the assembled output for machine-local references and can receive additional absolute checkout roots that must never appear in artifacts.

import { assertPortableTapPackageArtifacts } from '@theaiplatform/miniapp-sdk/rspack';

await assertPortableTapPackageArtifacts({
  output: './dist',
  forbiddenRoots: [process.cwd()],
});

Run the scan after assembly and before publication. Do not mutate the assembled directory afterward; any byte change invalidates its computed identity.

Register Manifest Formats

registerTapManifestAjvFormats installs the canonical TAP manifest formats on an AJV-compatible registry. Use it when a build-time tool validates config-schema.json directly so uri, uint8, uint16, and uint64 have the same behavior as SDK package validation.

import Ajv2020 from 'ajv/dist/2020.js';
import { registerTapManifestAjvFormats } from '@theaiplatform/miniapp-sdk/rspack';

const ajv = registerTapManifestAjvFormats(new Ajv2020({ allErrors: true }));
const validateManifest = ajv.compile(manifestSchema);

The helper mutates and returns the supplied registry. Register the formats before compiling the schema; invalid URI values and integers outside each unsigned range then fail validation normally.

Declare an Artifact Type

An artifact.type contribution declares a durable collaborative artifact type with package-qualified IDs, independently permissioned document lanes, and bounded payload limits. The authoring types mirror config-schema.json, so a satisfies annotation gives compile-time coverage before package validation runs.

import type { TapArtifactTypeContribution } from '@theaiplatform/miniapp-sdk/rspack';

const documentType = {
  kind: 'artifact.type',
  id: 'playground-document',
  apiVersion: 1,
  targets: { desktop: { runtime: 'host-declarative' } },
  lifecycleScope: 'installation',
  options: {
    typeId: 'playground.document.v1',
    displayName: 'Playground document',
    documents: [
      {
        id: 'content',
        syncProtocol: 'playground.content-operations.v1',
        snapshotSchema: 'schemas/content-snapshot.v1.json',
        operationSchema: 'schemas/content-operation.v1.json',
        writeAction: 'playground.edit',
        maxOperationBytes: 65_536,
        maxSnapshotBytes: 8_388_608,
      },
    ],
    compatibility: { minReaderVersion: 1, maxWriterVersion: 1 },
  },
} satisfies TapArtifactTypeContribution;

The build rejects unqualified type IDs, undeclared write actions, missing schema assets, and limits above the host ceilings before the package is signed. A package declaring an artifact.type contribution must also set compatibility.tapHost to exclude host versions before 2.19.0. Artifact file extensions and MIME selectors must be unique across all artifact.type contributions in a package release because dispatch has no type-specific tie-breaker. An artifact document's writeAction must be a reusable, direct-human action with Do autonomy; it is dedicated to artifact-type writes, may be shared by artifact types, and must not authorize unrelated contributions. An optional migration reference must name a workflow contribution with exactly one workflow-host module binding or a local.service contribution with the desktop host-declarative binding; kind alone does not admit a misbound runtime. A migrated artifact type must include receipt-journal in hostResources so migration execution has declared receipt authority.

Public Export Contract

ExportPurposeInputs and resultLifecycle and errorsWorking example
TapLibConfigDefines the patch-stable Rslib configuration returned by tapLib.Contains fixed TAP build settings plus extensible source, output, tools, and plugins.Type only; preserve required TAP tools and plugins when composing custom build behavior.Compile a target
TapRspackNormalizedConfigDescribes the normalized configuration passed to Rspack tool callbacks.Provides plugins, module rules, aliases, output, and open extension fields.Type only; callback mutations affect the active compilation and invalid values can fail.Customize Rspack
TapRspackConfigDescribes a partial structural Rspack configuration or callback patch.Accepts optional plugins, module rules, aliases, output, and extension fields.Type only; the build applies it during configuration and rejects invalid combinations.Customize Rspack
TapRspackConfigMutatorDefines a synchronous or asynchronous Rspack configuration callback.Receives normalized config and context; returns void or a partial config patch.A thrown or rejected callback stops the target build before package assembly.Customize Rspack
TapRspackToolComposes Rspack config objects and mutators behind a stable SDK type.Accepts one config, one mutator, or an ordered array containing either form.Preserve the tapLib base tool when extending it so TAP invariants remain installed.Customize Rspack
TapPackageTargetEnumerates independently compiled package targets.Supplies a desktop, mobile, QuickJS, worker, Node.js, or workflow-host target.Type only; an unsupported target fails configuration or assembly.Compile a target
TapPackageAssemblyOptionsSelects descriptor, output, and exact target roots for assembly.assembleTapPackage consumes the options and resolves with no value.Type only; missing, extra, or overlapping target roots reject.Assemble the package
TapPackageArtifactPortabilityOptionsConfigures an emitted-artifact portability scan.Selects output and optional forbidden absolute roots.Type only; invalid roots or nonportable bytes make the scan reject.Scan portability
TapPackageVerificationOptionsConfigures complete verification of one assembled package.Selects the assembled output directory to inspect without mutation.Type only; malformed paths or package bytes cause verification to reject.Validate and verify a package
assertPortableTapPackageArtifactsRejects machine-local references in assembled artifacts.Accepts portability options and returns a promise of void.Run after assembly and before publication; any finding rejects.Scan portability
assertValidTapMiniappBuildManifestValidates staged TAP build metadata before target compilation.Accepts a build-manifest path and resolves after schema and semantic validation.Placeholder values, invalid references, or malformed fields reject before compilation.Validate and verify a package
assembleTapPackageBuilds one immutable descriptor-backed package from target roots.Accepts assembly options and returns a promise of void.It swaps output transactionally; validation failure preserves the prior complete output.Assemble the package
pluginTapAdds descriptor and Federation package behavior to Rsbuild.Accepts build options and returns an RsbuildPlugin.It validates during build and fails when required package artifacts are missing.Compile a target
registerTapManifestAjvFormatsInstalls the canonical TAP manifest formats on an AJV-compatible registry.Accepts and returns the same registry after registering all required formats.Register before schema compilation; invalid format values make manifest validation fail.Register manifest formats
tapLibProduces an Rslib target configuration with package behavior installed.Accepts build options and returns a TapLibConfig.Use once per target build; configuration and artifact failures stop the build.Compile a target
tapLifecycleTargetProduces the Rslib target selected by the SDK package lifecycle.Reads lifecycle environment and returns a configured TapLibConfig.Use only through lifecycle orchestration; missing or malformed context throws.Build a lifecycle target
verifyTapPackageVerifies descriptor, locks, artifacts, Federation output, and runtime ABI.Accepts verification options and returns a promise after a read-only package audit.Any unlocked, malformed, nonportable, or integrity-mismatched artifact rejects.Validate and verify a package
TapArtifactTypeContributionTypes a complete artifact.type manifest contribution for authoring.Contains the contribution base fields plus the artifact type options object.Type only; invalid declarations fail schema and semantic validation during the build.Declare an artifact type
TapArtifactTypeOptionsTypes the options of one durable collaborative artifact type.Accepts the qualified type ID, document lanes, schemas, limits, and compatibility.Type only; unqualified IDs or oversized limits reject before package assembly.Declare an artifact type
TapArtifactDocumentDefinitionTypes one independently permissioned document lane of an artifact type.Accepts the lane ID, sync protocol, schema paths, write action, and byte limits.Type only; an undeclared write action or missing schema asset rejects the build.Declare an artifact type
TapArtifactTypeSchemasTypes the optional type-wide anchor, thread, presence, and preview schemas.Accepts package-relative JSON schema paths for each optional type-wide schema.Type only; unsafe or non-JSON schema paths reject during manifest validation.Declare an artifact type
TapArtifactMigrationRuntimeTypes the migration entry point reference of an artifact type.Accepts the contribution ID of an admitted non-UI runtime in the same package.Type only; UI surfaces and unknown contribution IDs reject during validation.Declare an artifact type
TapArtifactFileAssociationTypes one file-handler association of an artifact type.Accepts an ID, extensions, optional MIME types, and an import/export direction.Type only; duplicate or malformed extensions or MIME selectors reject during manifest validation.Declare an artifact type
TapArtifactFileDirectionEnumerates the import, export, or import-export association directions.Supplies one closed direction value for a file association.Type only; any other value fails closed schema validation.Declare an artifact type
TapArtifactHostResourceKindEnumerates the platform-owned resource kinds an artifact type may consume.Supplies one closed host resource kind such as sync-transport or snapshot-store.Type only; any unlisted resource kind fails closed schema validation.Declare an artifact type
TapArtifactTypeCompatibilityTypes the artifact format versions a release can read and write.Accepts the oldest readable and newest writable format version numbers.Type only; inverted or out-of-range versions reject during manifest validation.Declare an artifact type