UNPKG

2.68 kBJavaScriptView Raw
1/*
2 * init-opts.js
3 *
4 * async initOpts(cb) interface used by clientside _generator.js
5 * invokes $.getJSON to fetch opts (with in-line serialized data) and plugins
6 * if necessary fetch access token(s) from gatekeeper
7 * possibly by directing browser to gatekeeper for auth roundabout
8 * TODO: implement a mechanism to force re-authentication (logout gatekeeper)
9 *
10 * copyright 2015-2020, Jürgen Leschner - github.com/jldec - MIT license
11*/
12
13/* global $ */
14/* global pubRef */
15
16var dbg = require('debug');
17var debug = dbg('pub:generator');
18var asyncbuilder = require('asyncbuilder');
19var u = require('pub-util');
20
21require('pub-src-github'); // dummy require for browserify
22
23module.exports = function initOpts(cb) {
24 cb = u.onceMaybe(cb);
25
26 var staticRoot = location.pathname.slice(0, location.pathname.indexOf(pubRef.href));
27 debug('initOpts staticRoot: "' + staticRoot + '"');
28
29 $.getJSON(staticRoot + '/pub/_opts.json')
30 .fail(function(jqXHR) { cb(new Error(jqXHR.responseText)); })
31 .done(function(respData) {
32
33 // opts includes source.file data for all sources
34 // see pub-server serve-scripts
35 var opts = respData;
36
37 // inject runtime-inferred staticRoot into opts
38 opts.staticRoot = staticRoot;
39
40 // enable debug tracing on client
41 dbg.enable(opts.dbg);
42
43 var ab = asyncbuilder(function(err) { cb(err, opts); });
44
45 // recreate opts.source$ map (not serialized)
46 // and initialize credentials for writable static sources
47 opts.source$ = {};
48
49 opts.sources.forEach(function(source) {
50 opts.source$[source.name] = source;
51
52 // connect to static editor sources: github or dropbox
53 if (opts.staticHost && source.staticSrc) {
54 if (source.gatekeeper) {
55 var append = ab.asyncAppend();
56 debug('authenticating ' + source.gatekeeper);
57 $.getJSON(source.gatekeeper + '/status' + location.search)
58 .fail(function(jqXHR) { append(new Error(jqXHR.responseText)); })
59 .done(function(status) {
60
61 // if not logged in, send browser to gatekeeper for oauth
62 if (!status || !status.access_token) {
63 location.assign(source.gatekeeper +
64 '?ref=' + encodeURIComponent(location.href));
65 }
66 // finally we can create the source adapter to save to
67 else {
68 source.auth = status;
69 source.src = require(source.staticSrc)(source);
70 }
71 debug(status);
72 append(status);
73 });
74 }
75 }
76 });
77 ab.complete();
78
79 });
80};