Releases: cloudflare/miniflare
v2.0.0-rc.3
The Miniflare docs now include a migration guide for upgrading from version 1.
Breaking Changes
- Mounts are no longer accessible by default via
/<mount_name>. You must specify routes inwrangler.tomlusing theroute/routes/miniflare.route/miniflare.routesoptions for them to be accessible. See 🔌 Multiple Workers for more details. This feature was inspired bymultiflare, created by @dan-lee. - All file-path-valued options are now resolved relative to the
--rootoption Miniflare#dispatchFetchwill now rewrite the request's URL/Hostheader to match the upstream URL if specifiedconvertNodeRequestno longer accepts anupstreamparameter, it now always uses the request'sHostheader
Features
- Make
Request/Responsebodys byte streams, allowing them to be read with bring-your-own-buffer readers - Allow setting the
wrangler.tomlenvironment when mounting workers with the CLI. For example,--mount api=./api@devmounts the worker in the./apidirectory asapi, using thedevenvironment in./api/wrangler.toml. - Allow setting the Durable Object
script_nameoption via the CLI. For example,--do COUNTER=Counter@apibinds theCOUNTERDurable Object namespace using theCounterclass exported by the mountedapiworker. - Update error message when attempting to access bindings via global in modules mode for Cloudflare Pages
- When the
fetch_refuses_unknown_protocolscompatibility flag isn't set, log a warning when attempting to use a protocol other thanhttporhttps - The upstream URL is now validated on startup if specified
Fixes
- Copy
webSocketwhen constructing aResponsefrom an existingResponse, closes issue #100, thanks @universse - Allow constructing
nullbody with empty-string, closes issue #101, thanks @PH4NTOMiki - Remove ASCII whitespace from
atobinput, closes issue #104, thanks @dan-lee - Remove keys limit from Durable Objects
list()method, closes issue #105, thanks @vzaramel - Allow
Sec-WebSocket-Protocolheader in WebSocketfetch, closes issue #106, thanks @f5io - Fix uncaught rejection when closing server-sent events connection, closes issue #107, thanks @dan-lee
- Bump
undicito4.11.1, allowingResponses withnullbodies to be cloned, closes issue #110, thanks @payellodevsupport - Allow forbidden header mutation on
Request/Responseinstances, closes cloudflare/wrangler2 issue #59, thanks @oliverjam - Allow missing parent script with mounted workers
- Correctly handle attempting to read a key in a namespace that is also a key when using
FileStorage, and throw when trying to write in this case (this is a limitation of Miniflare's file-system storage). - When the
fetch_refuses_unknown_protocolscompatibility flag isn't set, correctly replace non-standard protocols (e.g.random://) withhttp://infetch. - Remove types dependency on
lib.webworker - Incoming
httpsrequests will now havehttpsURLs
v2.0.0-rc.2
Features
- Add
structuredCloneto the sandbox - Copy
--kv-persist,--cache-persistand--do-persistoptions to--mounts, so data is shared correctly - Resolve mount-custom storage persistence options relative to mounted directory
- Add a more helpful error message on
DurableObjectStorage#getdeserialization failure due to Miniflare 1 data - Add a more helpful error message on
Cache#matchdeserialization failure due to Miniflare 1 data - Add a more helpful error message when unable to find a matching module rule that suggests bundling npm packages
Fixes
- Bump
undicito4.10.2, closes issues #84 and #91, thanks @gzuidhof and @tranzium - Remove
HostandCF-Connecting-IPheaders whenfetching, closes issue #97, thanks @WalshyDev - Allow file-system persisted keys to start with
/, thanks @eidam for reporting this - Setting an option to
undefinednow overrides that option inwrangler.tomllike Miniflare 1 - When building mounted workers, set the current working directory to the mounted directory
- Respect the
fetch_refuses_unknown_protocolscompatibility flag inDurableObjectStub#fetch - Default
Response.redirectstatus to302instead of throwing - Improve spec-compliance of WebSocket event constructors
Jest Fixes 🙁
- Fix importing
miniflarein Jest when using thenodeenvironment, specifically fixWebSocketServerimport andatob/btoa/AbortSignalglobals - Add
Bufferto global injest-environment-node, thanks @dan-lee for the PR - Allow dynamic code generation in
jest-environment-nodefor coverage, thanks @dan-lee for reporting this
v2.0.0-rc.1
Breaking Changes
- Changed the priority of bindings, so it matches Miniflare 1. The new order (from lowest to highest priority) is:
- Variables from
wrangler.toml[vars] - Variables from
.envfiles - WASM module bindings (
--wasm,[wasm_modules]) - Custom bindings
- Variables from
- The result of
dispatchScheduledwill no longer includeundefinedif a module scheduled handler doesn't return a value
Features
- Added a custom Jest test environment for Miniflare. This allows you to run unit tests in the Miniflare sandbox, with isolated storage for each test. Install
jest-environment-miniflare@nextto get started and see 🤹 Jest Environment for more details. - Added support for running multiple workers in the same Miniflare instance. See 🔌 Multiple Workers for more details.
- Added support for the Durable Object
script_nameoption. See 📌 Durable Objects for more details. - Added support for the new
__STATIC_CONTENT_MANIFESTtext module for using Workers Sites in modules mode - Throw an error when a Durable Object
fetchhandler doesn't return aResponse - Added
queueMicrotaskto the sandbox - Added the
Miniflare#getCachesmethod for accessing the globalcachesoutside workers - Added back the
sourceMapoption toMiniflare - Changed the default location for the
update-checkandcf.jsonfiles to insidenode_modules - Switched the CRON validation and scheduling package from
node-crontocron-schedule. This improves error messages for invalid CRON expressions, and removes a transitive dependency onmoment-timezone, reducing the installation size by a further 5MB.
Fixes
- Allow any close code when a client closes a WebSocket connection. Closes issue #86, thanks @TimTinkers.
- Wait for worker response before opening WebSocket in client, closes issue #88, thanks @TimTinkers.
- Pass the
--envflag towrangler buildwhen--wrangler-envis set fortype = "webpack"/"rust"builds - Set correct
Hostheader with--upstreamflag set - Fixed memory leak in
HTMLRewriterwhen passing non-ArrayBuffer(View)chunks - Marked
@miniflare/coreand@miniflare/storage-memoryasdependenciesof@miniflare/durable-objects - Removed
ServiceWorkerGlobalScope#dispose()from global scope
v2.0.0-next.3
Fixes
- Remove
Content-Lengthheader fromHTMLRewritertransformedResponses - Update
Content-Lengthheader if set and live-reload is enabled - Inject the live-reload script when there is no closing
</body>tag. Closes issue #70, thanks @jed for reporting this, and @lukeed for the PR. - Bump
undicito4.9.3, fixing iteration ofHeaders. Closes issue #64, thanks @Kikobeats for reporting this, and @lukeed for fixing this inundici. - Added install-time check for minimum supported Node.js version. Thanks @lukeed for the PR.
- Updated build script to use ES module exports of dependencies where possible. Thanks @lukeed for the PR.
v2.0.0-next.2
Fixes
- Added support for the
Response#encodeBodyproperty. If this is omitted or set toauto,Responses with aContent-Encodingheader that includesgzip,deflateorbrwill be automatically encoded. Closes issue #72, thanks @SupremeTechnopriest. - Getters on
Request/Responseare now enumerable, and headers added toRequest/Responseinstances after construction will now be retained if those instances are used to construct newRequest/Responses. Closes issue #73, thanks @maraisr and @somebody1234. - Variables defined in
.envfiles now override those inwrangler.toml. Closes issue #75, thanks @payellodevsupport for the PR. httpandhttpsprotocols are now required for WebSocket upgrades viafetchas per the workers runtime- Miniflare-added
CF-*headers are now included in the HTML error response
v2.0.0-next.1
Miniflare 2 has been completely redesigned from version 1 with 3 primary design goals:
- 📚 Modular: Miniflare 2 splits Workers components (KV, Durable Objects, etc.) into separate packages (
@miniflare/kv,@miniflare/durable-objects, etc.) that you can import on their own for testing. - ✨ Lightweight: Miniflare 1 included 122 third-party packages with a total install size of
88.3MB. Miniflare 2 reduces this to 24 packages and11.5MB🤯. This can probably be reduced further too. - ✅ Correct: Miniflare 2 more accurately replicates the quirks and thrown errors of the real Workers runtime, so you'll know before you deploy if things are going to break.
The docs will be updated over the next few weeks.
Notable Changes
- ✳️ Node.js 16.7.0 is now the minimum required version
- 🎲 Added support for
crypto.randomUUID() - 🔐 Added support for the
NODE-ED25519algorithm - 📅 Added support for compatibility dates and flags:
durable_object_fetch_requires_full_url,fetch_refuses_unknown_protocols,formdata_parser_supports_files - 📚 Added a proper CommonJS module loader
- 🚪 Added Durable Object input and output gates, and write coalescing
- 🛑 Added the
DurableObjectState#blockConcurrencyWhile(callback)method - ⚡️ Added a live reload feature (
--live-reload) that automatically refreshes your browser when your worker reloads - 🗺 Automatically fetch the incoming
Request#cfobject from a trusted Cloudflare endpoint - ✉️ Added support for sending/receiving binary WebSocket messages
Breaking Changes
-
Node.js 16.7.0 is now the minimum required version. You should use the latest Node.js version if possible, as Cloudflare Workers use a very up-to-date version of V8. Consider using a Node.js version manager such as https://volta.sh/ or https://github.com/nvm-sh/nvm.
-
Changed the storage format for Durable Objects and cached responses. If you're using file-system or Redis storage, you'll need to delete these directories/namespaces.
-
Changed the Durable Object ID format to include a hash of the object name. Durable Object IDs generated in Miniflare 1 cannot be used with Miniflare 2.
-
Removed support for the Durable Object
script_nameoption. This was implemented incorrectly in Miniflare 1. It will be re-implemented correctly soon. -
Removed the non-standard
DurableObjectStub#storage()method. To access Durable Object storage outside a worker, use the newMiniflare#getDurableObjectStorage(id)method, passing aDurableObjectIdobtained from a stub. -
Renamed the
--disable-cache/disableCache: trueoption to--no-cache/cache: false -
Renamed the
--disable-updateroption to--no-update-check -
When using the API,
wrangler.toml,package.jsonand.envare now no longer automatically loaded from their default locations. To re-enable this behaviour, set these options totrue:const mf = new Miniflare({ wranglerConfigPath: true, packagePath: true, envPath: true, });
-
Replaced the
ConsoleLogclass with theLogclass from@miniflare/shared. You can construct this with a member from theLogLevelenumto control how much information is logged to the console:import { Miniflare } from "miniflare"; import { Log, LogLevel } from "@miniflare/shared"; const mf = new Miniflare({ log: new Log(LogLevel.DEBUG), });
-
Load WASM bindings from the standard
wasm_moduleswrangler.tomlkey instead ofminiflare.wasm_bindings.# wrangler.toml [miniflare] wasm_bindings = [ { name = "MODULE1", path="module1.wasm" }, { name = "MODULE2", path="module2.wasm" } ]
...should now be...
# wrangler.toml [wasm_modules] MODULE1 = "module1.wasm" MODULE2 = "module2.wasm"
-
Replaced the
Miniflare#reloadOptions()method with theMiniflare#reload()andMiniflare#setOptions({ ... })methods.reload()will reload options fromwrangler.toml(useful if not watching), andsetOptions()accepts the same options object as thenew Miniflareconstructor, applies those options, then reloads the worker. -
Miniflare#createServer()now always returns aPromisewhich you must await to get ahttp.Server/https.Serverinstance. You may want to check out the newMiniflare#startServer()method which automatically starts a server using the configuredhostandport. -
Miniflare no longer includes CommonJS exports. You must use ES modules. If you need to import
miniflarein a CommonJS file, use dynamic import:const { Miniflare } = await import("miniflare"). -
Redis support is no longer included by default. If you're persisting KV, Durable Objects or cached responses in Redis, you must install the
@miniflare/storage-redisoptional peer dependency. -
Replaced how Miniflare sanitises file paths for file-system storage so namespace separators (
/,\,:and|) now create new directories.
Features and Fixes
Cache:
- Added support for
cf.cacheKey,cf.cacheTtlandcf.cacheTtlByStatusonRequest. Closes issue #37, thanks @cdloh. - Added the
CF-Cache-Status: HITheader to matchedResponses - Log warning when trying to use cache with
workers_dev = trueinwrangler.toml. Cache operations are a no-op onworkers.devsubdomains. - Throw errors when trying to cache Web Socket, non-
GET,206 Partial Content, orVary: *responses - Throw an error when trying to
opena cache with a name longer than1024characters
CLI:
- Separated command line options into sections
- Validate types of all command line options
Builds:
- When running your worker's build script, Miniflare will set the environment variable
MINIFLARE=1. Closes issue #65, thanks @maraisr. - Added an alias,
-B, for the--build-commandoption - Multiple build watch paths can now be specified. If any of them change, your worker will rebuild and reload.
- Fixed an issue where workers would not rebuild if the build watch path started with
./. Closes issue #53, thanks @janat08.
Standards:
- Added support for
crypto.randomUUID() - Added support for the
NODE-ED25519algorithm tocrypto.subtle.sign()andcrypto.subtle.verify() - Throw an error when attempting to create a new
TextDecoderwith a non-UTF-8 encoding - Throw errors when attempting to use
FetchEvent/ScheduledEventmethods with incorrectly boundthis - Throw errors when attempting to call
respondWith()twice, or after thefetchhandler has finished executing synchronously. Closes issue #63, thanks @Kikobeats. - Added support for the
unhandledrejectionandrejectionhandledevents - Throw an error (with a suggested fix) when trying to access an
envbinding globally in modules mode - Throw errors when trying to use
addEventListener(),removeEventListener()anddispatchEvent()globals in modules mode - Split the
FetchError: No fetch handler responded and unable to proxy request to upstream?error into more specific errors with suggested fixes - Added the non-standard
Headers#getAll()method. This can only be used with theSet-Cookieheader. - Switch to a more spec-compliant
fetchimplementation, and getcrypto,EventTargetand Web Streams from Node.js. Closes issues #56 and #59, thanks @jasnell, @jonathannorris and @SupremeTechnopriest. - Throw an error when attempting to construct a WebSocket response with a status other than
101 - Throw an error when attempting to clone a WebSocket response
- Added support for the non-standard
ReadableStreamBYOBReader#readAtLeast(size, buffer)method - Include
Filein the Miniflare sandbox. Closes issue #66, thanks @tranzium.
Bindings:
- Added
--global KEY=VALUE/globals: { KEY: "value" }option for binding arbitrary values to the global scope. This behaves exactly like the--binding/bindings: { ... }option, but always binds to the global scope, even in modules mode. - Added a new global variable
MINIFLAREto the Miniflare sandbox, which will always have the valuetruewhen your script is running within Miniflare - Miniflare now stringifies all environment variables from
wrangler.toml. Closes issue #50, thanks @ozburo.
Core:
- Added support for compatibility dates and flags, specifically the flags
durable_object_fetch_requires_full_url,fetch_refuses_unknown_protocols,formdata_parser_supports_filesare now supported. This feature is exposed under the--compat-dateand--compat-flagCLI options, in addition to the standard keys inwrangler.toml. Closes issue #48, thanks @PaganMuffin. - Added a proper CommonJS module loader. Workers built with Webpack will be more likely to work with Miniflare now. Closes issue #44, thanks [@TimTinkers](https://github....
v1.4.1
v1.4.0
Features
- Added
EventandEventTargetto the sandbox. The global scope andWebSocketnow inherit fromEventTargetsoremoveEventListeneris now supported. Closes issue #18, thanks @jayphelps. - Added workers' uncompressed size to logs, closes issue #23, thanks @ItsWendell
- Switch to lighter dependencies, thanks @lukeed. There's still lots of work to do here for the next major release.
Fixes
- Require the
GETmethod for WebSocket upgrades, closes issue #25, thanks @ItsWendell - Added
WebSocketto the sandbox, closes issue #30, thanks @ItsWendell. Note you still need to useWebSocketPairandfetchto set up WebSocket connections. See ✉️ WebSockets for more details. - Fixed caching with
URLrequest keys, closes issue #33, thanks @TimTinkers - Disable the watcher whilst rebuilding, closes issue #34, thanks @TimTinkers
v1.3.3
Features
- Added an option to disable default and named caches. When disabled, the caches will still be available in the sandbox, they just won't cache anything. Thanks @frandiox for the suggestion. See ✨ Cache for more details.
- Added the corresponding
wrangler.tomlkey for the--disable-updaterflag:miniflare.disable_updater
Fixes
- Fixed the
package.jsonfile path the update checker checked against
v1.3.2
Features
- Responses are now streamed when using the built-in HTTP(S) server
- Return values of Durable Object transaction closures are now propagated as the return value of the
transactioncall
Fixes
- Upgraded
html-rewriter-wasmto version0.3.2, fixingasynchandler support, closeshtml-rewriter-wasmissue #1