@cloudflare/vite-plugin 2.0.0-rc.2 → 2.0.0-rc.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,132 @@
1
+ import { r as __toESM } from "./rolldown-runtime-kJ_i4yPo.mjs";
2
+ import { _ as getDockerPath } from "./misc-variables-6mf5dDi6-D3ykvtRq.mjs";
3
+ import { b as debuglog, c as require_picocolors, d as assertIsNotPreview, h as getCurrentWorkerNameToExportTypesMap, m as compareWorkerNameToExportTypesMaps, p as compareExportTypes } from "./tunnel-DSpiLlEf.mjs";
4
+ import { a as initRunners } from "./cloudflare-environment-_xlj7RBY.mjs";
5
+ import { u as prepareContainerImagesForCfConfig, y as UNKNOWN_HOST } from "./debug-BVzLHH7X.mjs";
6
+ import { n as getDevMiniflareOptions, t as handleWebSocket } from "./websockets-BJtLbshN.mjs";
7
+ import { a as kRequestType, createRequestHandler, r as ROUTER_WORKER_NAME, resolveRequestTarget, t as ASSET_WORKER_NAME } from "./request-handler-DoB8hTSz.mjs";
8
+ import assert from "node:assert";
9
+ import { CoreHeaders, buildPublicUrl } from "miniflare";
10
+ //#region ../workers-shared/asset-worker/src/utils/rules-engine.ts
11
+ const ESCAPE_REGEX_CHARACTERS = /[-/\\^$*+?.()|[\]{}]/g;
12
+ const escapeRegex = (str) => {
13
+ return str.replace(ESCAPE_REGEX_CHARACTERS, "\\$&");
14
+ };
15
+ const generateGlobOnlyRuleRegExp = (rule) => {
16
+ rule = rule.split("*").map(escapeRegex).join(".*");
17
+ rule = "^" + rule + "$";
18
+ return RegExp(rule);
19
+ };
20
+ const generateStaticRoutingRuleMatcher = (rules) => ({ request }) => {
21
+ const { pathname } = new URL(request.url);
22
+ for (const rule of rules) try {
23
+ if (generateGlobOnlyRuleRegExp(rule).test(pathname)) return true;
24
+ } catch {}
25
+ return false;
26
+ };
27
+ //#endregion
28
+ //#region src/plugins/dev.ts
29
+ var import_picocolors = /* @__PURE__ */ __toESM(require_picocolors(), 1);
30
+ /** Configure the Cloudflare runtime for Vite development. */
31
+ async function configureDevServer(ctx, viteDevServer) {
32
+ assertIsNotPreview(ctx);
33
+ const initialOptions = await getDevMiniflareOptions(ctx, viteDevServer);
34
+ let containerOptions = initialOptions.containerOptions;
35
+ await ctx.startOrUpdateMiniflare(initialOptions.miniflareOptions);
36
+ const closeServer = viteDevServer.close.bind(viteDevServer);
37
+ viteDevServer.close = async () => {
38
+ try {
39
+ await closeServer();
40
+ } finally {
41
+ if (!ctx.isRestartingDevServer) try {
42
+ await ctx.disposeMiniflare();
43
+ } catch (error) {
44
+ debuglog("Failed to dispose Miniflare instance:", error);
45
+ }
46
+ }
47
+ };
48
+ if (viteDevServer.httpServer) viteDevServer.httpServer.on("listening", () => {
49
+ const addr = viteDevServer.httpServer?.address();
50
+ if (typeof addr === "object" && addr !== null) {
51
+ const serverConfig = viteDevServer.config.server;
52
+ ctx.miniflare.publicUrl = buildPublicUrl({
53
+ hostname: typeof serverConfig.host === "string" ? serverConfig.host : void 0,
54
+ port: addr.port,
55
+ secure: !!serverConfig.https
56
+ });
57
+ }
58
+ });
59
+ if (ctx.resolvedPluginConfig.type === "workers") {
60
+ debuglog("Initializing the Vite module runners");
61
+ await initRunners(ctx.resolvedPluginConfig, viteDevServer, ctx.miniflare);
62
+ const currentWorkerNameToExportTypesMap = await getCurrentWorkerNameToExportTypesMap(ctx.resolvedPluginConfig, viteDevServer, ctx.miniflare);
63
+ if (compareWorkerNameToExportTypesMaps(ctx.workerNameToExportTypesMap, currentWorkerNameToExportTypesMap)) {
64
+ ctx.setWorkerNameToExportTypesMap(currentWorkerNameToExportTypesMap);
65
+ const updatedOptions = await getDevMiniflareOptions(ctx, viteDevServer);
66
+ containerOptions = updatedOptions.containerOptions;
67
+ await ctx.startOrUpdateMiniflare(updatedOptions.miniflareOptions);
68
+ await initRunners(ctx.resolvedPluginConfig, viteDevServer, ctx.miniflare);
69
+ }
70
+ for (const environmentName of ctx.resolvedPluginConfig.environmentNameToWorkerMap.keys()) {
71
+ const environment = viteDevServer.environments[environmentName];
72
+ assert(environment, `Expected environment "${environmentName}" to be defined`);
73
+ environment.hot.on("vite-plugin-cloudflare:worker-export-types", async (newExportTypes) => {
74
+ const workerConfig = ctx.getWorkerConfig(environmentName);
75
+ assert(workerConfig, `Expected workerConfig for environment "${environmentName}" to be defined`);
76
+ const oldExportTypes = ctx.workerNameToExportTypesMap.get(workerConfig.name);
77
+ assert(oldExportTypes, `Expected export types for Worker "${workerConfig.name}" to be defined`);
78
+ if (compareExportTypes(oldExportTypes, newExportTypes)) {
79
+ viteDevServer.config.logger.info(import_picocolors.default.dim(import_picocolors.default.yellow("Worker exports have changed. Restarting dev server.")));
80
+ await viteDevServer.restart();
81
+ }
82
+ });
83
+ }
84
+ const entryWorkerConfig = ctx.entryWorkerConfig;
85
+ assert(entryWorkerConfig, `No entry Worker config`);
86
+ const entryWorkerName = entryWorkerConfig.name;
87
+ if (viteDevServer.httpServer) handleWebSocket(viteDevServer.httpServer, ctx.miniflare, entryWorkerName, viteDevServer.config.server.ws !== false);
88
+ const staticRouting = entryWorkerConfig.assets?.runWorkerFirst === true ? { user_worker: ["/*"] } : ctx.resolvedPluginConfig.staticRouting;
89
+ if (staticRouting) {
90
+ const excludeRulesMatcher = generateStaticRoutingRuleMatcher(staticRouting.asset_worker ?? []);
91
+ const includeRulesMatcher = generateStaticRoutingRuleMatcher(staticRouting.user_worker);
92
+ const userWorkerHandler = createRequestHandler(async (request) => {
93
+ request.headers.set(CoreHeaders.ROUTE_OVERRIDE, entryWorkerName);
94
+ return ctx.miniflare.dispatchFetch(request, { redirect: "manual" });
95
+ });
96
+ viteDevServer.middlewares.use(function cloudflarePreMiddleware(req, res, next) {
97
+ assert(req.url, `req.url not defined`);
98
+ const request = new Request(resolveRequestTarget(req.url, UNKNOWN_HOST));
99
+ if (req[kRequestType] === "asset") next();
100
+ else if (excludeRulesMatcher({ request })) {
101
+ req[kRequestType] = "asset";
102
+ next();
103
+ } else if (includeRulesMatcher({ request })) userWorkerHandler(req, res, next);
104
+ else next();
105
+ });
106
+ }
107
+ if (containerOptions !== void 0) {
108
+ const dockerPath = getDockerPath();
109
+ viteDevServer.config.logger.info(import_picocolors.default.dim(import_picocolors.default.yellow("∷ Building container images for local development...\n")));
110
+ await prepareContainerImagesForCfConfig({
111
+ dockerPath,
112
+ containerOptions,
113
+ settings: ctx.resolvedPluginConfig.settings,
114
+ logger: viteDevServer.config.logger
115
+ });
116
+ viteDevServer.config.logger.info(import_picocolors.default.dim(import_picocolors.default.yellow("\n⚡️ Containers successfully built. To rebuild your containers during development, restart the Vite dev server (r + enter).")));
117
+ }
118
+ }
119
+ return () => {
120
+ viteDevServer.middlewares.use(createRequestHandler(async (request, req) => {
121
+ if (req[kRequestType] === "asset") {
122
+ request.headers.set(CoreHeaders.ROUTE_OVERRIDE, ASSET_WORKER_NAME);
123
+ return ctx.miniflare.dispatchFetch(request, { redirect: "manual" });
124
+ } else {
125
+ request.headers.set(CoreHeaders.ROUTE_OVERRIDE, ROUTER_WORKER_NAME);
126
+ return ctx.miniflare.dispatchFetch(request, { redirect: "manual" });
127
+ }
128
+ }));
129
+ };
130
+ }
131
+ //#endregion
132
+ export { configureDevServer };
package/dist/index.d.mts CHANGED
@@ -6,7 +6,7 @@ import { EventEmitter } from "node:events";
6
6
  import { Blob, File } from "node:buffer";
