middleware-multiworker-dev.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // @ts-nocheck
  2. /// <reference path="middleware-multiworker-dev.d.ts"/>
  3. import { workers } from "config:middleware/multiworker-dev";
  4. import type { WorkerRegistry } from "../../src/dev-registry";
  5. export function wrap(env: Record<string, unknown>) {
  6. const facadeEnv = { ...env };
  7. // For every Worker definition that's available,
  8. // create a fetcher for it on the facade env.
  9. // for const [name, binding] of env
  10. // if Workers[name]
  11. // const details = Workers[name];
  12. for (const [name, details] of Object.entries(workers as WorkerRegistry)) {
  13. if (details) {
  14. facadeEnv[name] = {
  15. async fetch(...reqArgs: Parameters<Fetcher["fetch"]>) {
  16. const reqFromArgs = new Request(...reqArgs);
  17. if (details.headers) {
  18. for (const [key, value] of Object.entries(details.headers)) {
  19. // In remote mode, you need to add a couple of headers
  20. // to make sure it's talking to the 'dev' preview session
  21. // (much like wrangler dev already does via proxy.ts)
  22. reqFromArgs.headers.set(key, value);
  23. }
  24. return (env[name] as Fetcher).fetch(reqFromArgs);
  25. }
  26. const url = new URL(reqFromArgs.url);
  27. if (details.protocol !== undefined) {
  28. url.protocol = details.protocol;
  29. }
  30. if (details.host !== undefined) {
  31. url.host = details.host;
  32. }
  33. if (details.port !== undefined) {
  34. url.port = details.port.toString();
  35. }
  36. const request = new Request(url.toString(), reqFromArgs);
  37. return fetch(request);
  38. },
  39. };
  40. } else {
  41. // This means there's no dev binding available.
  42. // Let's use whatever's available, or put a shim with a message.
  43. facadeEnv[name] = facadeEnv[name] || {
  44. async fetch() {
  45. return new Response(
  46. `You should start up wrangler dev --local on the ${name} worker`,
  47. { status: 404 }
  48. );
  49. },
  50. };
  51. }
  52. }
  53. return facadeEnv;
  54. }