@webqit/webflo 0.11.61-0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/.gitignore +7 -7
  2. package/LICENSE +20 -20
  3. package/README.md +2079 -2074
  4. package/docker/Dockerfile +42 -42
  5. package/docker/README.md +91 -91
  6. package/docker/package.json +2 -2
  7. package/package.json +80 -81
  8. package/src/{Context.js → AbstractContext.js} +71 -79
  9. package/src/config-pi/deployment/Env.js +68 -68
  10. package/src/config-pi/deployment/Layout.js +63 -63
  11. package/src/config-pi/deployment/Origins.js +139 -139
  12. package/src/config-pi/deployment/Proxy.js +74 -74
  13. package/src/config-pi/deployment/index.js +17 -17
  14. package/src/config-pi/index.js +15 -15
  15. package/src/config-pi/runtime/Client.js +116 -98
  16. package/src/config-pi/runtime/Server.js +125 -125
  17. package/src/config-pi/runtime/client/Worker.js +109 -134
  18. package/src/config-pi/runtime/client/index.js +11 -11
  19. package/src/config-pi/runtime/index.js +17 -17
  20. package/src/config-pi/runtime/server/Headers.js +74 -74
  21. package/src/config-pi/runtime/server/Redirects.js +69 -69
  22. package/src/config-pi/runtime/server/index.js +13 -13
  23. package/src/config-pi/static/Manifest.js +319 -319
  24. package/src/config-pi/static/Ssg.js +49 -49
  25. package/src/config-pi/static/index.js +13 -13
  26. package/src/deployment-pi/index.js +10 -10
  27. package/src/deployment-pi/origins/index.js +216 -216
  28. package/src/index.js +11 -19
  29. package/src/runtime-pi/HttpEvent.js +126 -106
  30. package/src/runtime-pi/HttpUser.js +126 -0
  31. package/src/runtime-pi/MessagingOverBroadcast.js +9 -0
  32. package/src/runtime-pi/MessagingOverChannel.js +85 -0
  33. package/src/runtime-pi/MessagingOverSocket.js +106 -0
  34. package/src/runtime-pi/MultiportMessagingAPI.js +81 -0
  35. package/src/runtime-pi/WebfloCookieStorage.js +27 -0
  36. package/src/runtime-pi/WebfloEventTarget.js +39 -0
  37. package/src/runtime-pi/WebfloMessageEvent.js +58 -0
  38. package/src/runtime-pi/WebfloMessagingAPI.js +69 -0
  39. package/src/runtime-pi/{Router.js → WebfloRouter.js} +99 -130
  40. package/src/runtime-pi/WebfloRuntime.js +52 -0
  41. package/src/runtime-pi/WebfloStorage.js +109 -0
  42. package/src/runtime-pi/client/ClientMessaging.js +5 -0
  43. package/src/runtime-pi/client/Context.js +3 -7
  44. package/src/runtime-pi/client/CookieStorage.js +17 -0
  45. package/src/runtime-pi/client/Router.js +38 -48
  46. package/src/runtime-pi/client/SessionStorage.js +33 -0
  47. package/src/runtime-pi/client/Url.js +156 -205
  48. package/src/runtime-pi/client/WebfloClient.js +544 -0
  49. package/src/runtime-pi/client/WebfloRootClient1.js +179 -0
  50. package/src/runtime-pi/client/WebfloRootClient2.js +109 -0
  51. package/src/runtime-pi/client/WebfloSubClient.js +165 -0
  52. package/src/runtime-pi/client/Workport.js +118 -178
  53. package/src/runtime-pi/client/generate.js +480 -471
  54. package/src/runtime-pi/client/index.js +16 -21
  55. package/src/runtime-pi/client/worker/ClientMessaging.js +5 -0
  56. package/src/runtime-pi/client/worker/Context.js +3 -7
  57. package/src/runtime-pi/client/worker/CookieStorage.js +17 -0
  58. package/src/runtime-pi/client/worker/SessionStorage.js +13 -0
  59. package/src/runtime-pi/client/worker/WebfloWorker.js +294 -0
  60. package/src/runtime-pi/client/worker/Workport.js +17 -85
  61. package/src/runtime-pi/client/worker/index.js +10 -21
  62. package/src/runtime-pi/index.js +6 -13
  63. package/src/runtime-pi/server/ClientMessaging.js +18 -0
  64. package/src/runtime-pi/server/ClientMessagingRegistry.js +57 -0
  65. package/src/runtime-pi/server/Context.js +11 -15
  66. package/src/runtime-pi/server/CookieStorage.js +17 -0
  67. package/src/runtime-pi/server/Router.js +93 -159
  68. package/src/runtime-pi/server/SessionStorage.js +53 -0
  69. package/src/runtime-pi/server/WebfloServer.js +755 -0
  70. package/src/runtime-pi/server/index.js +10 -21
  71. package/src/runtime-pi/util-http.js +322 -86
  72. package/src/runtime-pi/util-url.js +146 -146
  73. package/src/runtime-pi/xURL.js +108 -105
  74. package/src/runtime-pi/xfetch.js +22 -22
  75. package/src/services-pi/cert/http-auth-hook.js +22 -22
  76. package/src/services-pi/cert/http-cleanup-hook.js +22 -22
  77. package/src/services-pi/cert/index.js +79 -79
  78. package/src/services-pi/index.js +8 -8
  79. package/src/static-pi/index.js +10 -10
  80. package/src/webflo.js +30 -30
  81. package/test/index.test.js +26 -26
  82. package/test/site/package.json +9 -9
  83. package/test/site/public/bundle.html +5 -5
  84. package/test/site/public/bundle.html.json +3 -3
  85. package/test/site/public/bundle.js +2 -2
  86. package/test/site/public/bundle.webflo.js +15 -15
  87. package/test/site/public/index.html +29 -29
  88. package/test/site/public/index1.html +34 -34
  89. package/test/site/public/page-2/bundle.html +4 -4
  90. package/test/site/public/page-2/bundle.js +2 -2
  91. package/test/site/public/page-2/index.html +45 -45
  92. package/test/site/public/page-2/main.html +2 -2
  93. package/test/site/public/page-4/subpage/bundle.js +2 -2
  94. package/test/site/public/page-4/subpage/index.html +30 -30
  95. package/test/site/public/sparoots.json +4 -4
  96. package/test/site/public/worker.js +3 -3
  97. package/test/site/server/index.js +15 -15
  98. package/src/runtime-pi/Application.js +0 -29
  99. package/src/runtime-pi/Cookies.js +0 -82
  100. package/src/runtime-pi/Runtime.js +0 -21
  101. package/src/runtime-pi/client/Application.js +0 -100
  102. package/src/runtime-pi/client/Runtime.js +0 -332
  103. package/src/runtime-pi/client/createStorage.js +0 -57
  104. package/src/runtime-pi/client/oohtml/full.js +0 -7
  105. package/src/runtime-pi/client/oohtml/namespacing.js +0 -7
  106. package/src/runtime-pi/client/oohtml/scripting.js +0 -8
  107. package/src/runtime-pi/client/oohtml/templating.js +0 -8
  108. package/src/runtime-pi/client/worker/Application.js +0 -44
  109. package/src/runtime-pi/client/worker/Runtime.js +0 -269
  110. package/src/runtime-pi/server/Application.js +0 -116
  111. package/src/runtime-pi/server/Runtime.js +0 -557
  112. package/src/runtime-pi/xFormData.js +0 -24
  113. package/src/runtime-pi/xHeaders.js +0 -146
  114. package/src/runtime-pi/xRequest.js +0 -46
  115. package/src/runtime-pi/xRequestHeaders.js +0 -109
  116. package/src/runtime-pi/xResponse.js +0 -33
  117. package/src/runtime-pi/xResponseHeaders.js +0 -117
  118. package/src/runtime-pi/xxHttpMessage.js +0 -102
