keyNameFor static method

String keyNameFor(
  1. String baseUrl, {
  2. String? providerName,
})

The secure-store key name backing baseUrl's key: FA_KEY_LOCALHOST_11434, FA_KEY_API_ACME_COM (the store accepts [A-Za-z0-9_]+ only). With providerName (a saved entry's name) the name is appended — FA_KEY_API_KIMI_COM_WORK — so several accounts on the same endpoint keep separate keys instead of overwriting one host-scoped entry.

Implementation

static String keyNameFor(String baseUrl, {String? providerName}) {
  final uri = Uri.tryParse(baseUrl);
  var host = uri?.host ?? baseUrl;
  if (host.isEmpty) host = 'custom';
  final port = uri?.port;
  final defaultPort = uri?.scheme == 'https' ? 443 : 80;
  if (port != null && port != defaultPort) host = '${host}_$port';
  final sanitized = host
      .toUpperCase()
      .replaceAll(RegExp('[^A-Z0-9]+'), '_')
      .replaceAll(RegExp('^_+|_+\$'), '');
  final base = 'FA_KEY_${sanitized.isEmpty ? 'CUSTOM' : sanitized}';
  final name = providerName
      ?.toUpperCase()
      .replaceAll(RegExp('[^A-Z0-9]+'), '_')
      .replaceAll(RegExp('^_+|_+\$'), '');
  // A provider named after its host (the default derived name) must not
  // double the suffix: FA_KEY_API_AIIN_BY, not FA_KEY_API_AIIN_BY_API_AIIN_BY.
  return name == null || name.isEmpty || name == sanitized
      ? base
      : '${base}_$name';
}