7
7
  import { ConnectionOptions, TLSSocket } from "node:tls";
8
8
  import * as vite from "vite";
9
- //#region ../config/dist/public-BCKAFHC6.d.mts
9
+ //#region ../config/dist/public-34zSX4F6.d.mts
10
10
  //#endregion
11
11
  //#region src/bindings.d.ts
12
12
  /** Options that control a binding during local development. */
@@ -2665,6 +2665,12 @@ declare const WorkerConfigSchema: ZodObject<{
2665
2665
  identity: ZodOptional<ZodRecord<ZodString, ZodUnknown>>;
2666
2666
  }, $strict>>;
2667
2667
  }, $strict>>;
2668
+ images: ZodOptional<ZodObject<{
2669
+ urlTransformations: ZodOptional<ZodObject<{
2670
+ enabled: ZodBoolean;
2671
+ allowedOrigins: ZodOptional<ZodArray<ZodString>>;
2672
+ }, $strict>>;
2673
+ }, $strict>>;
2668
2674
  workersDev: ZodOptional<ZodBoolean>;
2669
2675
  previewUrls: ZodOptional<ZodBoolean>;
2670
2676
  experimental: ZodOptional<ZodObject<{
@@ -2876,6 +2882,12 @@ declare const CloudflareConfigSchema: ZodObject<{
2876
2882
  identity: ZodOptional<ZodRecord<ZodString, ZodUnknown>>;
2877
2883
  }, $strict>>;
2878
2884
  }, $strict>>;
