To provide a dynamic file, you need to make a Controller with a method like:

     public function serve(Request $request) {
        $file_str = $file_system->realpath($module_handler->getModule('my_module')->getPath()) . '/assets/js/service-worker.js';
    
        if (file_exists($file_str)) {
    
          $response = new BinaryFileResponse($file_str, 200);
          $response->headers->set('Content-Type', 'application/javascript');
          // Allow same origin service worker.
          $response->headers->set('Service-Worker-Allowed', '/');

          return $response;
        }
    
        throw new NotFoundHttpException();
      }

And then define a route for it, where the path is not existing as a static file, like:

    example.serviceworker:
      path: '/serviceworker' 
      defaults: 
        _controller: '\Drupal\my_module\Controller\ExampleController::serve' 
      requirements: 
        _permission: 'access content' 

see - https://www.drupal.org/docs/drupal-apis/routing-system/introductory-drupal-8-routes-and-controllers-example.