Git Product home page Git Product logo

ember-service-worker's Introduction

ember-service-worker's People

Contributors

andrejoaquim avatar artemgurzhii avatar bcardarella avatar cibernox avatar cyk avatar dependabot[bot] avatar ember-tomster avatar felixrieseberg avatar jrjohnson avatar marten-dockyard avatar ming-codes avatar minusfive avatar nullvoxpopuli avatar oskarrough avatar pangratz avatar poteto avatar rwjblue avatar scottkidder avatar simonihmig avatar sinankeskin avatar sivakumar-kailasam avatar stukalin avatar topaxi avatar turbo87 avatar villander avatar xiphiasuvella 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

ember-service-worker's Issues

Allow specifying babel config from addon

_babelTranspile in lib/service-worker-builder.js specifies its own babel config. Unfortunately, my configuration is very different (for example, I need the syntax-object-rest-spread plugin). I don't see a way to adjust this configuration from the outside.

Feature Request : Fastboot index.html

Following the guidelines for a feature request:

What will it allow you to do that you can't do today?
This feature request would allow the service worker to use the fastboot generated index.html where fastboot environments are enabled.

Why do you need this feature and how will it benefit other users?
I need this feature for my fastboot powered ember app, on first load users immediately see something as the emberjs libraries are downloaded. After installing the (awesome) ember-service-worker users see a blank white page which is the default index.html for a long time (~3 secs desktop, 10+ secs mobile). This feature request will benefit me and others speed up the performance perception of our app to users.

Are there any drawbacks to this feature?
Not that I can think of.

{{ROOT_URL}} (for registration) not getting replaced during build

all I have is this (in my ember-cli-config):

    'ember-service-worker': {  },

but in the output, I'm getting:

