applyCloudflareWorkersFunctions function

Future<bool> applyCloudflareWorkersFunctions({
  1. required String alias,
  2. required String package,
  3. required Map<String, String> functions,
})

Apply Cloudflare Workers functions to cloudflare/src/index.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.

cloudflare/src/index.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,
}) async {
  final indexFile = File("cloudflare/src/index.ts");
  if (!indexFile.existsSync()) {
    error(
      "The file `cloudflare/src/index.ts` 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) {
    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 `m.deploy([` in `cloudflare/src/index.ts`. Please check the Cloudflare Workers entrypoint.",
    );
    return false;
  }
  await indexFile.writeAsString(updated);
  return true;
}