@ohos-ports/cross-storage 1.0.0-beta.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.
package/dist/hub.js ADDED
@@ -0,0 +1,279 @@
1
+ /**
2
+ * cross-storage - Cross domain local storage
3
+ *
4
+ * @version 1.0.0
5
+ * @link https://github.com/zendesk/cross-storage
6
+ * @author Daniel St. Jules <danielst.jules@gmail.com>
7
+ * @copyright Zendesk
8
+ * @license Apache-2.0
9
+ */
10
+
11
+ ;(function(root) {
12
+ var CrossStorageHub = {};
13
+
14
+ /**
15
+ * Accepts an array of objects with two keys: origin and allow. The value
16
+ * of origin is expected to be a RegExp, and allow, an array of strings.
17
+ * The cross storage hub is then initialized to accept requests from any of
18
+ * the matching origins, allowing access to the associated lists of methods.
19
+ * Methods may include any of: get, set, del, getKeys and clear. A 'ready'
20
+ * message is sent to the parent window once complete.
21
+ *
22
+ * @example
23
+ * // Subdomain can get, but only root domain can set and del
24
+ * CrossStorageHub.init([
25
+ * {origin: /\.example.com$/, allow: ['get']},
26
+ * {origin: /:(www\.)?example.com$/, allow: ['get', 'set', 'del']}
27
+ * ]);
28
+ *
29
+ * @param {array} permissions An array of objects with origin and allow
30
+ */
31
+ CrossStorageHub.init = function(permissions) {
32
+ var available = true;
33
+
34
+ // Return if localStorage is unavailable, or third party
35
+ // access is disabled
36
+ try {
37
+ if (!window.localStorage) available = false;
38
+ } catch (e) {
39
+ available = false;
40
+ }
41
+
42
+ if (!available) {
43
+ try {
44
+ return window.parent.postMessage('cross-storage:unavailable', '*');
45
+ } catch (e) {
46
+ return;
47
+ }
48
+ }
49
+
50
+ CrossStorageHub._permissions = permissions || [];
51
+ CrossStorageHub._installListener();
52
+ window.parent.postMessage('cross-storage:ready', '*');
53
+ };
54
+
55
+ /**
56
+ * Installs the necessary listener for the window message event. Accommodates
57
+ * IE8 and up.
58
+ *
59
+ * @private
60
+ */
61
+ CrossStorageHub._installListener = function() {
62
+ var listener = CrossStorageHub._listener;
63
+ if (window.addEventListener) {
64
+ window.addEventListener('message', listener, false);
65
+ } else {
66
+ window.attachEvent('onmessage', listener);
67
+ }
68
+ };
69
+
70
+ /**
71
+ * The message handler for all requests posted to the window. It ignores any
72
+ * messages having an origin that does not match the originally supplied
73
+ * pattern. Given a JSON object with one of get, set, del or getKeys as the
74
+ * method, the function performs the requested action and returns its result.
75
+ *
76
+ * @param {MessageEvent} message A message to be processed
77
+ */
78
+ CrossStorageHub._listener = function(message) {
79
+ var origin, targetOrigin, request, method, error, result, response;
80
+
81
+ // postMessage returns the string "null" as the origin for "file://"
82
+ origin = (message.origin === 'null') ? 'file://' : message.origin;
83
+
84
+ // Handle polling for a ready message
85
+ if (message.data === 'cross-storage:poll') {
86
+ return window.parent.postMessage('cross-storage:ready', message.origin);
87
+ }
88
+
89
+ // Ignore the ready message when viewing the hub directly
90
+ if (message.data === 'cross-storage:ready') return;
91
+
92
+ // Check whether message.data is a valid json
93
+ try {
94
+ request = JSON.parse(message.data);
95
+ } catch (err) {
96
+ return;
97
+ }
98
+
99
+ // Check whether request.method is a string
100
+ if (!request || typeof request.method !== 'string') {
101
+ return;
102
+ }
103
+
104
+ method = request.method.split('cross-storage:')[1];
105
+
106
+ if (!method) {
107
+ return;
108
+ } else if (!CrossStorageHub._permitted(origin, method)) {
109
+ error = 'Invalid permissions for ' + method;
110
+ } else {
111
+ try {
112
+ result = CrossStorageHub['_' + method](request.params);
113
+ } catch (err) {
114
+ error = err.message;
115
+ }
116
+ }
117
+
118
+ response = JSON.stringify({
119
+ id: request.id,
120
+ error: error,
121
+ result: result
122
+ });
123
+
124
+ // postMessage requires that the target origin be set to "*" for "file://"
125
+ targetOrigin = (origin === 'file://') ? '*' : origin;
126
+
127
+ window.parent.postMessage(response, targetOrigin);
128
+ };
129
+
130
+ /**
131
+ * Returns a boolean indicating whether or not the requested method is
132
+ * permitted for the given origin. The argument passed to method is expected
133
+ * to be one of 'get', 'set', 'del' or 'getKeys'.
134
+ *
135
+ * @param {string} origin The origin for which to determine permissions
136
+ * @param {string} method Requested action
137
+ * @returns {bool} Whether or not the request is permitted
138
+ */
139
+ CrossStorageHub._permitted = function(origin, method) {
140
+ var available, i, entry, match;
141
+
142
+ available = ['get', 'set', 'del', 'clear', 'getKeys'];
143
+ if (!CrossStorageHub._inArray(method, available)) {
144
+ return false;
145
+ }
146
+
147
+ for (i = 0; i < CrossStorageHub._permissions.length; i++) {
148
+ entry = CrossStorageHub._permissions[i];
149
+ if (!(entry.origin instanceof RegExp) || !(entry.allow instanceof Array)) {
150
+ continue;
151
+ }
152
+
153
+ match = entry.origin.test(origin);
154
+ if (match && CrossStorageHub._inArray(method, entry.allow)) {
155
+ return true;
156
+ }
157
+ }
158
+
159
+ return false;
160
+ };
161
+
162
+ /**
163
+ * Sets a key to the specified value.
164
+ *
165
+ * @param {object} params An object with key and value
166
+ */
167
+ CrossStorageHub._set = function(params) {
168
+ window.localStorage.setItem(params.key, params.value);
169
+ };
170
+
171
+ /**
172
+ * Accepts an object with an array of keys for which to retrieve their values.
173
+ * Returns a single value if only one key was supplied, otherwise it returns
174
+ * an array. Any keys not set result in a null element in the resulting array.
175
+ *
176
+ * @param {object} params An object with an array of keys
177
+ * @returns {*|*[]} Either a single value, or an array
178
+ */
179
+ CrossStorageHub._get = function(params) {
180
+ var storage, result, i, value;
181
+
182
+ storage = window.localStorage;
183
+ result = [];
184
+
185
+ for (i = 0; i < params.keys.length; i++) {
186
+ try {
187
+ value = storage.getItem(params.keys[i]);
188
+ } catch (e) {
189
+ value = null;
190
+ }
191
+
192
+ result.push(value);
193
+ }
194
+
195
+ return (result.length > 1) ? result : result[0];
196
+ };
197
+
198
+ /**
199
+ * Deletes all keys specified in the array found at params.keys.
200
+ *
201
+ * @param {object} params An object with an array of keys
202
+ */
203
+ CrossStorageHub._del = function(params) {
204
+ for (var i = 0; i < params.keys.length; i++) {
205
+ window.localStorage.removeItem(params.keys[i]);
206
+ }
207
+ };
208
+
209
+ /**
210
+ * Clears localStorage.
211
+ */
212
+ CrossStorageHub._clear = function() {
213
+ window.localStorage.clear();
214
+ };
215
+
216
+ /**
217
+ * Returns an array of all keys stored in localStorage.
218
+ *
219
+ * @returns {string[]} The array of keys
220
+ */
221
+ CrossStorageHub._getKeys = function(params) {
222
+ var i, length, keys;
223
+
224
+ keys = [];
225
+ length = window.localStorage.length;
226
+
227
+ for (i = 0; i < length; i++) {
228
+ keys.push(window.localStorage.key(i));
229
+ }
230
+
231
+ return keys;
232
+ };
233
+
234
+ /**
235
+ * Returns whether or not a value is present in the array. Consists of an
236
+ * alternative to extending the array prototype for indexOf, since it's
237
+ * unavailable for IE8.
238
+ *
239
+ * @param {*} value The value to find
240
+ * @parma {[]*} array The array in which to search
241
+ * @returns {bool} Whether or not the value was found
242
+ */
243
+ CrossStorageHub._inArray = function(value, array) {
244
+ for (var i = 0; i < array.length; i++) {
245
+ if (value === array[i]) return true;
246
+ }
247
+
248
+ return false;
249
+ };
250
+
251
+ /**
252
+ * A cross-browser version of Date.now compatible with IE8 that avoids
253
+ * modifying the Date object.
254
+ *
255
+ * @return {int} The current timestamp in milliseconds
256
+ */
257
+ CrossStorageHub._now = function() {
258
+ if (typeof Date.now === 'function') {
259
+ return Date.now();
260
+ }
261
+
262
+ return new Date().getTime();
263
+ };
264
+
265
+ /**
266
+ * Export for various environments.
267
+ */
268
+ if (typeof module !== 'undefined' && module.exports) {
269
+ module.exports = CrossStorageHub;
270
+ } else if (typeof exports !== 'undefined') {
271
+ exports.CrossStorageHub = CrossStorageHub;
272
+ } else if (typeof define === 'function' && define.amd) {
273
+ define([], function() {
274
+ return CrossStorageHub;
275
+ });
276
+ } else {
277
+ root.CrossStorageHub = CrossStorageHub;
278
+ }
279
+ }(this));
@@ -0,0 +1,11 @@
1
+ /**
2
+ * cross-storage - Cross domain local storage
3
+ *
4
+ * @version 1.0.0
5
+ * @link https://github.com/zendesk/cross-storage
6
+ * @author Daniel St. Jules <danielst.jules@gmail.com>
7
+ * @copyright Zendesk
8
+ * @license Apache-2.0
9
+ */
10
+
11
+ !function(e){var t={};t.init=function(e){var r=!0;try{window.localStorage||(r=!1)}catch(n){r=!1}if(!r)try{return window.parent.postMessage("cross-storage:unavailable","*")}catch(n){return}t._permissions=e||[],t._installListener(),window.parent.postMessage("cross-storage:ready","*")},t._installListener=function(){var e=t._listener;window.addEventListener?window.addEventListener("message",e,!1):window.attachEvent("onmessage",e)},t._listener=function(e){var r,n,o,i,s,a,l;if(r="null"===e.origin?"file://":e.origin,"cross-storage:poll"===e.data)return window.parent.postMessage("cross-storage:ready",e.origin);if("cross-storage:ready"!==e.data){try{o=JSON.parse(e.data)}catch(c){return}if(o&&"string"==typeof o.method&&(i=o.method.split("cross-storage:")[1])){if(t._permitted(r,i))try{a=t["_"+i](o.params)}catch(c){s=c.message}else s="Invalid permissions for "+i;l=JSON.stringify({id:o.id,error:s,result:a}),n="file://"===r?"*":r,window.parent.postMessage(l,n)}}},t._permitted=function(e,r){var n,o,i,s;if(n=["get","set","del","clear","getKeys"],!t._inArray(r,n))return!1;for(o=0;o<t._permissions.length;o++)if(i=t._permissions[o],i.origin instanceof RegExp&&i.allow instanceof Array&&(s=i.origin.test(e),s&&t._inArray(r,i.allow)))return!0;return!1},t._set=function(e){window.localStorage.setItem(e.key,e.value)},t._get=function(e){var t,r,n,o;for(t=window.localStorage,r=[],n=0;n<e.keys.length;n++){try{o=t.getItem(e.keys[n])}catch(i){o=null}r.push(o)}return r.length>1?r:r[0]},t._del=function(e){for(var t=0;t<e.keys.length;t++)window.localStorage.removeItem(e.keys[t])},t._clear=function(){window.localStorage.clear()},t._getKeys=function(){var e,t,r;for(r=[],t=window.localStorage.length,e=0;t>e;e++)r.push(window.localStorage.key(e));return r},t._inArray=function(e,t){for(var r=0;r<t.length;r++)if(e===t[r])return!0;return!1},t._now=function(){return"function"==typeof Date.now?Date.now():(new Date).getTime()},"undefined"!=typeof module&&module.exports?module.exports=t:"undefined"!=typeof exports?exports.CrossStorageHub=t:"function"==typeof define&&define.amd?define([],function(){return t}):e.CrossStorageHub=t}(this);