(function(){"use strict"
function n(n){e.push(n)}var e=[],r=[]
"serviceWorker"in navigator&&navigator.serviceWorker.register("{{ROOT_URL}}sw.js",{scope:"{{ROOT_URL}}"}).

[FEATURE REQUEST] Import external dependencies in Service Worker

It seems you cannot import anything that is not local to the service-worker folder, and that is not an ES6 module. The config for rollup does not include any plugins to allow importing of CJS or AMD modules, and there is no way to change that config from the outside.

Use case: would want to use libs like localForage or in this case idb-keyval inside a service worker to queue requests while offline, as using IDB directly is a bit cumbersome and localStorage is not available. But for sure there will be other use cases as well.

Bump ember-cli-babel version to avoid DEPRECATION warnings every build

Getting the following warning every time I build with ember-service-worker installed:

DEPRECATION: ember-cli-babel 5.x has been deprecated. Please upgrade to at least ember-cli-babel 6.6. Version 5.2.8 located: ncs -> ember-service-worker -> ember-cli-babel

Can you bump the ember-cli-babel version to "at least 6.6" in your package.json so ember stops complaining when I use this addon? :) Thanks so much!

How do I test my custom service-worker code

Hey, thank you for the great addons.
I wrote some logic inside the service-worker folder and now want to test it.
My first question is if it is possible to write unit tests for functions. After the build process I can no longer import and execute functions from my tests since they are bundled inside the sw.js file. Is there maybe a way to execute tests in the context of the service-worker or any other workarround?
What about integration tests? According to this medium post there seems to be a lot of ways to write integration tests. Is there any preferred way for this addon?

Thank you in advance

Add tests for build process

Going to add to this issue as I see needs.

  1. checking that ROOT_URL is replaced appropriately.
    per #132
  2. checking for correct values to ensure not removed by rollup dead code removal (see conversation #125)

SW Invalidation Wish List

Developing with SWs is a difficult experience. I believe that we can do better. There are two specific changes that I believe can help improve this experience.

CLI Flag

Setting an explicit flag with ember s to completely disable the SW all together would be best. I believe if something like EMBER_SW=false is present on process.env then the SW should simply render as:

registration.unregister();

This would of course force the SW to not only run but also unregister its previous incarnation so that any lingering caches are invalidated.

Development Rebuilds

During development making changes to the add triggers a rebuild. This can lead to a difficult experience as it means you have to do a hard refresh in the browser. But the previous cached items are still there. So you can empty the cache or delete the SW.

It would be a better experience if during the development environment the SW is versioned to a datetime value of the last rebuild. Or maybe this is yet another strategy that is a default for dev. This would result in the SW re-registering itself after each rebuild.

{{ROOT_URL}} not getting replaced during build on Windows when the code is on drive D:\

Basically the same as #125 but under a certain scenario. The thing is that I use Windows and I keep my code on the D:\ drive. Ember 3.5 uses the drive where the TEMP folder is (in most cases C:).

The rollup plugin doesn't perform the transformation here because it fails to match the glob expression, which after a path.resolve() call deep down there it contains the drive letter, i.e. the /**/ember-service-worker/**/*.js becomes smt. like D:/**/ember-service-worker/**/*.js.

The fix comes next

Build Error (UglifyWriter)

Build Error (UglifyWriter)

Unexpected token: name (SUCCESS_HANDLERS)

I did some investigation and found that it could be this [email protected]. I believe this version is still using uglifyjs where it doesn't recognize ES6 syntax.

ember-cli-uglify has migrated to using terserjs, where it's a fork of uglifyjs that can recognize new ES6 syntax.

Please consider upgrading to the latest 2.2.0

Flag to disable?

Hi, is there an environment flag or similar that could kill the service-worker?

Working with a service-worker in development isn't always fun :)

esw + fastboot + prember

I'm having an issue where when I refresh the page and have the dev tools closed, when I visit /chat the / route flashes first. If I have the dev tools open, /chat is what is rendered right away.

my ember-cli-build.js https://gitlab.com/NullVoxPopuli/emberclear/blob/master/packages/frontend/ember-cli-build.js

relevant bits:

 let app = new EmberApp(defaults, {
    prember: {
      enabled: isProduction,
      urls: [
        '/',
        '/faq',
        '/chat',
        '/setup',
        '/login',
      ],
    },
    'esw-index': {
      includeScope: [
        /\//,
        /\/faq(\/.*)?/,
        /\/chat(\/.*)?/,
        /\/setup(\/.*)?/,
        /\/login(\/.*)?/,
        /translations/,
      ]
    },
    'esw-cache-fallback': { patterns: ['/'], version: '1' },
  });

in my chrome dev tools, I do have "Update on reload" and "Bypass for network" checked.
It seems that Bypass for network is what is allowing the correct page to be fetched upon refetch.

So, I assume that the service worker isn't fetching my prember'd /chat route? did I misconfigure something?

my dist folder looks like:

assets/...
chat/index.html
faq/index.html
...

RFC: Make registration pluggable.

Extract lib/registration.js to live inside of a plugin. This will allow various configurations for registration.

One specific example that I need/want is to be able to check the service worker after installation to ensure that it matches the running application. This prevents massive self-trollage when developing applications locally where a service worker could have been registered for http://localhost:4200 by project-a, then you switch to project-b and you are completely hosed. I have a working prototype of this in this branch, but if I have a different registration then I would imagine that others may as well.

If there are no objections, I'll extract the current registration system into ember-service-worker-basic-registration and my version into ember-service-worker-project-entangled-registration (naming sucks).

App not building after installing ember-service-worker

After running ember install ember-service-worker, my app fails to build. I'm not really getting much in terms of console output, but this is what I see:

Could not start watchman
Visit https://ember-cli.com/user-guide/#watchman for more info.
DEPRECATION: Addon files were detected in `/Users/caseyjenks/sites/fitbot-client/node_modules/ember-inject-script/addon`, but no JavaScript preprocessors were found for `ember-inject-script`. Please make sure to add a preprocessor (most likely `ember-cli-babel`) to in `dependencies` (NOT `devDependencies`) in `ember-inject-script`'s `package.json`.
Warning: failed to stat /Users/caseyjenks/sites/fitbot-client/tmp/autoprefixer_filter-tmp_dest_dir-2PQnDGhJ.tmp/assets/failed.png

The deprecation warning shows up in master branch of the project, but the Warning: failed to stat... is new.

Any ideas?

Version: 0.6.12

Documentation/Recipe around integrating/interfacing ember-service-worker with an Ember Service.

For context, I'm looking to use ember-service-worker to facilitate push notifications using the PushSubscription API.

My app has a service which is responsible for maintaining user session information, and I would like to expose that session service to the service worker, so that it can map push subscriptions to a specific user. I imagine this is a fairly common pattern for folks who are looking to use service workers for the purpose of push subscriptions, however the documentation seems geared solely towards using service workers for the purpose of making apps offline first.

Safari Version 11.1 (13605.1.33.1.2) is bombing out with ember SW apps

Examples: https://dockyard.com, https://hightide.earth

Steps to reproduce:

  1. Use Safari 11.1
  2. Clear caches
  3. Visit either app from above

You will see something like

screen shot 2018-05-26 at 6 20 31 pm

If you disable Service Workers the apps load as expected. This issue appears to be resolved in the WebKit nightly, however other Service Worker enabled apps that aren't ember-service-worker are not having this problem which leads me to believe that this is somehow isolated to esw.

Unfortunately Safari is not giving any additional information than the screen shot from above. There is nothing in the console or the network tab that may explain why this extreme error is happening.

This feels like a critical bug and should be prioritized, even though future versions of WebKit appear to be working this is a current production issue for all esw enabled apps with Safari visitors.

Holistic approach to fetch settings

Most SW plugins make fetch calls and there is a need to enable authorization to be sent. This seems like something that should be configured rather than defaulted, but it applies to many different plugins. Rather than having a configuration per plugin that has the application developer repeat, it may make sense to have some sort of fetch init configuration specified in the the overall service worker addon. In some ways I could also see this as an odd choice from a purist standpoint because it isn't used by the SW addon directly. The original PR that triggered this is DockYard/ember-service-worker-cache-fallback#9

Creating this issue as a place to discuss pros/cons....

ember-cli-babel deprecation warning

Hi guys,

[email protected]
[email protected]
[email protected]
[email protected]
[email protected]

Just wanted to let you know I'm getting the following deprecation message using the above versions:

DEPRECATION: ember-cli-babel 5.x has been deprecated. Please upgrade to at least ember-cli-babel 6.6. Version 5.2.8 located: (project name redacted) -> ember-service-worker -> ember-cli-babel

Figured I'd start an issue so you can track the fix. No rush! Thanks for a great plugin.

Feature: inline sw-registration.js

Hi, now that we're in the business of optimizing everything, would it make sense to inline the sw-registration.js file in index.html?

On 3G the request for the file is around 250ms 🥇

Allow url patterns from other origins

Hi there,

The issue I'm facing is actually with the ember-service-workers-cache-fallback package, but the utils originate here.

Currently, all the patterns provided in the EmberApp configuration are mapped with createUrlRegEx from the ember-service-workers package. As part of createUrlRegEx the pattern is then passed through createNormalizedUrl which, by default, prepends the url with the baseUrl of self.location. This effectively means it will only cache responses from the same origin.

In some projects, and in development an api call will be made to a different origin but in this case it cannot be cached with this addon.

Would we be able decouple createUrlRegEx from createNormalizedUrl so there is less restriction on api response caching?

Let me know if you would not like this to happen otherwise, I'm happy to submit a PR for it.

Cheers!
Dylan

Is there a way to have a custom service worker communicate with the ember app?

Let's say I want to have a service worker control a websocket or webRTC connection -- could I have my ember app push messages to the service worker, and receive messages back from it so I can interact with ember-data?

I'm wanting to use a service worker for a persistent background connection on mobile devices. I know Web Workers have pushing of messages between scripts, but I don't know if they keep running when the app is not in focus / closed.

Why no fingerprinting?

All of my assets are fingerprinted and prefixed with the CDN address. Is there a reason why the sw.js and sw-registion.js are excluded?

Test against multiple versions of sample app

Find a way to utilize ember-try (or be inspired by it) to test against multiple versions of ember. It appears that the only customization to the fixture sample app is the lib in-repo-addon to install test service worker plugins.

Will not allow empty sting as rootURL

in the index.js, it finds the settings for the rootURL. However, it only looks to see if they are truthy or not. So for an app that has its rootURL at '', it actually sets it to '/'

Deprecation Warning in Ember 2.18

I'm experimenting with PWA, thanks for the great work! I thought I'd share this deprecation I got on a fresh install:

DEPRECATION: An addon is trying to access project.nodeModulesPath. This is not a reliable way to discover npm modules. Instead, consider doing: require("resolve").sync(something, { basedir: project.root }). Accessed from:   new NPMDependencyVersionChecker (/.../node_modules/ember-service-worker/node_modules/ember-cli-version-checker/src/npm-dependency-version-checker.js:11:33)

Version 0.7.2 breaks Glimmer.js app

We used ember-service-worker with our Glimmer.js app and it just worked fine with version v0.6.2 now we tried to upgrade to the newest version which is currently v0.7.2 but this upgrade broke our build. This is due to the fact, that Glimmer.js has not installed ember-cli-babel and therefore the following code breaks:

_babelTranspile(tree) {

On the other hand adding ember-cli-babel breaks our Glimmer.js build. So I'm not sure how to resolve this issue.

I know that Ember.js is not Glimmer.js and therefore I'm not sure if this is an issue with ember-service-worker or a Glimmer.js issue. Nevertheless it would be great to share as much addons and plugins as possible between Ember.js and Glimmer.js

Just let me know what you think about this issue

still unsafe?

Is the statement on the README still the situation?

Do not use this in production right now, you will troll your users and they will be unable to use your app.

If it is, is there any feeling for a rough timeframe this might be addressed?

Provide documentation for application service worker

There doesn't seem to be any documentation for the feature outlined in the issue #18, I mentioned it in the issue it self but I feel like tracking that as an issue may be easier if I create a seperate issue.

I've read the documentation a couple of times, but I can't seem to locate any mention of this feature, but I get the feeling there was documentation for this at some point, so if there's a git hash that can be pointed out I'd be happy to make a PR to pull it into the current documentation.

First try

I installed:
ember install ember-service-worker-asset-cache
ember install ember-service-worker-cache-fallback
ember install ember-service-worker-cache-first

First:
404 Not Found GET http://localhost/sw.js
404 Not Found GET http://localhost/sw-registration.js

Changing
<script src="/sw-registration.js"></script>
to
<script src="sw-registration.js"></script>

and changing navigator.serviceWorker.register('/sw.js', without /

I don't have my dist folder served at localhost/

Running ember serve:
No name was provided for external module 'ember-service-workers/service-worker' in options.globals – guessing 'emberServiceWorkers_serviceWorker'

New error :S

Document `addEventListener` in README.

Looks like self.addFetchListener is used in the various pre-built plugins, but is not documented in the README so I am unsure if this is intended as public API or just an internal private API for use by "first party" addons.

CSS Hot Reload is Broken

When using Ember service worker anytime a scss file changes sw.js changes and i think this causes a full page reload

Build successful (4967ms) – Serving on http://localhost:8088/
  ember-cli:live-reload: files %a [ 'index.html', 'sw.js', 'tests/index.html' ] +19m

RFC: Middleware design

Summary

Managing many Service Worker event handlers isolated from each other will require middleware to effectively handle that.

Design

A service worker plugin should at least have a index module that exports a JavaScript object, that object should have event handlers as properties named after the event that it desires to handler (e.g. fetch, install).

Event handler functions should receive the event object as the first argument. Event handlers should return a promise or undefined. Event handlers should not call waitUntil, the middleware layer should be responsible for calling waitUntil when a event handler returns a promise. This also goes for fetch event handlers, they should not call respondWith themselves, the middleware should call respondWith when one of the fetch event handlers' promise resolves to a response.

An example:

const CACHE_NAME = 'my-cache-v1';
const ASSETS = [
  'index.html',
  '/assets/app.js',
  '/assets/vendor.js',
  '/assets/app.css',
  '/assets/vendor.css'
];

export default {
  install() {
    return caches
      .open(CACHE_NAME)
      .then((cache) => cache.addAll(ASSETS));
  },

  afterInstall() {
    self.skipWaiting();
  },

  fetch(event) {
    return caches.match(event.request, { cacheName: CACHE_NAME });
  }
}

Middleware behaviour

The middleware layer should register one listener for each event using ServiceWorkerGlobalScope.addEventListener, when one of those registered listeners is triggered, it should in turn call all other handlers from the modules from the service worker plugins. The behaviour specification per event type is specified below.

Activate, Install

The activate and install handler should execute all handlers at once and then wrap all returned promises by the handlers in a Promise.all call and use that promise to call event.waitUntil.

Service worker plugins should be able to register a afterActivate, afterInstall hook. These hooks should be executed after all the main handlers are resolved.

Example simplified implementation of the install middleware handler:

self.addEventListener('install', (event) => {
  let promises = serviceWorkerPlugins.map((plugin) => {
     if (plugin.install) {
        return plugin.install(event);
     }
  });

  event.waitUntil(promises);

  promises.then(() => {
    serviceWorkerPlugins.map((plugin) => {
      if (plugin.afterInstall) {
        plugin.afterInstall();
      }
    });
  });
});

Fetch

The fetch handler should execute all handlers one by one. It should execute one handler, wait for the promise to resolve (if returned), then either call event.respondWith if the handler resolves to a response or execute the next hander.

Example simplified implementation of the fetch middleware handler:

self.addEventListener('fetch', (event) {
  let fetchHandlers = serviceWorkerPlugins.reduce((handlers, plugin) => {
     if (plugin.fetch) {
        handlers.push(plugin.fetch);
     }

    return handlers;
  }, []);

  let resolveHandler = (resolve, reject, index) => {
    if (!index) {
      index = 0;
    }

     if (index >= fetchHandlers.length) {
        return;
     }

     fetchHandlers[index](event)
        .then((response) => {
           if (response) {
             return resolve(response);
           } else {
             return resolveHandler(resolve, reject, index + 1);
           }
        })
        .catch(reject);
  };

  new Promise(resolveHandler)
     .then((response) => {
        if (response) {
           event.respondWith(response);
        }
    });
});

All other events

As far as I know all other events are synchronous and thus the handlers can just be executed one by one, without any promise semantics.

Explore using GoogleChrome/sw-helpers

(Moving the conversation from https://twitter.com/Martndemus/status/828688823634767872)

Google's Web DevRel team has been working on a collection of small modules that when used together constitute a full-featured service worker framework: https://github.com/GoogleChrome/sw-helpers/

There are a few different categories of modules there—some provide some basic building blocks, like routing and runtime caching strategies, and I think those overlap a bit with what you've already developed. If you have solutions that already work well for Ember apps, then those modules wouldn't necessarily add in additional value.

Others, though, could be useful if they were exposed to the ember-service-worker audience, most likely with a lightweight wrapper that help them tie in to your request and caching lifecycle.

There's also sw-precaching, that takes in a manifest of URLs and hashes, and manages cache entries.

If there is functionality covered by any of those modules that you'd find useful within your framework, we're happy to walk through what the integration points are for each of the modules. Our documentation is very much a work in progress, so it might not be obvious from reading that alone.

CC: @addyosmani @gauntface

Uncaught ReferenceError: ESW_INLINE_PLACEHOLDER is not defined

When I set registrationStrategy to inline, my test fails with:

"Uncaught ReferenceError: ESW_INLINE_PLACEHOLDER is not defined"

My config:

'ember-service-worker': {
  enabled: true,
  versionStrategy: 'every-build',
  registrationStrategy: 'inline'
},

Ember-cli 2.17.1

How to configure path to sw.js when using CDN

Using ember-cli-deploy I'm fingerprinting my assets and prefixing with https://subdomain.cloudfront.net.

I understand fingerprinting sw.js will break the service worker update mechanism so it makes sense to disable fingerprinting that file, however I would still like it to retain the CDN prefix.
Can anyone recommend the best way to do this?

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.