hooks library

This package provides the API for hooks in Dart. Hooks are Dart scripts placed in the hook/ directory of a Dart package, designed to automate tasks for a Dart package.

Currently, the main supported hook is the build hook (hook/build.dart). The build hook is executed during a Dart build and enables you to bundle assets with a Dart package. The main entrypoint for build hooks is build.

The second hook available in this API is the link hook (hook/link.dart). The main entrypoint for link hooks is link.

Hooks can for example be used to bundle native source code with a Dart package:

import 'package:code_assets/code_assets.dart';
import 'package:hooks/hooks.dart';
import 'package:native_toolchain_c/native_toolchain_c.dart';

void main(List<String> args) async {
  await build(args, (input, output) async {
    if (input.config.buildCodeAssets) {
      final builder = CBuilder.library(
        name: 'sqlite3',
        assetName: 'src/third_party/sqlite3.g.dart',
        sources: ['third_party/sqlite/sqlite3.c'],
        defines: {
          if (input.config.code.targetOS == OS.windows)
            // Ensure symbols are exported in dll.
            'SQLITE_API': '__declspec(dllexport)',
        },
      );
      await builder.run(input: input, output: output);
    }
  });
}

Hooks can also be used to bundle precompiled native code with a package:

import 'package:code_assets/code_assets.dart';
import 'package:hooks/hooks.dart';

void main(List<String> args) async {
  await build(args, (input, output) async {
    if (input.config.buildCodeAssets) {
      final packageName = input.packageName;
      final assetPathInPackage = input.packageRoot.resolve('...');
      final assetPathDownload = input.outputDirectoryShared.resolve('...');

      output.assets.code.add(
        CodeAsset(
          package: packageName,
          name: '...',
          linkMode: DynamicLoadingBundled(),
          file: assetPathInPackage,
        ),
      );
    }
  });
}

For more information see dart.dev/tools/hooks.

Environment

Hooks are executed in a semi-hermetic environment. This means that Platform.environment does not expose all environment variables from the parent process. This ensures that hook invocations are reproducible and cacheable, and do not depend on accidental environment variables.

However, some environment variables are necessary for locating tools (like compilers) or configuring network access. The following environment variables are passed through to the hook process:

  • Path and system roots:
    • PATH: Invoke native tools.
    • HOME, USERPROFILE: Find tools in default install locations.
    • SYSTEMDRIVE, SYSTEMROOT, WINDIR: Process invocations and CMake on Windows.
    • PROGRAMDATA: For vswhere.exe on Windows.
  • Temporary directories:
    • TEMP, TMP, TMPDIR: Temporary directories.
  • HTTP proxies:
    • HTTP_PROXY, HTTPS_PROXY, NO_PROXY: Network access behind proxies.
  • Clang/LLVM:
    • LIBCLANG_PATH: Rust's bindgen + clang-sys.
  • Android NDK:
    • ANDROID_HOME: Standard location for the Android SDK/NDK.
    • ANDROID_NDK, ANDROID_NDK_HOME, ANDROID_NDK_LATEST_HOME, ANDROID_NDK_ROOT: Alternative locations for the NDK.
  • Ccache:
    • Any variable starting with CCACHE_.
  • Nix:
    • Any variable starting with NIX_.

Any changes to these environment variables will cause cache invalidation for hooks.

All other environment variables are stripped.

Classes

AssetRouting
The destination for assets in the BuildOutput.
BuildConfig
The configuration in BuildInput.config.
BuildConfigBuilder
The builder for BuildConfig.
Builder
A builder to be run in build in hook/build.dart.
BuildInput
The input for hook/build.dart.
BuildInputAssets
The assets in BuildInput.assets.
BuildInputBuilder
The builder for BuildInput.
BuildInputMetadata
The metadata in BuildInput.metadata.
BuildOutput
The output from a hook/build.dart on success.
BuildOutputAssets
The assets in BuildOutput.assets.
BuildOutputAssetsBuilder
The builder for BuildOutputAssets.
BuildOutputBuilder
The builder for BuildOutput.
BuildOutputFailure
The output from a hook/build.dart on failure.
BuildOutputMaybeFailure
Either a successful BuildOutput or a BuildOutputFailure.
BuildOutputMetadataBuilder
The builder for BuildOutputBuilder.metadata.
EncodedAsset
An encoded asset.
FailureType
A type of failure that occurred during a hook execution.
HookConfig
The configuration in HookInput.config.
HookConfigBuilder
The builder for HookConfig.
HookInput
The input for hook/build.dart or hook/link.dart.
HookInputBuilder
The builder for HookInput.
HookInputUserDefines
The user-defines in HookInput.userDefines.
HookOutput
The output from a hook/build.dart or hook/link.dart.
HookOutputBuilder
The builder for HookOutput.
HookOutputDependenciesBuilder
The builder for HookOutput.dependencies.
HookOutputFailure
The output of a hook that has failed.
LinkAssetRouting
The destination for assets in the LinkOutput.
LinkConfig
The configuration in LinkInput.config.
LinkConfigBuilder
The builder for BuildConfig.
Linker
A builder to be run in link in hook/link.dart.
LinkInput
The input for a hook/link.dart.
LinkInputAssets
The assets in LinkInput.assets;
LinkInputBuilder
The builder for LinkInput.
LinkOutput
The output for a hook/link.dart on success.
LinkOutputAssets
The assets in LinkOutput.assets.
LinkOutputAssetsBuilder
The builder for LinkOutput.assets in LinkOutputBuilder.
LinkOutputBuilder
The builder for LinkOutput.
LinkOutputFailure
The output from a hook/link.dart on failure.
LinkOutputMaybeFailure
Either a successful LinkOutput or a LinkOutputFailure.
LinkOutputMetadataBuilder
The builder for LinkOutputBuilder.metadata.
PackageMetadata
The metadata from a specific package, available in BuildInput.metadata.
PackageUserDefines
The user-defines for HookInputBuilder.setupShared.
PackageUserDefinesSource
A source of user-defines in a PackageUserDefines.
ProtocolBase
The base protocol for hook/build.dart and hook/link.dart which can be extended with ProtocolExtensions.
ProtocolExtension
An extension to the ProtocolBase for hook/build.dart and hook/link.dart.
ToAppBundle
Assets with this AssetRouting in the HookOutput will be sent to the SDK to be bundled with the app.
ToBuildHooks
Assets with this AssetRouting in the BuildOutput will be sent to build hooks.
ToLinkHook
Assets with this AssetRouting in the HookOutput will be sent to the link hook of packageName.

Functions

build(List<String> arguments, Future<void> builder(BuildInput input, BuildOutputBuilder output)) Future<void>
Builds assets in a hook/build.dart.
Links assets in a hook/link.dart.
testBuildHook({required FutureOr<void> mainMethod(List<String> arguments), required FutureOr<void> check(BuildInput input, BuildOutput output), bool? linkingEnabled, required List<ProtocolExtension> extensions, PackageUserDefines? userDefines, Map<String, List<EncodedAsset>>? assets}) Future<void>
Tests the main function of a hook/build.dart.

Typedefs

ValidationErrors = List<String>
A list of error messages from validation.

Exceptions / Errors

BuildError
An error indicating a problem with the build logic within a hook.
HookError
Base class for errors that can be thrown during a build or link invocation.
InfraError
An error indicating an infrastructure-related problem during hook execution.