GithubHelp home page GithubHelp logo

ember-cli / ember-fetch Goto Github PK

View Code? Open in Web Editor NEW
176.0 16.0 82.0 4.91 MB

HTML5 fetch polyfill from github wrapped and bundled for ember-cli users.

License: MIT License

JavaScript 84.90% HTML 2.51% Perl 2.81% TypeScript 9.13% Handlebars 0.65%

ember-fetch's Introduction

ember-fetch

Build Status Build status Ember Observer Score npm version

HTML5 fetch polyfill from github wrapped and bundled for ember-cli users.

Installation

  • ember install ember-fetch

ember-fetch requries ember-cli 2.13 or above.

Usage

import Route from '@ember/routing/route';
import fetch from 'fetch';

export default Route.extend({
  model() {
    return fetch('/my-cool-end-point.json').then(function(response) {
      return response.json();
    });
  }
});

Available imports:

import fetch, { Headers, Request, Response, AbortController } from 'fetch';

Use with TypeScript

To use ember-fetch with TypeScript or enable editor's type support, You can add "fetch": ["node_modules/ember-fetch"] to your tsconfig.json.

{
  "compilerOptions": {
    "paths": {
      "fetch": [
        "node_modules/ember-fetch"
      ]
    }
  }
}

Use with Ember Data

[email protected] was released with built-in fetch support, if your ember-data is below 3.9.2, please checkout ember-fetch v7.x.

Use with Fastboot

relative url

ember-fetch uses node-fetch in Fastboot, which doesn't allow relative URL.

url should be an absolute url, such as https://example.com/. A path-relative URL (/file/under/root) or protocol-relative URL (//can-be-http-or-https.com/) will result in a rejected promise.

However, ember-fetch grabs the protocol and host info from fastboot request after the instance-initializes. This allows you to make a relative URL request unless the app is not initialized, e.g. initializers and app.js.

top-level addon

For addon authors, if the addon supports Fastboot mode, ember-fetch should also be listed as a peer dependency. This is because Fastboot only invokes top-level addon's updateFastBootManifest (detail), thus ember-fetch has to be a top-level addon installed by the host app.

Allow native fetch

ember-fetch allows access to native fetch in browser through a build config flag:

// ember-cli-build.js
let app = new EmberAddon(defaults, {
  // Add options here
  'ember-fetch': {
    preferNative: true
  }
});

If set to true, the fetch polyfill will be skipped if native fetch is available, otherwise the polyfilled fetch will be installed during the first pass of the vendor js file.

If set to false, the polyfilled fetch will replace native fetch be there or not.

If all your browser targets support native fetch, and preferNative: true, the polyfill will not be included in the output build. If, for some reason, you still need the polyfill to be included in the bundle, you can set alwaysIncludePolyfill: true.

The way you do import remains same.

Use native promise instead of RSVP

If you do not want to use RSVP, but native Promises, you can specify this build config flag:

// ember-cli-build.js
let app = new EmberAddon(defaults, {
  // Add options here
  'ember-fetch': {
    nativePromise: true
  }
});

Error Handling

A fetch response is successful if response.ok is true, otherwise you can read the status code to determine the bad response type. fetch will only reject with network errors.

ember-fetch provides some utility functions:

  • isBadRequestResponse (400)
  • isUnauthorizedResponse (401)
  • isForbiddenResponse (403)
  • isNotFoundResponse (404)
  • isConflictResponse (409)
  • isGoneResponse (410)
  • isInvalidResponse (422)
  • isServerErrorResponse (5XX)
  • isAbortError Aborted network error
import Route from '@ember/routing/route';
import fetch from 'fetch';
import {
  isAbortError,
  isServerErrorResponse,
  isUnauthorizedResponse
} from 'ember-fetch/errors';

export default Route.extend({
  model() {
    return fetch('/omg.json')
      .then(function(response) {
        if (response.ok) {
          return response.json();
        } else if (isUnauthorizedResponse(response)) {
          // handle 401 response
        } else if (isServerErrorResponse(response)) {
          // handle 5xx respones
        }
      })
      .catch(function(error) {
        if (isAbortError(error)) {
          // handle aborted network error
        }
        // handle network error
      });
  }
});

Browser Support

Q & A

Does it work with pretender?

What about all the run-loop and promise mixing details?

  • taken care of for you

Why is this wrapper needed?

  • original emits a global
  • original requires a Promise polyfill (ember users have RSVP)
  • original isn't Ember run-loop aware

Won't this wrapper get out-of-sync?

  • we actually don't bundle github/fetch rather we merely wrap/transform what comes from node_modules, so we should be resilient to changes assuming semver from the fetch module

ember-fetch's People

Contributors

2hu12 avatar aquamme avatar barrythepenguin avatar bobisjan avatar buschtoens avatar calvinmetcalf avatar chancancode avatar chriskrycho avatar cibernox avatar cvx avatar dependabot-preview[bot] avatar dependabot-support avatar dependabot[bot] avatar ember-tomster avatar houfeng0923 avatar jasonmit avatar knownasilya avatar kratiahuja avatar meirish avatar mixonic avatar nlfurniss avatar rwjblue avatar scottmessinger avatar sergeastapov avatar stefanpenner avatar tchak avatar topaxi avatar toranb avatar turbo87 avatar xg-wang avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ember-fetch's Issues

Installing ember-fetch breaks source maps for prod builds

Demo: https://github.com/buschtoens/ember-fetch-sourcemap-bug

Installing ember-fetch breaks source maps for prod builds (i.e. builds with minification enabled).

During the build, the following warning is emitted:

[WARN] (broccoli-uglify-sourcemap) "ember-fetch.map" referenced in "assets/vendor.js" could not be found

Source map output without ember-fetch:

