dockyard / ember-service-worker Goto Github PK
View Code? Open in Web Editor NEWA pluggable approach to Service Workers for Ember.js
Home Page: http://ember-service-worker.com
License: MIT License
A pluggable approach to Service Workers for Ember.js
Home Page: http://ember-service-worker.com
License: MIT License
I am testing this addon on https://bloggr.exmer.com but each time I deploy I also have to clear the SW in Chrome before the Bloggr App works again. Since there are no issues reported on this behavior I was wondering if someone can hint where to look. Source: https://github.com/broerse/ember-cli-blog
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.
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.
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.
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.
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.
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 :)
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?
See: https://www.youtube.com/watch?v=1V10bgdIp2M
When the service worker is running and assets are cached a reload of a non-landing page will cause the app landing page to blink. Deleting the service worker temporarily fixes the problem but after the assets are cached again the problem is back.
I don't know if this is an actual service worker issue or how Ember is rendering based upon available assets.
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
_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.
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
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:
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
If you had a gh-pages for it, I would like to at least look and see how hard it would be to see do both of these things and then PR.
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)
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.
Managing many Service Worker event handlers isolated from each other will require middleware to effectively handle that.
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 });
}
}
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.
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();
}
});
});
});
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);
}
});
});
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.
Currently it is imposible. But in ember if no rootURL is defined assets inserted with relative url.
I think "last resort" should be '' but not '/' here https://github.com/DockYard/ember-service-worker/blob/master/index.js#L144
PS. I have a project with no deterministic root url. Just imagine a 'skel' with symlinks to it, and logic depends of result url.
Anyway I implemented SW by my own (with 'scope':'./'), but it is big mistake to restrict relative urls...
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).
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....
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?
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
This would allow for small project level tweaks/experimentation to be done in the project itself.
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
See: #86 (comment)
Also related: #84
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
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
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.
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
On the service-worker-registration.js
Delay registration until after the page has loaded, to ensure that our precaching requests don't degrade the first visit experience.
See https://developers.google.com/web/fundamentals/instant-and-offline/service-worker/registration they recommend doing this so...
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('/service-worker.js');
});
}
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.
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
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 🥇
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
...
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?
The ember-cli-babel dependency should be updated to the latest version to allow consuming apps to drop ember-cli-shims as a dependency of ember 2.16+ apps.
https://www.emberjs.com/blog/2017/11/20/ember-2-17-released.html#toc_changes-in-ember-cli-2-17
(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.
sw-background-sync-queue
, for queueing and retrying failed requests via the sync
event.sw-broadcast-cache-update
, to announce changes to cached entries.sw-cache-expiration
, to automatically expire runtime caches entries based on maximum size or age criteria.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.
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 '/'
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.
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}}"}).
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.
@martndemus would you mind cutting a bugfix release with these: f13a7e0#diff-65a8cac6085d6a16feee20105f04e29f changes? I'm getting an error when the service worker is trying to register.
Examples: https://dockyard.com, https://hightide.earth
Steps to reproduce:
You will see something like
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.
According to this Google documentation regarding the SW lifecycle sw updates are checked once every 24 hours. Is there a way to force the update and/or changing the max-age
value?
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!
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.
For example:
var app = new EmberAddon(defaults, {
'ember-service-worker': {
immediateClaim: false
}
});
This should inject
const IMMEDIATE_CLAIM = false
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.