2885
+ images: ZodOptional<ZodObject<{
2886
+ urlTransformations: ZodOptional<ZodObject<{
2887
+ enabled: ZodBoolean;
2888
+ allowedOrigins: ZodOptional<ZodArray<ZodString>>;
2889
+ }, $strict>>;
2890
+ }, $strict>>;
2879
2891
  workersDev: ZodOptional<ZodBoolean>;
2880
2892
  previewUrls: ZodOptional<ZodBoolean>;
2881
2893
  experimental: ZodOptional<ZodObject<{
@@ -3081,7 +3093,7 @@ declare const CloudflareConfigSchema: ZodObject<{
3081
3093
  }, $strict>;
3082
3094
  type ParsedCloudflareConfig = output<typeof CloudflareConfigSchema>;
3083
3095
  //#endregion
3084
- //#region ../../node_modules/.pnpm/undici@7.30.1/node_modules/undici/types/formdata.d.ts
3096
+ //#region ../../node_modules/.pnpm/undici@7.30.2/node_modules/undici/types/formdata.d.ts
3085
3097
  declare module 'node:buffer' {
3086
3098
  interface File {
3087
3099
  readonly [Symbol.toStringTag]: string;
@@ -3190,11 +3202,11 @@ type DD = `${number}${number}`;
3190
3202
  */
3191
3203
  type CompatDate = `${YYYY}-${MM}-${DD}`;
3192
3204
  //#endregion
3193
- //#region ../../node_modules/.pnpm/undici@7.30.1/node_modules/undici/types/utility.d.ts
3205
+ //#region ../../node_modules/.pnpm/undici@7.30.2/node_modules/undici/types/utility.d.ts
3194
3206
  type AutocompletePrimitiveBaseType<T> = T extends string ? string : T extends number ? number : T extends boolean ? boolean : never;
3195
3207
  type Autocomplete<T> = T | (AutocompletePrimitiveBaseType<T> & Record<never, never>);
3196
3208
  //#endregion
3197
- //#region ../../node_modules/.pnpm/undici@7.30.1/node_modules/undici/types/header.d.ts
3209
+ //#region ../../node_modules/.pnpm/undici@7.30.2/node_modules/undici/types/header.d.ts
3198
3210
  /**
3199
3211
  * The header type declaration of `undici`.
3200
3212
  */
@@ -3206,7 +3218,7 @@ type KnownHeaderValues = {
3206
3218
  };
3207
3219
  type HeaderRecord = { [K in HeaderNames | Lowercase<HeaderNames>]?: Lowercase<K> extends keyof KnownHeaderValues ? KnownHeaderValues[Lowercase<K>] : string; };
3208
3220
  //#endregion
3209
- //#region ../../node_modules/.pnpm/undici@7.30.1/node_modules/undici/types/readable.d.ts
3221
+ //#region ../../node_modules/.pnpm/undici@7.30.2/node_modules/undici/types/readable.d.ts
3210
3222
  declare class BodyReadable extends Readable {
3211
3223
  constructor(opts: {
3212
3224
  resume: (this: Readable, size: number) => void | null;
@@ -3265,7 +3277,7 @@ declare class BodyReadable extends Readable {
3265
3277
  }): Promise<void>;
3266
3278
  }
3267
3279
  //#endregion
3268
- //#region ../../node_modules/.pnpm/undici@7.30.1/node_modules/undici/types/fetch.d.ts
3280
+ //#region ../../node_modules/.pnpm/undici@7.30.2/node_modules/undici/types/fetch.d.ts
3269
3281
  type BodyInit = ArrayBuffer | AsyncIterable<Uint8Array> | Blob | FormData | Iterable<Uint8Array> | NodeJS.ArrayBufferView | URLSearchParams | null | string;
3270
3282
  interface SpecIterator<T, TReturn = any, TNext = undefined> {
3271
3283
  next(...args: [] | [TNext]): IteratorResult<T, TReturn>;
@@ -3311,7 +3323,7 @@ declare class Headers implements SpecIterable<[string, string]> {
3311
3323
  readonly [Symbol.iterator]: () => SpecIterableIterator<[string, string]>;
3312
3324
  }
3313
3325
  //#endregion
3314
- //#region ../../node_modules/.pnpm/undici@7.30.1/node_modules/undici/types/formdata.d.ts
3326
+ //#region ../../node_modules/.pnpm/undici@7.30.2/node_modules/undici/types/formdata.d.ts
3315
3327
  declare module 'node:buffer' {
3316
3328
  interface File {
3317
3329
  readonly [Symbol.toStringTag]: string;
@@ -3405,7 +3417,7 @@ declare class FormData {
3405
3417
  readonly [Symbol.toStringTag]: string;
3406
3418
  }
3407
3419
  //#endregion
3408
- //#region ../../node_modules/.pnpm/undici@7.30.1/node_modules/undici/types/connector.d.ts
3420
+ //#region ../../node_modules/.pnpm/undici@7.30.2/node_modules/undici/types/connector.d.ts
3409
3421
  declare function buildConnector(options?: buildConnector.BuildOptions): buildConnector.connector;
3410
3422
  declare namespace buildConnector {
3411
3423
  export type BuildOptions = (ConnectionOptions | TcpNetConnectOpts | IpcNetConnectOpts) & {
@@ -3435,7 +3447,7 @@ declare namespace buildConnector {
3435
3447
  }
3436
3448
  }
3437
3449
  //#endregion
3438
- //#region ../../node_modules/.pnpm/undici@7.30.1/node_modules/undici/types/client-stats.d.ts
3450
+ //#region ../../node_modules/.pnpm/undici@7.30.2/node_modules/undici/types/client-stats.d.ts
3439
3451
  declare class ClientStats {
3440
3452
  constructor(pool: Client);
3441
3453
  /** If socket has open connection. */
@@ -3448,7 +3460,7 @@ declare class ClientStats {
3448
3460
  size: number;
3449
3461
  }
3450
3462
  //#endregion
3451
- //#region ../../node_modules/.pnpm/undici@7.30.1/node_modules/undici/types/client.d.ts
3463
+ //#region ../../node_modules/.pnpm/undici@7.30.2/node_modules/undici/types/client.d.ts
3452
3464
  type ClientConnectOptions = Omit<Dispatcher.ConnectOptions, 'origin'>;
3453
3465
  /**
3454
3466
  * A basic HTTP/1.1 client, mapped on top a single TCP/TLS connection. Pipelining is disabled by default.
@@ -3588,7 +3600,7 @@ declare namespace Client {
3588
3600
  }
3589
3601
  }
3590
3602
  //#endregion
3591
- //#region ../../node_modules/.pnpm/undici@7.30.1/node_modules/undici/types/errors.d.ts
3603
+ //#region ../../node_modules/.pnpm/undici@7.30.2/node_modules/undici/types/errors.d.ts
3592
3604
  declare namespace Errors {
3593
3605
  export class UndiciError extends Error {
3594
3606
  name: string;
@@ -3722,7 +3734,7 @@ declare namespace Errors {
3722
3734
  }
3723
3735
  }
3724
3736
  //#endregion
3725
- //#region ../../node_modules/.pnpm/undici@7.30.1/node_modules/undici/types/dispatcher.d.ts
3737
+ //#region ../../node_modules/.pnpm/undici@7.30.2/node_modules/undici/types/dispatcher.d.ts
3726
3738
  type AbortSignal$1 = unknown;
3727
3739
  type UndiciHeaders = Record<string, string | string[]> | IncomingHttpHeaders | string[] | Iterable<[string, string | string[] | undefined]> | null;
3728
3740
  /** Dispatcher is the core API used to dispatch requests. */
@@ -3813,7 +3825,7 @@ declare namespace Dispatcher {
3813
3825
  idempotent?: boolean;
3814
3826
  /** Whether the response is expected to take a long time and would end up blocking the pipeline. When this is set to `true` further pipelining will be avoided on the same connection until headers have been received. Defaults to `method !== 'HEAD'`. */
3815
3827
  blocking?: boolean;
3816
- /** The IP Type of Service (ToS) value for the request socket. Must be an integer between 0 and 255. Default: `0` */
3828
+ /** The IP Type of Service (ToS) value for the request socket. Must be an integer between 0 and 255. */
3817
3829
  typeOfService?: number | null;
3818
3830
  /** Upgrade the request. Should be used to specify the kind of upgrade i.e. `'Websocket'`. Default: `method === 'CONNECT' || null`. */
3819
3831
  upgrade?: boolean | string | null;
@@ -3972,7 +3984,7 @@ declare namespace Dispatcher {
3972
3984
  }
3973
3985
  }
3974
3986
  //#endregion
3975
- //#region ../../node_modules/.pnpm/undici@7.30.1/node_modules/undici/types/mock-interceptor.d.ts
3987
+ //#region ../../node_modules/.pnpm/undici@7.30.2/node_modules/undici/types/mock-interceptor.d.ts
3976
3988
  /** The scope associated with a mock dispatch. */
3977
3989
  declare class MockScope<TData extends object = object> {
3978
3990
  constructor(mockDispatch: MockInterceptor.MockDispatch<TData>);