{"version":3,"sources":["vendor/ember-cli/vendor-prefix.js","vendor/loader/loader.js","vendor/ember-resolver/legacy-shims.js", ...

Source map output with ember-fetch:

{"version":3,"sources":["0"],"names":["window","Ember ...

ember-fetch lowercases header keys

import fetch from "ember-fetch";

const url = ...
const headers = { ...headers, "Content-Type": "xxx/yyy" };

fetch(url, {
  headers
})

results in request with header "content-type", which is not working, since headers keys are case sensitive.

Are autoruns expected?

I'm finding that ember-fetch is consistently creating autoruns when xhr.onload or reader.onload is triggered. Is this intended? I'm encountering issues with my acceptance tests finishing and being torn down before requests finish and I'm trying to track down the cause.

indicating progress

This ticket is similar to the already closed #53, however as ember is moving towards making jQuery optional, we are going to need a feature complete replacement for making XmlHttpRequests. Currently the lack of displaying progress is blocking some people from using ember-fetch as such a replacement. Even though it seems that progress will not be supported when the polyfill is used, I think it is important to add this feature in order to allow projects that target up to date browser to make usage of this addon.

I can put some time into putting together a PR, but as there are other aspects involved like #63 or #45, I think it is best to agree on an approach and details first.

Ember-Cli 3.5 + Ember-Fetch 6.1.0 + Monorepo Build Fails

Update & Solution

Big thanks to @buschtoens in the Ember Discord - he quickly noted that this PR --> #135 will solve this issue.

Until that merges, if you run into this issue, you can use this branch: "ember-fetch": "buschtoens/ember-fetch#upgrade"


We are in the process of upgrading a large set of applications and addons to Ember 3.5. We are almost done with this project - we started with the addons, and are working on the applications, and we ran into this bug:

Ember 3.5 + Ember Fetch > 5.2.1 + Monorepo: Build Fails with Error: Couldn't find preset "env" relative to directory

When we force ember to use the broccoli 1 build (i.e. EMBER_CLI_BROCCOLI_2=false ember b), it works

Note: Cross-posted as an issue in ember-cli as I'm not quite sure where the issue really lies

Repro Example

I've created a repo with the repro scenario https://github.com/dbouwman/ember-fetch-monorepo-bug

Repro Steps (from README.md in the repo)

We suspect this is related to the use of Rollup within Ember-Fetch as the same error happens w Ember Fetch 5.1.2+ which is where the Rollup integration was added.

Repro Steps

  • create a monorepo using lerna + workspaces + yarn, add a package that is just a new ember 3.5 app, or just clone https://github.com/dbouwman/ember-fetch-monorepo-bug...
  • ensure you have lerna installed globally (npm i -g lerna)
  • ensure you have yarn
  • in the root, on master, run yarn bootstrap to install all the deps

State 1: No Ember-Fetch - Build is Fine...

  • cd packages/ember-app
  • ember b - this should succeed with the following:
➜  ember-app git:(master) ✗ ember b
Environment: development
cleaning up...
Built project successfully. Stored in "dist/".

State 2: Ember-Fetch ^6.1.0

  • either ember install ember-fetch or switch to the ember-fetch-installed branch and run yarn bootstrap in the root again.
  • run a build with ember b

This will fail with a message like:

➜  ember-app git:(ember-fetch-installed) ✗ ember b
Environment: development
(node:76156) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Couldn't find preset "env" relative to directory "/var/folders/d8/rshjcmrd3_dcshnzs8f0hw7h0000gp/T/broccoli-76156VKmrFUG5tIdB/cache-037-rollup/build/src"
(node:76156) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
(node:76156) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 1)
cleaning up...
Build Error (Rollup)

Couldn't find preset "env" relative to directory "/var/folders/d8/rshjcmrd3_dcshnzs8f0hw7h0000gp/T/broccoli-76156VKmrFUG5tIdB/cache-037-rollup/build/src"


Stack Trace and Error Report: /var/folders/d8/rshjcmrd3_dcshnzs8f0hw7h0000gp/T/error.dump.a7d6df92295e51ce96d01a261577f0ce.log

View the Stack Trace

State 3: Use old Build Pipeline

  • with ember-fetch installed, run a build using the old build system - and it works.
➜  ember-app git:(ember-fetch-installed) ✗ EMBER_CLI_BROCCOLI_2=false ember b
Environment: development
cleaning up...
Built project successfully. Stored in "dist/".

problem with AdapterFetch when fast boot is enabled

App is being served by FastBoot
DEBUG: -------------------------------
DEBUG: Ember : 2.17.0
DEBUG: Ember Data : 2.17.0
DEBUG: Ember Bootstrap : 1.0.0
DEBUG: -------------------------------
TypeError: Cannot read property 'catch' of undefined
at Class.ajax (/Users/javierarpa/desa/tourme/tourme/tmp/broccoli_merge_trees-output_path-JCZ0mPSY.tmp/assets/addon-tree-output/ember-fetch/mixins/adapter-fetch.js:211:1)
at Class.findAll (/Users/javierarpa/desa/tourme/tourme/tmp/broccoli_merge_trees-output_path-JCZ0mPSY.tmp/assets/addon-tree-output/modules/ember-data/adapters/rest.js:364:1)

if fast boot is disabled, all work fine. it seems a problem with the import of the fetch on ember-fetch/mixins/adapter-fetch.js

Adapter:

export default RESTAdapter.extend(AdapterFetch, {
namespace: 'api/v1/col',
host: 'https://zzzz.zzzzz.net:4285'
});

Route:

model() {
return this.get('store').findAll('city');
},

ember-fetch + fastboot + ember-data sadness

fastboot and fetch share the same extension point in ember-data, and today they do not work together.

Long-term, I suspect fastboot should provide a XMLHTTPRequest global, and a fetch global. That way it doesn't interfere in high level code, and would also "just work" with things like pretender/mirage.

Rollup issues

Just tried 5.1.2 and hit:

  - broccoliBuilderErrorStack: ReferenceError: [BABEL] /Users/rwwagner/shipshape/shipshape.io/tmp/rollup-cache_path-q3trla78.tmp/build/src/x.js: Unknown option: direct.presets
    at error (/Users/rwwagner/shipshape/shipshape.io/node_modules/ember-fetch/node_modules/rollup/dist/rollup.js:224:15)
    at Object.error (/Users/rwwagner/shipshape/shipshape.io/node_modules/ember-fetch/node_modules/rollup/dist/rollup.js:17174:21)
    at /Users/rwwagner/shipshape/shipshape.io/node_modules/ember-fetch/node_modules/rollup/dist/rollup.js:17183:29
    at process._tickCallback (internal/process/next_tick.js:68:7)
  - codeFrame: [BABEL] /Users/rwwagner/shipshape/shipshape.io/tmp/rollup-cache_path-q3trla78.tmp/build/src/x.js: Unknown option: direct.presets
  - errorMessage: Build Canceled: Broccoli Builder ran into an error with `Rollup` plugin. 💥

Handling error payloads in the adapter mixin

In the ajaxError method only the response.statusText is being passed to the this.parseErrorResponse method, but if a error payload has been passed back, it places the body in a _bodyText property.

It would be nice to have a new method that is called which passes in the raw response that one could extend to pull out what is desired.

  ajaxError(error, response = {}, requestData) {
    if (error instanceof Error) {
      return error;
    } else {
       return this.handleResponse(
        response.status,
         headersToObject(response.headers),
        this.parseErrorResponse(response.statusText) || error,
        requestData
      );
    }
  }

[Question]: why no "failed to find import" message when using fetch?

I was doing some hacking with ember-fetch as usual this morning and spent a good deal of time looking at my mirage configuration/ other dependencies because a fetch based POST was resulting in a 404. Many hours later I finally found that my component was missing the import (and nothing more).

import fetch from 'fetch';

Any idea why the build didn't blow up w/out this to begin with? I wanted to see what I could do to help save others like me precious time when an import is missing like this :)

Here is the code if that helps - building with ember-cli v2.8.0 (node v5.12) and running in Chrome 54

import Ember from 'ember';
import hbs from 'htmlbars-inline-precompile';
import connect from 'ember-redux/components/connect';
import _ from 'npm:lodash';
import fetch from 'fetch';

var stateToComputed = (state) => {
  return {
    result: _.get(state.results.all, state.results.selectedId)
  };
};

var dispatchToActions = (dispatch) => {
  return {
    rate: (id, rating) => fetch(`/api/results/${id}`, {method: 'POST', body: JSON.stringify({rating: rating})}).then(fetched => fetched.json()).then((response) => dispatch({type: 'RATE_ITEM', response: response.item}))
  };
};

var WelpResultComponent = Ember.Component.extend({
  layout: hbs`
    {{yield result (action "rate")}}
  `
});

export default connect(stateToComputed, dispatchToActions)(WelpResultComponent);

findAll hangs with ember-fetch + Ember 3.1 beta

I am using the prescribed workarounds from the README to get things working with fastboot with the ajax initializer noop and ember-data with the adapter mixin, which has worked great, until now. After updating to Ember 3.1, my this.store.findAll calls all the sudden just hang forever. They do not error out, but just seem to never resolve or something. I believe the issue lies with ember-fetch, but it could be the setup has changed and just needs some tweaks. I also opened an issue for fastboot here ember-fastboot/ember-cli-fastboot#575. Any ideas on what could be happening?

yarn / NPM can't resolve xg-wang/whatwg-fetch required by ember-fetch

NPM error:

error Couldn't find package "@xg-wang/whatwg-fetch@^3.0.0" required by "ember-fetch@^2.1.0 || ^3.0.0 || ^4.0.0 || ^5.0.0" on the "npm" registry.

To reproduce,

git clone [email protected]:ember-cli/ember-fetch.git
cd ember-fetch
yarn
yarn install v1.7.0
[1/5] 🔍  Validating package.json...
[2/5] 🔍  Resolving packages...
[3/5] 🚚  Fetching packages...
error An unexpected error occurred: "https://registry.yarnpkg.com/@xg-wang/whatwg-fetch/-/whatwg-fetch-3.0.0.tgz: Request failed \"404 Not Found\"".
info If you think this is a bug, please open a bug report with the information provided in "/Users/lsmith/projects/opensource/ember-fetch/yarn-error.log".
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.

Could not find module `fetch/setup` imported from `prog/instance-initializers/setup-fetch`

Hello, I'm getting the following build error on my CI server. Downgrading to 5.1 (before /instance-initializers/setup-fetch was introduced) fixes the issue.

Build Error (prember)

Could not find module `fetch/setup` imported from `prog/instance-initializers/setup-fetch`

=================================================================================

ENV Summary:

  TIME: Sat Nov 17 2018 19:26:34 GMT+0000 (UTC)
  TITLE: ember
  ARGV:
  - /usr/bin/node
  - /usr/local/bin/ember
  - b
  - -prod
  EXEC_PATH: /usr/bin/node
  TMPDIR: /tmp
  SHELL: /bin/ash
  PATH:
  - /usr/local/sbin
  - /usr/local/bin
  - /usr/sbin
  - /usr/bin
  - /sbin
  - /bin
  PLATFORM: linux x64
  FREEMEM: 9050533888
  TOTALMEM: 73765941248
  UPTIME: 78321
  LOADAVG: 8.33837890625,5.37841796875,3.8583984375
  CPUS:
  - Intel(R) Xeon(R) Platinum 8124M CPU @ 3.00GHz - 3000
  - Intel(R) Xeon(R) Platinum 8124M CPU @ 3.00GHz - 3000
  - Intel(R) Xeon(R) Platinum 8124M CPU @ 3.00GHz - 3000
  - Intel(R) Xeon(R) Platinum 8124M CPU @ 3.00GHz - 3000
  - Intel(R) Xeon(R) Platinum 8124M CPU @ 3.00GHz - 3000
  - Intel(R) Xeon(R) Platinum 8124M CPU @ 3.00GHz - 3000
  - Intel(R) Xeon(R) Platinum 8124M CPU @ 3.00GHz - 3000
  - Intel(R) Xeon(R) Platinum 8124M CPU @ 3.00GHz - 3000
  - Intel(R) Xeon(R) Platinum 8124M CPU @ 3.00GHz - 3000
  - Intel(R) Xeon(R) Platinum 8124M CPU @ 3.00GHz - 3000
  - Intel(R) Xeon(R) Platinum 8124M CPU @ 3.00GHz - 3000
  - Intel(R) Xeon(R) Platinum 8124M CPU @ 3.00GHz - 3000
  - Intel(R) Xeon(R) Platinum 8124M CPU @ 3.00GHz - 3000
  - Intel(R) Xeon(R) Platinum 8124M CPU @ 3.00GHz - 3000
  - Intel(R) Xeon(R) Platinum 8124M CPU @ 3.00GHz - 3000
  - Intel(R) Xeon(R) Platinum 8124M CPU @ 3.00GHz - 3000
  - Intel(R) Xeon(R) Platinum 8124M CPU @ 3.00GHz - 3000
  - Intel(R) Xeon(R) Platinum 8124M CPU @ 3.00GHz - 3000
  - Intel(R) Xeon(R) Platinum 8124M CPU @ 3.00GHz - 3000
  - Intel(R) Xeon(R) Platinum 8124M CPU @ 3.00GHz - 3000
  - Intel(R) Xeon(R) Platinum 8124M CPU @ 3.00GHz - 3000
  - Intel(R) Xeon(R) Platinum 8124M CPU @ 3.00GHz - 3000
  - Intel(R) Xeon(R) Platinum 8124M CPU @ 3.00GHz - 3000
  - Intel(R) Xeon(R) Platinum 8124M CPU @ 3.00GHz - 3000
  - Intel(R) Xeon(R) Platinum 8124M CPU @ 3.00GHz - 3000
  - Intel(R) Xeon(R) Platinum 8124M CPU @ 3.00GHz - 3000
  - Intel(R) Xeon(R) Platinum 8124M CPU @ 3.00GHz - 3000
  - Intel(R) Xeon(R) Platinum 8124M CPU @ 3.00GHz - 3000
  - Intel(R) Xeon(R) Platinum 8124M CPU @ 3.00GHz - 3000
  - Intel(R) Xeon(R) Platinum 8124M CPU @ 3.00GHz - 3000
  - Intel(R) Xeon(R) Platinum 8124M CPU @ 3.00GHz - 3000
  - Intel(R) Xeon(R) Platinum 8124M CPU @ 3.00GHz - 3000
  - Intel(R) Xeon(R) Platinum 8124M CPU @ 3.00GHz - 3000
  - Intel(R) Xeon(R) Platinum 8124M CPU @ 3.00GHz - 3000
  - Intel(R) Xeon(R) Platinum 8124M CPU @ 3.00GHz - 3000
  - Intel(R) Xeon(R) Platinum 8124M CPU @ 3.00GHz - 3000
  ENDIANNESS: LE
  VERSIONS:
  - ares: 1.14.0
  - cldr: 32.0
  - http_parser: 2.8.1
  - icu: 60.1
  - modules: 57
  - napi: 3
  - nghttp2: 1.32.0
  - node: 8.11.4
  - openssl: 1.0.2o
  - tz: 2017c
  - unicode: 10.0
  - uv: 1.20.2
  - v8: 6.2.414.54
  - zlib: 1.2.11

ERROR Summary:

  - broccoliBuilderErrorStack: Error: Could not find module `fetch/setup` imported from `prog/instance-initializers/setup-fetch`
    at /tmp/broccoli-206JY0r2WxIPHx0/out-908-uglify_writer/assets/vendor.js:11:31
    at l (/tmp/broccoli-206JY0r2WxIPHx0/out-908-uglify_writer/assets/vendor.js:11:96)
    at a.findDeps (/tmp/broccoli-206JY0r2WxIPHx0/out-908-uglify_writer/assets/vendor.js:23:158)
    at l (/tmp/broccoli-206JY0r2WxIPHx0/out-908-uglify_writer/assets/vendor.js:11:152)
    at requireModule (/tmp/broccoli-206JY0r2WxIPHx0/out-908-uglify_writer/assets/vendor.js:5:60)
    at t (/tmp/broccoli-206JY0r2WxIPHx0/out-908-uglify_writer/assets/vendor.js:11178:21)
    at /tmp/broccoli-206JY0r2WxIPHx0/out-908-uglify_writer/assets/vendor.js:11182:233
    at e.default (/tmp/broccoli-206JY0r2WxIPHx0/out-908-uglify_writer/assets/vendor.js:11182:242)
    at a.callback (/tmp/broccoli-206JY0r2WxIPHx0/out-908-uglify_writer/assets/prog.js:585:145)
    at a.exports (/tmp/broccoli-206JY0r2WxIPHx0/out-908-uglify_writer/assets/vendor.js:18:21)
    at a._reify (/tmp/broccoli-206JY0r2WxIPHx0/out-908-uglify_writer/assets/vendor.js:21:35)
    at a.reify (/tmp/broccoli-206JY0r2WxIPHx0/out-908-uglify_writer/assets/vendor.js:20:23)
    at a.exports (/tmp/broccoli-206JY0r2WxIPHx0/out-908-uglify_writer/assets/vendor.js:17:84)
    at Object.requireModule (/tmp/broccoli-206JY0r2WxIPHx0/out-908-uglify_writer/assets/vendor.js:5:106)
    at Object.<anonymous> (/src/prog/node_modules/fastboot/src/ember-app.js:179:18)
    at VMSandbox.run (/src/prog/node_modules/fastboot/src/vm-sandbox.js:18:15)
    at EmberApp.createEmberApp (/src/prog/node_modules/fastboot/src/ember-app.js:178:30)
    at EmberApp.retrieveSandboxedApp (/src/prog/node_modules/fastboot/src/ember-app.js:203:17)
    at new EmberApp (/src/prog/node_modules/fastboot/src/ember-app.js:59:21)
    at FastBoot._buildEmberApp (/src/prog/node_modules/fastboot/src/index.js:114:17)
    at new FastBoot (/src/prog/node_modules/fastboot/src/index.js:52:10)
    at Prerender.build (/src/prog/node_modules/prember/lib/prerender.js:83:15)
    at <anonymous>
  - codeFrame: Could not find module `fetch/setup` imported from `prog/instance-initializers/setup-fetch`
  - errorMessage: Could not find module `fetch/setup` imported from `prog/instance-initializers/setup-fetch`
        at prember
-~- created here: -~-
    at new Plugin (/src/prog/node_modules/broccoli-plugin/index.js:7:31)
    at new Prerender (/src/prog/node_modules/prember/lib/prerender.js:19:5)
    at Class.postprocessTree (/src/prog/node_modules/prember/index.js:25:9)
    at projectOrAddon.addons.reduce (/src/prog/node_modules/ember-cli/lib/utilities/addon-process-tree.js:6:25)
    at Array.reduce (<anonymous>)
    at addonProcessTree (/src/prog/node_modules/ember-cli/lib/utilities/addon-process-tree.js:4:32)
    at EmberApp.addonPostprocessTree (/src/prog/node_modules/ember-cli/lib/broccoli/ember-app.js:843:12)
    at EmberApp.host.addonPostprocessTree (/src/prog/node_modules/ember-auto-import/js/auto-import.js:94:20)
    at EmberApp.toTree (/src/prog/node_modules/ember-cli/lib/broccoli/ember-app.js:1772:17)
    at module.exports (/src/prog/ember-cli-build.js:100:16)
-~- (end) -~-
  - errorType: Build Error
  - location:
    - column: [undefined]
    - file: [undefined]
    - line: [undefined]
    - treeDir: [undefined]
  - message: Could not find module `fetch/setup` imported from `prog/instance-initializers/setup-fetch`
        at prember
-~- created here: -~-
    at new Plugin (/src/prog/node_modules/broccoli-plugin/index.js:7:31)
    at new Prerender (/src/prog/node_modules/prember/lib/prerender.js:19:5)
    at Class.postprocessTree (/src/prog/node_modules/prember/index.js:25:9)
    at projectOrAddon.addons.reduce (/src/prog/node_modules/ember-cli/lib/utilities/addon-process-tree.js:6:25)
    at Array.reduce (<anonymous>)
    at addonProcessTree (/src/prog/node_modules/ember-cli/lib/utilities/addon-process-tree.js:4:32)
    at EmberApp.addonPostprocessTree (/src/prog/node_modules/ember-cli/lib/broccoli/ember-app.js:843:12)
    at EmberApp.host.addonPostprocessTree (/src/prog/node_modules/ember-auto-import/js/auto-import.js:94:20)
    at EmberApp.toTree (/src/prog/node_modules/ember-cli/lib/broccoli/ember-app.js:1772:17)
    at module.exports (/src/prog/ember-cli-build.js:100:16)
-~- (end) -~-
  - name: BuildError
  - nodeAnnotation: [undefined]
  - nodeName: prember
  - originalErrorMessage: Could not find module `fetch/setup` imported from `prog/instance-initializers/setup-fetch`
  - stack: Error: Could not find module `fetch/setup` imported from `prog/instance-initializers/setup-fetch`
    at /tmp/broccoli-206JY0r2WxIPHx0/out-908-uglify_writer/assets/vendor.js:11:31
    at l (/tmp/broccoli-206JY0r2WxIPHx0/out-908-uglify_writer/assets/vendor.js:11:96)
    at a.findDeps (/tmp/broccoli-206JY0r2WxIPHx0/out-908-uglify_writer/assets/vendor.js:23:158)
    at l (/tmp/broccoli-206JY0r2WxIPHx0/out-908-uglify_writer/assets/vendor.js:11:152)
    at requireModule (/tmp/broccoli-206JY0r2WxIPHx0/out-908-uglify_writer/assets/vendor.js:5:60)
    at t (/tmp/broccoli-206JY0r2WxIPHx0/out-908-uglify_writer/assets/vendor.js:11178:21)
    at /tmp/broccoli-206JY0r2WxIPHx0/out-908-uglify_writer/assets/vendor.js:11182:233
    at e.default (/tmp/broccoli-206JY0r2WxIPHx0/out-908-uglify_writer/assets/vendor.js:11182:242)
    at a.callback (/tmp/broccoli-206JY0r2WxIPHx0/out-908-uglify_writer/assets/prog.js:585:145)
    at a.exports (/tmp/broccoli-206JY0r2WxIPHx0/out-908-uglify_writer/assets/vendor.js:18:21)
    at a._reify (/tmp/broccoli-206JY0r2WxIPHx0/out-908-uglify_writer/assets/vendor.js:21:35)
    at a.reify (/tmp/broccoli-206JY0r2WxIPHx0/out-908-uglify_writer/assets/vendor.js:20:23)
    at a.exports (/tmp/broccoli-206JY0r2WxIPHx0/out-908-uglify_writer/assets/vendor.js:17:84)
    at Object.requireModule (/tmp/broccoli-206JY0r2WxIPHx0/out-908-uglify_writer/assets/vendor.js:5:106)
    at Object.<anonymous> (/src/prog/node_modules/fastboot/src/ember-app.js:179:18)
    at VMSandbox.run (/src/prog/node_modules/fastboot/src/vm-sandbox.js:18:15)
    at EmberApp.createEmberApp (/src/prog/node_modules/fastboot/src/ember-app.js:178:30)
    at EmberApp.retrieveSandboxedApp (/src/prog/node_modules/fastboot/src/ember-app.js:203:17)
    at new EmberApp (/src/prog/node_modules/fastboot/src/ember-app.js:59:21)
    at FastBoot._buildEmberApp (/src/prog/node_modules/fastboot/src/index.js:114:17)
    at new FastBoot (/src/prog/node_modules/fastboot/src/index.js:52:10)
    at Prerender.build (/src/prog/node_modules/prember/lib/prerender.js:83:15)
    at <anonymous>

=================================================================================

Exited with code 1

"Invalid Mapping" from ember-cli-uglify on build

Getting this error on minify from ember-cli-uglify on build...

File: assets/vendor.js
Invalid mapping: {"generated":{"line":111536,"column":-5},"source":"vendor/whatwg-fetch/fetch.js","original":{"line":1,"column":0},"name":null}
Error: Invalid mapping: {"generated":{"line":111536,"column":-5},"source":"vendor/whatwg-fetch/fetch.js","original":{"line":1,"column":0},"name":null}
    at SourceMapGenerator_validateMapping [as _validateMapping] (/Users/chrism/myapp/node_modules/ember-cli-uglify/node_modules/broccoli-uglify-sourcemap/node_modules/uglify-js/node_modules/source-map/lib/source-map/source-map-generator.js:272:15)
    at SourceMapGenerator_addMapping [as addMapping] (/Users/chrism/myapp/node_modules/ember-cli-uglify/node_modules/broccoli-uglify-sourcemap/node_modules/uglify-js/node_modules/source-map/lib/source-map/source-map-generator.js:102:12)
    at /Users/chrism/myapp/node_modules/ember-cli-uglify/node_modules/broccoli-uglify-sourcemap/node_modules/uglify-js/node_modules/source-map/lib/source-map/source-map-generator.js:74:19
    at Array.forEach (native)
    at SourceMapConsumer_eachMapping [as eachMapping] (/Users/chrism/myapp/node_modules/ember-cli-uglify/node_modules/broccoli-uglify-sourcemap/node_modules/uglify-js/node_modules/source-map/lib/source-map/source-map-consumer.js:473:10)
    at Function.SourceMapGenerator_fromSourceMap [as fromSourceMap] (/Users/chrism/myapp/node_modules/ember-cli-uglify/node_modules/broccoli-uglify-sourcemap/node_modules/uglify-js/node_modules/source-map/lib/source-map/source-map-generator.js:50:26)
    at Context.SourceMap (/Users/chrism/myapp/node_modules/ember-cli-uglify/node_modules/broccoli-uglify-sourcemap/node_modules/uglify-js/lib/sourcemap.js:59:52)
    at Object.exports.minify (/Users/chrism/myapp/node_modules/ember-cli-uglify/node_modules/broccoli-uglify-sourcemap/node_modules/uglify-js/tools/node.js:111:38)
    at UglifyWriter.processFile (/Users/chrism/myapp/node_modules/ember-cli-uglify/node_modules/broccoli-uglify-sourcemap/index.js:99:27)
    at /Users/chrism/myapp/node_modules/ember-cli-uglify/node_modules/broccoli-uglify-sourcemap/index.js:46:14

This may be an issue in the actual github-fetch polyfill ?

Ember CLI v1.13.7
Ember v1.13.10

Flickering test failures w/ Ember 2.18.2 & 3.4.7

This is a follow up on comments in #25 starting here.

Background

In preparation to upgrading from Ember 2.18.2 to 3.4.7, I've been refactoring a fairly complex custom ajax service that my app uses to rely on ember-fetch instead of ic-ajax (ember-ajax has its own service implementation that was in conflict, so opted to move all the way up to fetch based solution).

Everything in development mode seemed to be working fine in 2.18.2, but when I ran my full test suite (modern 3.x testing style already migrated), I began to get a number of failures due to tests not waiting for fetch requests to finish as expected by await calls.

What I have observed

In 2.18.2 with ember-fetch 6.3.1, ember-test-helpers 1.1.0, and ember-qunit 4.2.0:

  • if I reran the tests individually, most tests would pass as expected
  • adding await settled() calls at a point before the test failure would most times alleviate the test failure when running full suite (after doing this several places, I gave up on this before adding tons of these allover the whole suite)
  • ember-fetch registerWaiter seems to be working as designed, but is not enough - I added logging to see if the waiter function was being set up and called as well as the decrementing and they were

It was almost like there was leak somewhere...

A coworker wondered if anything would be different if I tried things under Ember 3.4.7. Unfortunately, the problem was still there. However...

What allows the tests to run as expected in Ember 3.4.7, but not 2.18.2

Under Ember 3.4.7 when I changed ember-cli-build.js to the following, the test suite passed!

  let app = new EmberApp(defaults, {
    // tests: false,
    'ember-fetch': {
      preferNative: true // later added logic here to only be true in test env
    },
   ...

However, when I circled back and tried this with 2.18.2, I got different failures, e.g. Promise rejected during "Help with a ongoing cost": Cannot read property 'error' of undefined, that I assume are related to native promises not being supported in the same way as later Ember 3.x releases.

Since my ultimate goal is to be able to upgrade away from 2.18.2, I'm personally unblocked, but this does seem like an issue with the polyfil either in ember-fetch or possibly upstream.

(@viniciussbs hopefully my workaround helps you, too)

Anyone using this w/ typescript yet?

I'm looking around for a type def file for ember-fetch and thought I might give npm install --save @types/whatwg-fetch a look first / but during that time I wanted to see if others are already using this with TS

self is not window => always polyfilling

Hi,

I'm having a bit of an issue with both this lib and ember-network. They both wrap the whatwg-fetch in an IIFE which tests self.fetch but self is not window.

It lives inside this IIFE:

(function (global) {
  define('fetch', ['ember', 'exports'], function(Ember, self) {
...

at this point self is a pojo which means fetch is always polyfilled. I'm not overly familiar with the reification process but I can't quite see how exports maps to something that could be tested for fetch?

Is this some sort of build issue my side or should the variable self be renamed so it's not shadowed by the whatwg-fetch test?

[raised a speculative PR #20]

Cannot read property 'preferNative' of undefined

I am trying to replace ember-ajax with ember-fetch in an addon I use, but when I do it get the error:
Cannot read property 'preferNative' of undefined

content of error dump file can be seen below.


ENV Summary:

  TIME: Wed Oct 17 2018 12:56:02 GMT+0200 (Romance Daylight Time)
  TITLE: ember
  ARGV:
  - C:\Program Files\nodejs\node.exe
  - C:\Users\mmi\AppData\Roaming\npm\node_modules\ember-cli\bin\ember
  - build
  EXEC_PATH: C:\Program Files\nodejs\node.exe
  TMPDIR: C:\Users\mmi\AppData\Local\Temp
  SHELL: null
  PATH:
  - C
  - \Users\mmi\Desktop\Cmder_mini\bin;C
  - \Users\mmi\Desktop\Cmder_mini\vendor\conemu-maximus5\ConEmu\Scripts;C
  - \Users\mmi\Desktop\Cmder_mini\vendor\conemu-maximus5;C
  - \Users\mmi\Desktop\Cmder_mini\vendor\conemu-maximus5\ConEmu;C
  - \Program Files (x86)\Common Files\Oracle\Java\javapath;C
  - \Python27\;C
  - \Program Files (x86)\Intel\iCLS Client\;C
  - \Program Files\Intel\iCLS Client\;C
  - \WINDOWS\system32;C
  - \WINDOWS;C
  - \WINDOWS\System32\Wbem;C
  - \WINDOWS\System32\WindowsPowerShell\v1.0\;C
  - \Program Files (x86)\Microsoft SQL Server\80\Tools\Binn\;C
  - \Program Files\Microsoft SQL Server\90\DTS\Binn\;C
  - \Program Files\Microsoft SQL Server\90\Tools\binn\;C
  - \Program Files (x86)\Microsoft SQL Server\90\Tools\binn\;C
  - \Program Files (x86)\Microsoft SQL Server\90\DTS\Binn\;C
  - \Program Files (x86)\Microsoft SQL Server\90\Tools\Binn\VSShell\Common7\IDE\;C
  - \Program Files (x86)\Microsoft Visual Studio 8\Common7\IDE\PrivateAssemblies\;C
  - \Program Files (x86)\Windows Kits\8.1\Windows Performance Toolkit\;C
  - \Program Files\Microsoft SQL Server\110\Tools\Binn\;C
  - \dev\Development\Tools\Nant\nant-0.92\bin;c
  - \Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\;C
  - \Program Files\Microsoft\Web Platform Installer\;C
  - \Program Files\Microsoft SQL Server\120\Tools\Binn\;C
  - \Program Files (x86)\Microsoft SQL Server\120\Tools\Binn\;C
  - \Program Files (x86)\Microsoft SQL Server\120\DTS\Binn\;C
  - \Program Files\Microsoft SQL Server\120\DTS\Binn\;C
  - \Program Files\Microsoft SQL Server\130\Tools\Binn\;C
  - \Program Files\Microsoft SQL Server\Client SDK\ODBC\110\Tools\Binn\;C
  - \Program Files (x86)\Microsoft SQL Server\120\Tools\Binn\ManagementStudio\;C
  - \Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C
  - \Program Files\Intel\Intel(R) Management Engine Components\DAL;C
  - \Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C
  - \Program Files\Intel\Intel(R) Management Engine Components\IPT;C
  - \Program Files (x86)\Microsoft SQL Server\110\DTS\Binn\;C
  - \Program Files (x86)\Microsoft SQL Server\130\DTS\Binn\;C
  - \Program Files (x86)\Windows Kits\10\Windows Performance Toolkit\;C
  - \Program Files (x86)\Microsoft SQL Server\Client SDK\ODBC\130\Tools\Binn\;C
  - \Program Files (x86)\Microsoft SQL Server\130\Tools\Binn\;C
  - \Program Files (x86)\Microsoft SQL Server\130\Tools\Binn\ManagementStudio\;C
  - \Program Files\dotnet\;C
  - \Program Files (x86)\Microsoft SQL Server\140\Tools\Binn\;C
  - \Program Files (x86)\Microsoft SQL Server\140\DTS\Binn\;C
  - \Program Files (x86)\Microsoft SQL Server\140\Tools\Binn\ManagementStudio\;C
  - \Program Files\nodejs\;C
  - \WINDOWS\System32\OpenSSH\;C
  - \Program Files (x86)\Common Files\Acronis\VirtualFile\;C
  - \Program Files (x86)\Common Files\Acronis\VirtualFile64\;C
  - \Program Files (x86)\Common Files\Acronis\SnapAPI\;C
  - \Program Files\Git\cmd;C
  - \Program Files\TortoiseHg\;C
  - \Program Files (x86)\Yarn\bin\;C
  - \Users\mmi\.dnx\bin;C
  - \Users\mmi\AppData\Local\Microsoft\WindowsApps;C
  - \Program Files\Microsoft VS Code\bin;C
  - \Users\mmi\AppData\Local\GitHubDesktop\bin;C
  - \Users\mmi\AppData\Roaming\npm;C
  - \Users\mmi\AppData\Local\Microsoft\WindowsApps;C
  - \Users\mmi\AppData\Local\Programs\Microsoft VS Code\bin;C
  - \Users\mmi\AppData\Local\Yarn\bin;C
  - \Program Files\Git\usr\bin;C
  - \Program Files\Git\usr\share\vim\vim74;C
  - \Users\mmi\Desktop\Cmder_mini\
  PLATFORM: win32 x64
  FREEMEM: 4853907456
  TOTALMEM: 17080877056
  UPTIME: 571690.2593529
  LOADAVG: 0,0,0
  CPUS:
  - Intel(R) Core(TM) i7-4770 CPU @ 3.40GHz - 3392
  - Intel(R) Core(TM) i7-4770 CPU @ 3.40GHz - 3392
  - Intel(R) Core(TM) i7-4770 CPU @ 3.40GHz - 3392
  - Intel(R) Core(TM) i7-4770 CPU @ 3.40GHz - 3392
  - Intel(R) Core(TM) i7-4770 CPU @ 3.40GHz - 3392
  - Intel(R) Core(TM) i7-4770 CPU @ 3.40GHz - 3392
  - Intel(R) Core(TM) i7-4770 CPU @ 3.40GHz - 3392
  - Intel(R) Core(TM) i7-4770 CPU @ 3.40GHz - 3392
  ENDIANNESS: LE
  VERSIONS:
  - ares: 1.10.1-DEV
  - cldr: 31.0.1
  - http_parser: 2.7.0
  - icu: 59.1
  - modules: 57
  - nghttp2: 1.25.0
  - node: 8.9.1
  - openssl: 1.0.2m
  - tz: 2017b
  - unicode: 9.0
  - uv: 1.15.0
  - v8: 6.1.534.47
  - zlib: 1.2.11

ERROR Summary:

  - broccoliBuilderErrorStack: [undefined]
  - codeFrame: [undefined]
  - errorMessage: Cannot read property 'preferNative' of undefined
  - errorType: [undefined]
  - location:
    - column: [undefined]
    - file: [undefined]
    - line: [undefined]
  - message: Cannot read property 'preferNative' of undefined
  - name: TypeError
  - nodeAnnotation: [undefined]
  - nodeName: [undefined]
  - originalErrorMessage: [undefined]
  - stack: TypeError: Cannot read property 'preferNative' of undefined
    at Class.treeForVendor (C:\dev\GitHub\ember-cli-new-version\node_modules\ember-fetch\index.js:113:43)
    at Class._treeFor (C:\dev\GitHub\ember-cli-new-version\node_modules\ember-cli\lib\models\addon.js:616:33)
    at Class.treeFor (C:\dev\GitHub\ember-cli-new-version\node_modules\ember-cli\lib\models\addon.js:576:21)
    at addons.reduce (C:\dev\GitHub\ember-cli-new-version\node_modules\ember-cli\lib\models\addon.js:449:26)
    at Array.reduce (<anonymous>)
    at Class.eachAddonInvoke (C:\dev\GitHub\ember-cli-new-version\node_modules\ember-cli\lib\models\addon.js:446:24)
    at Class.treeFor (C:\dev\GitHub\ember-cli-new-version\node_modules\ember-cli\lib\models\addon.js:575:22)
    at project.addons.reduce (C:\dev\GitHub\ember-cli-new-version\node_modules\ember-cli\lib\broccoli\ember-app.js:699:26)
    at Array.reduce (<anonymous>)
    at EmberAddon._addonTreesFor (C:\dev\GitHub\ember-cli-new-version\node_modules\ember-cli\lib\broccoli\ember-app.js:697:32)

=================================================================================

You can check out this branch https://github.com/initram/ember-cli-new-version/tree/upgrade-no-jquery

Then run yarn and ember build to reproduce the error.

I tried to figure out what is going on my self, but I could not figure out if the addon that I am trying to change is doing something really weird that is causing the error or what.

Should this wrapper use native fetch, when available?

I spent some time today writing some tests to expose what I thought was a bug here -- the polyfill is always used by ember-fetch; it will never fall back to native fetch, even when its available.

I was sure this was a bug until I found pretenderjs/pretender#60 with comments indicating that it was intended that this addon always uses the polyfill.

It's been almost a year since those comments, and Chrome and Firefox now appear to support fetch (http://caniuse.com/#search=fetch), should the native fetch be used, if available? Alternatively, a note in the Readme about why it always uses the polyfill would be great.

Incidentally, I started down this path when someone told me they were using ember-network + fetch and were also using ember-cli-mirage for testing on a recent Chrome and I felt I had to solve the mystery of how that worked. So, I have no real use case here and I certainly don't mind it using ajax. It does make testing easier that way, at least until pretender supports fetch.

Ember-fetch incorrectly handles HTTP 303 status

  1. Perform POST
  2. backend responds with HTTP Status 303
  3. An automatic redirect to new resource (from Location Header) is done
  4. we get proper response, but in order to be able to do totally different request in the future, we need access to either mentioned LocationHeader or to URL of redirected request.

Because the redirect is done, it is not possible to get access to LocationHeader, ember-fetch in response object returns URL of initial (POST) request and not the one after redirect, so we use normal fetch in order to get proper URL from received response object.

Only absolute URLs are supported

How can I use this with fastboot / node-fetch? I always get Only absolute URLs are supported when trying to fetch /foo. This works in the browser, but not in fastboot.

Credentials are always set as 'same-origin'

I'm spiking out a project to use Simple Auth, Fastboot, and Fetch with DRF adapters. I have to send a httpOnly cookie, as we're currently not using tokens other than CSRF. I'm able to set X-CSRFToken via headers, but I can't get around setting 'credentials':'include', as the AdapterFetch mixin always sets it as same-origin.

In mungOptionsForFetch:

const options = combineObjs({
    credentials: 'same-origin',
  }, _options);

I'm curious as to why credentials cannot be overridden? I can override ajaxOptions method and use my own options munger, but that seems a bit much for something that should be simple.

`Import fetch from 'fetch'` not working w/ 3.2.8

Running ember-fetch in a Fastboot enabled app, we see the same issue mentioned in #26

Running without Fastboot works fine.

The project is huge so I'm not sure if this is a straight-up an ember-fetch issue, or a complex mix of other factors. We don't have any dependencies relying on ember-network.

PUT body no longer set.

Up until v3.4.1, mungOptionsForFetch sets the PUT body correctly.

Example failing test case:

  const baseOptions = {
    url: '/',
    method: 'PUT',
    data: { a: 1 }
  };

  let options = mungOptionsForFetch(baseOptions, this.basicAdapter);
  assert.equal(options.body, JSON.stringify(baseOptions.data), 'PUT request body correctly set');

Don't work as dependencies

ember-fecth does not work in my consumer app with Fastboot enabled, when I put ember-fetch as dependencies in my addon

cosumer app - https://github.com/villander/ember-mvp
addon - https://github.com/villander/ember-apollo-client/blob/apollo-client-2.0/package.json#L34

looks like ember-fetch specifically doesn’t work with fastboot when it’s a nested dependency
because its updateFastBootManifest() method is never called

the question is what happens when you wind up calling that hook multiple times?
like if ember-mvp and ember-apollo-client both have ember-fetch installed, does it get called twice?

is it ember-fetch’s responsibility to guard against that?

Error: Cannot find module 'abortcontroller-polyfill/dist/cjs-ponyfill'

A similar issue was recently closed #115 but I do not understand how to resolve this issue in the case of linking a local dependency now with these recent updates.

For example, I currently need to use a branch of ember-cli-fastboot to fix an issue with the shoebox so I until the PR is merged I use this branch https://github.com/chrism/ember-cli-fastboot/tree/fix-shoebox which works when the remote URL is used in my package.json.

However, if I try to use this same branch locally, by using yarn link and yarn link "ember-cli-fastboot" in my test application then whereas this used to work I now get this error.

Error: Cannot find module 'abortcontroller-polyfill/dist/cjs-ponyfill'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15)
    at Function.Module._load (internal/modules/cjs/loader.js:507:25)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:20:18)
    at Object.require (/Users/example/git/ember-cli-fastboot/node_modules/fastboot/src/ember-app.js:130:18)
    at Module.callback (/Users/example/git/example/tmp/broccoli_persistent_filterfastboot_manifest_rewrite__broccoli_asset_revfastboot_manifest_rewrite-output_path-nEn9sQXU.tmp/ember-fetch/fastboot-fetch-0afba248f49db81597281d5d1218fbf9.js:6:42)
    at Module.exports (/Users/example/git/example/tmp/broccoli_persistent_filterfastboot_manifest_rewrite__broccoli_asset_revfastboot_manifest_rewrite-output_path-nEn9sQXU.tmp/assets/vendor/loader/loader.js:106:1)
    at Module._reify (/Users/example/git/example/tmp/broccoli_persistent_filterfastboot_manifest_rewrite__broccoli_asset_revfastboot_manifest_rewrite-output_path-nEn9sQXU.tmp/assets/vendor/loader/loader.js:143:1)
    at Module.reify (/Users/example/git/example/tmp/broccoli_persistent_filterfastboot_manifest_rewrite__broccoli_asset_revfastboot_manifest_rewrite-output_path-nEn9sQXU.tmp/assets/vendor/loader/loader.js:130:1)
    at Module.exports (/Users/example/git/example/tmp/broccoli_persistent_filterfastboot_manifest_rewrite__broccoli_asset_revfastboot_manifest_rewrite-output_path-nEn9sQXU.tmp/assets/vendor/loader/loader.js:104:1)

This seems like a regression because it was working until recently (I needed it to work to develop the shoebox fix in the first place).

Have I missed something, or is this no longer possible?

Fastboot dependency whitelisting

Since Ember Fetch 1.4.2, there appears to be an issue with using the import fetch from 'fetch' syntax in Fastboot apps, requiring a change to the fastboot dependency whitelist in package.json.

This issue relates to Ember Simple Auth, which has broken session restoration for Fastboot apps ever since upgrading to a later version of Ember Fetch. More details: mainmatter/ember-simple-auth#1138 (comment).

The fix appears to be to change "node-fetch" to just "fetch" in the app's fastbootDependencies. I'm just wondering whether that's an anticipated requirement for using Ember Fetch since defining fetch as a module import (see here) and whether it should be mentioned in the docs?

Usage in a glimmer app

Is there a way to use this in a Glimmer app while app.import is being sorted in the Glimmer build pipeline?

1.4.0 breaks for addons

Probably needs in included:

    // see: https://github.com/ember-cli/ember-cli/issues/3718
    if (typeof(app.import) !== 'function' && app.app) {
      app = app.app;
    }

Also, even if I fix that part, it seems to conflict with ember-network/fetch somehow. e.g. my addon uses ember-fetch. my app uses the addon with ember-fetch and also ember-simple-auth which depends on ember-network. If i add the above to ember-fetch for my addon , in my app ember-simple-auth starts throwing a fit about not being able to import fetch from ember-network. Not sure how this is happening.

Downgrading ember-fetch to 1.3.0 makes it all go back to normal.

ember-simple-auth 1.4.0 create a strange file when I "ember build -prod"

I switched from 1.3.0 to 1.4.0 and now when I ember build -prod I have a new file in:

dist/ember-fetch/fastboot-fetch-a4c28b6b7b24781cc7616fb44c1def25.js:

(function(){define('fetch',['exports'],function(a){var b=FastBoot.require('node-fetch');a['default']=b,a.Headers=b.Headers,a.Request=b.Request,a.Response=b.Response}),define('fetch/ajax',['exports'],function(){throw new Error('You included fetch/ajaxbut it was renamed toember-fetch/ajax')})})();

Why this?

I don't want this file in my prod dist folder.

I'm not using fastboot.

FastBoot is not defined from Browser Console

I see the following error in my browser console:

Error in Component#send ReferenceError: FastBoot is not defined

Though this cannot be correct, as our Ember Application is NOT FastBoot enabled.

Culprit?
Also in Chrome Dev Tools - Sources I see a file named: fastboot-fetch.js

(function() {
  define('fetch', ['exports'], function(self) {
    var fetch = FastBoot.require('node-fetch');
    self['default'] = fetch;
    self['Headers'] = fetch.Headers;
    self['Request'] = fetch.Request;
    self['Response'] = fetch.Response;
  });

  define('fetch/ajax', ['exports'], function() {
    throw new Error('You included `fetch/ajax` but it was renamed to `ember-fetch/ajax`');
  });
})();

Our Context
We have not explicitly installed this ember-fetch package. Rather ember-fetch is a dependency upon ember-simple-auth, which we have explicitly npm installed.

We are using Ember Engines with lazyLoading enabled.

Similar Issue
The GitHub Repo ember-cli-moment-shim had a similar issue:
Issue: jasonmit/ember-cli-moment-shim#145
Fix: jasonmit/ember-cli-moment-shim@591ae7a

v5.0.0 has an error to include yetch-polyfill

Upgrade to v5.0.0 recently and found there was an error:

=================================================================================

ENV Summary:

  TIME: Sat Jun 23 2018 11:48:25 GMT+0800 (CST)
  TITLE: ember
  ARGV:
  - /usr/local/bin/node
  - /Users/nightire/Code/choice-form/os-client/node_modules/.bin/ember
  - serve
  - --ssl
  EXEC_PATH: /usr/local/bin/node
  TMPDIR: /var/folders/9_/y4f4n_cd5ddbzftt3x0rz19w0000gn/T
  SHELL: /bin/zsh
  PATH:
  - /usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin
  - /Users/nightire/Code/choice-form/os-client/node_modules/.bin
  - /usr/local/bin
  - /usr/bin
  - /bin
  - /usr/sbin
  - /sbin
  - /Users/nightire/.rbenv/shims
  - /Users/nightire/.cargo/bin
  - /Users/nightire/.config/yarn/global/node_modules/.bin
  - /usr/local/opt/gnu-tar/libexec/gnubin
  - /usr/local/Cellar/zplug/2.4.2/bin
  - /usr/local/opt/zplug/bin
  - /usr/local/sbin
  PLATFORM: darwin x64
  FREEMEM: 55902208
  TOTALMEM: 17179869184
  UPTIME: 393513
  LOADAVG: 5.244140625,3.9296875,2.80859375
  CPUS:
  - Intel(R) Core(TM) i7-6700K CPU @ 4.00GHz - 4000
  - Intel(R) Core(TM) i7-6700K CPU @ 4.00GHz - 4000
  - Intel(R) Core(TM) i7-6700K CPU @ 4.00GHz - 4000
  - Intel(R) Core(TM) i7-6700K CPU @ 4.00GHz - 4000
  - Intel(R) Core(TM) i7-6700K CPU @ 4.00GHz - 4000
  - Intel(R) Core(TM) i7-6700K CPU @ 4.00GHz - 4000
  - Intel(R) Core(TM) i7-6700K CPU @ 4.00GHz - 4000
  - Intel(R) Core(TM) i7-6700K CPU @ 4.00GHz - 4000
  ENDIANNESS: LE
  VERSIONS:
  - ares: 1.10.1-DEV
  - cldr: 32.0
  - http_parser: 2.8.0
  - icu: 60.1
  - modules: 57
  - napi: 3
  - nghttp2: 1.29.0
  - node: 8.11.2
  - openssl: 1.0.2o
  - tz: 2017c
  - unicode: 10.0
  - uv: 1.19.1
  - v8: 6.2.414.54
  - zlib: 1.2.11

ERROR Summary:

  - broccoliBuilderErrorStack: [undefined]
  - codeFrame: [undefined]
  - errorMessage: ENOTDIR: not a directory, lstat '/Users/nightire/Code/choice-form/os-client/node_modules/yetch/dist/yetch-polyfill.js/yetch-polyfill.js'
  - errorType: [undefined]
  - location:
    - column: [undefined]
    - file: [undefined]
    - line: [undefined]
  - message: ENOTDIR: not a directory, lstat '/Users/nightire/Code/choice-form/os-client/node_modules/yetch/dist/yetch-polyfill.js/yetch-polyfill.js'
  - name: Error
  - nodeAnnotation: [undefined]
  - nodeName: [undefined]
  - originalErrorMessage: [undefined]
  - stack: Error: ENOTDIR: not a directory, lstat '/Users/nightire/Code/choice-form/os-client/node_modules/yetch/dist/yetch-polyfill.js/yetch-polyfill.js'

=================================================================================

"Maximum call stack size exceeded" on build

My ember-cli builds are failing since introducing ember-fetch as a dependency.

This may be an issue with broccoli-stew, but hopefully the stack trace below will help pinpoint the exact issue.

I'm on Windows 8.1 using ember-cli v0.2.3.

I know this version of ember-cli is out of date. I can update my global cli version, but updating the app isn't an option.

Build failed.
Maximum call stack size exceeded
RangeError: Maximum call stack size exceeded
    at new Error (native)
    at Error (native)
    at Object.fs.mkdirSync (fs.js:799:18)
    at sync (C:\Users\ismyrnow\Git\myapp\dashboard\node_modules\ember-fetch\node_modules\broccoli-stew\node_modules\broccoli-funnel\node_modules\mkdirp\index.js:71:13)
    at sync (C:\Users\ismyrnow\Git\myapp\dashboard\node_modules\ember-fetch\node_modules\broccoli-stew\node_modules\broccoli-funnel\node_modules\mkdirp\index.js:77:24)
    at sync (C:\Users\ismyrnow\Git\myapp\dashboard\node_modules\ember-fetch\node_modules\broccoli-stew\node_modules\broccoli-funnel\node_modules\mkdirp\index.js:78:17)
    at sync (C:\Users\ismyrnow\Git\myapp\dashboard\node_modules\ember-fetch\node_modules\broccoli-stew\node_modules\broccoli-funnel\node_modules\mkdirp\index.js:78:17)
    at sync (C:\Users\ismyrnow\Git\myapp\dashboard\node_modules\ember-fetch\node_modules\broccoli-stew\node_modules\broccoli-funnel\node_modules\mkdirp\index.js:78:17)
    at sync (C:\Users\ismyrnow\Git\myapp\dashboard\node_modules\ember-fetch\node_modules\broccoli-stew\node_modules\broccoli-funnel\node_modules\mkdirp\index.js:78:17)
    at sync (C:\Users\ismyrnow\Git\myapp\dashboard\node_modules\ember-fetch\node_modules\broccoli-stew\node_modules\broccoli-funnel\node_modules\mkdirp\index.js:78:17)

Typescript definitions don't work

If you import fetch from 'fetch', typescript won't resolve it.
If you import fetch from 'ember-fetch', typescript will resolve it, but you'll have a runtime error.

When you import fetch, typescript looks in node_modules/fetch. It won't scan the whole node_modules directory for anyone exporting a fetch module. You can work around this with an explicit path mapping in tsconfig.json, but it's not conventional.

Maybe this package could export ember-fetch, and eventually deprecate fetch?

/cc @toranb @chriskrycho

Not working with Fastboot and ember-data

I've followed the documentation to add the initializer in fastboot/initializer/ajax.js

export default {
  name: 'ajax-service',
  initialize() {
    // noop
    // This is to override Fastboot's initializer which prevents ember-fetch from working
    // https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/fastboot/initializers/ajax.js
  }
}

and adding the AdapterFetch mixin to my adapters/application.js

import DS from 'ember-data';
import AdapterFetch from 'ember-fetch/mixins/adapter-fetch';

export default DS.JSONAPIAdapter.extend(AdapterFetch, {
});

But am still getting an error message

TypeError: Only absolute URLs are supported

Looking into this error I've seen that there is already an issue relating to it
#110

And also a PR which looks to address it
#128

But I cannot determine the correct path to resolving the issue.

In the comments of the issue there is a suggestion that this is fixed for ember-data but I don't see how to achieve this.

The PR seems out of date now due to so many subsequent commits so I tried to fork the ember-fetch repo and make the changes myself.

So I added ember-fetch-adapter as a dependency to the package.json and updating addon/mixins/adapter-fetch.js to use the adapter instead, by including the service in the mixin

  adapter: service(),

and using the adapter service in the fetch request

  _fetchRequest(url, options) {
    return this.adapter.fetch(url, options);
  },

But this now gives another error

Error: Assertion Failed: Attempting to inject an unknown injection: 'service:adapter'

I'm now at a loss as to how I can resolve this and to get ember-fetch working with ember-data and Fastboot.

I'm open to any solution, is this absolute URL issue fixable yet?

Dependency issue with fastboot-app-server

I am getting the following error when attempting to use an ember app that uses ember-fetch with fastboot-app-server

Error: Cannot find module 'abortcontroller-polyfill/dist/cjs-ponyfill'
    at Function.Module._resolveFilename (module.js:547:15)
    at Function.Module._load (module.js:474:25)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
    at Object.require (/Users/user/node_modules/fastboot/src/ember-app.js:130:18)
    at s.callback (/Users/user/fb-test/dist/ember-fetch/fastboot-fetch-ee5cef26e0470d371ec08fef9ba4a5b8.js:1:55)
    at s.exports (/Users/user/fb-test/dist/assets/vendor-12033a7caf9c9a2eebca95e833f776cb.js:19:21)
    at s._reify (/Users/user/fb-test/dist/assets/vendor-12033a7caf9c9a2eebca95e833f776cb.js:22:35)
    at s.reify (/Users/user/fb-test/dist/assets/vendor-12033a7caf9c9a2eebca95e833f776cb.js:21:23)
    at s.exports (/Users/user/fb-test/dist/assets/vendor-12033a7caf9c9a2eebca95e833f776cb.js:18:84)

I do not get this error when visiting the same page when serving the app with ember s

Here is a very simple app that will recreate this error when using the fastboot-app-server defaults:

https://github.com/Mciocca/fastboot-test

A co-worker was also able to recreate this error. He followed the tutorial on the ember fastboot site.

appveyor failing due to Firefox

Looks like this started failing after bf75750. @tchak can you investigate.

Sample Appveyor test output

ok 44 PhantomJS 2.1 - Unit | Mixin | adapter-fetch: ajaxOptions returns the correct data
not ok 45 Firefox - error
    ---
        message: >
            Error: Browser failed to connect within 30s. testem.js not loaded?
            
        Log: |
            { type: 'error',
              text: 'Error: Browser failed to connect within 30s. testem.js not loaded?' }
    ...
ok 46 Chrome 60.0 - ESLint | addon: ember-fetch/ajax.js
ok 47 Chrome 60.0 - ESLint | addon: ember-fetch/mixins/adapter-fetch.js
ok 48 Chrome 60.0 - Acceptance: Root: visiting /

Link to test output

indicating progressbar

how to provide a progress when post or get wit this library?
i tried this but doesnt work?

service(type = this.method.get, url = '', authorization = null, body = null) {
    const context = this;
    return new Ember.RSVP.Promise(
      function (resolve, reject) {
        fetch(url, {
          method: type,
          headers: {
            'Content-Type': 'application/json',
            "Authorization": authorization
          },
          body: body,
          xhrFields: {
            onprogress: function (e) {
              context.debug(e);
            }
          }
        }).progress(function (progress) {
          context.debug(progress);
        }).then(function (response) {
          resolve(response);
        }).catch(function (error) {
          reject(error);
        })
      });
  },

Adapter mixin causes error when API returns empty object & 204

Getting this ember-data error after migrating to fetch and using the adapter mixin: Assertion Failed: normalizeResponse must return a valid JSON API document: One or more of the following keys must be present: "data", "errors", "meta".

This happens when the API returns a 204 response, but with an empty objects as the payload ("{}"). Our real API actually doesn't do this, but Mirage's default handler for DELETE calls seems to return this.

It seems this was caused by #60, which changed the way a 204 response is handled in determineBodyPromise().

jQuery's ajax seems to handle this differently. The raw xhr object has a status of 204 and "{}" as the responseText, but the success hook nevertheless receives undefined as the payload, as can be seen on this screenshot:

image

To be a drop-in replacement, I think this should behave the same way as before, i.e. return undefined (or maybe { data: null } as it was before)!?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.