applyCloudflareWorkersFunctions function

Future<bool> applyCloudflareWorkersFunctions({
  1. required String alias,
  2. required String package,
  3. required Map<String, String> functions,
  4. bool replaceExisting = true,
  5. String entry = cloudflareEdgeEntryPath,
})

Apply Cloudflare Workers functions to the Worker entrypoint entry (defaults to cloudflare/src/edge.ts).

Ensures the import of package with alias, and inserts each entry of functions (a map of function name to the code to insert) into m.deploy([...]) if it does not already exist. Existing calls are replaced.

Workerのエントリファイルentry(既定はcloudflare/src/edge.ts)にCloudflare WorkersのFunctionを適用します。

alias付きのpackageのimportを保証し、functions(関数名から挿入コードへのマップ)の 各エントリーが存在しない場合はm.deploy([...])に挿入します。既存の呼び出しは置き換えられます。

Implementation

Future<bool> applyCloudflareWorkersFunctions({
  required String alias,
  required String package,
  required Map<String, String> functions,
  bool replaceExisting = true,
  String entry = cloudflareEdgeEntryPath,
}) async {
  final indexFile = File(entry);
  if (!indexFile.existsSync()) {
    error(
      "The file `$entry` does not exist. Initialize Cloudflare Workers by enabling [cloudflare]->[workers]->[enable] and executing `katana apply`.",
    );
    return false;
  }
  var source = await indexFile.readAsString();
  source = CloudflareSourceUtils.ensureImport(
    source,
    alias: alias,
    package: package,
  );
  final inserts = <String>[];
  for (final entry in functions.entries) {
    if (replaceExisting) {
      source = CloudflareSourceUtils.replaceFunctionCall(
        source,
        entry.key,
        entry.value,
      );
    }
    if (!CloudflareSourceUtils.containsFunctionCall(source, entry.key)) {
      inserts.add(entry.value);
    }
  }
  final updated = CloudflareSourceUtils.insertDeployFunctions(source, inserts);
  if (updated == null) {
    error(
      "Could not find the Cloudflare deploy array in `$entry`. Please check the namespace import and Workers entrypoint.",
    );
    return false;
  }
  await indexFile.writeAsString(updated);
  return true;
}