@@ -1,269 +0,0 @@
1
-
2
- /**
3
- * @imports
4
- */
5
- import { _any } from '@webqit/util/arr/index.js';
6
- import { Observer } from '@webqit/oohtml-ssr/apis.js';
7
- import { pattern } from '../../util-url.js';
8
- import Workport from './Workport.js';
9
- import _Runtime from '../../Runtime.js';
10
- import xRequest from "../../xRequest.js";
11
- import xResponse from "../../xResponse.js";
12
- import xfetch from '../../xfetch.js';
13
- import HttpEvent from '../../HttpEvent.js';
14
-
15
- export {
16
- HttpEvent,
17
- Observer,
18
- }
19
-
20
- /**
21
- * ---------------------------
22
- * The Runtime Initializer
23
- * ---------------------------
24
- */
25
-
26
- export default class Runtime extends _Runtime {
27
-
28
- /**
29
- * Runtime
30
- *
31
- * @param Object cx
32
- * @param Function applicationInstance
33
- *
34
- * @return void
35
- */
36
- constructor(cx, applicationInstance) {
37
- super(cx, applicationInstance);
38
- // ---------------
39
- this.mockSessionStore = {};
40
- // --------------
41
- // ONINSTALL
42
- self.addEventListener('install', evt => {
43
- if (this.cx.params.skip_waiting) { self.skipWaiting(); }
44
- // Manage CACHE
45
- if (this.cx.params.cache_name && (this.cx.params.cache_only_urls || []).length) {
46
- // Add files to cache
47
- evt.waitUntil( self.caches.open(this.cx.params.cache_name).then(cache => {
48
- if (this.cx.logger) { this.cx.logger.log('[ServiceWorker] Pre-caching resources.'); }
49
- const cache_only_urls = (this.cx.params.cache_only_urls || []).map(c => c.trim()).filter(c => c && !pattern(c, self.origin).isPattern());
50
- return cache.addAll(cache_only_urls);
51
- }) );
52
- }
53
- });
54
-
55
- // -------------
56
- // ONACTIVATE
57
- self.addEventListener('activate', evt => {
58
- evt.waitUntil( new Promise(async resolve => {
59
- if (this.cx.params.skip_waiting) { await self.clients.claim(); }
60
- // Manage CACHE
61
- if (this.cx.params.cache_name) {
62
- // Clear outdated CACHES
63
- await self.caches.keys().then(keyList => {
64
- return Promise.all(keyList.map(key => {
65
- if (key !== this.cx.params.cache_name && key !== this.cx.params.cache_name + '_json') {
66
- if (this.cx.logger) { this.cx.logger.log('[ServiceWorker] Removing old cache:', key); }
67
- return self.caches.delete(key);
68
- }
69
- }));
70
- })
71
- }
72
- resolve();
73
- }) );
74
- });
75
-
76
- // ---------------
77
- Observer.set(this, 'location', {});
78
- Observer.set(this, 'network', {});
79
- // ---------------
80
- Observer.observe(this.network, es => {
81
- //console.log('//////////', ...es.map(e => `${e.name}: ${e.value}`))
82
- });
83
-
84
- // -------------
85
- // ONFETCH
86
- self.addEventListener('fetch', event => {
87
- // URL schemes that might arrive here but not supported; e.g.: chrome-extension://
88
- if (!event.request.url.startsWith('http')) return;
89
- event.respondWith((async evt => {
90
- let requestingClient = await self.clients.get(evt.clientId);
91
- this.workport.setCurrentClient(requestingClient);
92
- const [ url, requestInit ] = await xRequest.rip(evt.request);
93
- // Now, the following is key:
94
- // The browser likes to use "force-cache" for "navigate" requests, when, e.g: re-entering your site with the back button
95
- // Problem here, force-cache forces out JSON not HTML as per webflo's design.
96
- // So, we detect this scenerio and avoid it.
97
- if (requestInit.cache === 'force-cache'/* && evt.request.mode === 'navigate' - even webflo client init call also comes with that... needs investigation */) {
98
- requestInit.cache = 'default';
99
- }
100
- return this.go(url, requestInit, { event: evt });
101
- })(event));
102
- });
103
-
104
- // -------------
105
- // Workport
106
- const workport = new Workport();
107
- Observer.set(this, 'workport', workport);
108
-
109
- // -------------
110
- // Initialize
111
- (async () => {
112
- if (!this.app.init) return;
113
- const request = this.generateRequest('/');
114
- const httpEvent = new HttpEvent(request, { srcType: 'initialization' }, (id = null, persistent = false) => this.getSession(httpEvent, id, persistent));
115
- await this.app.init(httpEvent, ( ...args ) => this.remoteFetch( ...args ));
116
- })();
117
-
118
- }
119
-
120
- /**
121
- * Performs a request.
122
- *
123
- * @param object|string url
124
- * @param object|Request init
125
- * @param object detail
126
- *
127
- * @return Response
128
- */
129
- async go(url, init = {}, detail = {}) {
130
- // ------------
131
- url = typeof url === 'string' ? new URL(url, self.location.origin) : url;
132
- if (!(init instanceof Request) && !init.referrer) {
133
- init = { referrer: this.location.href, ...init };
134
- }
135
- // ------------
136
- // The request object
137
- const request = this.generateRequest(url.href, init);
138
- if (detail.event) { Object.defineProperty(detail.event, 'request', { value: request }); }
139
- // The navigation event
140
- const httpEvent = new HttpEvent(request, detail, (id = null, persistent = false) => this.getSession(httpEvent, id, persistent));
141
- httpEvent.port.listen(message => {
142
- if (message.$type === 'handler:hints' && message.session) {
143
- // TODO: Sync session data from client
144
- return Promise.resolve();
145
- }
146
- });
147
- // Response
148
- let response;
149
- if (httpEvent.request.url.startsWith(self.origin)/* && httpEvent.request.mode === 'navigate'*/) {
150
- response = await this.app.handle(httpEvent, ( ...args ) => this.remoteFetch( ...args ));
151
- } else {
152
- response = await this.remoteFetch(httpEvent.request);
153
- }
154
- const finalResponse = await this.handleResponse(httpEvent, response);
155
- // Return value
156
- return finalResponse;
157
- }
158
-
159
- // Generates request object
160
- generateRequest(href, init = {}) {
161
- const request = new xRequest(href, init);
162
- return request;
163
- }
164
-
165
- // Generates session object
166
- getSession(e, id = null, persistent = false) {
167
- return {
168
- get: () => this.mockSessionStore,
169
- set: value => { this.mockSessionStore = value },
170
- };
171
- }
172
-
173
- // Initiates remote fetch and sets the status
174
- remoteFetch(request, ...args) {
175
- if (arguments.length > 1) {
176
- request = this.generateRequest(request, ...args);
177
- }
178
- const matchUrl = (patterns, url) => _any((patterns || []).map(p => p.trim()).filter(p => p), p => pattern(p, self.origin).test(url));
179
- const execFetch = () => {
180
- // network_first_urls
181
- if (!this.cx.params.default_fetching_strategy || this.cx.params.default_fetching_strategy === 'network-first' || matchUrl(this.cx.params.network_first_urls, request.url)) {
182
- Observer.set(this.network, 'strategy', 'network-first');
183
- return this.networkFetch(request, { cacheFallback: true, cacheRefresh: true });
184
- }
185
- // cache_first_urls
186
- if (this.cx.params.default_fetching_strategy === 'cache-first' || matchUrl(this.cx.params.cache_first_urls, request.url)) {
187
- Observer.set(this.network, 'strategy', 'cache-first');
188
- return this.cacheFetch(request, { networkFallback: true, cacheRefresh: true });
189
- }
190
- // network_only_urls
191
- if (this.cx.params.default_fetching_strategy === 'network-only' || matchUrl(this.cx.params.network_only_urls, request.url)) {
192
- Observer.set(this.network, 'strategy', 'network-only');
193
- return this.networkFetch(request, { cacheFallback: false, cacheRefresh: false });
194
- }
195
- // cache_only_urls
196
- if (this.cx.params.default_fetching_strategy === 'cache-only' || matchUrl(this.cx.params.cache_only_urls, request.url)) {
197
- Observer.set(this.network, 'strategy', 'cache-only');
198
- return this.cacheFetch(request, { networkFallback: false, cacheRefresh: false });
199
- }
200
- };
201
- let response = execFetch(request);
202
- // This catch() is NOT intended to handle failure of the fetch
203
- response.catch(e => Observer.set(this.network, 'error', e.message));
204
- // Return xResponse
205
- return response.then(_response => xResponse.compat(_response));
206
- }
207
-
208
- // Caching strategy: network_first
209
- networkFetch(request, params = {}) {
210
- if (!params.cacheFallback) {
211
- Observer.set(this.network, 'remote', true);
212
- return xfetch(request);
213
- }
214
- return xfetch(request).then(response => {
215
- if (params.cacheRefresh) this.refreshCache(request, response);
216
- Observer.set(this.network, 'remote', true);
217
- return response;
218
- }).catch(() => this.getRequestCache(request).then(cache => {
219
- Observer.set(this.network, 'cache', true);
220
- return cache.match(request);
221
- }));
222
- }
223
-
224
- // Caching strategy: cache_first
225
- cacheFetch(request, params = {}) {
226
- return this.getRequestCache(request).then(cache => cache.match(request).then(response => {
227
- // Nothing cache, use network
228
- if (!response && params.networkFallback) return this.networkFetch(request, { ...params, cacheFallback: false });
229
- // Note: fetch, but for refreshing purposes only... not the returned response
230
- if (response && params.cacheRefresh) this.networkFetch(request, { ...params, justRefreshing: true });
231
- Observer.set(this.network, 'cache', true);
232
- return response;
233
- }));
234
- }
235
-
236
- // Caches response
237
- refreshCache(request, response) {
238
- // Check if we received a valid response
239
- if (request.method !== 'GET' || !response || response.status !== 200 || (response.type !== 'basic' && response.type !== 'cors')) {
240
- return response;
241
- }
242
- // IMPORTANT: Clone the response. A response is a stream
243
- // and because we want the browser to consume the response
244
- // as well as the cache consuming the response, we need
245
- // to clone it so we have two streams.
246
- var responseToCache = response.clone();
247
- this.getRequestCache(request).then(cache => {
248
- Observer.set(this.network, 'cacheRefresh', true);
249
- cache.put(request, responseToCache);
250
- });
251
- return response;
252
- }
253
-
254
- // Returns either the regular cache or a json-specific cache
255
- getRequestCache(request) {
256
- let cacheName = request.headers.get('Accept') === 'application/json'
257
- ? this.cx.params.cache_name + '_json'
258
- : this.cx.params.cache_name;
259
- return self.caches.open(cacheName);
260
- }
261
-
262
- // Handles response object
263
- handleResponse(e, response) {
264
- if (!response && response !== 0) { response = new xResponse(null, { status: 404 }); }
265
- else if (!(response instanceof xResponse)) { response = xResponse.compat(response); }
266
- return response;
267
- }
268
-
269
- }
@@ -1,116 +0,0 @@
1
-
2
- /**
3
- * imports
4
- */
5
- import Fs from 'fs';
6
- import Path from 'path';
7
- import QueryString from 'querystring';
8
- import Router from './Router.js';
9
- import _Application from '../Application.js';
10
-
11
- export default class Application extends _Application {
12
-
13
- /**
14
- * Application
15
- *
16
- * @param Context cx
17
- */
18
- constructor(cx) {
19
- super(cx);
20
- this.renderFileCache = {};
21
- }
22
-
23
- // Returns router class
24
- get Router() {
25
- return Router;
26
- }
27
-
28
- /**
29
- * Handles navigation events.
30
- *
31
- * @param NavigationEvent httpEvent
32
- * @param Function remoteFetch
33
- *
34
- * @return Response
35
- */
36
- async handle(httpEvent, remoteFetch) {
37
- // The app router
38
- const router = new this.Router(this.cx, httpEvent.url.pathname);
39
- const handle = async () => {
40
- // --------
41
- // ROUTE FOR DATA
42
- // --------
43
- let response = await router.route([httpEvent.request.method, 'default'], httpEvent, {}, async event => {
44
- return router.file(event);
45
- }, remoteFetch);
46
- if (!(response instanceof httpEvent.Response)) {
47
- response = httpEvent.Response.compat(response);
48
- }
49
- // --------
50
- // Rendering
51
- // --------
52
- if (response.ok && response.meta.type === 'json' && typeof response.meta.body === 'object' && response.meta.body && httpEvent.request.headers.accept.match('text/html')) {
53
- let rendering = await this.render(httpEvent, router, response);
54
- if (typeof rendering !== 'string' && !(typeof rendering === 'object' && rendering && typeof rendering.toString === 'function')) {
55
- throw new Error('render() must return a string response or an object that implements toString()..');
56
- }
57
- rendering = rendering.toString();
58
- response = new httpEvent.Response(rendering, {
59
- headers: { ...response.headers.json(), contentType: 'text/html', contentLength: (new Blob([rendering]).size) },
60
- status: response.status,
61
- });
62
- }
63
-
64
- return response;
65
- };
66
- // --------
67
- // PIPE THROUGH MIDDLEWARES
68
- // --------
69
- return (this.cx.middlewares || []).concat(handle).reverse().reduce((next, fn) => {
70
- return () => fn.call(this.cx, httpEvent, router, next);
71
- }, null)();
72
- }
73
-
74
- // Renderer
75
- async render(httpEvent, router, response) {
76
- let data = await response.jsonfy();
77
- let rendering = await router.route('render', httpEvent, data, async (httpEvent, data) => {
78
- var renderFile, pathnameSplit = httpEvent.url.pathname.split('/');
79
- while ((renderFile = Path.join(this.cx.CWD, this.cx.layout.PUBLIC_DIR, './' + pathnameSplit.join('/'), 'index.html'))
80
- && (this.renderFileCache[renderFile] === false/* false on previous runs */ || !Fs.existsSync(renderFile))) {
81
- this.renderFileCache[renderFile] = false;
82
- pathnameSplit.pop();
83
- }
84
- const instanceParams = QueryString.stringify({
85
- file: renderFile,
86
- url: httpEvent.url.href,
87
- root: this.cx.CWD,
88
- oohtml_level: this.cx.server.oohtml_support,
89
- });
90
- const { window } = await import('@webqit/oohtml-ssr/instance.js?' + instanceParams);
91
- // --------
92
- // OOHTML would waiting for DOM-ready in order to be initialized
93
- if (window.WebQit.DOM) {
94
- await new Promise(res => window.WebQit.DOM.ready(res));
95
- }
96
- if (window.document.templates) {
97
- await new Promise(res => (window.document.templatesReadyState === 'complete' && res(), window.document.addEventListener('templatesreadystatechange', res)));
98
- }
99
- if (window.document.state) {
100
- if (!window.document.state.env) {
101
- window.document.setState({
102
- env: 'server',
103
- }, { update: true });
104
- }
105
- window.document.setState({ data, url: httpEvent.url }, { update: 'merge' });
106
- }
107
- if (window.document.templates) {
108
- window.document.body.setAttribute('template', 'routes/' + httpEvent.url.pathname.split('/').filter(a => a).map(a => a + '+-').join('/'));
109
- }
110
- await new Promise(res => setTimeout(res, 60));
111
- return window;
112
- });
113
- return rendering + '';
114
- }
115
-
116
- }