The lightweight reactive data library for JavaScript applications
[](https://github.com/emberjs/data/actions?workflow=CI)
[](https://codeclimate.com/github/emberjs/data)
[](https://discord.gg/zT3asNS)
+---
-# Overview
+Wrangle your application's data management with scalable patterns for developer productivity.
-`EmberData` is a lightweight reactive data library for JavaScript applications that provides composable primitives for ordering query/mutation/peek flows, managing network and cache, and reducing data for presentation. You can plug-and-play as desired for any api structure and format.
+- β‘οΈ Committed to Best-In-Class Performance
+- π² Focused on being as svelte as possible
+- π SSR Ready
+- π Typescript Support
+- πΉ Built with β₯οΈ by [Ember](https://emberjs.com)
+- βοΈ Supports any API: `GraphQL` `JSON:API` `REST` `tRPC` ...bespoke or a mix
-It was designed for robustly managing data in applications built with [Ember](https://github.com/emberjs/ember.js/) and is agnostic to the underlying persistence mechanism, so it works just as well with [JSON:API](https://jsonapi.org/) or [GraphQL](https://graphql.org/) over `HTTPS` as it does with streaming `WebSockets` or local `IndexedDB` storage.
+### π On This Page
-It provides many of the features you'd find in server-side `ORM`s like `ActiveRecord`, but is designed specifically for the unique environment of `JavaScript` in the browser.
+- [Overview](./#overview)
+ - [Architecture](./#-architecture)
+ - [Basic Installation](./#basic-installation)
+ - [Advanced Installation](./#advanced-installation)
+- [Configuration](./#configuration)
+ - [Deprecation Stripping](./#deprecation-stripping)
+ - [randomUUID polyfill](./#randomuuid-polyfill)
+ - [Removing inspector support in production](./#removing-inspector-support-in-production)
+ - [Debugging](./#debugging)
+- [Contributing](./#contributing)
+
+# Overview
+
+*Ember***Data** is a lightweight reactive data library for JavaScript applications that provides composable primitives for ordering query/mutation/peek flows, managing network and cache, and reducing data for presentation.
-- [Usage Guide](https://guides.emberjs.com/release/models/)
- [API Documentation](https://api.emberjs.com/ember-data/release)
+- [Community & Help](https://emberjs.com/community)
- [Contributing Guide](./CONTRIBUTING.md)
+- [Usage Guide](https://guides.emberjs.com/release/models/)
- [RFCs](https://github.com/emberjs/rfcs/labels/T-ember-data)
-- [Community](https://emberjs.com/community)
- [Team](https://emberjs.com/team)
- [Blog](https://emberjs.com/blog)
+
+## πͺ Architecture
+
+*Ember***Data** is both *resource* centric and *document* centric in it's approach to caching, requesting and presenting data. Your application's configuration and usage drives which is important and when.
+
+The `Store` is a **coordinator**. When using a `Store` you configure what cache to use, how cache data should be presented to the UI, and where it should look for requested data when it is not available in the cache.
+
+This coordination is handled opaquely to the nature of the requests issued and the format of the data being handled. This approach gives applications broad flexibility to configure *Ember***Data** to best suite their needs. This makes *Ember***Data** a powerful solution for applications regardless of their size and complexity.
+
+*Ember***Data** is designed to scale, with a religious focus on performance and asset-size to keep its footprint small but speedy while still being able to handle large complex APIs in huge data-driven applications with no additional code and no added application complexity. It's goal is to prevent applications from writing code to manage data that is difficult to maintain or reason about.
+
+*Ember***Data**'s power comes not from specific features, data formats, or adherence to specific API specs such as `JSON:API` `trpc` or `GraphQL`, but from solid conventions around requesting and mutating data developed over decades of experience scaling developer productivity.
+
+
+
## Basic Installation
Install using your javascript package manager of choice. For instance with [pnpm](https://pnpm.io/)
```no-highlight
-pnpm add -D ember-data
+pnpm add ember-data
```
`ember-data` is installed by default for new applications generated with `ember-cli`. You can check what version is installed by looking in the `devDependencies` hash of your project's [package.json](https://docs.npmjs.com/cli/v8/configuring-npm/package-json) file.
@@ -38,7 +89,7 @@ not wish to use `ember-data`, remove `ember-data` from your project's `package.j
## Advanced Installation
-EmberData is organized into primitives that compose together via public APIs.
+*Ember***Data** is organized into primitives that compose together via public APIs.
- [@ember-data/store](./packages/store) is the core and handles coordination
- [@ember-data/record-data](./packages/record-data) is a resource cache for JSON:API structured data. It integrates with the store via the hook `createRecordDataFor`
@@ -56,7 +107,7 @@ public APIs, other libraries or applications may provide their own implementatio
### Deprecation Stripping
-EmberData allows users to opt-in and remove code that exists to support deprecated behaviors.
+*Ember***Data** allows users to opt-in and remove code that exists to support deprecated behaviors.
If your app has resolved all deprecations present in a given version, you may specify that version as your "compatibility" version to remove the code that supported the deprecated behavior from your app.
@@ -72,7 +123,7 @@ let app = new EmberApp(defaults, {
### randomUUID polyfill
-EmberData uses `UUID V4` by default to generate identifiers for new data created on the client. Identifier generation is configurable, but we also for convenience will polyfill
+*Ember***Data** uses `UUID V4` by default to generate identifiers for new data created on the client. Identifier generation is configurable, but we also for convenience will polyfill
the necessary feature if your browser support or deployment environment demands it. To
activate this polyfill:
diff --git a/docs-generator/yuidoc.json b/docs-generator/yuidoc.json
index 40143b558c0..7d4b84c2d9f 100644
--- a/docs-generator/yuidoc.json
+++ b/docs-generator/yuidoc.json
@@ -20,7 +20,9 @@
"../packages/record-data/addon",
"../packages/debug/addon",
"../packages/private-build-infra/addon",
- "../packages/canary-features/addon"
+ "../packages/canary-features/addon",
+ "../packages/tracking/src",
+ "../packages/request/src"
],
"exclude": "vendor",
"outdir": "../packages/-ember-data/dist/docs"
diff --git a/ember-data-logo-dark.svg b/ember-data-logo-dark.svg
new file mode 100644
index 00000000000..737a4aa4321
--- /dev/null
+++ b/ember-data-logo-dark.svg
@@ -0,0 +1,12 @@
+
diff --git a/ember-data-logo-light.svg b/ember-data-logo-light.svg
new file mode 100644
index 00000000000..58ac3d4e544
--- /dev/null
+++ b/ember-data-logo-light.svg
@@ -0,0 +1,12 @@
+
diff --git a/package.json b/package.json
index 2992d1e1a6d..3c1359fdc12 100644
--- a/package.json
+++ b/package.json
@@ -7,12 +7,12 @@
"url": "git+ssh://git@github.com:emberjs/data.git"
},
"scripts": {
- "build-v2-addons": "pnpm --filter @ember-data/tracking build",
+ "build-v2-addons": "pnpm --filter @ember-data/tracking --filter @ember-data/request build",
"build:docs": "mkdir -p packages/-ember-data/dist && cd ./docs-generator && node ./compile-docs.js",
"lint:js": "eslint --cache --ext=js,ts .",
"preinstall": "npx only-allow pnpm",
"problems": "tsc -p tsconfig.json --noEmit --pretty false",
- "test": "pnpm --filter main-test-app --filter graph-test-app run test",
+ "test": "pnpm --filter main-test-app --filter graph-test-app --filter request-test-app run test",
"test:production": "pnpm --filter main-test-app --filter graph-test-app run test -e production",
"test:try-one": "pnpm --filter main-test-app run test:try-one",
"test:docs": "pnpm build:docs && pnpm --filter docs-tests test",
diff --git a/packages/-ember-data/addon/index.js b/packages/-ember-data/addon/index.js
index d8e1d8d225a..033298cdc9c 100644
--- a/packages/-ember-data/addon/index.js
+++ b/packages/-ember-data/addon/index.js
@@ -1,13 +1,75 @@
/**
- # Overview
+
+
+
-`EmberData` is a lightweight reactive data library for javascript applications that provides composable primitives for ordering query/mutation/peek flows, managing network and cache, and reducing data for presentation that you can plug-and-play as desired for any api structure and format.
+
The lightweight reactive data library for JavaScript applications
-It was designed for robustly managing data in applications built with [Ember](https://github.com/emberjs/ember.js/) and is agnostic to the underlying persistence mechanism, so it works just as well with [JSON:API](https://jsonapi.org/) or [GraphQL](https://graphql.org/) over `HTTPS` as it does with streaming `WebSockets` or local `IndexedDB` storage.
+---
-It provides many of the facilities you'd find in server-side `ORM`s like `ActiveRecord`, but is designed specifically for the unique environment of `JavaScript` in the browser.
+Wrangle your application's data management with scalable patterns for developer productivity.
-EmberData is organized into primitives that compose together via public APIs.
+- β‘οΈ Committed to Best-In-Class Performance
+- π² Focused on being as svelte as possible
+- π SSR Ready
+- π Typescript Support
+- πΉ Built with β₯οΈ by [Ember](https://emberjs.com)
+- βοΈ Supports any API: `GraphQL` `JSON:API` `REST` `tRPC` ...bespoke or a mix
+
+### π On This Page
+
+- [Overview](./#overview)
+ - [Architecture](#πͺ-architecture)
+ - [Basic Installation](#basic-installation)
+ - [Advanced Installation](#advanced-installation)
+- [Configuration](#configuration)
+ - [Deprecation Stripping](#deprecation-stripping)
+ - [randomUUID polyfill](#randomuuid-polyfill)
+ - [Removing inspector support in production](#removing-inspector-support-in-production)
+ - [Debugging](#debugging)
+
+
+# Overview
+
+*Ember*β**Data** is a lightweight reactive data library for JavaScript applications that provides composable primitives for ordering query/mutation/peek flows, managing network and cache, and reducing data for presentation.
+
+## πͺ Architecture
+
+The core of *Ember*β**Data** is the `Store`, which coordinates interaction between your application, the `Cache`, and sources of data (such as your `API` or a local persistence layer).
+Optionally, the Store can be configured to hydrate the response data into rich presentation classes.
+
+*Ember*β**Data** is both resource centric and document centric in it's approach to caching, requesting and presenting data. Your application's configuration and usage drives which is important and when.
+
+The `Store` is a **coordinator**. When using a `Store` you configure what cache to use, how cache data should be presented to the UI, and where it should look for requested data when it is not available in the cache.
+
+This coordination is handled opaquely to the nature of the requests issued and the format of the data being handled. This approach gives applications broad flexibility to configure *Ember*β**Data** to best suite their needs. This makes *Ember*β**Data** a powerful solution for applications regardless of their size and complexity.
+
+*Ember*β**Data** is designed to scale, with a religious focus on performance and asset-size to keep its footprint small but speedy while still being able to handle large complex APIs in huge data-driven applications with no additional code and no added application complexity. It's goal is to prevent applications from writing code to manage data that is difficult to maintain or reason about.
+
+*Ember*β**Data**'s power comes not from specific features, data formats, or adherence to specific API specs such as `JSON:API` `trpc` or `GraphQL`, but from solid conventions around requesting and mutating data developed over decades of experience scaling developer productivity.
+
+## Basic Installation
+
+Install using your javascript package manager of choice. For instance with [pnpm](https://pnpm.io/)
+
+```no-highlight
+pnpm add ember-data
+```
+
+`ember-data` is installed by default for new applications generated with `ember-cli`. You can check what version is installed by looking in the `devDependencies` hash of your project's [package.json](https://docs.npmjs.com/cli/v8/configuring-npm/package-json) file.
+
+If you have generated a new `Ember` application using `ember-cli` but do
+not wish to use `ember-data`, remove `ember-data` from your project's `package.json` file and run your package manager's install command to update your lockfile.
+
+## Advanced Installation
+
+*Ember*β**Data** is organized into primitives that compose together via public APIs.
- [@ember-data/store](/ember-data/release/modules/@ember-data%2Fstore) is the core and handles coordination
- [@ember-data/record-data](/ember-data/release/modules/@ember-data%2Frecord-data) is a resource cache for JSON:API structured data. It integrates with the store via the hook `createRecordDataFor`
@@ -25,7 +87,7 @@ public APIs, other libraries or applications may provide their own implementatio
### Deprecation Stripping
-EmberData allows users to opt-in and remove code that exists to support deprecated behaviors.
+*Ember*β**Data** allows users to opt-in and remove code that exists to support deprecated behaviors.
If your app has resolved all deprecations present in a given version, you may specify that version as your "compatibility" version to remove the code that supported the deprecated behavior from your app.
@@ -41,7 +103,7 @@ let app = new EmberApp(defaults, {
### randomUUID polyfill
-EmberData uses `UUID V4` by default to generate identifiers for new data created on the client. Identifier generation is configurable, but we also for convenience will polyfill
+*Ember*β**Data** uses `UUID V4` by default to generate identifiers for new data created on the client. Identifier generation is configurable, but we also for convenience will polyfill
the necessary feature if your browser support or deployment environment demands it. To
activate this polyfill:
diff --git a/packages/tracking/lib/transform-ext.js b/packages/private-build-infra/src/transforms/babel-plugin-transform-ext.js
similarity index 100%
rename from packages/tracking/lib/transform-ext.js
rename to packages/private-build-infra/src/transforms/babel-plugin-transform-ext.js
diff --git a/packages/request/LICENSE.md b/packages/request/LICENSE.md
new file mode 100644
index 00000000000..8a71a0b5226
--- /dev/null
+++ b/packages/request/LICENSE.md
@@ -0,0 +1,11 @@
+The MIT License (MIT)
+
+Copyright (C) 2017-2022 Ember.js contributors
+Portions Copyright (C) 2011-2017 Tilde, Inc. and contributors.
+Portions Copyright (C) 2011 LivingSocial Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/packages/request/README.md b/packages/request/README.md
new file mode 100644
index 00000000000..508171fa861
--- /dev/null
+++ b/packages/request/README.md
@@ -0,0 +1,366 @@
+
+
+
+
+
+
β‘οΈ a simple abstraction over fetch to enable easy management of request/response flows
+
+This package provides [*Ember***Data**](https://github.com/emberjs/data/)'s `RequestManager`, a framework agnostic library that can be integrated with any Javascript application to make [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) happen.
+
+## Installation
+
+Install using your javascript package manager of choice. For instance with [pnpm](https://pnpm.io/)
+
+```no-highlight
+pnpm add @ember-data/request
+```
+
+## π Basic Usage
+
+A `RequestManager` provides a request/response flow in which configured handlers are successively given the opportunity to handle, modify, or pass-along a request.
+
+The RequestManager on its own does not know how to fulfill requests. For this we must register at least one handler. A basic `Fetch` handler is provided that will take the request options provided and execute `fetch`.
+
+```ts
+import { RequestManager } from '@ember-data/request';
+import { Fetch } from '@ember-data/request/fetch';
+import { apiUrl } from './config';
+
+// ... create manager and add our Fetch handler
+const manager = new RequestManager();
+manager.use([Fetch]);
+
+// ... execute a request
+const response = await manager.request({
+ url: `${apiUrl}/users`
+});
+```
+
+
+## πͺ Architecture
+
+A `RequestManager` receives a request and manages fulfillment via configured handlers. It may be used standalone from the rest of *Ember***Data** and is not specific to any library or framework.
+
+```mermaid
+flowchart LR
+ A[fa:fa-terminal App] <--> B{{fa:fa-sitemap RequestManager}}
+ B <--> C[(fa:fa-database Source)]
+```
+
+Each handler may choose to fulfill the request using some source of data or to pass the request along to other handlers.
+
+```mermaid
+flowchart LR
+ A[fa:fa-terminal App] <--> B{{fa:fa-sitemap RequestManager}}
+ B <--> C(handler)
+ C <--> E(handler)
+ E <--> F(handler)
+ C <--> D[(fa:fa-database Source)]
+ E <--> G[(fa:fa-database Source)]
+ F <--> H[(fa:fa-database Source)]
+```
+
+The same or a separate instance of a `RequestManager` may also be used to fulfill requests issued by [*Ember***Data**{Store}](https://github.com/emberjs/data/tree/master/packages/store)
+
+```mermaid
+flowchart LR
+ A[fa:fa-terminal App] <--> D{fa:fa-code-fork Store}
+ B{{fa:fa-sitemap RequestManager}} <--> C[(fa:fa-database Source)]
+ D <--> E[(fa:fa-archive Cache)]
+ D <--> B
+ click D href "https://github.com/emberjs/data/tree/master/packages/store" "Go to @ember-data/store" _blank
+ click E href "https://github.com/emberjs/data/tree/master/packages/record-data" "Go to @ember-data/record-data" _blank
+ style D color:#58a6ff;
+ style E color:#58a6ff;
+```
+
+When the same instance is used by both this allows for simple coordination throughout the application. Requests issued by the Store will use the in-memory cache
+and return hydrated responses, requests issued directly to the RequestManager
+will skip the in-memory cache and return raw responses.
+
+```mermaid
+flowchart LR
+ A[fa:fa-terminal App] <--> B{{fa:fa-sitemap RequestManager}}
+ B <--> C[(fa:fa-database Source)]
+ A <--> D{fa:fa-code-fork Store}
+ D <--> E[(fa:fa-archive Cache)]
+ D <--> B
+ click D href "https://github.com/emberjs/data/tree/master/packages/store" "Go to @ember-data/store" _blank
+ click E href "https://github.com/emberjs/data/tree/master/packages/record-data" "Go to @ember-data/record-data" _blank
+ style D color:#58a6ff;
+ style E color:#58a6ff;
+```
+
+## Usage
+
+
+ Making Requests
+
+`RequestManager` has a single asyncronous method as it's API: `request`
+
+```ts
+class RequestManager {
+ async request(req: RequestInfo): Future;
+}
+```
+
+`manager.request` accepts a `RequestInfo`, an object containing the information
+necessary for the request to be handled successfully.
+
+`RequestInfo` extends the [options](https://developer.mozilla.org/en-US/docs/Web/API/fetch#parameters) provided to `fetch`, and can accept a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request). All properties accepted by Request options and fetch options are valid on `RequestInfo`.
+
+```ts
+interface RequestInfo extends FetchOptions {
+ url: string;
+ /**
+ * data that a handler should convert into
+ * the query (GET) or body (POST)
+ */
+ data?: Record;
+ /**
+ * options specifically intended for handlers
+ * to utilize to process the request
+ */
+ options?: Record;
+}
+```
+
+> **note:** providing a `signal` is unnecessary as an `AbortController` is automatically provided if none is present.
+
+
+
+ Using the Response
+
+`manager.request` returns a `Future`, which allows access to limited information about the request while it is still pending and fulfills with the final state when the request completes and the response has been read.
+
+A `Future` is cancellable via `abort`.
+
+Handlers may *optionally* expose a ReadableStream to the `Future` for streaming data; however, when doing so the handler should not resolve until it has fully read the response stream itself.
+
+```ts
+interface Future extends Promise> {
+ abort(): void;
+
+ async getStream(): ReadableStream | null;
+}
+```
+
+A Future resolves or rejects with a `StructuredDocument`.
+
+```ts
+interface StructuredDocument {
+ request: RequestInfo;
+ response: ResponseInfo | null;
+ data?: T;
+ error?: Error;
+}
+```
+
+The `RequestInfo` specified by `document.request` is the same as originally provided to `manager.request`. If any handler fulfilled this request using different request info it is not represented here. This contract helps to ensure that `retry` and `caching` are possible since the original arguments are correctly preserved. This also allows handlers to "fork" the request or fulfill from multiple sources without the details of fulfillment muddying the original request.
+
+The `ResponseInfo` is a serializable fulfilled subset of a [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response) if set via `setResponse`. If no response was ever set this will be `null`.
+
+```ts
+/**
+ * All readonly properties available on a Response
+ *
+ */
+interface ResponseInfo {
+ headers?: Record;
+ ok?: boolean;
+ redirected?: boolean;
+ status?: HTTPStatusCode;
+ statusText?: string;
+ type?: 'basic' | 'cors';
+ url?: string;
+}
+```
+
+
+
+
Handling Requests
+
+ { async request(context, next): T; }
+
+Requests are fulfilled by handlers. A handler receives the request context
+as well as a `next` function with which to pass along a request to the next
+handler if it so chooses.
+
+A handler may be any object with a `request` method. This allows both stateful and non-stateful
+handlers to be utilized.
+
+If a handler calls `next`, it receives a `Future` which resolves to a `StructuredDocument`
+that it can then compose how it sees fit with its own response.
+
+```ts
+
+type NextFn
): T;
+}
+```
+
+`RequestContext` contains a readonly version of the RequestInfo as well as a few methods for building up the `StructuredDocument` and `Future` that will be part of the response.
+
+```ts
+interface RequestContext {
+ readonly request: RequestInfo;
+
+ setStream(stream: ReadableStream | Promise): void;
+ setResponse(response: Response | ResponseInfo): void;
+}
+```
+
+A basic `fetch` handler with support for streaming content updates while
+the download is still underway might look like the following, where we use
+[`response.clone()`](https://developer.mozilla.org/en-US/docs/Web/API/Response/clone) to `tee` the `ReadableStream` into two streams.
+
+A more efficient handler might read from the response stream, building up the
+response data before passing along the chunk downstream.
+
+```ts
+const FetchHandler = {
+ async request(context) {
+ const response = await fetch(context.request);
+ context.setResponse(reponse);
+ context.setStream(response.clone().body);
+
+ return response.json();
+ }
+}
+```
+
+Request handlers are registered by configuring the manager via `use`
+
+```ts
+manager.use([Handler1, Handler2])
+```
+
+Handlers will be invoked in the order they are registered ("fifo", first-in first-out), and may only be registered up until the first request is made. It is recommended but not required to register all handlers at one time in order to ensure explicitly visible handler ordering.
+
+
+
+
+ Stream Currying
+
+`RequestManager.request` and `next` differ from `fetch` in one **crucial detail** in that the outer Promise resolves only once the response stream has been processed.
+
+For context, it helps to understand a few of the use-cases that RequestManager
+is intended to allow.
+
+- to manage and return streaming content (such as video files)
+- to fulfill a request from multiple sources or by splitting one request into multiple requests
+ - for instance one API call for a user and another for the user's friends
+ - or e.g. fulfilling part of the request from one source (one API, in-memory, localStorage, IndexedDB
+ etc.) and the rest from another source (a different API, a WebWorker, etc.)
+- to coalesce multiple requests
+- to decorate a request with additional info
+ - e.g. an Auth handler that ensures the correct tokens or headers or cookies are attached.
+
+`await fetch()` resolves at the moment headers are received. This allows for the body of the request to be processed as a stream by application
+code *while chunks are still being received by the browser*.
+
+When an app chooses to `await response.json()` what occurs is the browser reads the stream to completion and then returns the result. Additionally, this stream may only be read **once**.
+
+The `RequestManager` preserves this ability to subscribe to and utilize the stream by either the application or the handler βΒ thereby delivering the full power and flexibility of native APIs β without restricting developers in ways that lead to complicated workarounds.
+
+Each handler may call `setStream` only once, but may do so *at any time* until the promise that the handler returns has resolved. The associated promise returned by calling `future.getStream` will resolve with the stream set by `setStream` if that method is called, or `null` if that method
+has not been called by the time that the handler's request method has resolved.
+
+Handlers that do not create a stream of their own, but which call `next`, should defensively pipe the stream forward. While this is not required (see automatic currying below) it is better to do so in most cases as otherwise the stream may not become available to downstream handlers or the application until the upstream handler has fully read it.
+
+```ts
+context.setStream(future.getStream());
+```
+
+Handlers that either call `next` multiple times or otherwise have reason to create multiple fetch requests should either choose to return no stream, meaningfully combine the streams, or select a single prioritized stream.
+
+Of course, any handler may choose to read and handle the stream, and return either no stream or a different stream in the process.
+
+
+
+
+ Automatic Currying of Stream and Response
+
+In order to simplify the common case for handlers which decorate a request, if `next` is called only a single time and `setResponse` was never called by the handler, the response set by the next handler in the chain will be applied to that handler's outcome. For instance, this makes the following pattern possible `return (await next()).data;`.
+
+Similarly, if `next` is called only a single time and neither `setStream` nor `getStream` was called, we automatically curry the stream from the future returned by `next` onto the future returned by the handler.
+
+Finally, if the return value of a handler is a `Future`, we curry `data` and `errors` as well, thus enabling the simplest form `return next()`.
+
+In the case of the `Future` being returned, `Stream` proxying is automatic and immediate and does not wait for the `Future` to resolve.
+
+
+
+### Using as a Service
+
+Most applications will desire to have a single `RequestManager` instance, which can be achieved using module-state patterns for singletons, or for [Ember](https://emberjs.com) applications by exporting the manager as a [service](https://guides.emberjs.com/release/services/).
+
+*services/request.ts*
+```ts
+import { RequestManager } from '@ember-data/request';
+import { Fetch } from '@ember-data/request/fetch';
+import Auth from 'ember-simple-auth/ember-data-handler';
+
+export default class extends RequestManager {
+ constructor(createArgs) {
+ super(createArgs);
+ this.use([Auth, Fetch]);
+ }
+}
+```
+
+### Using with `@ember-data/store`
+
+To have a request service unique to a Store:
+
+```ts
+import Store from '@ember-data/store';
+import { RequestManager } from '@ember-data/request';
+import { Fetch } from '@ember-data/request/fetch';
+
+class extends Store {
+ requestManager = new RequestManager();
+
+ constructor(args) {
+ super(args);
+ this.requestManager.use([Fetch]);
+ }
+}
+```
+
+### Using with `ember-data`
+
+If using the package [ember-data](https://github.com/emberjs/data/tree/master/packages/-ember-data), the following configuration will automatically be done in order to preserve the legacy [Adapter](https://github.com/emberjs/data/tree/master/packages/adapter) and [Serializer](https://github.com/emberjs/data/tree/master/packages/serializer) behavior. Additional handlers or a service injection like the above would need to be done by the consuming application in order to make broader use of `RequestManager`.
+
+```ts
+import Store from '@ember-data/store';
+import { RequestManager } from '@ember-data/request';
+import { LegacyHandler } from '@ember-data/legacy-network-handler';
+
+export default class extends Store {
+ requestManager = new RequestManager();
+
+ constructor(args) {
+ super(args);
+ this.requestManager.use([LegacyHandler]);
+ }
+}
+```
+
+Because the application's store service (if present) will override the store supplied by `ember-data`, all that is required to define your own ordering and handlers is to supply a store service extending from `@ember-data/store` and configure as shown above.
+
+For usage of the store's `requestManager` via `store.request()` see the [Store](https://api.emberjs.com/ember-data/release/modules/@ember-data%2Fstore) documentation.
diff --git a/packages/request/addon-main.js b/packages/request/addon-main.js
new file mode 100644
index 00000000000..459ef9174ca
--- /dev/null
+++ b/packages/request/addon-main.js
@@ -0,0 +1,19 @@
+module.exports = {
+ name: require('./package.json').name,
+
+ treeForVendor() {
+ return;
+ },
+ treeForPublic() {
+ return;
+ },
+ treeForStyles() {
+ return;
+ },
+ treeForAddonStyles() {
+ return;
+ },
+ treeForApp() {
+ return;
+ },
+};
diff --git a/packages/request/babel.config.json b/packages/request/babel.config.json
new file mode 100644
index 00000000000..fea1b66f091
--- /dev/null
+++ b/packages/request/babel.config.json
@@ -0,0 +1,8 @@
+{
+ "plugins": [
+ "@babel/plugin-transform-runtime",
+ ["@babel/plugin-transform-typescript", { "allowDeclareFields": true }],
+ ["@babel/plugin-proposal-decorators", { "legacy": true }],
+ "@babel/plugin-proposal-class-properties"
+ ]
+}
diff --git a/packages/request/ember-data-logo-dark.svg b/packages/request/ember-data-logo-dark.svg
new file mode 100644
index 00000000000..737a4aa4321
--- /dev/null
+++ b/packages/request/ember-data-logo-dark.svg
@@ -0,0 +1,12 @@
+
diff --git a/packages/request/ember-data-logo-light.svg b/packages/request/ember-data-logo-light.svg
new file mode 100644
index 00000000000..58ac3d4e544
--- /dev/null
+++ b/packages/request/ember-data-logo-light.svg
@@ -0,0 +1,12 @@
+
diff --git a/packages/request/package.json b/packages/request/package.json
new file mode 100644
index 00000000000..7507e1f4c57
--- /dev/null
+++ b/packages/request/package.json
@@ -0,0 +1,62 @@
+{
+ "name": "@ember-data/request",
+ "description": "β‘οΈ A simple, small and fast framework-agnostic library to make `fetch` happen",
+ "version": "4.9.0-alpha.14",
+ "private": false,
+ "license": "MIT",
+ "author": "Chris Thoburn ",
+ "repository": {
+ "type": "git",
+ "url": "git+ssh://git@github.com:emberjs/data.git",
+ "directory": "packages/request"
+ },
+ "homepage": "https://github.com/emberjs/data",
+ "bugs": "https://github.com/emberjs/data/issues",
+ "engines": {
+ "node": "14.* || 16.* || >= 18"
+ },
+ "keywords": ["ember-addon"],
+ "volta": {
+ "extends": "../../package.json"
+ },
+ "dependencies": {
+ "ember-cli-babel": "^7.26.11",
+ "@embroider/macros": "^1.9.0"
+ },
+ "files": [
+ "addon-main.js",
+ "addon"
+ ],
+ "scripts": {
+ "build": "rollup --config && babel ./addon --out-dir addon --plugins=../private-build-infra/src/transforms/babel-plugin-transform-ext.js",
+ "start": "rollup --config --watch",
+ "prepack": "pnpm build"
+ },
+ "ember-addon": {
+ "main": "addon-main.js",
+ "type": "addon",
+ "version": 1
+ },
+ "peerDependencies": {},
+ "devDependencies": {
+ "@embroider/addon-dev": "^2.0.0",
+ "rollup": "^3.2.3",
+ "@babel/core": "^7.19.6",
+ "@babel/cli": "^7.19.3",
+ "@babel/plugin-proposal-class-properties": "^7.18.6",
+ "@babel/plugin-proposal-decorators": "^7.20.0",
+ "@babel/plugin-transform-typescript": "^7.20.0",
+ "@babel/plugin-transform-runtime": "^7.19.6",
+ "@babel/preset-typescript": "^7.18.6",
+ "@babel/preset-env": "^7.19.4",
+ "@babel/runtime": "^7.20.0",
+ "@rollup/plugin-babel":"^6.0.2",
+ "@rollup/plugin-node-resolve": "^15.0.1",
+ "tslib": "^2.4.0",
+ "walk-sync": "^3.0.0",
+ "typescript": "^4.8.4"
+ },
+ "ember": {
+ "edition": "octane"
+ }
+}
diff --git a/packages/request/rollup.config.mjs b/packages/request/rollup.config.mjs
new file mode 100644
index 00000000000..34fe8a317de
--- /dev/null
+++ b/packages/request/rollup.config.mjs
@@ -0,0 +1,31 @@
+import { Addon } from '@embroider/addon-dev/rollup';
+import babel from '@rollup/plugin-babel';
+import { nodeResolve } from '@rollup/plugin-node-resolve';
+
+const addon = new Addon({
+ srcDir: 'src',
+ destDir: 'addon',
+});
+
+export default {
+ // This provides defaults that work well alongside `publicEntrypoints` below.
+ // You can augment this if you need to.
+ output: addon.output(),
+
+ external: ['@embroider/macros'],
+
+ plugins: [
+ // These are the modules that users should be able to import from your
+ // addon. Anything not listed here may get optimized away.
+ addon.publicEntrypoints(['index.js', '-private.js']),
+
+ nodeResolve({ extensions: ['.ts'] }),
+ babel({
+ extensions: ['.ts'],
+ babelHelpers: 'runtime', // we should consider "external",
+ }),
+
+ // Remove leftover build artifacts when starting a new build.
+ addon.clean(),
+ ],
+};
diff --git a/packages/request/src/-private/context.ts b/packages/request/src/-private/context.ts
new file mode 100644
index 00000000000..285d19c1aa5
--- /dev/null
+++ b/packages/request/src/-private/context.ts
@@ -0,0 +1,142 @@
+import { isDevelopingApp, macroCondition } from '@embroider/macros';
+
+import { deepFreeze } from './debug';
+import { createDeferred } from './future';
+import type { Deferred, GodContext, ImmutableHeaders, ImmutableRequestInfo, RequestInfo, ResponseInfo } from './types';
+
+export class ContextOwner {
+ hasSetStream = false;
+ hasSetResponse = false;
+ hasSubscribers = false;
+ stream: Deferred = createDeferred();
+ response: ResponseInfo | null = null;
+ request: ImmutableRequestInfo;
+ enhancedRequest: ImmutableRequestInfo;
+ nextCalled: number = 0;
+ god: GodContext;
+ controller: AbortController;
+
+ constructor(request: RequestInfo, god: GodContext) {
+ this.controller = request.controller || god.controller;
+ if (request.controller) {
+ if (request.controller !== god.controller) {
+ god.controller.signal.addEventListener('abort', () => {
+ this.controller.abort();
+ });
+ }
+ delete request.controller;
+ }
+ let enhancedRequest: ImmutableRequestInfo = Object.assign(
+ { signal: god.controller.signal },
+ request
+ ) as ImmutableRequestInfo;
+ if (macroCondition(isDevelopingApp())) {
+ request = deepFreeze(request) as ImmutableRequestInfo;
+ enhancedRequest = deepFreeze(enhancedRequest);
+ } else {
+ if (request.headers) {
+ (request.headers as ImmutableHeaders).clone = () => {
+ return new Headers([...request.headers!.entries()]);
+ };
+ (request.headers as ImmutableHeaders).toJSON = () => {
+ return [...request.headers!.entries()];
+ };
+ }
+ }
+ this.enhancedRequest = enhancedRequest;
+ this.request = request as ImmutableRequestInfo;
+ this.god = god;
+ this.stream.promise = this.stream.promise.then((stream: ReadableStream | null) => {
+ if (this.god.stream === stream && this.hasSubscribers) {
+ this.god.stream = null;
+ }
+ return stream;
+ });
+ }
+
+ getResponse(): ResponseInfo | null {
+ if (this.hasSetResponse) {
+ return this.response;
+ }
+ if (this.nextCalled === 1) {
+ return this.god.response;
+ }
+ return null;
+ }
+ getStream(): Promise {
+ this.hasSubscribers = true;
+ return this.stream.promise;
+ }
+ abort() {
+ this.controller.abort();
+ }
+
+ setStream(stream: ReadableStream | Promise | null) {
+ if (!this.hasSetStream) {
+ this.hasSetStream = true;
+
+ if (!(stream instanceof Promise)) {
+ this.god.stream = stream;
+ }
+ // @ts-expect-error
+ this.stream.resolve(stream);
+ }
+ }
+
+ resolveStream() {
+ this.setStream(this.nextCalled === 1 ? this.god.stream : null);
+ }
+
+ setResponse(response: ResponseInfo | Response | null) {
+ if (this.hasSetResponse) {
+ if (macroCondition(isDevelopingApp())) {
+ throw new Error(`Cannot setResponse when a response has already been set`);
+ }
+ return;
+ }
+ this.hasSetResponse = true;
+ if (response instanceof Response) {
+ const { headers, ok, redirected, status, statusText, type, url } = response;
+ (headers as ImmutableHeaders).clone = () => {
+ return new Headers([...headers.entries()]);
+ };
+ (headers as ImmutableHeaders).toJSON = () => {
+ return [...headers.entries()];
+ };
+ let responseData: ResponseInfo = {
+ headers: headers as ImmutableHeaders,
+ ok,
+ redirected,
+ status,
+ statusText,
+ type,
+ url,
+ };
+ if (macroCondition(isDevelopingApp())) {
+ responseData = deepFreeze(responseData);
+ }
+ this.response = responseData;
+ this.god.response = responseData;
+ } else {
+ this.response = response;
+ this.god.response = response;
+ }
+ }
+}
+
+export class Context {
+ #owner: ContextOwner;
+ request: ImmutableRequestInfo;
+
+ constructor(owner: ContextOwner) {
+ this.#owner = owner;
+ this.request = owner.enhancedRequest;
+ }
+ setStream(stream: ReadableStream | Promise) {
+ this.#owner.setStream(stream);
+ }
+ setResponse(response: ResponseInfo | Response | null) {
+ this.#owner.setResponse(response);
+ }
+}
+export type HandlerRequestContext = Context;
diff --git a/packages/request/src/-private/debug.ts b/packages/request/src/-private/debug.ts
new file mode 100644
index 00000000000..775dbcfce1e
--- /dev/null
+++ b/packages/request/src/-private/debug.ts
@@ -0,0 +1,310 @@
+import { isDevelopingApp, macroCondition } from '@embroider/macros';
+
+import { Context } from './context';
+import type { ImmutableHeaders, RequestInfo } from './types';
+
+const ValidKeys = new Map([
+ ['data', 'json'],
+ ['options', 'object'],
+ ['url', 'string'],
+ ['cache', ['default', 'force-cache', 'no-cache', 'no-store', 'only-if-cached', 'reload']],
+ ['credentials', ['include', 'omit', 'same-origin']],
+ [
+ 'destination',
+ [
+ '',
+ 'object',
+ 'audio',
+ 'audioworklet',
+ 'document',
+ 'embed',
+ 'font',
+ 'frame',
+ 'iframe',
+ 'image',
+ 'manifest',
+ 'paintworklet',
+ 'report',
+ 'script',
+ 'sharedworker',
+ 'style',
+ 'track',
+ 'video',
+ 'worker',
+ 'xslt',
+ ],
+ ],
+ ['headers', 'headers'],
+ ['integrity', 'string'],
+ ['keepalive', 'boolean'],
+ ['method', ['GET', 'PUT', 'PATCH', 'DELETE', 'POST', 'OPTIONS']],
+ ['mode', ['same-origin', 'cors', 'navigate', 'no-cors']],
+ ['redirect', ['error', 'follow', 'manual']],
+ ['referrer', 'string'],
+ ['signal', 'AbortSignal'],
+ ['controller', 'AbortController'],
+ [
+ 'referrerPolicy',
+ [
+ '',
+ 'same-origin',
+ 'no-referrer',
+ 'no-referrer-when-downgrade',
+ 'origin',
+ 'origin-when-cross-origin',
+ 'strict-origin',
+ 'strict-origin-when-cross-origin',
+ 'unsafe-url',
+ ],
+ ],
+]);
+
+const IS_FROZEN = Symbol('FROZEN');
+
+function freezeHeaders(headers: Headers | ImmutableHeaders): ImmutableHeaders {
+ headers.delete =
+ headers.set =
+ headers.append =
+ () => {
+ throw new Error(`Cannot Mutate Immutatable Headers, use headers.clone to get a copy`);
+ };
+ (headers as ImmutableHeaders).clone = () => {
+ return new Headers([...headers.entries()]);
+ };
+ return headers as ImmutableHeaders;
+}
+
+export function deepFreeze(value: T): T {
+ if (value && value[IS_FROZEN]) {
+ return value;
+ }
+ const _type = typeof value;
+ switch (_type) {
+ case 'boolean':
+ case 'string':
+ case 'number':
+ case 'symbol':
+ case 'undefined':
+ case 'bigint':
+ return value;
+ case 'function':
+ throw new Error(`Cannot deep-freeze a function`);
+ case 'object': {
+ const _niceType = niceTypeOf(value);
+ switch (_niceType) {
+ case 'array': {
+ const arr = (value as unknown[]).map(deepFreeze);
+ arr[IS_FROZEN] = true;
+ return Object.freeze(arr) as T;
+ }
+ case 'null':
+ return value;
+ case 'object':
+ Object.keys(value as {}).forEach((key) => {
+ (value as {})[key] = deepFreeze((value as {})[key]) as {};
+ });
+ value[IS_FROZEN] = true;
+ return Object.freeze(value);
+ case 'headers':
+ return freezeHeaders(value as Headers) as T;
+ case 'AbortSignal':
+ return value;
+ case 'date':
+ case 'map':
+ case 'set':
+ case 'error':
+ case 'stream':
+ default:
+ throw new Error(`Cannot deep-freeze ${_niceType}`);
+ }
+ }
+ }
+}
+
+function isMaybeContext(request: unknown) {
+ if (request && typeof request === 'object') {
+ const keys = Object.keys(request);
+ if (keys.length === 1 && keys[0] === 'request') {
+ return true;
+ }
+ }
+ return false;
+}
+
+function niceTypeOf(v: unknown) {
+ if (v === null) {
+ return 'null';
+ }
+ if (typeof v === 'string') {
+ return v ? 'non-empty-string' : 'empty-string';
+ }
+ if (!v) {
+ return typeof v;
+ }
+ if (Array.isArray(v)) {
+ return 'array';
+ }
+ if (v instanceof Date) {
+ return 'date';
+ }
+ if (v instanceof Map) {
+ return 'map';
+ }
+ if (v instanceof Set) {
+ return 'set';
+ }
+ if (v instanceof Error) {
+ return 'error';
+ }
+ if (v instanceof ReadableStream || v instanceof WritableStream || v instanceof TransformStream) {
+ return 'stream';
+ }
+ if (v instanceof Headers) {
+ return 'headers';
+ }
+ if (typeof v === 'object' && v.constructor && v.constructor.name !== 'Object') {
+ return v.constructor.name;
+ }
+ return typeof v;
+}
+
+function validateKey(key: string, value: unknown, errors: string[]) {
+ const schema = ValidKeys.get(key);
+ if (!schema && !IgnoredKeys.has(key)) {
+ errors.push(`InvalidKey: '${key}'`);
+ return;
+ }
+ if (schema) {
+ if (Array.isArray(schema)) {
+ if (!schema.includes(value as string)) {
+ errors.push(
+ `InvalidValue: key ${key} should be a one of '${schema.join("', '")}', received ${
+ typeof value === 'string' ? value : ''
+ }`
+ );
+ }
+ return;
+ } else if (schema === 'json') {
+ try {
+ JSON.stringify(value);
+ } catch (e) {
+ errors.push(
+ `InvalidValue: key ${key} should be a JSON serializable value, but failed to serialize with Error - ${
+ (e as Error).message
+ }`
+ );
+ }
+ return;
+ } else if (schema === 'headers') {
+ if (!(value instanceof Headers)) {
+ errors.push(`InvalidValue: key ${key} should be an instance of Headers, received ${niceTypeOf(value)}`);
+ }
+ return;
+ } else if (schema === 'record') {
+ const _type = typeof value;
+ // record must extend plain object or Object.create(null)
+ if (!value || _type !== 'object' || (value.constructor && value.constructor !== Object)) {
+ errors.push(
+ `InvalidValue: key ${key} should be a dictionary of string keys to string values, received ${niceTypeOf(
+ value
+ )}`
+ );
+ return;
+ }
+ const keys = Object.keys(value);
+ keys.forEach((k) => {
+ let v: unknown = value[k];
+ if (typeof k !== 'string') {
+ errors.push(`\tThe key ${String(k)} on ${key} should be a string key`);
+ } else if (typeof v !== 'string') {
+ errors.push(`\tThe value of ${key}.${k} should be a string not ${niceTypeOf(v)}`);
+ }
+ });
+ return;
+ } else if (schema === 'string') {
+ if (typeof value !== 'string' || value.length === 0) {
+ errors.push(
+ `InvalidValue: key ${key} should be a non-empty string, received ${
+ typeof value === 'string' ? "''" : typeof value
+ }`
+ );
+ }
+ return;
+ } else if (schema === 'object') {
+ if (!value || Array.isArray(value) || typeof value !== 'object') {
+ errors.push(`InvalidValue: key ${key} should be an object`);
+ }
+ return;
+ } else if (schema === 'boolean') {
+ if (typeof value !== 'boolean') {
+ errors.push(`InvalidValue: key ${key} should be a boolean, received ${typeof value}`);
+ }
+ return;
+ }
+ }
+}
+
+const IgnoredKeys = new Set([]);
+
+export function assertValidRequest(
+ request: RequestInfo | Context,
+ isTopLevel: boolean
+): asserts request is RequestInfo {
+ if (macroCondition(isDevelopingApp())) {
+ // handle basic shape
+ if (!request) {
+ throw new Error(
+ `Expected ${
+ isTopLevel ? 'RequestManager.request' : 'next'
+ }() to be called with a request, but none was provided.`
+ );
+ }
+ if (Array.isArray(request) || typeof request !== 'object') {
+ throw new Error(
+ `The \`request\` passed to \`${
+ isTopLevel ? 'RequestManager.request' : 'next'
+ }()\` should be an object, received \`${niceTypeOf(request)}\``
+ );
+ }
+ if (Object.keys(request).length === 0) {
+ throw new Error(
+ `The \`request\` passed to \`${
+ isTopLevel ? 'RequestManager.request' : 'next'
+ }()\` was empty (\`{}\`). Requests need at least one valid key.`
+ );
+ }
+
+ // handle accidentally passing context entirely
+ if (request instanceof Context) {
+ throw new Error(
+ `Expected a request passed to \`${
+ isTopLevel ? 'RequestManager.request' : 'next'
+ }()\` but received the previous handler's context instead`
+ );
+ }
+ // handle Object.assign({}, context);
+ if (isMaybeContext(request)) {
+ throw new Error(
+ `Expected a request passed to \`${
+ isTopLevel ? 'RequestManager.request' : 'next'
+ }()\` but received an object with a request key instead.`
+ );
+ }
+
+ // handle schema
+ const keys = Object.keys(request);
+ const validationErrors = [];
+ keys.forEach((key) => {
+ validateKey(key, request[key], validationErrors);
+ });
+ if (validationErrors.length) {
+ const error: Error & { errors: string[] } = new Error(
+ `Invalid Request passed to \`${
+ isTopLevel ? 'RequestManager.request' : 'next'
+ }()\`.\n\nThe following issues were found:\n\n\t${validationErrors.join('\n\t')}`
+ ) as Error & { errors: string[] };
+ error.errors = validationErrors;
+ throw error;
+ }
+ }
+}
diff --git a/packages/request/src/-private/future.ts b/packages/request/src/-private/future.ts
new file mode 100644
index 00000000000..cbfe798256b
--- /dev/null
+++ b/packages/request/src/-private/future.ts
@@ -0,0 +1,35 @@
+import type { ContextOwner } from './context';
+import type { Deferred, DeferredFuture, Future } from './types';
+
+const IS_FUTURE = Symbol('IS_FUTURE');
+
+export function isFuture(maybe: T | Future | Promise): maybe is Future {
+ return maybe[IS_FUTURE] === true;
+}
+
+export function createDeferred(): Deferred {
+ let resolve!: (v: T) => void;
+ let reject!: (v: unknown) => void;
+ let promise = new Promise((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ return { resolve, reject, promise };
+}
+
+export function createFuture(owner: ContextOwner): DeferredFuture {
+ const deferred = createDeferred() as unknown as DeferredFuture;
+ let { promise } = deferred;
+ promise = promise.finally(() => {
+ owner.resolveStream();
+ }) as Future;
+ promise[IS_FUTURE] = true;
+ promise.getStream = () => {
+ return owner.getStream();
+ };
+ promise.abort = () => {
+ owner.abort();
+ };
+ deferred.promise = promise;
+ return deferred;
+}
diff --git a/packages/request/src/-private/manager.ts b/packages/request/src/-private/manager.ts
new file mode 100644
index 00000000000..e1d47a76ea4
--- /dev/null
+++ b/packages/request/src/-private/manager.ts
@@ -0,0 +1,479 @@
+/* eslint-disable no-irregular-whitespace */
+/**
+ *
+