How to use _cacheDisabled method in Puppeteer

Best JavaScript code snippet using puppeteer

baas.js

Source:baas.js Github

copy

Full Screen

1/*!2 * NEC Mobile Backend Platform JavaScript SDK version 7.5.03 *4 * Copyright (C) 2014-2018, NEC CORPORATION.5 * All rights reserved.6 *7 * 1. Redistributions of source code must retain the above copyright notice,8 * this list of conditions and the following disclaimer.9 * 2. Redistributions in binary form must reproduce the above copyright notice,10 * this list of conditions and the following disclaimer in the documentation11 * and/or other materials provided with the distribution.12 *13 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS14 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT15 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR16 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT17 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,18 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT19 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,20 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY21 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE23 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.24 */25"use strict";26var XMLHttpRequest, localStorage;27(function(root, setup) {28 var _module = {exports: {}};29 var _exports = _module.exports;30 setup.call(root, _module, _exports);31 if (typeof module !== "undefined" &&32 typeof module.exports !== "undefined" &&33 typeof process !== "undefined" &&34 typeof require !== "undefined") {35 module.exports = _exports;36 } else {37 root.Nebula = _exports.Nebula;38 }39})(this, function(module, exports) {40"use strict";41var __extends = (this && this.__extends) || (function () {42 var extendStatics = function (d, b) {43 extendStatics = Object.setPrototypeOf ||44 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||45 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };46 return extendStatics(d, b);47 }48 return function (d, b) {49 extendStatics(d, b);50 function __() { this.constructor = d; }51 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());52 };53})();54Object.defineProperty(exports, "__esModule", { value: true });55exports.root = this;56exports.nbError = function (message) {57 if (typeof console !== "undefined") {58 console.log("[BAAS ERROR] : " + message);59 }60};61exports.nbLogger = function (message) {62 if (exports.Nebula.getDebugMode() === "debug" && typeof console !== "undefined") {63 console.log("[BAAS] : " + message);64 }65};66exports._doBadRequestCallback = function (callbacks, name) {67 exports.nbLogger(name + "#invalid parameter.");68 var error = exports._createError(400, "Invalid Arguments", "Invalid Arguments");69 if (callbacks && callbacks.error) {70 callbacks.error(error);71 return;72 }73 else {74 return Promise.reject(error);75 }76};77exports._promisify = function (promise, callbacks) {78 if (callbacks) {79 promise.then(function (arg) {80 if (callbacks.success) {81 callbacks.success(arg);82 }83 }).catch(function (err) {84 if (callbacks.error) {85 callbacks.error(err);86 }87 });88 return undefined;89 }90 else {91 return promise;92 }93};94exports._createError = function (status, statusText, responseText, data) {95 var error = new Error(statusText + "(" + status + ")");96 error.status = status;97 error.statusText = statusText;98 error.responseText = responseText;99 if (data) {100 error.data = data;101 }102 return error;103};104exports._errorText = function (error) {105 if (error && error.message) {106 return error.message;107 }108 return error;109};110exports._isObject = function (value) {111 var type = typeof value;112 return value && type === 'object' || type === 'function';113};114exports._compareObject = function (src, target) {115 var srcKeys = Object.keys(src);116 var targetKeys = Object.keys(target);117 if (srcKeys.length !== targetKeys.length) {118 return false;119 }120 for (var _i = 0, srcKeys_1 = srcKeys; _i < srcKeys_1.length; _i++) {121 var key = srcKeys_1[_i];122 if (exports._isObject(src[key]) && exports._isObject(target[key])) {123 if (!exports._compareObject(src[key], target[key])) {124 return false;125 }126 }127 else {128 if (src[key] !== target[key]) {129 return false;130 }131 }132 }133 return true;134};135exports.nbAssert = function (assert, message) {136 if (!assert) {137 if (exports.Nebula.getDebugMode() === "debug") {138 throw new Error("Assertion failed. " + message);139 }140 else {141 exports.nbError("Assertion failed. " + message);142 }143 }144};145exports.isNodeJs = function () {146 return typeof require !== "undefined" && typeof process !== "undefined";147};148exports._node_require = function (module) {149 try {150 if (exports.isNodeJs()) {151 return eval('require')(module);152 }153 else {154 return null;155 }156 }157 catch (e) {158 return null;159 }160};161exports.URL = exports._node_require('url');162exports.https = exports._node_require('https');163exports.http = exports._node_require('http');164exports.tls = exports._node_require('tls');165exports.fs = exports._node_require('fs');166exports.util = exports._node_require('util');167var __http2 = null;168try {169 __http2 = exports._node_require('http2'); 170}171catch (e) {172}173exports.http2 = __http2;174exports._hasXhr = function () {175 return typeof XMLHttpRequest !== "undefined";176};177var HttpRequestExecutor = (function () {178 function HttpRequestExecutor(req) {179 this._req = req;180 this._resolve = req._resolve;181 this._reject = req._reject;182 }183 HttpRequestExecutor.closeHttp2Session = function (authority) {184 if (exports._hasXhr()) {185 HttpXhr.closeHttp2Session(authority);186 }187 else {188 HttpNode.closeHttp2Session(authority);189 }190 };191 HttpRequestExecutor.create = function (req) {192 if (exports._hasXhr()) {193 return this._xhrFactory(req);194 }195 else {196 return this._nodeFactory(req);197 }198 };199 HttpRequestExecutor.setXhrFactory = function (factory) {200 this._xhrFactory = factory;201 };202 HttpRequestExecutor.setNodeFactory = function (factory) {203 this._nodeFactory = factory;204 };205 return HttpRequestExecutor;206}());207exports.HttpRequestExecutor = HttpRequestExecutor;208var HttpRequest = (function () {209 function HttpRequest(service, path, option) {210 this._rawMessage = false;211 this._useHttp2 = false;212 exports.nbLogger("HttpRequest#start:path = " + path);213 this._service = service;214 this._url = this._service.getBaseUri();215 if (!(option && option.noprefix)) {216 this._url += "/" + this._service.getRestApiVersion() + "/" + this._service.getTenantID();217 }218 this._url = encodeURI(this._url) + path;219 this._headers = {};220 this._contentType = null;221 this._responseType = null;222 this._queryParams = null;223 this._data = null;224 this._receiveResponseHeaders = false;225 this._timeout = HttpRequest.getDefaultTimeout();226 this._useHttp2 = this._service.getHttp2();227 var _currentObj = this._service.getCurrentUser();228 if (_currentObj === null) {229 this._sessionToken = null;230 }231 else {232 this._sessionToken = _currentObj.sessionToken;233 }234 }235 HttpRequest.getProxy = function () {236 return HttpRequest._proxy;237 };238 HttpRequest.setProxy = function (proxy) {239 HttpRequest._proxy = proxy;240 };241 HttpRequest.setHttpAgent = function (agent) {242 HttpRequest._httpAgent = agent;243 };244 HttpRequest.setHttpsAgent = function (agent, options) {245 HttpRequest._httpsAgent = agent;246 HttpRequest._httpsAgentOptions = options;247 };248 Object.defineProperty(HttpRequest.prototype, "service", {249 get: function () {250 return this._service;251 },252 enumerable: true,253 configurable: true254 });255 Object.defineProperty(HttpRequest.prototype, "responseHeaders", {256 get: function () {257 return this._responseHeaders;258 },259 set: function (value) {260 this._responseHeaders = value;261 },262 enumerable: true,263 configurable: true264 });265 HttpRequest.setDefaultTimeout = function (timeout) {266 this._defaultTimeout = timeout;267 };268 HttpRequest.getDefaultTimeout = function () {269 return this._defaultTimeout;270 };271 Object.defineProperty(HttpRequest.prototype, "rawMessage", {272 get: function () {273 return this._rawMessage;274 },275 set: function (value) {276 this._rawMessage = value;277 },278 enumerable: true,279 configurable: true280 });281 Object.defineProperty(HttpRequest.prototype, "useHttp2", {282 get: function () {283 return this._useHttp2;284 },285 set: function (value) {286 if (value && exports.http2 == null) {287 throw new Error("No http2 support.");288 }289 this._useHttp2 = value;290 },291 enumerable: true,292 configurable: true293 });294 HttpRequest.prototype.setReceiveResponseHeaders = function (receive) {295 this._receiveResponseHeaders = receive;296 return this;297 };298 HttpRequest.prototype.execute = function () {299 var _this = this;300 return new Promise(function (resolve, reject) {301 _this._resolve = resolve;302 _this._reject = reject;303 _this._headers["X-Application-Id"] = _this._service.getAppID();304 _this._headers["X-Application-Key"] = _this._service.getAppKey();305 if (_this._contentType !== null) {306 _this._headers["Content-Type"] = _this._contentType;307 }308 if (_this._sessionToken !== null) {309 _this._headers["X-Session-Token"] = _this._sessionToken;310 }311 var url = _this._url;312 if (_this._queryParams) {313 var p = [];314 for (var _i = 0, _a = Object.keys(_this._queryParams); _i < _a.length; _i++) {315 var key = _a[_i];316 if (_this._queryParams.hasOwnProperty(key)) {317 p.push(encodeURIComponent(key) + "=" + encodeURIComponent(_this._queryParams[key]));318 }319 }320 if (p.length > 0) {321 url += "?" + p.join("&");322 }323 }324 var body;325 if (!(_this._data != null)) {326 body = null;327 }328 else if ((typeof _this._data === "string") ||329 (typeof Blob !== "undefined" && Blob !== null && _this._data instanceof Blob) ||330 (typeof Buffer !== "undefined" && Buffer !== null && Buffer.isBuffer(_this._data))) {331 body = _this._data;332 }333 else {334 body = JSON.stringify(_this._data);335 }336 var executor = HttpRequestExecutor.create(_this);337 if (_this._rawMessage) {338 executor.setReturnRawMessage(_this._rawMessage);339 }340 executor.execute(_this._method, url, _this._headers, body, _this._timeout, _this._responseType, _this._receiveResponseHeaders, _this._useHttp2);341 });342 };343 HttpRequest.closeHttp2Session = function (authority) {344 HttpRequestExecutor.closeHttp2Session(authority);345 };346 HttpRequest.prototype.setMethod = function (method) {347 this._method = method;348 return this;349 };350 HttpRequest.prototype.setContentType = function (contentType) {351 this._contentType = contentType;352 return this;353 };354 HttpRequest.prototype.setQueryParams = function (params) {355 this._queryParams = params;356 return this;357 };358 HttpRequest.prototype.addQueryParams = function (params) {359 if (params) {360 for (var _i = 0, _a = Object.keys(params); _i < _a.length; _i++) {361 var key = _a[_i];362 this.setQueryParam(key, params[key]);363 }364 }365 return this;366 };367 HttpRequest.prototype.setQueryParam = function (key, value) {368 if (!this._queryParams) {369 this._queryParams = {};370 }371 this._queryParams[key] = value;372 return this;373 };374 HttpRequest.prototype.setData = function (data) {375 this._data = data;376 return this;377 };378 HttpRequest.prototype.setSessionToken = function (sessionToken) {379 this._sessionToken = sessionToken;380 return this;381 };382 HttpRequest.prototype.setResponseType = function (responseType) {383 this._responseType = responseType;384 return this;385 };386 HttpRequest.prototype.addRequestHeader = function (header, value) {387 if (this._headers[header] !== undefined) {388 exports.nbLogger("HTTP Request Warning : This header already exists.");389 }390 this._headers[header] = value;391 return this;392 };393 HttpRequest._defaultTimeout = 0;394 return HttpRequest;395}());396exports.HttpRequest = HttpRequest;397exports.initHttpXhr = function () {398 HttpRequestExecutor.setXhrFactory(function (req) { return new HttpXhr(req); });399};400var HttpXhr = (function (_super) {401 __extends(HttpXhr, _super);402 function HttpXhr(req) {403 var _this = _super.call(this, req) || this;404 _this._onReadyStateChange = _this._onReadyStateChange.bind(_this);405 return _this;406 }407 HttpXhr.prototype.setReturnRawMessage = function (rawMessage) {408 throw new Error("Not supported");409 };410 HttpXhr.prototype.execute = function (method, url, headers, body, timeout, responseType, receiveResponseHeaders, useHttp2) {411 var _this = this;412 this._receiveResponseHeaders = receiveResponseHeaders;413 this._xhr = this._createXhr();414 this._xhr.open(method, url, true);415 this._xhr.onreadystatechange = this._onReadyStateChange;416 for (var _i = 0, _a = Object.keys(headers); _i < _a.length; _i++) {417 var key = _a[_i];418 var value = headers[key];419 this._xhr.setRequestHeader(key, value);420 }421 this._xhr.timeout = timeout;422 this._xhr.ontimeout = function (e) {423 _this._onXhrTimeout(e);424 };425 try {426 var userAgent = exports.root.navigator.userAgent.toLowerCase();427 if (userAgent.match(/msie/) || userAgent.match(/trident/)) {428 this._xhr.setRequestHeader("Pragma", "no-cache");429 this._xhr.setRequestHeader("Cache-Control", "no-cache");430 this._xhr.setRequestHeader("If-Modified-Since", "Thu, 01 Jun 1970 00:00:00 GMT");431 }432 else {433 }434 }435 catch (e) {436 }437 if (responseType != null) {438 this._xhr.responseType = responseType;439 }440 this._xhr.send(body);441 };442 HttpXhr.closeHttp2Session = function (authority) {443 throw new Error("not support");444 };445 HttpXhr.prototype._createXhr = function () {446 if (!exports._hasXhr()) {447 throw new Error("No XMLHttpRequest");448 }449 return new XMLHttpRequest();450 };451 HttpXhr.prototype._onReadyStateChange = function () {452 var xhr = this._xhr;453 if (xhr.readyState === 4) {454 if (xhr.status >= 200 && xhr.status < 300) {455 var body = (xhr.response != null) ? xhr.response : xhr.responseText;456 if (this._receiveResponseHeaders) {457 return this._resolve({458 body: body,459 headers: xhr.getAllResponseHeaders(),460 status: xhr.status461 });462 }463 else {464 return this._resolve(body);465 }466 }467 else {468 var error = exports._createError(xhr.status, xhr.statusText, "");469 if (xhr.responseType !== "blob") {470 error.responseText = xhr.responseText;471 }472 if (xhr.status === 0) {473 error.statusText = "Not Found";474 error.responseText = "Not found anything that matches the request URI.";475 }476 exports.nbError("HTTP Request Error: " + error.message + " " + error.responseText);477 return this._reject(error);478 }479 }480 };481 HttpXhr.prototype._onXhrTimeout = function (e) {482 var error = exports._createError(0, "Timeout error", e.toString());483 exports.nbError("HTTP Response Error: Timeout Error: " + e.toString());484 this._reject(error);485 };486 return HttpXhr;487}(HttpRequestExecutor));488exports.HttpXhr = HttpXhr;489HttpRequestExecutor.setXhrFactory(function (req) {490 return new HttpXhr(req);491});492exports.initHttpNode = function () {493 HttpRequestExecutor.setNodeFactory(function (req) { return new HttpNode(req); });494};495var HttpNode = (function (_super) {496 __extends(HttpNode, _super);497 function HttpNode(req) {498 var _this = _super.call(this, req) || this;499 _this._rawMessage = false;500 return _this;501 }502 HttpNode.prototype.setReturnRawMessage = function (returnRawMessage) {503 this._rawMessage = returnRawMessage;504 };505 HttpNode.prototype.execute = function (method, urlString, headers, body, timeout, responseType, receiveResponseHeaders, useHttp2) {506 this._responseType = responseType;507 this._receiveResponseHeaders = receiveResponseHeaders;508 var url;509 try {510 url = exports.URL.parse(urlString);511 }512 catch (e) {513 exports.nbError("Bad URL: " + urlString);514 this._reject(exports._createError(0, "Bad URL: " + urlString, ""));515 return;516 }517 var isHttps = HttpNode._isHttps(url);518 var options = {519 method: method,520 hostname: url.hostname,521 port: url.port,522 path: url.path,523 headers: headers,524 agent: isHttps ? HttpRequest._httpsAgent : HttpRequest._httpAgent,525 timeout: timeout,526 pfx: null,527 passphrase: null,528 key: null,529 cert: null,530 ca: null,531 rejectUnauthorized: true532 };533 if (isHttps) {534 var allowedClientCertOptions = ['pfx', 'passphrase', 'key', 'cert', 'ca'];535 var clientCertOptions = this._req.service._config.clientCertOptions;536 if (clientCertOptions != null) {537 for (var key in clientCertOptions) {538 if (allowedClientCertOptions.indexOf(key) >= 0) {539 options[key] = clientCertOptions[key];540 }541 else {542 exports.nbError('invalid parameter ' + key + ' detected. value: ' + JSON.stringify(clientCertOptions[key]));543 this._reject(exports._createError(0, 'invalid parameter: ' + key, ' value: ' + JSON.stringify(clientCertOptions[key])));544 return;545 }546 }547 }548 if (this._req.service._config.allowSelfSignedCert) {549 options.rejectUnauthorized = false;550 exports.nbLogger('HTTPS Request Warning : accept self-signed certificate. make sure the risk of this setting.');551 }552 else {553 options.rejectUnauthorized = true;554 }555 }556 if (isHttps && options.agent != null && HttpRequest._httpsAgentOptions != null) {557 try {558 exports.tls.createSecureContext(HttpRequest._httpsAgentOptions);559 }560 catch (e) {561 exports.nbError("HttpsAgentOptions invalid. check proxy options " + e.toString());562 var error = exports._createError(0, "Client Error", e.toString());563 this._reject(error);564 return;565 }566 }567 if (exports.http2 != null && useHttp2) {568 this._sendHttp2Request(url, options, body);569 }570 else {571 this._sendHttpRequest(url, options, body);572 }573 };574 HttpNode.prototype._sendHttp2Request = function (url, options, body) {575 var authority = url.protocol + '//' + url.hostname;576 if (url.port != null) {577 authority += ':' + url.port;578 }579 var sessions = HttpNode.getHttp2Sessions();580 for (var key in sessions) {581 var session = sessions[key];582 if (session.destroyed == true || session.closed == true) {583 exports.nbLogger('http2 session ' + authority + ' is destroyed or closed state');584 HttpNode.closeHttp2Session(key);585 }586 }587 var http2Session = HttpNode.getHttp2Session(authority);588 if (http2Session == null) {589 exports.nbLogger('create http2 session: [' + authority + ']');590 var http2SessionOptions = {591 allowHTTP1: true,592 pfx: options['pfx'],593 passphrase: options['passphrase'],594 key: options['key'],595 cert: options['cert'],596 ca: options['ca'],597 rejectUnauthorized: options['rejectUnauthorized']598 };599 http2Session = exports.http2.connect(authority, (HttpNode._isHttps(url) ? http2SessionOptions : undefined));600 HttpNode.setHttp2Session(authority, http2Session);601 }602 var outgoingHttpHeaders = options.headers;603 outgoingHttpHeaders[':method'] = options.method;604 outgoingHttpHeaders[':path'] = url.path;605 var http2Stream = http2Session.request(outgoingHttpHeaders);606 if (options.timeout > 0) {607 http2Stream.setTimeout(options.timeout, function () {608 HttpNode._closeStream(http2Stream);609 var error = exports._createError(0, "HTTP/2 Request timeout: " + options.timeout + "[msec]", "");610 exports.nbError("Timeout detected: " + error);611 });612 }613 if (this._rawMessage) {614 this._resolve(http2Stream); 615 }616 else {617 this._setHttp2ResponseHandlers(http2Stream);618 }619 if (body != null) {620 if (typeof body === "string" || body instanceof String || body instanceof Buffer) {621 http2Stream.write(body);622 }623 else {624 http2Stream.write(JSON.stringify(body));625 }626 }627 http2Stream.end();628 };629 HttpNode.prototype._sendHttpRequest = function (url, options, body) {630 var _this = this;631 var handler = function (res) {632 if (_this._rawMessage) {633 _this._resolve(res);634 }635 else {636 var status_1 = res.statusCode;637 _this._req.responseHeaders = res.headers;638 _this._setResponseHandlers(status_1, res);639 }640 };641 var req = HttpNode._isHttps(url) ? exports.https.request(options, handler) : exports.http.request(options, handler);642 if (options.timeout > 0) {643 req.setTimeout(options.timeout, function () { return req.abort(); });644 }645 req.on('error', function (e) {646 var error = exports._createError(0, "HTTP request error", e.toString());647 exports.nbError("HTTP Request Error: " + e.toString());648 _this._reject(error);649 });650 if (body != null) {651 if (typeof body === "string" || body instanceof String || body instanceof Buffer) {652 req.write(body);653 }654 else {655 req.write(JSON.stringify(body));656 }657 }658 req.end();659 };660 HttpNode._isHttps = function (url) {661 return (url.protocol === 'https:');662 };663 HttpNode.prototype._setResponseHandlers = function (status, res) {664 var _this = this;665 var chunks = [];666 res.on('data', function (data) {667 chunks.push(data);668 });669 res.on('end', function () {670 var buffer = Buffer.concat(chunks);671 var responseBody = _this._parseNodeResponse(buffer);672 if (200 <= status && status < 300) {673 if (_this._receiveResponseHeaders) {674 _this._resolve({675 body: responseBody,676 headers: res.headers,677 status: status678 });679 }680 else {681 _this._resolve(responseBody);682 }683 }684 else {685 var responseText = (_this._responseType !== "buffer" && responseBody != null) ? responseBody.toString() : "";686 var error = exports._createError(status, res.statusMessage, responseText, responseBody);687 exports.nbError("HTTP Response Error: status=" + status + " - " + res.statusMessage);688 _this._reject(error);689 }690 });691 res.on('error', function (e) {692 var error = exports._createError(0, "Client Error", e.toString());693 exports.nbError("HTTP Response Error: Client Error: " + e.toString());694 _this._reject(error);695 });696 };697 HttpNode.prototype._setHttp2ResponseHandlers = function (stream) {698 var _this = this;699 var chunks = [];700 var resHeaders = {};701 var statusCode = 0;702 stream.on('response', function (headers, flags) {703 resHeaders = headers;704 statusCode = Number(headers[exports.http2.constants.HTTP2_HEADER_STATUS]);705 }).on('data', function (data) {706 chunks.push(data);707 }).on('end', function () {708 var buffer = Buffer.concat(chunks);709 var responseBody = _this._parseNodeResponse(buffer);710 HttpNode._closeStream(stream);711 if (200 <= statusCode && statusCode < 300) {712 if (_this._receiveResponseHeaders) {713 _this._resolve({714 body: responseBody,715 headers: resHeaders,716 status: statusCode717 });718 }719 else {720 _this._resolve(responseBody);721 }722 }723 else {724 var statusMessage = (statusCode == 0) ? "Unable to get proper response" : "";725 var responseText = (_this._responseType !== "buffer" && responseBody != null) ? responseBody.toString() : "";726 var error = exports._createError(statusCode, statusMessage, responseText, responseBody);727 exports.nbError("HTTP/2 Response Error: status=" + statusCode);728 _this._reject(error);729 }730 }).on('error', function (e) {731 HttpNode._closeStream(stream);732 var error = exports._createError(0, "HTTP/2 Stream Error", e.toString());733 exports.nbError("HTTP/2 Stream Error: " + e.toString());734 _this._reject(error);735 }).on('push', function (headers, flags) {736 exports.nbLogger('HTTP/2 Stream push');737 }).on('finish', function () {738 exports.nbLogger('HTTP/2 Stream finish');739 }).on('altsvc', function (alt, origin, streamId) {740 exports.nbLogger('HTTP/2 Stream altsvc');741 }).on('aborted', function () {742 exports.nbLogger('HTTP/2 Stream aborted');743 });744 };745 HttpNode.prototype._parseNodeResponse = function (buffer) {746 try {747 switch (this._responseType) {748 default:749 case 'text':750 return buffer.toString('utf-8');751 case 'json':752 var s = buffer.toString('utf-8');753 try {754 return JSON.parse(s);755 }756 catch (e) {757 return s;758 }759 case 'buffer':760 return buffer;761 }762 }763 catch (e) {764 exports.nbError("bad response: e=" + e.toString());765 return null;766 }767 };768 HttpNode._closeSession = function (session, callback) {769 if ('close' in session) {770 session.close(callback); 771 }772 else if ('shutdown' in session) {773 var options = { 'graceful': true };774 session.shutdown(options, callback); 775 }776 else {777 session.destroy();778 session.removeAllListeners();779 }780 };781 HttpNode._closeStream = function (stream) {782 if ('close' in stream) {783 stream.close(); 784 }785 else {786 stream.destroy(); 787 }788 };789 HttpNode.getHttp2Sessions = function () {790 return HttpNode._http2Sessions;791 };792 HttpNode.getHttp2Session = function (authority) {793 var session = null;794 if (authority in HttpNode._http2Sessions) {795 session = HttpNode._http2Sessions[authority];796 }797 return session;798 };799 HttpNode.setHttp2Session = function (authority, session) {800 HttpNode._http2Sessions[authority] = session;801 };802 HttpNode.closeHttp2Session = function (authority) {803 if (authority === undefined) {804 for (var key in HttpNode._http2Sessions) {805 HttpNode.closeHttp2Session(key);806 }807 return;808 }809 var session = HttpNode._http2Sessions[authority];810 if (session != null) {811 if (session.destroyed) {812 session.removeAllListeners();813 exports.nbLogger('HTTP/2 session [' + authority + '] is already destroyed');814 }815 else {816 exports.nbLogger('HTTP/2 session [' + authority + '] is going to close');817 HttpNode._closeSession(session, function () {818 session.removeAllListeners();819 exports.nbLogger('HTTP/2 session [' + authority + '] has been closed');820 });821 }822 delete HttpNode._http2Sessions[authority];823 }824 };825 HttpNode._http2Sessions = {};826 return HttpNode;827}(HttpRequestExecutor));828exports.HttpNode = HttpNode;829HttpRequestExecutor.setNodeFactory(function (req) {830 return new HttpNode(req);831});832var _SdeRequest = (function () {833 function _SdeRequest(className, methodName) {834 exports.nbLogger("_SdeRequest(), className=" + (className) + ", methodName=" + (methodName));835 this._className = className;836 this._methodName = methodName;837 this._data = null;838 }839 _SdeRequest.prototype.setData = function (data) {840 return this._data = data;841 };842 _SdeRequest.prototype.execute = function () {843 var callbacks = {};844 var promise = new Promise(function (resolve, reject) {845 callbacks.success = resolve;846 return callbacks.error = reject;847 });848 var reqId = _SdeRequest._createRequestId();849 _SdeRequest._callbacks[reqId] = callbacks;850 exports.nbLogger("_SdeRequest.execute(), reqId=" + reqId);851 if (!(this._data != null)) {852 this._data = {};853 }854 var data = {855 data: this._data 856 };857 var sdeParams = {858 action: ((this._className) + "." + (this._methodName)),859 request_id: reqId,860 params: JSON.stringify(data),861 callback: "Nebula._SdeRequest.sdeCallback"862 };863 exports.nbLogger("_SdeRequest.execute(), sdeParams=" + JSON.stringify(sdeParams));864 exports.sde.smt.common.exIfExecute("NebulaSdePlugin", "execute", sdeParams);865 return promise;866 };867 _SdeRequest._createRequestId = function () {868 for (var i = 0; i < 1000; i++) {869 var requestId = "id_" + this._requestId;870 this._requestId++;871 if (this._requestId >= 1000) {872 this._requestId = 0;873 }874 if (!this._callbacks[requestId]) {875 exports.nbLogger("_SdeRequest._createRequestId(), requestId=" + requestId);876 return requestId;877 }878 }879 exports.nbLogger("FATAL Error: Nebula._SdeRequest._createRequestId(), callback slot full!");880 throw new Error("Could not create request ID, callback slot full!");881 };882 _SdeRequest.sdeCallback = function (params) {883 try {884 exports.nbLogger("_SdeRequest.sdeCallback()");885 exports.nbLogger(" params=" + JSON.stringify(params));886 exports.nbLogger(" requestId=" + params.requestId);887 exports.nbLogger(" status=" + params.status);888 exports.nbLogger(" statusText=" + params.statusText);889 exports.nbLogger(" responseText=" + params.responseText);890 exports.nbLogger(" response=" + params.response);891 var requestId = params.requestId;892 if (requestId != null && _SdeRequest._callbacks[requestId] != null) {893 var callbacks = _SdeRequest._callbacks[requestId];894 exports.nbLogger(" requestId=" + requestId);895 exports.nbLogger(" _callbacks[requestId]=" + callbacks);896 var status_2 = params.status;897 if (!status_2) {898 exports.nbLogger("_SdeRequest.sdeCallback(), warning:: not found status property");899 status_2 = 0;900 }901 if (status_2 >= 200 && status_2 < 300) {902 exports.nbLogger("_SdeRequest.sdeCallback(), call success callback");903 callbacks.success(JSON.stringify(params.response));904 }905 else {906 var errorResult = exports._createError(params.status, params.statusText, params.responseText);907 exports.nbLogger("Nebula._SdeRequest.sdeCallback(), call error callback: " + errorResult.message908 + " " + errorResult.responseText);909 callbacks.error(errorResult);910 }911 delete _SdeRequest._callbacks[requestId];912 exports.nbLogger("_SdeRequest.sdeCallback(), _callbacks : " + JSON.stringify(_SdeRequest._callbacks));913 }914 else {915 exports.nbError("_SdeRequest.sdeCallback(), not found requestId=" + requestId);916 }917 }918 catch (e) {919 exports.nbError("_SdeRequest.sdeCallback(), e=" + e);920 }921 };922 _SdeRequest._callbacks = {};923 _SdeRequest._requestId = 0;924 return _SdeRequest;925}());926exports._SdeRequest = _SdeRequest;927var _SdeNetworkEventListener = (function () {928 function _SdeNetworkEventListener() {929 }930 _SdeNetworkEventListener.setCallback = function (callback) {931 this._callback = callback;932 exports.nbLogger("_SdeNetworkEventListener.setCallback(), callback=" + callback);933 var data = {};934 if (callback) {935 data.set = true;936 }937 else {938 data.set = false;939 }940 var sdeParams = {941 params: JSON.stringify(data),942 callback: ""943 };944 exports.nbLogger("_SdeNetworkEventListener.setCallback(), sdeParams=" + JSON.stringify(sdeParams));945 return exports.sde.smt.common.exIfExecute("NebulaNetworkEventManager", "setNetworkEventListener", sdeParams);946 };947 _SdeNetworkEventListener.onNetworkStateChanged = function (params) {948 try {949 exports.nbLogger("_SdeNetworkEventListener.onNetworkStateChanged(), params=" + JSON.stringify(params));950 if (this._callback != null && this._callback.onNetworkStateChanged != null) {951 if (params.isOnline != null) {952 this._callback.onNetworkStateChanged(params.isOnline);953 }954 else {955 exports.nbError("_SdeNetworkEventListener.onNetworkStateChanged(), invalid parameters");956 }957 }958 else {959 exports.nbLogger("_SdeNetworkEventListener.onNetworkStateChanged(), no callback");960 }961 }962 catch (e) {963 exports.nbError("_SdeNetworkEventListener.onNetworkStateChanged(), exception=" + e);964 }965 };966 return _SdeNetworkEventListener;967}());968exports._SdeNetworkEventListener = _SdeNetworkEventListener;969var _SdeSyncEventListener = (function () {970 function _SdeSyncEventListener() {971 }972 _SdeSyncEventListener.setListener = function (bucket, listener) {973 if (bucket == null) {974 exports.nbError("_SdeSyncEventListener.setCallback(), no bucket");975 return;976 }977 exports.nbLogger("_SdeSyncEventListener.setCallback(), before : _listeners=" + JSON.stringify(this._listeners));978 var bucketName = bucket.getBucketName();979 var bucketMode = bucket.getBucketMode();980 if (listener == null) {981 this._listeners[bucketName] = listener;982 this._bucketMode[bucketName] = bucketMode;983 }984 else {985 if (this._listeners[bucketName] != null) {986 delete this._listeners[bucketName];987 }988 if (this._bucketMode[bucketName] != null) {989 delete this._bucketMode[bucketName];990 }991 }992 exports.nbLogger("_SdeSyncEventListener.setCallback(), after : _listeners=" + JSON.stringify(this._listeners));993 var data = {};994 data.bucketName = bucketName;995 data.bucketMode = bucketMode;996 if (listener) {997 data.set = true;998 }999 else {1000 data.set = false;1001 }1002 var sdeParams = {1003 params: JSON.stringify(data),1004 callback: ""1005 };1006 exports.nbLogger("_SyncEventListener.setCallback(), sdeParams=" + JSON.stringify(sdeParams));1007 return exports.sde.smt.common.exIfExecute("NebulaSyncEventManager", "setSyncEventListener", sdeParams);1008 };1009 _SdeSyncEventListener.resolveConflict = function (data) {1010 exports.nbLogger("_SyncEventListener.resolveConflict(), data=" + data);1011 var sdeParams = {1012 params: JSON.stringify(data),1013 callback: ""1014 };1015 exports.nbLogger("_SyncEventListener.resolveConflict(), sdeParams=" + JSON.stringify(sdeParams));1016 return exports.sde.smt.common.exIfExecute("NebulaSyncEventManager", "resolveConflict", sdeParams);1017 };1018 _SdeSyncEventListener.onSyncStart = function (params) {1019 try {1020 exports.nbLogger("_SdeSyncEventListener.onSyncStart(), params=" + JSON.stringify(params));1021 if (params.bucketName != null) {1022 var bucketName = params.bucketName;1023 var listener = _SdeSyncEventListener._listeners[bucketName];1024 if (listener && listener.onSyncStart) {1025 listener.onSyncStart(bucketName);1026 }1027 else {1028 exports.nbLogger("_SdeSyncEventListener.onSyncStart(), no callback or onSyncStart");1029 }1030 }1031 else {1032 exports.nbLogger("_SdeSyncEventListener.onSyncStart(), no bucketName");1033 }1034 }1035 catch (e) {1036 exports.nbLogger("_SdeSyncEventListener.onSyncStart(), exception=" + e);1037 }1038 };1039 _SdeSyncEventListener.onSyncCompleted = function (params) {1040 try {1041 exports.nbLogger("_SdeSyncEventListener.onSyncCompleted(), params=" + JSON.stringify(params));1042 exports.nbLogger("_SdeSyncEventListener.onSyncCompleted(), bucketName=" + params.bucketName);1043 exports.nbLogger("_SdeSyncEventListener.onSyncCompleted(), objectIds=" + params.objectIds);1044 if (params.bucketName != null && params.objectIds != null) {1045 var bucketName = params.bucketName;1046 var listener = _SdeSyncEventListener._listeners[bucketName];1047 if (listener && listener.onSyncCompleted) {1048 listener.onSyncCompleted(bucketName, params.objectIds);1049 }1050 else {1051 exports.nbLogger("_SdeSyncEventListener.onSyncCompleted(), no callback or onSyncCompleted");1052 }1053 }1054 else {1055 exports.nbLogger("_SdeSyncEventListener.onSyncCompleted(), no bucketName or objectIds");1056 }1057 }1058 catch (e) {1059 exports.nbLogger("_SdeSyncEventListener.onSyncCompleted(), exception=" + e);1060 }1061 };1062 _SdeSyncEventListener.onSyncConflicted = function (params) {1063 try {1064 exports.nbLogger("_SdeSyncEventListener.onSyncConflicted(), params=" + JSON.stringify(params));1065 exports.nbLogger("_SdeSyncEventListener.onSyncConflicted(), bucketName=" + params.bucketName);1066 exports.nbLogger("_SdeSyncEventListener.onSyncConflicted(), resolveId=" + params.resolveId);1067 exports.nbLogger("_SdeSyncEventListener.onSyncConflicted(), client=" + params.client);1068 exports.nbLogger("_SdeSyncEventListener.onSyncConflicted(), server=" + params.server);1069 if (params.bucketName != null && params.resolveId != null && params.client != null && params.server != null) {1070 var bucketName = params.bucketName;1071 var bucketMode = this._bucketMode[bucketName];1072 if (!(bucketMode != null)) {1073 bucketMode = exports.Nebula.BUCKET_MODE_REPLICA;1074 }1075 var listener = this._listeners[bucketName];1076 if (listener && listener.onSyncConflicted) {1077 var bucket = new exports.Nebula.ObjectBucket(bucketName, bucketMode);1078 bucket._setResolveId(params.resolveId);1079 listener.onSyncConflicted(bucket, params.client, params.server);1080 }1081 else {1082 exports.nbLogger("_SdeSyncEventListener.onSyncConflicted(), no callback or onSyncCompleted");1083 }1084 }1085 else {1086 exports.nbLogger("_SdeSyncEventListener.onSyncConflicted(), invalid parameters");1087 }1088 }1089 catch (e) {1090 exports.nbLogger("_SdeSyncEventListener.onSyncConflicted(), exception=" + e);1091 }1092 };1093 _SdeSyncEventListener.onResolveConflict = function (params) {1094 try {1095 exports.nbLogger("_SdeSyncEventListener.onResolveConflict(), params=" + JSON.stringify(params));1096 exports.nbLogger("_SdeSyncEventListener.onResolveConflict(), resolve=" + params.resolve);1097 exports.nbLogger("_SdeSyncEventListener.onResolveConflict(), object=" + params.object);1098 if (params.bucketName != null && params.resolve != null && params.object != null) {1099 var bucketName = params.bucketName;1100 var listener = _SdeSyncEventListener._listeners[bucketName];1101 if (listener && listener["onResolveConflict"]) {1102 listener.onResolveConflict(params.object, params.resolve);1103 }1104 else {1105 exports.nbLogger("Nebula._SdeSyncEventListener.onResolveConflict(), no callback or onResolveConflict");1106 }1107 }1108 else {1109 exports.nbLogger("_SdeSyncEventListener.onSyncConflicted(), invalid parameters");1110 }1111 }1112 catch (e) {1113 exports.nbLogger("_SdeSyncEventListener.onResolveConflict(), exception=" + e);1114 }1115 };1116 _SdeSyncEventListener.onSyncError = function (params) {1117 try {1118 exports.nbLogger("_SdeSyncEventListener.onSyncError(), params=" + JSON.stringify(params));1119 exports.nbLogger("_SdeSyncEventListener.onSyncError(), errorCode=" + params.errorCode);1120 exports.nbLogger("_SdeSyncEventListener.onSyncError(), object=" + params.object);1121 if (params.bucketName != null && params.errorCode != null && params.object != null) {1122 var bucketName = params.bucketName;1123 var listener = _SdeSyncEventListener._listeners[bucketName];1124 if (listener != null && listener.onSyncError != null) {1125 listener.onSyncError(params.errorCode, params.object);1126 }1127 else {1128 exports.nbLogger("_SdeSyncEventListener.onSyncError(), no callback or onSyncError");1129 }1130 }1131 else {1132 exports.nbLogger("_SdeSyncEventListener.onSyncError(), invalid parameters");1133 }1134 }1135 catch (e) {1136 exports.nbLogger("_SdeSyncEventListener.onSyncError(), exception=" + e);1137 }1138 };1139 _SdeSyncEventListener._listeners = {};1140 _SdeSyncEventListener._bucketMode = {};1141 return _SdeSyncEventListener;1142}());1143exports._SdeSyncEventListener = _SdeSyncEventListener;1144var AccountLink = (function () {1145 function AccountLink() {1146 }1147 Object.defineProperty(AccountLink.prototype, "_id", {1148 get: function () { return this.__id; },1149 set: function (value) { this.__id = value; },1150 enumerable: true,1151 configurable: true1152 });1153 Object.defineProperty(AccountLink.prototype, "iss", {1154 get: function () { return this._iss; },1155 set: function (value) { this._iss = value; },1156 enumerable: true,1157 configurable: true1158 });1159 Object.defineProperty(AccountLink.prototype, "sub", {1160 get: function () { return this._sub; },1161 set: function (value) { this._sub = value; },1162 enumerable: true,1163 configurable: true1164 });1165 Object.defineProperty(AccountLink.prototype, "op", {1166 get: function () { return this._op; },1167 set: function (value) { this._op = value; },1168 enumerable: true,1169 configurable: true1170 });1171 AccountLink.prototype._setAccountLink = function (obj) {1172 if (obj._id != null) {1173 this.__id = obj._id;1174 }1175 if (obj.iss != null) {1176 this._iss = obj.iss;1177 }1178 if (obj.sub != null) {1179 this._sub = obj.sub;1180 }1181 if (obj.op != null) {1182 this._op = obj.op;1183 }1184 return this;1185 };1186 return AccountLink;1187}());1188exports.AccountLink = AccountLink;1189exports.AclPermission = {1190 READ: "r",1191 WRITE: "w",1192 CREATE: "c",1193 UPDATE: "u",1194 DELETE: "d",1195 ADMIN: "admin",1196 OWNER: "owner"1197};1198exports.AclGroup = {1199 AUTHENTICATED: "g:authenticated",1200 ANONYMOUS: "g:anonymous"1201};1202var Acl = (function () {1203 function Acl(json) {1204 exports.nbLogger("Acl(), json=" + json);1205 this._acl = {1206 r: [],1207 w: [],1208 c: [],1209 u: [],1210 d: [],1211 admin: []1212 };1213 if (json) {1214 for (var _i = 0, _a = [Acl.OWNER, Acl.READ, Acl.WRITE, Acl.CREATE, Acl.UPDATE, Acl.DELETE, Acl.ADMIN]; _i < _a.length; _i++) {1215 var key = _a[_i];1216 if (json[key]) {1217 this._acl[key] = json[key];1218 }1219 }1220 }1221 }1222 Acl.prototype.addEntry = function (permission, entry) {1223 var entries = this._acl[permission];1224 if (!entries) {1225 return false;1226 }1227 if (!entry) {1228 return false;1229 }1230 var add = null;1231 if (entry instanceof User) {1232 add = entry._id;1233 }1234 else if (entry instanceof Group) {1235 add = "g:" + entry.groupname;1236 }1237 else {1238 add = entry;1239 }1240 var exist = false;1241 for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {1242 var target = entries_1[_i];1243 if (target === add) {1244 exist = true;1245 break;1246 }1247 }1248 if (!exist) {1249 entries.push(add);1250 exports.nbLogger("Acl.addEntry(), added entry=" + add);1251 return true;1252 }1253 return false;1254 };1255 Acl.prototype.removeEntry = function (permission, entry) {1256 var entries = this._acl[permission];1257 if (!entries) {1258 return false;1259 }1260 if (!entry) {1261 return false;1262 }1263 var remove = null;1264 if (entry instanceof User) {1265 remove = entry._id;1266 }1267 else if (entry instanceof Group) {1268 remove = "g:" + entry.groupname;1269 }1270 else {1271 remove = entry;1272 }1273 for (var i = 0; i < entries.length; i++) {1274 var target = entries[i];1275 if (target === remove) {1276 entries.splice(i, 1);1277 exports.nbLogger("Acl.removeEntry(), removed entry=" + remove);1278 break;1279 }1280 }1281 };1282 Acl.prototype._setOwner = function (owner) {1283 this._acl[Acl.OWNER] = owner;1284 };1285 Acl.prototype.getOwner = function () {1286 if (this._acl.owner) {1287 return this._acl.owner;1288 }1289 return null;1290 };1291 Acl.prototype.getEntries = function (permission) {1292 var entries = this._acl[permission];1293 if (!entries) {1294 return null;1295 }1296 return entries;1297 };1298 Acl.prototype._set = function (acl) {1299 this._acl = acl;1300 };1301 Acl.prototype._hasEntry = function (permission, target) {1302 var entries = this._acl[permission];1303 if (entries) {1304 for (var _i = 0, entries_2 = entries; _i < entries_2.length; _i++) {1305 var entry = entries_2[_i];1306 if (entry === target) {1307 return true;1308 }1309 }1310 }1311 return false;1312 };1313 Acl.prototype._toString = function (keyName) {1314 return JSON.stringify(this._toJsonObject(keyName));1315 };1316 Acl.prototype._toJsonObject = function (keyName) {1317 if (keyName === "ACL" || keyName === "contentACL") {1318 var json = {};1319 json[keyName] = this._acl;1320 return json;1321 }1322 else {1323 return this._acl;1324 }1325 };1326 Acl.READ = "r";1327 Acl.WRITE = "w";1328 Acl.CREATE = "c";1329 Acl.UPDATE = "u";1330 Acl.DELETE = "d";1331 Acl.ADMIN = "admin";1332 Acl.OWNER = "owner";1333 Acl.AUTHENTICATED = "g:authenticated";1334 Acl.ANONYMOUS = "g:anonymous";1335 return Acl;1336}());1337exports.Acl = Acl;1338exports.RegexOption = {1339 CASE_INSENSITIVITY: "i"1340};1341var Clause = (function () {1342 function Clause(clause) {1343 if (clause != null) {1344 this._clause = clause;1345 }1346 else {1347 this._clause = {};1348 }1349 }1350 Clause.prototype._setParams = function (key, operator, value, options) {1351 if (operator === null) {1352 this._clause[key] = value;1353 }1354 else {1355 var data = {};1356 if (exports._isObject(this._clause[key])) {1357 data = this._clause[key];1358 }1359 data[operator] = value;1360 if (options) {1361 data["$options"] = options;1362 }1363 this._clause[key] = data;1364 }1365 return this;1366 };1367 Clause.prototype.json = function () {1368 return this._clause;1369 };1370 Clause.equals = function (key, value) {1371 return new Clause().equals(key, value);1372 };1373 Clause.prototype.equals = function (key, value) {1374 var operator = null;1375 if (value != null && exports._isObject(value)) {1376 operator = "$eq";1377 }1378 return this._setParams(key, operator, value);1379 };1380 Clause.notEquals = function (key, value) {1381 return new Clause().notEquals(key, value);1382 };1383 Clause.prototype.notEquals = function (key, value) {1384 return this._setParams(key, "$ne", value);1385 };1386 Clause.lessThan = function (key, value) {1387 return new Clause().lessThan(key, value);1388 };1389 Clause.prototype.lessThan = function (key, value) {1390 return this._setParams(key, "$lt", value);1391 };1392 Clause.lessThanOrEqual = function (key, value) {1393 return new Clause().lessThanOrEqual(key, value);1394 };1395 Clause.prototype.lessThanOrEqual = function (key, value) {1396 return this._setParams(key, "$lte", value);1397 };1398 Clause.greaterThan = function (key, value) {1399 return new Clause().greaterThan(key, value);1400 };1401 Clause.prototype.greaterThan = function (key, value) {1402 return this._setParams(key, "$gt", value);1403 };1404 Clause.greaterThanOrEqual = function (key, value) {1405 return new Clause().greaterThanOrEqual(key, value);1406 };1407 Clause.prototype.greaterThanOrEqual = function (key, value) {1408 return this._setParams(key, "$gte", value);1409 };1410 Clause.in = function (key, values) {1411 return new Clause().in(key, values);1412 };1413 Clause.prototype.in = function (key, values) {1414 return this._setParams(key, "$in", values);1415 };1416 Clause.all = function (key, values) {1417 return new Clause().all(key, values);1418 };1419 Clause.prototype.all = function (key, values) {1420 return this._setParams(key, "$all", values);1421 };1422 Clause.exist = function (key, value) {1423 return new Clause().exist(key, value);1424 };1425 Clause.prototype.exist = function (key, value) {1426 if (typeof value === "boolean") {1427 return this._setParams(key, "$exists", value);1428 }1429 throw new Error("exist: value is not boolean");1430 };1431 Clause.regex = function (key, expression, option) {1432 return new Clause().regex(key, expression, option);1433 };1434 Clause.prototype.regex = function (key, expression, option) {1435 return this._setParams(key, "$regex", expression, option);1436 };1437 Clause.prototype.not = function (key) {1438 var data;1439 if (this._clause === null || !(this._clause[key] != null)) {1440 return null;1441 }1442 else if (exports._isObject(this._clause[key])) {1443 data = {1444 "$not": this._clause[key]1445 };1446 this._clause[key] = data;1447 }1448 else {1449 data = {1450 "$not": {1451 "$eq": this._clause[key]1452 }1453 };1454 this._clause[key] = data;1455 }1456 return this;1457 };1458 Clause.and = function () {1459 var clauses = [];1460 for (var _i = 0; _i < arguments.length; _i++) {1461 clauses[_i] = arguments[_i];1462 }1463 var values = Clause._convertClauseArray(clauses);1464 return new Clause()._setParams("$and", null, values);1465 };1466 Clause.or = function () {1467 var clauses = [];1468 for (var _i = 0; _i < arguments.length; _i++) {1469 clauses[_i] = arguments[_i];1470 }1471 var values = Clause._convertClauseArray(clauses);1472 return new Clause()._setParams("$or", null, values);1473 };1474 Clause._convertClauseArray = function (clauseArray) {1475 var values = [];1476 for (var _i = 0, clauseArray_1 = clauseArray; _i < clauseArray_1.length; _i++) {1477 var clause = clauseArray_1[_i];1478 var value = clause.json();1479 if (value != null) {1480 values.push(value);1481 }1482 }1483 return values;1484 };1485 return Clause;1486}());1487exports.Clause = Clause;1488var ObjectQuery = (function () {1489 function ObjectQuery() {1490 this._clause = null;1491 this._limit = -1;1492 this._skip = 0;1493 this._sort = [];1494 this._deleteMark = false;1495 this._countQuery = false;1496 this._projection = null;1497 }1498 ObjectQuery.prototype.getClause = function () {1499 return this._clause;1500 };1501 ObjectQuery.prototype.getLimit = function () {1502 return this._limit;1503 };1504 ObjectQuery.prototype.getSkipCount = function () {1505 return this._skip;1506 };1507 ObjectQuery.prototype.getSort = function () {1508 return this._sort;1509 };1510 ObjectQuery.prototype.getSortOrder = function () {1511 var result = [];1512 for (var i = 0; i < this._sort.length; i++) {1513 var key = this._sort[i];1514 var e = {};1515 if (key.match(/^-/)) {1516 e[key.substr(1)] = false;1517 }1518 else {1519 e[key] = true;1520 }1521 result.push(e);1522 }1523 return result;1524 };1525 ObjectQuery.prototype._getDeleteMark = function () {1526 return this._deleteMark;1527 };1528 ObjectQuery.prototype.getProjection = function () {1529 return this._projection;1530 };1531 ObjectQuery.prototype._setDeleteMark = function (mark) {1532 if (typeof mark === "boolean") {1533 exports.nbLogger("ObjectQuery._setDeleteMark(), mark=" + mark + ", cur=" + this._deleteMark);1534 this._deleteMark = mark;1535 }1536 else {1537 throw new Error("deleteMark must be boolean");1538 }1539 };1540 ObjectQuery.prototype._toParam = function () {1541 var json = this._toParamJson();1542 if (json.where) {1543 json.where = JSON.stringify(json.where);1544 }1545 if (json.projection) {1546 json.projection = JSON.stringify(json.projection);1547 }1548 return json;1549 };1550 ObjectQuery.prototype._toParamJson = function () {1551 var json = {};1552 if (this._clause) {1553 json.where = this._clause.json();1554 }1555 if (this._sort.length > 0) {1556 json.order = this._sort.join(",");1557 }1558 json.skip = this._skip;1559 json.limit = this._limit;1560 if (this._countQuery) {1561 json.count = 1;1562 }1563 if (this._deleteMark) {1564 json.deleteMark = 1;1565 }1566 if (this._projection) {1567 json.projection = this._projection;1568 }1569 return json;1570 };1571 ObjectQuery._toObjectQuery = function (queryJson) {1572 var query = new ObjectQuery();1573 exports.nbLogger("ObjectQuery._toObjectQuery(), queryJson=" + JSON.stringify(queryJson));1574 if (queryJson["limit"] != null) {1575 query.setLimit(queryJson["limit"]);1576 }1577 if (queryJson["skip"] != null) {1578 query.setSkipCount(queryJson["skip"]);1579 }1580 var sort = queryJson["sort"];1581 if (sort != null) {1582 for (var _i = 0, _a = Object.keys(sort); _i < _a.length; _i++) { 1583 var sortKey = _a[_i];1584 query.setSortOrder(sortKey, sort[sortKey]);1585 }1586 }1587 var clause = queryJson["clause"];1588 if (clause != null && Object.keys(clause).length !== 0) {1589 query.setClause(new Clause(clause));1590 }1591 if (queryJson["deleteMark"] != null) {1592 query._setDeleteMark(queryJson["deleteMark"]);1593 }1594 if (queryJson["countQuery"] != null) {1595 query._setCountQuery(queryJson["countQuery"]);1596 }1597 return query;1598 };1599 ObjectQuery.prototype._equals = function (that) {1600 if (this._limit !== that.getLimit()) {1601 return false;1602 }1603 if (this._skip !== that.getSkipCount()) {1604 return false;1605 }1606 if (this._deleteMark !== that._getDeleteMark()) {1607 return false;1608 }1609 if (this._countQuery !== that._isCountQuery()) {1610 return false;1611 }1612 if (this._projection) {1613 if (that.getProjection()) {1614 if (!exports._compareObject(this._projection, that.getProjection())) {1615 return false;1616 }1617 }1618 else {1619 return false;1620 }1621 }1622 else {1623 if (that.getProjection()) {1624 return false;1625 }1626 }1627 if (this._clause) {1628 if (that.getClause()) {1629 if (!exports._compareObject(this._clause.json(), that.getClause().json())) {1630 return false;1631 }1632 }1633 else {1634 return false;1635 }1636 }1637 else {1638 if (that.getClause()) {1639 return false;1640 }1641 }1642 return exports._compareObject(this._sort, that.getSortOrder());1643 };1644 ObjectQuery.prototype.setClause = function (clause) {1645 if (clause === null || clause instanceof Clause) {1646 this._clause = clause;1647 }1648 else {1649 throw new Error("clause must be instanceof Nebula.Clause or null");1650 }1651 return this;1652 };1653 ObjectQuery.prototype.setLimit = function (limit) {1654 if (limit >= -1) {1655 this._limit = limit;1656 }1657 else {1658 throw new Error("Invalid limit range");1659 }1660 return this;1661 };1662 ObjectQuery.prototype.setSkipCount = function (skip) {1663 if (skip >= 0) {1664 this._skip = skip;1665 }1666 else {1667 throw new Error("Invalid skip range");1668 }1669 return this;1670 };1671 ObjectQuery.prototype.setSort = function (sort) {1672 this._sort = sort;1673 return this;1674 };1675 ObjectQuery.prototype.setSortOrder = function (key, isAsc) {1676 if (!key) {1677 throw new Error("No key");1678 }1679 if (typeof isAsc !== "boolean") {1680 throw new Error("isAsc must be boolean");1681 }1682 if (isAsc) {1683 this._sort.push(key);1684 }1685 else {1686 this._sort.push("-" + key);1687 }1688 return this;1689 };1690 ObjectQuery.prototype.clearSortOrder = function (key) {1691 if (key === void 0) { key = null; }1692 if (!key) {1693 this._sort = [];1694 }1695 else {1696 for (var i = 0; i < this._sort.length; i++) {1697 var k = this._sort[i];1698 if (k === key || k === "-" + key) {1699 this._sort.splice(i, 1);1700 break;1701 }1702 }1703 }1704 return this;1705 };1706 ObjectQuery.prototype._setCountQuery = function (countQuery) {1707 if (typeof countQuery === "boolean") {1708 this._countQuery = countQuery;1709 }1710 else {1711 throw new Error("countQuery must be boolean");1712 }1713 return this;1714 };1715 ObjectQuery.prototype._isCountQuery = function () {1716 return this._countQuery;1717 };1718 ObjectQuery.prototype.setProjection = function (projectionJson) {1719 if (projectionJson && exports._isObject(projectionJson)) {1720 this._projection = projectionJson;1721 }1722 else if (projectionJson === null) {1723 this._projection = null;1724 }1725 else {1726 throw new Error("projection must be object or null");1727 }1728 return this;1729 };1730 return ObjectQuery;1731}());1732exports.ObjectQuery = ObjectQuery;1733var User = (function () {1734 function User(service) {1735 if (service === void 0) { service = exports.Nebula; }1736 this._service = service;1737 this.__id = null;1738 this._username = null;1739 this._email = null;1740 this._password = null;1741 this._options = null;1742 this._groups = null;1743 this._createdAt = null;1744 this._updatedAt = null;1745 this._lastLoginAt = null;1746 this._etag = null;1747 this._sessionToken = null;1748 this._expire = null;1749 this._clientCertUser = null;1750 this._federated = false;1751 this._primaryLinkedUserId = null;1752 }1753 Object.defineProperty(User.prototype, "_id", {1754 get: function () { return this.__id; },1755 set: function (value) { this.__id = value; },1756 enumerable: true,1757 configurable: true1758 });1759 Object.defineProperty(User.prototype, "username", {1760 get: function () { return this._username; },1761 set: function (value) { this._username = value; },1762 enumerable: true,1763 configurable: true1764 });1765 Object.defineProperty(User.prototype, "email", {1766 get: function () { return this._email; },1767 set: function (value) { this._email = value; },1768 enumerable: true,1769 configurable: true1770 });1771 Object.defineProperty(User.prototype, "password", {1772 get: function () { return this._password; },1773 set: function (value) { this._password = value; },1774 enumerable: true,1775 configurable: true1776 });1777 Object.defineProperty(User.prototype, "options", {1778 get: function () { return this._options; },1779 set: function (value) { this._options = value; },1780 enumerable: true,1781 configurable: true1782 });1783 Object.defineProperty(User.prototype, "groups", {1784 get: function () { return this._groups; },1785 set: function (value) { this._groups = value; },1786 enumerable: true,1787 configurable: true1788 });1789 Object.defineProperty(User.prototype, "createdAt", {1790 get: function () { return this._createdAt; },1791 set: function (value) { this._createdAt = value; },1792 enumerable: true,1793 configurable: true1794 });1795 Object.defineProperty(User.prototype, "updatedAt", {1796 get: function () { return this._updatedAt; },1797 set: function (value) { this._updatedAt = value; },1798 enumerable: true,1799 configurable: true1800 });1801 Object.defineProperty(User.prototype, "lastLoginAt", {1802 get: function () { return this._lastLoginAt; },1803 set: function (value) { this._lastLoginAt = value; },1804 enumerable: true,1805 configurable: true1806 });1807 Object.defineProperty(User.prototype, "etag", {1808 get: function () { return this._etag; },1809 set: function (value) { this._etag = value; },1810 enumerable: true,1811 configurable: true1812 });1813 Object.defineProperty(User.prototype, "sessionToken", {1814 get: function () { return this._sessionToken; },1815 set: function (value) { this._sessionToken = value; },1816 enumerable: true,1817 configurable: true1818 });1819 Object.defineProperty(User.prototype, "expire", {1820 get: function () { return this._expire; },1821 set: function (value) { this._expire = value; },1822 enumerable: true,1823 configurable: true1824 });1825 Object.defineProperty(User.prototype, "clientCertUser", {1826 get: function () { return this._clientCertUser; },1827 set: function (value) { this._clientCertUser = value; },1828 enumerable: true,1829 configurable: true1830 });1831 Object.defineProperty(User.prototype, "federated", {1832 get: function () { return this._federated; },1833 set: function (value) { this._federated = value; },1834 enumerable: true,1835 configurable: true1836 });1837 Object.defineProperty(User.prototype, "primaryLinkedUserId", {1838 get: function () { return this._primaryLinkedUserId; },1839 set: function (value) { this._primaryLinkedUserId = value; },1840 enumerable: true,1841 configurable: true1842 });1843 User.prototype._setUserInfo = function (response) {1844 exports.nbLogger("User._setUserInfo#start");1845 var jsonObj;1846 try {1847 jsonObj = JSON.parse(response);1848 }1849 catch (undefined) {1850 exports.nbError("User._setUserInfo#json error.");1851 jsonObj = null;1852 }1853 if (jsonObj !== null) {1854 if (jsonObj._id !== undefined) {1855 this._id = jsonObj._id;1856 }1857 if (jsonObj.username !== undefined) {1858 this.username = jsonObj.username;1859 }1860 if (jsonObj.email !== undefined) {1861 this.email = jsonObj.email;1862 }1863 if (jsonObj.password !== undefined) {1864 this.password = jsonObj.password;1865 }1866 if (jsonObj.options !== undefined) {1867 this.options = jsonObj.options;1868 }1869 if (jsonObj.groups !== undefined) {1870 this.groups = jsonObj.groups;1871 }1872 if (jsonObj.createdAt !== undefined) {1873 this.createdAt = jsonObj.createdAt;1874 }1875 if (jsonObj.updatedAt !== undefined) {1876 this.updatedAt = jsonObj.updatedAt;1877 }1878 if (jsonObj.lastLoginAt !== undefined) {1879 this.lastLoginAt = jsonObj.lastLoginAt;1880 }1881 if (jsonObj.etag !== undefined) {1882 this.etag = jsonObj.etag;1883 }1884 if (jsonObj.sessionToken !== undefined) {1885 this.sessionToken = jsonObj.sessionToken;1886 }1887 if (jsonObj.expire !== undefined) {1888 this.expire = jsonObj.expire;1889 }1890 if (jsonObj.clientCertUser !== undefined) {1891 this.clientCertUser = jsonObj.clientCertUser;1892 }1893 if (jsonObj.federated !== undefined) {1894 this.federated = jsonObj.federated;1895 }1896 if (jsonObj.primaryLinkedUserId !== undefined) {1897 this.primaryLinkedUserId = jsonObj.primaryLinkedUserId;1898 }1899 }1900 };1901 User.prototype.set = function (property, value) {1902 switch (property) {1903 case "_id":1904 this._id = value;1905 break;1906 case "username":1907 this.username = value;1908 break;1909 case "email":1910 this.email = value;1911 break;1912 case "password":1913 this.password = value;1914 break;1915 case "options":1916 this.options = value;1917 break;1918 case "createdAt":1919 this.createdAt = value;1920 break;1921 case "updatedAt":1922 this._updatedAt = value;1923 break;1924 case "sessionToken":1925 this.sessionToken = value;1926 break;1927 case "expire":1928 this.expire = value;1929 break;1930 case "clientCertUser":1931 this.clientCertUser = value;1932 break;1933 case "federated":1934 this.federated = value;1935 break;1936 case "primaryLinkedUserId":1937 this.primaryLinkedUserId = value;1938 break;1939 default:1940 exports.nbError("Invalid property: " + property);1941 throw new Error("Invalid property: " + property);1942 }1943 };1944 User.prototype.get = function (property) {1945 switch (property) {1946 case "_id":1947 return this._id;1948 case "username":1949 return this.username;1950 case "email":1951 return this.email;1952 case "password":1953 return this.password;1954 case "options":1955 return this.options;1956 case "groups":1957 return this.groups;1958 case "createdAt":1959 return this.createdAt;1960 case "updatedAt":1961 return this.updatedAt;1962 case "sessionToken":1963 return this.sessionToken;1964 case "expire":1965 return this.expire;1966 case "clientCertUser":1967 return this.clientCertUser;1968 case "federated":1969 return this.federated;1970 case "primaryLinkedUserId":1971 return this.primaryLinkedUserId;1972 default:1973 exports.nbError("Invalid property");1974 throw new Error("Invalid property name");1975 }1976 };1977 User.prototype.register = function (callbacks) {1978 var _this = this;1979 exports.nbLogger("User.register#start");1980 var request;1981 if (this._service.isOffline()) {1982 request = new _SdeRequest("NebulaUser", "register");1983 }1984 else {1985 var path = "/users";1986 exports.nbLogger("User.register#REST API Request path = " + path);1987 request = new HttpRequest(this._service, path);1988 request.setMethod("POST");1989 request.setContentType("application/json");1990 }1991 var registerParams;1992 if (this.clientCertUser === true) {1993 registerParams = {1994 clientCertUser: true,1995 username: this.username1996 };1997 }1998 else {1999 registerParams = {2000 email: this.email,2001 password: this.password2002 };2003 if (this.username != null) {2004 registerParams.username = this.username;2005 }2006 }2007 if (this.options !== null) {2008 registerParams.options = this.options;2009 }2010 request.setData(registerParams);2011 var promise = request.execute()2012 .then(function (response) {2013 exports.nbLogger("User.register#success callback start");2014 exports.nbLogger("User.register#response = " + response);2015 _this._setUserInfo(response);2016 return _this;2017 })2018 .catch(function (error) {2019 exports.nbLogger("User.register#error callback start");2020 exports.nbLogger(("User.register#error = " + (exports._errorText(error))));2021 return Promise.reject(error);2022 });2023 exports.nbLogger("User.register#end");2024 return exports._promisify(promise, callbacks);2025 };2026 User.login = function (userInfo, callbacks) { return null; };2027 User._login = function (service, userInfo, callbacks) {2028 exports.nbLogger("User.login#start");2029 if (userInfo == null || (userInfo.email == null && userInfo.username == null && userInfo.token == null)) {2030 throw new Error("User.login: No username nor email nor token");2031 }2032 if (userInfo.password == null && userInfo.token == null) {2033 throw new Error("User.login: No password nor token");2034 }2035 var request;2036 if (service.isOffline()) {2037 request = new _SdeRequest("NebulaUser", "login");2038 }2039 else {2040 var path = "/login";2041 exports.nbLogger("User.login#REST API Request path = " + path);2042 request = new HttpRequest(service, path);2043 request.setSessionToken(null);2044 request.setMethod("POST");2045 request.setContentType("application/json");2046 }2047 request.setData(userInfo);2048 var user = new service.User();2049 user.email = userInfo.email;2050 user.username = userInfo.username;2051 var promise = request.execute()2052 .then(function (response) {2053 exports.nbLogger("User.login#success callback start");2054 exports.nbLogger("User.login#response = " + response);2055 user._setUserInfo(response);2056 service.setCurrentUser(user);2057 return user;2058 })2059 .catch(function (error) {2060 exports.nbLogger("User.login#error callback start");2061 exports.nbLogger(("User.login#error = " + (exports._errorText(error))));2062 return Promise.reject(error);2063 });2064 exports.nbLogger("User.login#end");2065 return exports._promisify(promise, callbacks);2066 };2067 User.logout = function (callbacks) { return null; };2068 User._logout = function (service, callbacks) {2069 exports.nbLogger("User.logout#start");2070 var request;2071 if (service.isOffline()) {2072 request = new _SdeRequest("NebulaUser", "logout");2073 }2074 else {2075 var path = "/login";2076 exports.nbLogger("User.logout#REST API Request path = " + path);2077 request = new HttpRequest(service, path);2078 request.setMethod("DELETE");2079 request.setContentType("application/json");2080 }2081 var promise = request.execute()2082 .then(function (response) {2083 exports.nbLogger("User.logout#success callback start");2084 exports.nbLogger("User.logout#response = " + response);2085 service.removeCurrentUser();2086 return;2087 })2088 .catch(function (error) {2089 exports.nbLogger("User.logout#error callback start");2090 exports.nbLogger(("User.logout#error = " + (exports._errorText(error))));2091 service.removeCurrentUser();2092 return Promise.reject(error);2093 });2094 exports.nbLogger("User.logout#end");2095 return exports._promisify(promise, callbacks);2096 };2097 User.current = function (callbacks) { return null; };2098 User._current = function (service, callbacks) {2099 var user = null;2100 var _currentObj = service.getCurrentUser();2101 if (_currentObj !== null) {2102 user = new service.User();2103 user._setUserInfo(JSON.stringify(_currentObj));2104 }2105 if (callbacks && callbacks.success) {2106 callbacks.success(user);2107 }2108 return user;2109 };2110 User.saveCurrent = function (userInfo) { };2111 User._saveCurrent = function (service, userInfo) {2112 if (service.isOffline()) {2113 throw new Error("Not supported in offline mode");2114 }2115 if ((userInfo === null)) {2116 service.removeCurrentUser();2117 }2118 else {2119 var newInfo = service.getCurrentUser() || {};2120 for (var key in userInfo) {2121 if (userInfo.hasOwnProperty(key)) {2122 newInfo[key] = userInfo[key];2123 }2124 }2125 var user = new service.User();2126 user._setUserInfo(JSON.stringify(newInfo));2127 service.setCurrentUser(user);2128 }2129 };2130 User.queryCurrent = function (callbacks) { return null; };2131 User._queryCurrent = function (service, callbacks) {2132 exports.nbLogger("User.queryCurrent#start");2133 var request;2134 if (service.isOffline()) {2135 var _currentObj = service.getCurrentUser();2136 if (_currentObj === null) {2137 return exports._promisify(Promise.resolve(null), callbacks);2138 }2139 request = new _SdeRequest("NebulaUser", "current");2140 }2141 else {2142 var path = "/users/current";2143 exports.nbLogger("User.queryCurrent#REST API Request path = " + path);2144 request = new HttpRequest(service, path);2145 request.setMethod("GET");2146 request.setContentType("application/json");2147 }2148 var promise = request.execute()2149 .then(function (response) {2150 exports.nbLogger("User.queryCurrent#success callback start");2151 exports.nbLogger("User.queryCurrent#response = " + response);2152 var user = new service.User();2153 user._setUserInfo(response);2154 return user;2155 })2156 .catch(function (error) {2157 exports.nbLogger("User.queryCurrent#error callback start");2158 exports.nbLogger(("User.queryCurrent#error = " + (exports._errorText(error))));2159 return Promise.reject(error);2160 });2161 exports.nbLogger("User.queryCurrent#end");2162 return exports._promisify(promise, callbacks);2163 };2164 User.query = function (conditions, callbacks) { return null; };2165 User._query = function (service, conditions, callbacks) {2166 exports.nbLogger("User.query#start");2167 var request;2168 if (service.isOffline()) {2169 request = new _SdeRequest("NebulaUser", "query");2170 if (conditions !== null) {2171 request.setData(conditions);2172 }2173 }2174 else {2175 var path = "/users";2176 var queryParams = {};2177 if (conditions) {2178 if (conditions._id) {2179 path = "/users/" + encodeURIComponent(conditions._id);2180 }2181 else if (conditions.email) {2182 queryParams.email = conditions.email;2183 }2184 else if (conditions.username) {2185 queryParams.username = conditions.username;2186 }2187 if (conditions.skip != null) {2188 queryParams.skip = conditions.skip;2189 }2190 if (conditions.limit != null) {2191 queryParams.limit = conditions.limit;2192 }2193 } 2194 exports.nbLogger("User.query#REST API Request path = " + path);2195 request = new HttpRequest(service, path);2196 request.setMethod("GET");2197 request.setQueryParams(queryParams);2198 request.setContentType("application/json");2199 }2200 var promise = request.execute()2201 .then(function (response) {2202 exports.nbLogger("User.query#success callback start");2203 exports.nbLogger("User.query#response = " + response);2204 var obj = JSON.parse(response);2205 var objArray = [];2206 var userArray = [];2207 var i = 0;2208 if (obj.results === undefined) {2209 objArray.push(obj);2210 }2211 else {2212 objArray = obj.results;2213 }2214 while (i < objArray.length) {2215 var user = new service.User();2216 user._setUserInfo(JSON.stringify(objArray[i]));2217 userArray.push(user);2218 i++;2219 }2220 if (conditions != null && conditions.countQuery) {2221 return {2222 users: userArray,2223 count: obj.count2224 };2225 }2226 else {2227 return userArray;2228 }2229 })2230 .catch(function (error) {2231 exports.nbLogger("User.query#error callback start");2232 exports.nbLogger(("User.query#error = " + (exports._errorText(error))));2233 return Promise.reject(error);2234 });2235 exports.nbLogger("User.query#end");2236 return exports._promisify(promise, callbacks);2237 };2238 User.update = function (user, callbacks) { return null; };2239 User._update = function (service, user, callbacks) {2240 if (!(user instanceof User)) {2241 throw new Error("User.update: not User instance");2242 }2243 if (user._service !== service) {2244 throw new Error("Service does not match");2245 }2246 return user._update(callbacks);2247 };2248 User.prototype._update = function (callbacks) {2249 var _this = this;2250 var path;2251 var request;2252 var error;2253 exports.nbLogger("User.update#start");2254 if (this._id === null) {2255 exports.nbLogger("User.update: no user id");2256 error = exports._createError(400, "Bad Request (local)", "no user id.");2257 return exports._promisify(Promise.reject(error), callbacks);2258 }2259 var updateParams = {};2260 if (this._service.isOffline()) {2261 request = new _SdeRequest("NebulaUser", "update");2262 updateParams._id = this._id;2263 }2264 else {2265 path = "/users/" + this._id;2266 exports.nbLogger("User.update#REST API Request path = " + path);2267 request = new HttpRequest(this._service, path);2268 request.setMethod("PUT");2269 request.setContentType("application/json");2270 delete updateParams._id;2271 }2272 if (this.email !== null) {2273 updateParams.email = this.email;2274 }2275 if (this.username !== null) {2276 updateParams.username = this.username;2277 }2278 if (this.password !== null) {2279 updateParams.password = this.password;2280 }2281 if (this.options !== null) {2282 updateParams.options = this.options;2283 }2284 request.setData(updateParams);2285 var promise = request.execute()2286 .then(function (response) {2287 exports.nbLogger("User.update#success callback start");2288 exports.nbLogger("User.update#response = " + response);2289 _this._setUserInfo(response);2290 return _this;2291 })2292 .catch(function (error) {2293 exports.nbLogger("User.update#error callback start");2294 exports.nbLogger(("User.update#error = " + (exports._errorText(error))));2295 return Promise.reject(error);2296 });2297 exports.nbLogger("User.update#end");2298 return exports._promisify(promise, callbacks);2299 };2300 User.remove = function (user, callbacks) { return null; };2301 User._remove = function (service, user, callbacks) {2302 if (!(user instanceof User)) {2303 throw new Error("User.remove: not User instance");2304 }2305 if (user._service !== service) {2306 throw new Error("User.remove: service does not match");2307 }2308 return user._remove(callbacks);2309 };2310 User.prototype._remove = function (callbacks) {2311 var _this = this;2312 exports.nbLogger("User.remove#start");2313 if (this._id === null) {2314 exports.nbLogger("User.remove: no user id.");2315 var error = exports._createError(400, "Bad argument (local)", "no user id.");2316 return exports._promisify(Promise.reject(error), callbacks);2317 }2318 var request;2319 if (this._service.isOffline()) {2320 request = new _SdeRequest("NebulaUser", "delete");2321 request.setData({2322 _id: this._id2323 });2324 }2325 else {2326 var path = "/users/" + this._id;2327 exports.nbLogger("User.remove#REST API Request path = " + path);2328 request = new HttpRequest(this._service, path);2329 request.setMethod("DELETE");2330 }2331 var promise = request.execute()2332 .then(function (response) {2333 exports.nbLogger("User.remove#success callback start");2334 exports.nbLogger("User.remove#response = " + response);2335 var _currentUser = _this._service.getCurrentUser();2336 if (_currentUser !== null) {2337 if (_this._id === _currentUser._id) {2338 exports.nbLogger("User.remove#delete user is current user");2339 _this._service.removeCurrentUser();2340 }2341 }2342 return;2343 })2344 .catch(function (error) {2345 exports.nbLogger("User.remove#error callback start");2346 exports.nbLogger(("User.remove#error = " + (exports._errorText(error))));2347 return Promise.reject(error);2348 });2349 exports.nbLogger("User.remove#end");2350 return exports._promisify(promise, callbacks);2351 };2352 User.resetPassword = function (userInfo, callbacks) { return null; };2353 User._resetPassword = function (service, userInfo, callbacks) {2354 exports.nbLogger("User.resetPassword#start");2355 if (userInfo == null || (userInfo.email == null && userInfo.username == null)) {2356 throw new Error("User.resetPassword: bad arguments");2357 }2358 var request;2359 if (service.isOffline()) {2360 request = new _SdeRequest("NebulaUser", "resetPassword");2361 }2362 else {2363 var path = "/request_password_reset";2364 exports.nbLogger("User.resetPassword#REST API Request path = " + path);2365 request = new HttpRequest(service, path);2366 request.setSessionToken(null);2367 request.setMethod("POST");2368 request.setContentType("application/json");2369 }2370 var resetParams;2371 if (((userInfo.email !== undefined) && (userInfo.username !== undefined))) {2372 resetParams = {2373 email: userInfo.email,2374 username: userInfo.username2375 };2376 }2377 else if (((userInfo.email !== undefined) && (userInfo.username === undefined))) {2378 resetParams = {2379 email: userInfo.email2380 };2381 }2382 else if (((userInfo.email === undefined) && (userInfo.username !== undefined))) {2383 resetParams = {2384 username: userInfo.username2385 };2386 }2387 request.setData(resetParams);2388 var promise = request.execute()2389 .then(function (response) {2390 exports.nbLogger("User.resetPassword#success callback start");2391 exports.nbLogger("User.resetPassword#response = " + response);2392 return;2393 })2394 .catch(function (error) {2395 exports.nbLogger("User.resetPassword#error callback start");2396 exports.nbLogger(("User.resetPassword#error = " + (exports._errorText(error))));2397 return Promise.reject(error);2398 });2399 exports.nbLogger("User.delete#end");2400 return exports._promisify(promise, callbacks);2401 };2402 User.getAccountLinks = function (user, callbacks) { return null; };2403 User._getAccountLinks = function (service, user, callbacks) {2404 if (!(user instanceof User)) {2405 throw new Error("User.getAccountLinks: not User instance");2406 }2407 if (user._service !== service) {2408 throw new Error("User.getAccountLinks: Service does not match");2409 }2410 return user._getAccountLinks(callbacks);2411 };2412 User.prototype._getAccountLinks = function (callbacks) {2413 exports.nbLogger("User.getAccountLinks#start");2414 if (this._service.isOffline()) {2415 throw new Error("User.getAccountLinks: offline mode is not supported");2416 }2417 if (this._id === null) {2418 throw new Error("User.getAccountLinks: no user id");2419 }2420 var path = "/users/" + this._id + "/links";2421 exports.nbLogger("User.getAccountLinks#REST API Request path = " + path);2422 var request = new HttpRequest(this._service, path);2423 request.setMethod("GET");2424 var promise = request.execute()2425 .then(function (response) {2426 exports.nbLogger("User.getAccountLinks#response = " + response);2427 var resObj = JSON.parse(response);2428 var resArray = resObj.results;2429 var links = [];2430 if (resArray != null) {2431 for (var _i = 0, resArray_1 = resArray; _i < resArray_1.length; _i++) {2432 var obj = resArray_1[_i];2433 var link = new AccountLink();2434 link._setAccountLink(obj);2435 links.push(link);2436 }2437 }2438 return links;2439 })2440 .catch(function (error) {2441 exports.nbLogger(("User.getAccountLinks#error = " + (exports._errorText(error))));2442 return Promise.reject(error);2443 });2444 exports.nbLogger("User.getAccountLinks#end");2445 return exports._promisify(promise, callbacks);2446 };2447 User.deleteAccountLink = function (user, linkedUserId, callbacks) { return null; };2448 User._deleteAccountLink = function (service, user, linkedUserId, callbacks) {2449 if (!(user instanceof User)) {2450 throw new Error("User.deleteAccountLink: not User instance");2451 }2452 if (user._service !== service) {2453 throw new Error("User.deleteAccountLink: Service does not match");2454 }2455 if (linkedUserId == null) {2456 throw new Error("User.deleteAccountLink: no linkedUserId");2457 }2458 return user._deleteAccountLink(linkedUserId, callbacks);2459 };2460 User.prototype._deleteAccountLink = function (linkedUserId, callbacks) {2461 exports.nbLogger("User.deleteAccountLink#start");2462 if (this._service.isOffline()) {2463 throw new Error("User.deleteAccountLink: offline mode is not supported");2464 }2465 if (this._id === null) {2466 throw new Error("User.deleteAccountLink: no user id");2467 }2468 if (this.primaryLinkedUserId !== null && this.primaryLinkedUserId === linkedUserId) {2469 throw new Error("User.deleteAccountLink: linkedUserId is primaryLinkedUserId");2470 }2471 var path = "/users/" + this._id + "/links/" + linkedUserId;2472 exports.nbLogger("User.deleteAccountLink#REST API Request path = " + path);2473 var request = new HttpRequest(this._service, path);2474 request.setMethod("DELETE");2475 var promise = request.execute()2476 .then(function (response) {2477 exports.nbLogger("User.deleteAccountLink#response = " + response);2478 return;2479 })2480 .catch(function (error) {2481 exports.nbLogger(("User.deleteAccountLink#error = " + (exports._errorText(error))));2482 return Promise.reject(error);2483 });2484 exports.nbLogger("User.deleteAccountLink#end");2485 return exports._promisify(promise, callbacks);2486 };2487 return User;2488}());2489exports.User = User;2490exports.declareUser = function (_service) {2491 var _a;2492 _service.User = (_a = (function (_super) {2493 __extends(_User, _super);2494 function _User() {2495 var _this = _super.call(this, _service) || this;2496 exports.nbLogger("User.constructor");2497 return _this;2498 }2499 _User.login = function (userInfo, callbacks) {2500 return _super._login.call(this, _service, userInfo, callbacks);2501 };2502 _User.logout = function (callbacks) {2503 return _super._logout.call(this, _service, callbacks);2504 };2505 _User.current = function (callbacks) {2506 return _super._current.call(this, _service, callbacks);2507 };2508 _User.saveCurrent = function (userInfo) {2509 _super._saveCurrent.call(this, _service, userInfo);2510 };2511 _User.queryCurrent = function (callbacks) {2512 return _super._queryCurrent.call(this, _service, callbacks);2513 };2514 _User.query = function (conditions, callbacks) {2515 return _super._query.call(this, _service, conditions, callbacks);2516 };2517 _User.update = function (user, callbacks) {2518 return _super._update.call(this, _service, user, callbacks);2519 };2520 _User.remove = function (user, callbacks) {2521 return _super._remove.call(this, _service, user, callbacks);2522 };2523 _User.resetPassword = function (userInfo, callbacks) {2524 return _super._resetPassword.call(this, _service, userInfo, callbacks);2525 };2526 _User.getAccountLinks = function (user, callbacks) {2527 return _super._getAccountLinks.call(this, _service, user, callbacks);2528 };2529 _User.deleteAccountLink = function (user, linkedUserId, callbacks) {2530 return _super._deleteAccountLink.call(this, _service, user, linkedUserId, callbacks);2531 };2532 return _User;2533 }(User)),2534 _a.delete = _a.remove,2535 _a);2536};2537var Group = (function () {2538 function Group(groupname, service) {2539 if (service === void 0) { service = exports.Nebula; }2540 this._service = service;2541 this._id = null;2542 this.groupname = null;2543 this.users = [];2544 this.groups = [];2545 this.acl = null;2546 this.createdAt = null;2547 this.updatedAt = null;2548 this.etag = null;2549 if (((typeof groupname) === "string") && groupname !== "") {2550 this.groupname = groupname;2551 }2552 }2553 Object.defineProperty(Group.prototype, "_id", {2554 get: function () { return this.__id; },2555 set: function (value) { this.__id = value; },2556 enumerable: true,2557 configurable: true2558 });2559 Object.defineProperty(Group.prototype, "groupname", {2560 get: function () { return this._groupname; },2561 set: function (value) { this._groupname = value; },2562 enumerable: true,2563 configurable: true2564 });2565 Object.defineProperty(Group.prototype, "users", {2566 get: function () { return this._users; },2567 set: function (value) { this._users = value; },2568 enumerable: true,2569 configurable: true2570 });2571 Object.defineProperty(Group.prototype, "groups", {2572 get: function () { return this._groups; },2573 set: function (value) { this._groups = value; },2574 enumerable: true,2575 configurable: true2576 });2577 Object.defineProperty(Group.prototype, "acl", {2578 get: function () { return this._acl; },2579 set: function (value) {2580 if (value != null && !(value instanceof Acl)) {2581 throw new Error("acl is not Acl instance!");2582 }2583 this._acl = value;2584 },2585 enumerable: true,2586 configurable: true2587 });2588 Object.defineProperty(Group.prototype, "createdAt", {2589 get: function () { return this._createdAt; },2590 set: function (value) { this._createdAt = value; },2591 enumerable: true,2592 configurable: true2593 });2594 Object.defineProperty(Group.prototype, "updatedAt", {2595 get: function () { return this._updatedAt; },2596 set: function (value) { this._updatedAt = value; },2597 enumerable: true,2598 configurable: true2599 });2600 Object.defineProperty(Group.prototype, "etag", {2601 get: function () { return this._etag; },2602 set: function (value) { this._etag = value; },2603 enumerable: true,2604 configurable: true2605 });2606 Group.prototype._setGroupInfo = function (response) {2607 var jsonObj;2608 try {2609 jsonObj = JSON.parse(response);2610 }2611 catch (undefined) {2612 exports.nbError("Group._setGroupInfo#json error.");2613 return;2614 }2615 if (jsonObj._id !== undefined) {2616 this._id = jsonObj._id;2617 }2618 if (jsonObj.name !== undefined) {2619 this.groupname = jsonObj.name;2620 }2621 if (jsonObj.users !== undefined) {2622 this.users = jsonObj.users;2623 }2624 if (jsonObj.groups !== undefined) {2625 this.groups = jsonObj.groups;2626 }2627 if (jsonObj.ACL !== undefined) {2628 this.acl = new Acl();2629 this.acl._set(jsonObj.ACL);2630 if (jsonObj.ACL.owner !== undefined) {2631 this.acl._setOwner(jsonObj.ACL.owner);2632 }2633 }2634 if (jsonObj.createdAt !== undefined) {2635 this.createdAt = jsonObj.createdAt;2636 }2637 if (jsonObj.updatedAt !== undefined) {2638 this.updatedAt = jsonObj.updatedAt;2639 }2640 if (jsonObj.etag !== undefined) {2641 return this.etag = jsonObj.etag;2642 }2643 };2644 Group.prototype.set = function (property, value) {2645 switch (property) {2646 case "_id":2647 this._id = value;2648 break;2649 case "groupname":2650 this.groupname = value;2651 break;2652 case "users":2653 this.users = value;2654 break;2655 case "groups":2656 this.groups = value;2657 break;2658 case "acl":2659 this.acl = value;2660 break;2661 case "createdAt":2662 this.createdAt = value;2663 break;2664 case "updatedAt":2665 this.updatedAt = value;2666 break;2667 case "etag":2668 this.etag = value;2669 break;2670 default:2671 exports.nbError("Invalid property: " + property);2672 throw new Error("Invalid property: " + property);2673 }2674 };2675 Group.prototype.get = function (property) {2676 switch (property) {2677 case "_id":2678 return this._id;2679 case "groupname":2680 return this.groupname;2681 case "users":2682 return this.users;2683 case "groups":2684 return this.groups;2685 case "acl":2686 return this.acl;2687 case "createdAt":2688 return this.createdAt;2689 case "updatedAt":2690 return this.updatedAt;2691 case "etag":2692 return this.etag;2693 default:2694 exports.nbError("Invalid property: " + property);2695 throw new Error("Invalid property: " + property);2696 }2697 };2698 Group.prototype.addEntry = function (entry) {2699 exports.nbLogger("Group.addEntry#start");2700 var _entries = [];2701 var _add = null;2702 if (entry instanceof this._service.User) {2703 _add = entry._id;2704 _entries = this.users;2705 }2706 else if (entry instanceof this._service.Group) {2707 _add = entry.groupname;2708 _entries = this.groups;2709 }2710 else {2711 throw new Error("Group.addEntry: Invalid entry");2712 }2713 var _exists = false;2714 for (var _i = 0, _entries_1 = _entries; _i < _entries_1.length; _i++) {2715 var _entry = _entries_1[_i];2716 if (_entry === _add) {2717 _exists = true;2718 }2719 }2720 if (!_exists) {2721 _entries.push(_add);2722 }2723 exports.nbLogger("Group.addEntry#end");2724 return true;2725 };2726 Group.prototype.removeEntry = function (entry) {2727 exports.nbLogger("Group.removeEntry#start");2728 var _entries = [];2729 var _remove = null;2730 if (entry instanceof this._service.User) {2731 _remove = entry._id;2732 _entries = this.users;2733 }2734 else if (entry instanceof this._service.Group) {2735 _remove = entry.groupname;2736 _entries = this.groups;2737 }2738 else {2739 throw new Error("Group.removeEntry: Invalid entry");2740 }2741 for (var i = 0; i < _entries.length; i++) {2742 if (_entries[i] === _remove) {2743 _entries.splice(i, 1);2744 break;2745 }2746 }2747 exports.nbLogger("Group.removeEntry#end");2748 return true;2749 };2750 Group.prototype.save = function (callbacks) {2751 var _this = this;2752 exports.nbLogger("Group.save#start");2753 if (this.groupname == null) {2754 throw new Error("Group.save: no group name");2755 }2756 var saveParams = {};2757 var request;2758 if (this._service.isOffline()) {2759 request = new _SdeRequest("NebulaGroup", "save");2760 saveParams.groupname = this.groupname;2761 if (this.etag != null) {2762 saveParams.etag = this.etag;2763 }2764 }2765 else {2766 var path = "/groups/" + encodeURIComponent(this.groupname);2767 exports.nbLogger("Group.save#REST API Request path = " + path);2768 request = new HttpRequest(this._service, path);2769 if (this.etag != null) {2770 request.setQueryParam("etag", this.etag);2771 }2772 request.setMethod("PUT");2773 request.setContentType("application/json");2774 }2775 saveParams.users = this.users;2776 saveParams.groups = this.groups;2777 if (this.acl !== null) {2778 saveParams.ACL = this.acl._toJsonObject();2779 }2780 request.setData(saveParams);2781 var promise = request.execute().then(function (response) {2782 exports.nbLogger("Group.save#success callback start");2783 exports.nbLogger("Group.save#response = " + response);2784 _this._setGroupInfo(response);2785 return _this;2786 }).catch(function (error) {2787 exports.nbLogger("Group.save#error callback start");2788 exports.nbLogger(("Group.save#error = " + (exports._errorText(error))));2789 return Promise.reject(error);2790 });2791 exports.nbLogger("Group.save#end");2792 return exports._promisify(promise, callbacks);2793 };2794 Group.prototype.addMembers = function (userIds, groups, callbacks) {2795 return this._addRemoveMembers("add", userIds, groups, callbacks);2796 };2797 Group.prototype.removeMembers = function (userIds, groups, callbacks) {2798 return this._addRemoveMembers("remove", userIds, groups, callbacks);2799 };2800 Group.prototype._addRemoveMembers = function (mode, userIds, groups, callbacks) {2801 var _this = this;2802 exports.nbLogger("Group." + mode + "Members#start");2803 if (this.groupname == null) {2804 throw new Error("No group name");2805 }2806 if (this._service.isOffline()) {2807 throw new Error("offline mode is not supported.");2808 }2809 var path = "/groups/" + encodeURIComponent(this.groupname) + ("/" + mode + "Members");2810 var request = new HttpRequest(this._service, path);2811 request.setMethod("PUT");2812 request.setContentType("application/json");2813 var body = {2814 users: userIds != null ? userIds : [],2815 groups: groups != null ? groups : []2816 };2817 request.setData(body);2818 var promise = request.execute().then(function (response) {2819 exports.nbLogger("Group." + mode + "Members#response = " + response);2820 _this._setGroupInfo(response);2821 return _this;2822 }).catch(function (error) {2823 exports.nbLogger("Group." + mode + "Members#error = " + exports._errorText(error));2824 return Promise.reject(error);2825 });2826 return exports._promisify(promise, callbacks);2827 };2828 Group.remove = function (group, callbacks) { return null; };2829 Group._remove = function (service, group, callbacks) {2830 if (!(group instanceof Group)) {2831 throw new Error("Group.remove: not Group instance!");2832 }2833 if (group._service !== service) {2834 throw new Error("Service does not match");2835 }2836 return group._remove(callbacks);2837 };2838 Group.prototype._remove = function (callbacks) {2839 exports.nbLogger("Group.remove#start");2840 var request;2841 if (this._service.isOffline()) {2842 request = new _SdeRequest("NebulaGroup", "delete");2843 var deleteParams = {2844 groupname: this.groupname2845 };2846 var etag = this.etag;2847 if (etag != null) {2848 deleteParams.etag = etag;2849 }2850 request.setData(deleteParams);2851 }2852 else {2853 var path = "/groups/" + encodeURIComponent(this.groupname);2854 exports.nbLogger("Group.remove#REST API Request path = " + path);2855 request = new HttpRequest(this._service, path);2856 var etag = this.etag;2857 if (etag != null) {2858 request.setQueryParam("etag", etag);2859 }2860 request.setMethod("DELETE");2861 }2862 var promise = request.execute().then(function (response) {2863 exports.nbLogger("Group.remove#success callback start");2864 exports.nbLogger("Group.remove#response = " + response);2865 return;2866 }).catch(function (error) {2867 exports.nbLogger("Group.remove#error callback start");2868 exports.nbLogger(("Group.remove#error = " + (exports._errorText(error))));2869 return Promise.reject(error);2870 });2871 exports.nbLogger("Group.remove#end");2872 return exports._promisify(promise, callbacks);2873 };2874 Group.query = function (conditions, callbacks) { return null; };2875 Group._query = function (service, conditions, callbacks) {2876 exports.nbLogger("Group.query#start");2877 var groupname = null;2878 if (conditions != null) {2879 if (conditions.groupname != null) {2880 groupname = conditions.groupname;2881 }2882 else {2883 throw new Error("Group.query: no groupname in conditions");2884 }2885 }2886 var request;2887 if (service.isOffline()) {2888 request = new _SdeRequest("NebulaGroup", "query");2889 if (groupname !== null) {2890 request.setData({2891 groupname: groupname2892 });2893 }2894 }2895 else {2896 var path = void 0;2897 if (groupname !== null) {2898 path = "/groups/" + encodeURIComponent(groupname);2899 }2900 else {2901 path = "/groups";2902 }2903 exports.nbLogger("Group.query#REST API Request path = " + path);2904 request = new HttpRequest(service, path);2905 request.setMethod("GET");2906 request.setContentType("application/json");2907 }2908 var promise = request.execute().then(function (response) {2909 exports.nbLogger("Group.query#response = " + response);2910 var obj = JSON.parse(response);2911 var objArray = [];2912 var groupArray = [];2913 if (obj.results === undefined) {2914 objArray.push(obj);2915 }2916 else {2917 objArray = obj.results;2918 }2919 for (var _i = 0, objArray_1 = objArray; _i < objArray_1.length; _i++) {2920 var obj_1 = objArray_1[_i];2921 var group = new service.Group(obj_1.name);2922 group._setGroupInfo(JSON.stringify(obj_1));2923 groupArray.push(group);2924 }2925 return groupArray;2926 }).catch(function (error) {2927 exports.nbLogger(("Group.query#error = " + (exports._errorText(error))));2928 return Promise.reject(error);2929 });2930 exports.nbLogger("Group.query#end");2931 return exports._promisify(promise, callbacks);2932 };2933 return Group;2934}());2935exports.Group = Group;2936exports.declareGroup = function (_service) {2937 var _a;2938 _service.Group = (_a = (function (_super) {2939 __extends(_Group, _super);2940 function _Group(groupname) {2941 var _this = _super.call(this, groupname, _service) || this;2942 exports.nbLogger("Group.constructor");2943 return _this;2944 }2945 _Group.remove = function (group, callbacks) {2946 return _super._remove.call(this, _service, group, callbacks);2947 };2948 _Group.query = function (conditions, callbacks) {2949 return _super._query.call(this, _service, conditions, callbacks);2950 };2951 return _Group;2952 }(Group)),2953 _a.delete = _a.remove,2954 _a);2955};2956var FileMetadata = (function () {2957 function FileMetadata() {2958 this._createdAt = null;2959 this._updatedAt = null;2960 this._acl = null;2961 this._contentType = null;2962 this._publicUrl = null;2963 this._fileName = null;2964 this._fileSize = -1;2965 this._syncState = FileMetadata.SYNC_STATE_UNDEFINED;2966 this._lastSyncTime = null;2967 this._metaId = null;2968 this._metaETag = null;2969 this._fileETag = null;2970 this._options = null;2971 this._cacheDisabled = false;2972 }2973 FileMetadata.prototype.getFileName = function () {2974 return this._fileName;2975 };2976 FileMetadata.prototype.setFileName = function (fileName) {2977 exports.nbLogger("FileMetadata.setFileName(), " + this._fileName + " ---> " + fileName);2978 this._fileName = fileName;2979 return this;2980 };2981 FileMetadata.prototype.getAcl = function () {2982 return this._acl;2983 };2984 FileMetadata.prototype.setAcl = function (acl) {2985 if (acl != null && !(acl instanceof Acl)) {2986 throw new Error("FileMetadata.setAcl: Not Acl instance!");2987 }2988 this._acl = acl;2989 return this;2990 };2991 FileMetadata.prototype.getContentType = function () {2992 return this._contentType;2993 };2994 FileMetadata.prototype.setContentType = function (contentType) {2995 exports.nbLogger("FileMetadata.setContentType(), " + this._contentType + " -> " + contentType);2996 this._contentType = contentType;2997 return this;2998 };2999 FileMetadata.prototype.getCreatedAt = function () {3000 return this._createdAt;3001 };3002 FileMetadata.prototype._setCreatedAt = function (createdAt) {3003 this._createdAt = createdAt;3004 return this;3005 };3006 FileMetadata.prototype.getUpdatedAt = function () {3007 return this._updatedAt;3008 };3009 FileMetadata.prototype._setUpdatedAt = function (updatedAt) {3010 this._updatedAt = updatedAt;3011 return this;3012 };3013 FileMetadata.prototype.getSize = function () {3014 return this._fileSize;3015 };3016 FileMetadata.prototype._setSize = function (size) {3017 this._fileSize = size;3018 return this;3019 };3020 FileMetadata.prototype.getPublicUrl = function () {3021 return this._publicUrl;3022 };3023 FileMetadata.prototype._setPublicUrl = function (url) {3024 this._publicUrl = url;3025 return this;3026 };3027 FileMetadata.prototype.getFileSyncState = function () {3028 return this._syncState;3029 };3030 FileMetadata.prototype._setFileSyncState = function (syncState) {3031 this._syncState = syncState;3032 return this;3033 };3034 FileMetadata.prototype.getLastSyncTime = function () {3035 return this._lastSyncTime;3036 };3037 FileMetadata.prototype._setLastSyncTime = function (lastSyncTime) {3038 this._lastSyncTime = lastSyncTime;3039 return this;3040 };3041 FileMetadata.prototype.getMetaId = function () {3042 return this._metaId;3043 };3044 FileMetadata.prototype._setMetaId = function (metaId) {3045 this._metaId = metaId;3046 return this;3047 };3048 FileMetadata.prototype.getMetaETag = function () {3049 return this._metaETag;3050 };3051 FileMetadata.prototype._setMetaETag = function (metaETag) {3052 this._metaETag = metaETag;3053 return this;3054 };3055 FileMetadata.prototype.getFileETag = function () {3056 return this._fileETag;3057 };3058 FileMetadata.prototype._setFileETag = function (fileETag) {3059 this._fileETag = fileETag;3060 return this;3061 };3062 FileMetadata.prototype.getOptions = function () {3063 return this._options;3064 };3065 FileMetadata.prototype.setOptions = function (options) {3066 this._options = options;3067 return this;3068 };3069 FileMetadata.prototype.isCacheDisabled = function () {3070 return this._cacheDisabled;3071 };3072 FileMetadata.prototype.setCacheDisabled = function (cacheDisabled) {3073 this._cacheDisabled = cacheDisabled;3074 return this;3075 };3076 FileMetadata.prototype._setMetadata = function (obj) {3077 if (obj.filename != null) {3078 this.setFileName(obj.filename);3079 }3080 if (obj.contentType != null) {3081 this.setContentType(obj.contentType);3082 }3083 if (obj.ACL != null) {3084 var acl = new Acl(obj.ACL);3085 this.setAcl(acl);3086 }3087 if (obj["length"] != null) {3088 this._setSize(obj["length"]);3089 }3090 if (obj.publicUrl != null) {3091 this._setPublicUrl(obj.publicUrl);3092 }3093 if (obj.createdAt != null) {3094 this._setCreatedAt(obj.createdAt);3095 }3096 if (obj.updatedAt != null) {3097 this._setUpdatedAt(obj.updatedAt);3098 }3099 if (obj.lastSyncTime != null) {3100 this._setLastSyncTime(obj.lastSyncTime);3101 }3102 if (obj.metaId != null) {3103 this._setMetaId(obj.metaId);3104 }3105 if (obj.metaETag != null) {3106 this._setMetaETag(obj.metaETag);3107 }3108 if (obj.fileETag != null) {3109 this._setFileETag(obj.fileETag);3110 }3111 if (obj.options != null) {3112 this.setOptions(obj.options);3113 }3114 if (obj.cacheDisabled != null) {3115 this.setCacheDisabled(obj.cacheDisabled);3116 }3117 if (obj.fileSyncState != null) {3118 this._setFileSyncState(obj.fileSyncState);3119 }3120 return this;3121 };3122 FileMetadata.SYNC_STATE_UNDEFINED = -1;3123 FileMetadata.SYNC_STATE_SYNCED = 0;3124 FileMetadata.SYNC_STATE_DIRTY = 1;3125 FileMetadata.SYNC_STATE_SYNCING = 3;3126 FileMetadata.SYNC_STATE_CONFLICTED = 5;3127 return FileMetadata;3128}());3129exports.FileMetadata = FileMetadata;3130var BaseBucket = (function () {3131 function BaseBucket(service, name, type, mode) {3132 if (mode === void 0) { mode = exports.Nebula.BUCKET_MODE_ONLINE; }3133 this._service = service;3134 this._type = type;3135 this._name = name;3136 this._acl = null;3137 this._contentAcl = null;3138 this._description = null;3139 if (mode !== exports.Nebula.BUCKET_MODE_ONLINE && mode !== exports.Nebula.BUCKET_MODE_REPLICA && mode !== exports.Nebula.BUCKET_MODE_LOCAL) {3140 this._mode = exports.Nebula.BUCKET_MODE_ONLINE;3141 }3142 else {3143 this._mode = mode;3144 }3145 }3146 BaseBucket._baseLoadBucket = function (type, service, name, mode, callbacks) {3147 exports.nbLogger("BaseBucket.loadBucket(), name=" + name + ", type=" + type + ", callbacks=" + callbacks + ", mode=" + mode);3148 var req;3149 if (service.isOffline()) {3150 req = new _SdeRequest(BaseBucket.getClassName(type), "loadBucket");3151 var body = {3152 bucketName: name3153 };3154 if (mode !== exports.Nebula.BUCKET_MODE_ONLINE && mode !== exports.Nebula.BUCKET_MODE_REPLICA && mode !== exports.Nebula.BUCKET_MODE_LOCAL) {3155 mode = exports.Nebula.BUCKET_MODE_ONLINE;3156 }3157 body.bucketMode = mode;3158 req.setData(body);3159 }3160 else {3161 var path = "/buckets/" + type + "/" + encodeURIComponent(name);3162 req = new HttpRequest(service, path);3163 req.setMethod("GET");3164 req.setContentType("application/json");3165 }3166 var promise = req.execute().then(function (response) {3167 try {3168 exports.nbLogger("BaseBucket.loadBucket(), success : " + response);3169 var resObj = JSON.parse(response);3170 var resName = resObj.name;3171 if (resName == null) {3172 exports.nbLogger("BaseBucket.loadBucket(), invalid bucket name, name=" + resName);3173 var error = exports._createError(0, "Invalid response", "", name);3174 return Promise.reject(error);3175 }3176 exports.nbLogger("BaseBucket.loadBucket(), new Bucket, name=" + resName);3177 var bucket = void 0;3178 if (type === "file") {3179 bucket = new service.FileBucket(resName);3180 }3181 else {3182 bucket = new service.ObjectBucket(resName, mode);3183 }3184 var resAcl = resObj.ACL;3185 if (resAcl != null) {3186 exports.nbLogger("BaseBucket.loadBucket(), acl=" + resAcl);3187 var acl = new Acl();3188 acl._set(resAcl);3189 bucket.setAcl(acl);3190 }3191 var resContentAcl = resObj.contentACL;3192 if (resContentAcl != null) {3193 exports.nbLogger("BaseBucket.loadBucket(), contentAcl=" + resContentAcl);3194 var contentAcl = new Acl();3195 contentAcl._set(resContentAcl);3196 bucket.setContentAcl(contentAcl);3197 }3198 var resDescription = resObj.description;3199 if (resDescription != null) {3200 exports.nbLogger("BaseBucket.loadBucket(), description=" + resDescription);3201 bucket.setDescription(resDescription);3202 }3203 return Promise.resolve(bucket);3204 }3205 catch (e) {3206 exports.nbLogger("BaseBucket.loadBucket(), error : exception" + e);3207 var error = exports._createError(0, e, e.toString(), name);3208 return Promise.reject(error);3209 }3210 }, function (error) {3211 exports.nbLogger(("BaseBucket.loadBucket(), error: " + (exports._errorText(error))));3212 error.data = name;3213 return Promise.reject(error);3214 });3215 return exports._promisify(promise, callbacks);3216 };3217 BaseBucket._baseGetBucketList = function (type, service, local, callbacks) {3218 exports.nbLogger("BaseBucket.getBucketList(), type=" + type + ", callbacks=" + callbacks);3219 var req;3220 if (service.isOffline()) {3221 var method = "getBucketList";3222 if (local) {3223 method = "getLocalBucketList";3224 }3225 req = new _SdeRequest(BaseBucket.getClassName(type), method);3226 }3227 else {3228 var path = "/buckets/" + type;3229 req = new HttpRequest(service, path);3230 req.setMethod("GET");3231 req.setContentType("application/json");3232 }3233 var promise = req.execute().then(function (response) {3234 try {3235 exports.nbLogger("BaseBucket.getBucketList(), success : " + response);3236 var resObj = JSON.parse(response);3237 var buckets = resObj.results;3238 if (buckets != null) {3239 exports.nbLogger("BaseBucket.getBucketList(), buckets=" + buckets);3240 var bucketNames = [];3241 for (var _i = 0, buckets_1 = buckets; _i < buckets_1.length; _i++) {3242 var bucket = buckets_1[_i];3243 exports.nbLogger("BaseBucket.getBucketList(), success : add bucketName = " + bucket.name);3244 if (bucket.name != null) {3245 bucketNames.push(bucket.name);3246 }3247 else {3248 exports.nbLogger("BaseBucket.getBucketList(), [WARNING] No name in response");3249 }3250 }3251 return Promise.resolve(bucketNames);3252 }3253 else {3254 exports.nbLogger("BaseBucket.getBucketList(), invalid response");3255 var error = exports._createError(0, "Invalid response", "", name);3256 return Promise.reject(error);3257 }3258 }3259 catch (e) {3260 exports.nbLogger("BaseBucket.getBucketList(), error : exception" + e);3261 var error = exports._createError(0, e, e);3262 return Promise.reject(error);3263 }3264 }, function (error) {3265 exports.nbLogger(("BaseBucket.getBucketList(), error: " + (exports._errorText(error))));3266 return Promise.reject(error);3267 });3268 return exports._promisify(promise, callbacks);3269 };3270 BaseBucket.prototype.saveBucket = function (callbacks) {3271 var _this = this;3272 exports.nbLogger("BaseBucket.saveBucket(), callbacks=" + callbacks);3273 var req;3274 if (this._service.isOffline()) {3275 req = new _SdeRequest(BaseBucket.getClassName(this._type), "saveBucket");3276 }3277 else {3278 var path = this.getPath();3279 req = new HttpRequest(this._service, path);3280 req.setMethod("PUT");3281 req.setContentType("application/json");3282 }3283 var body = {};3284 if (this._acl != null) {3285 body.ACL = this._acl._toJsonObject();3286 }3287 if (this._contentAcl != null) {3288 body.contentACL = this._contentAcl._toJsonObject();3289 }3290 if (this._description != null) {3291 body.description = this._description;3292 }3293 if (this._service.isOffline()) {3294 body.bucketName = this.getBucketName();3295 body.bucketMode = this.getBucketMode();3296 }3297 req.setData(body);3298 exports.nbLogger("BaseBucket.saveBucket(), body=" + JSON.stringify(body));3299 var promise = req.execute().then(function (response) {3300 exports.nbLogger("success : " + response);3301 exports.nbLogger("bucketName : " + _this.getBucketName());3302 try {3303 exports.nbLogger("success : " + response);3304 var resObj = JSON.parse(response);3305 if (resObj.ACL != null) {3306 if (!_this._acl) {3307 _this._acl = new Acl();3308 }3309 _this._acl._set(resObj.ACL);3310 }3311 if (resObj.contentACL != null) {3312 if (!_this._contentAcl) {3313 _this._contentAcl = new Acl();3314 }3315 _this._contentAcl._set(resObj.contentACL);3316 }3317 return Promise.resolve(_this);3318 }3319 catch (e) {3320 exports.nbLogger("error : " + e);3321 return Promise.reject(e);3322 }3323 }, function (err) {3324 exports.nbLogger(("error: " + (exports._errorText(err))));3325 err.data = _this;3326 return Promise.reject(err);3327 });3328 return exports._promisify(promise, callbacks);3329 };3330 BaseBucket.prototype.deleteBucket = function (callbacks) {3331 var _this = this;3332 exports.nbLogger("BaseBucket.deleteBucket(), callbacks=" + callbacks);3333 var req;3334 if (this._service.isOffline()) {3335 req = new _SdeRequest(BaseBucket.getClassName(this._type), "deleteBucket");3336 var body = {3337 bucketName: this.getBucketName(),3338 bucketMode: this.getBucketMode()3339 };3340 req.setData(body);3341 }3342 else {3343 var path = this.getPath();3344 req = new HttpRequest(this._service, path);3345 req.setMethod("DELETE");3346 req.setContentType("application/json");3347 }3348 var promise = req.execute().then(function () {3349 exports.nbLogger("BaseBucket.deleteBucket(), success");3350 return _this;3351 }, function (err) {3352 exports.nbLogger(("BaseBucket.deleteBucket(), error: " + (exports._errorText(err))));3353 err.data = _this;3354 return Promise.reject(err);3355 });3356 return exports._promisify(promise, callbacks);3357 };3358 BaseBucket.prototype.setAcl = function (acl) {3359 if (acl != null && !(acl instanceof Acl)) {3360 throw new Error("setAcl: not Acl instance!");3361 }3362 this._acl = acl;3363 };3364 BaseBucket.prototype.getAcl = function () {3365 return this._acl;3366 };3367 BaseBucket.prototype.setContentAcl = function (acl) {3368 if (acl != null && !(acl instanceof Acl)) {3369 throw new Error("setContentAcl: not Acl instance!");3370 }3371 this._contentAcl = acl;3372 };3373 BaseBucket.prototype.getContentAcl = function () {3374 return this._contentAcl;3375 };3376 BaseBucket.prototype.setDescription = function (description) {3377 this._description = description;3378 };3379 BaseBucket.prototype.getDescription = function () {3380 return this._description;3381 };3382 BaseBucket.prototype.getBucketName = function () {3383 return this._name;3384 };3385 BaseBucket.prototype.setBucketName = function (name) {3386 this._name = name;3387 };3388 BaseBucket.prototype.getBucketMode = function () {3389 return this._mode;3390 };3391 BaseBucket.prototype.getPath = function (option) {3392 var path = "/buckets" + "/" + this._type + "/" + encodeURIComponent(this._name);3393 if (option != null) {3394 path = path + option;3395 }3396 return path;3397 };3398 BaseBucket.prototype.getDataPath = function (option) {3399 var dataType = "objects";3400 if (this._type === "file") {3401 dataType = "files";3402 }3403 var path = "/" + dataType + "/" + encodeURIComponent(this._name);3404 if (option != null) {3405 path = path + option;3406 }3407 return path;3408 };3409 BaseBucket.getClassName = function (type) {3410 var className = "NebulaObjectBucket";3411 if (type === "file") {3412 className = "NebulaFileBucket";3413 }3414 return className;3415 };3416 BaseBucket.prototype.getClassName = function () {3417 return BaseBucket.getClassName(this._type);3418 };3419 return BaseBucket;3420}());3421exports.BaseBucket = BaseBucket;3422var ObjectBucket = (function (_super) {3423 __extends(ObjectBucket, _super);3424 function ObjectBucket(name, mode, service) {3425 if (mode === void 0) { mode = exports.Nebula.BUCKET_MODE_ONLINE; }3426 if (service === void 0) { service = exports.Nebula; }3427 var _this = _super.call(this, service, name, "object", mode) || this;3428 _this._resolveId = null;3429 return _this;3430 }3431 ObjectBucket.loadBucket = function (name, callbacks, mode) { return null; };3432 ObjectBucket._loadBucket = function (service, name, callbacks, mode) {3433 exports.nbLogger("ObjectBucket.loadBucket(), name=" + name + ", callbacks=" + callbacks);3434 return BaseBucket._baseLoadBucket("object", service, name, mode, callbacks);3435 };3436 ObjectBucket.getBucketList = function (callbacks) { return null; };3437 ObjectBucket._getBucketList = function (service, callbacks) {3438 exports.nbLogger("ObjectBucket.getBucketList(), callbacks=" + callbacks);3439 return BaseBucket._baseGetBucketList("object", service, false, callbacks);3440 };3441 ObjectBucket.getLocalBucketList = function (callbacks) { return null; };3442 ObjectBucket._getLocalBucketList = function (service, callbacks) {3443 exports.nbLogger("ObjectBucket.getLocalBucketList(), callbacks=" + callbacks);3444 return BaseBucket._baseGetBucketList("object", service, true, callbacks);3445 };3446 ObjectBucket.prototype.saveBucket = function (callbacks) {3447 return _super.prototype.saveBucket.call(this, callbacks);3448 };3449 ObjectBucket.prototype.deleteBucket = function (callbacks) {3450 return _super.prototype.deleteBucket.call(this, callbacks);3451 };3452 ObjectBucket.prototype.setAcl = function (acl) {3453 _super.prototype.setAcl.call(this, acl);3454 return this;3455 };3456 ObjectBucket.prototype.getAcl = function () {3457 return _super.prototype.getAcl.call(this);3458 };3459 ObjectBucket.prototype.setContentAcl = function (acl) {3460 _super.prototype.setContentAcl.call(this, acl);3461 return this;3462 };3463 ObjectBucket.prototype.getContentAcl = function () {3464 return _super.prototype.getContentAcl.call(this);3465 };3466 ObjectBucket.prototype.setDescription = function (description) {3467 return _super.prototype.setDescription.call(this, description);3468 };3469 ObjectBucket.prototype.getDescription = function () {3470 return _super.prototype.getDescription.call(this);3471 };3472 ObjectBucket.prototype.getBucketName = function () {3473 return _super.prototype.getBucketName.call(this);3474 };3475 ObjectBucket.prototype._setBucketName = function (name) {3476 return _super.prototype.setBucketName.call(this, name);3477 };3478 ObjectBucket.prototype.getBucketMode = function () {3479 return _super.prototype.getBucketMode.call(this);3480 };3481 ObjectBucket.prototype.load = function (objectId, callbacks) {3482 exports.nbLogger("ObjectBucket.load()");3483 if (objectId == null) {3484 exports.nbError("ObjectBucket.load(), Parameter is invalid");3485 throw new Error("No objectId");3486 }3487 var req;3488 if (this._service.isOffline()) {3489 req = new _SdeRequest(this.getClassName(), "load");3490 var body = {3491 bucketName: this.getBucketName(),3492 bucketMode: this.getBucketMode(),3493 objectId: objectId3494 };3495 req.setData(body);3496 }3497 else {3498 var path = this.getDataPath("/" + objectId);3499 req = new HttpRequest(this._service, path);3500 req.setMethod("GET");3501 req.setContentType("application/json");3502 }3503 var promise = req.execute().then(function (response) {3504 try {3505 var resObj = JSON.parse(response);3506 exports.nbLogger("ObjectBucket.load(), success : response=" + response);3507 return Promise.resolve(resObj);3508 }3509 catch (e) {3510 exports.nbLogger("ObjectBucket.load(), error : response=" + response);3511 var errorResult = exports._createError(0, "Invalid response from server", e);3512 errorResult.data = objectId;3513 return Promise.reject(errorResult);3514 }3515 }, function (err) {3516 exports.nbLogger(("ObjectBucket.load(), error: " + (exports._errorText(err))));3517 err.data = objectId;3518 return Promise.reject(err);3519 });3520 return exports._promisify(promise, callbacks);3521 };3522 ObjectBucket.prototype.remove = function (objectId, callbacks, etag) {3523 exports.nbLogger("ObjectBucket.delete)");3524 if (!objectId) {3525 exports.nbError("ObjectBucket.remove(), Parameter is invalid");3526 throw new Error("No objectId");3527 }3528 var req;3529 if (this._service.isOffline()) {3530 req = new _SdeRequest(this.getClassName(), "delete");3531 var body = {3532 bucketName: this.getBucketName(),3533 bucketMode: this.getBucketMode(),3534 objectId: objectId3535 };3536 if (etag) {3537 body.etag = etag;3538 }3539 req.setData(body);3540 }3541 else {3542 var path = this.getDataPath("/" + objectId);3543 req = new HttpRequest(this._service, path);3544 req.setMethod("DELETE");3545 req.setContentType("application/json");3546 if (etag) {3547 req.setQueryParam("etag", etag);3548 }3549 }3550 var promise = req.execute().then(function (response) {3551 exports.nbLogger("ObjectBucket.delete(), success");3552 return objectId;3553 }, function (err) {3554 exports.nbLogger(("ObjectBucket.delete(), error: " + (exports._errorText(err))));3555 err.objectId = objectId;3556 return Promise.reject(err);3557 });3558 return exports._promisify(promise, callbacks);3559 };3560 ObjectBucket.prototype.delete = function (objectId, callbacks, etag) {3561 return this.remove(objectId, callbacks, etag);3562 };3563 ObjectBucket.prototype.save = function (object, callbacks) {3564 exports.nbLogger("ObjectBucket.save()");3565 if (!object) {3566 exports.nbError("ObjectBucket.save(), Parameter is invalid");3567 throw new Error("No object");3568 }3569 var req;3570 if (this._service.isOffline()) {3571 req = new _SdeRequest(this.getClassName(), "save");3572 var body = {3573 object: object,3574 bucketName: this.getBucketName(),3575 bucketMode: this.getBucketMode()3576 };3577 req.setData(body);3578 }3579 else {3580 var queryParams = {};3581 var path = void 0, method = void 0;3582 if (object._id != null) {3583 path = this.getDataPath("/" + object._id);3584 method = "PUT";3585 if (object.etag != null) {3586 queryParams.etag = object.etag;3587 }3588 }3589 else {3590 path = this.getDataPath();3591 method = "POST";3592 }3593 exports.nbLogger("ObjectBucket.save(), path=" + path);3594 req = new HttpRequest(this._service, path);3595 req.setContentType("application/json");3596 req.setMethod(method);3597 req.setQueryParams(queryParams);3598 req.setData(object);3599 }3600 var promise = req.execute().then(function (response) {3601 try {3602 var resObj = JSON.parse(response);3603 exports.nbLogger("ObjectBucket.save(), success");3604 return resObj;3605 }3606 catch (e) {3607 exports.nbLogger("ObjectBucket.save(), error : exception=" + e);3608 var errorResult = exports._createError(0, "Invalid response from server", e);3609 errorResult.data = object;3610 return Promise.reject(errorResult);3611 }3612 }, function (err) {3613 exports.nbLogger(("ObjectBucket.save(), error: " + (exports._errorText(err))));3614 err.data = object;3615 return Promise.reject(err);3616 });3617 return exports._promisify(promise, callbacks);3618 };3619 ObjectBucket.prototype.query = function (aQuery, callbacks) {3620 return this._query(aQuery, {3621 longQuery: this._service.ObjectBucket.useLongQuery3622 }, callbacks);3623 };3624 ObjectBucket.prototype.longQuery = function (aQuery, callbacks) {3625 return this._query(aQuery, {3626 longQuery: true3627 }, callbacks);3628 };3629 ObjectBucket.prototype.queryWithCount = function (aQuery, callbacks) {3630 return this._query(aQuery, {3631 countQuery: true,3632 longQuery: this._service.ObjectBucket.useLongQuery3633 }, callbacks);3634 };3635 ObjectBucket.prototype.longQueryWithCount = function (aQuery, callbacks) {3636 return this._query(aQuery, {3637 countQuery: true,3638 longQuery: true3639 }, callbacks);3640 };3641 ObjectBucket.prototype._query = function (aQuery, option, callbacks) {3642 exports.nbLogger("ObjectBucket.query()");3643 if (option.countQuery) {3644 if (aQuery == null) {3645 aQuery = new ObjectQuery();3646 }3647 aQuery._setCountQuery(option.countQuery);3648 }3649 var req;3650 var path;3651 if (this._service.isOffline()) {3652 req = new _SdeRequest(this.getClassName(), "query");3653 var body = {};3654 if (aQuery != null) {3655 if (aQuery.getClause() != null && aQuery.getClause().json() != null) {3656 body.clause = aQuery.getClause().json();3657 }3658 body.limit = aQuery.getLimit();3659 body.skip = aQuery.getSkipCount();3660 body.sort = aQuery.getSort();3661 body.deleteMark = aQuery._getDeleteMark();3662 body.countQuery = aQuery._isCountQuery();3663 }3664 body.bucketName = this.getBucketName();3665 body.bucketMode = this.getBucketMode();3666 req.setData(body);3667 }3668 else if (!option.longQuery) {3669 path = this.getDataPath();3670 req = new HttpRequest(this._service, path);3671 req.setMethod("GET");3672 if (aQuery != null) {3673 req.setQueryParams(aQuery._toParam());3674 }3675 }3676 else {3677 path = this.getDataPath("/_query");3678 req = new HttpRequest(this._service, path);3679 req.setMethod("POST");3680 req.setContentType("application/json");3681 req.setData((aQuery != null) ? aQuery._toParamJson() : {});3682 }3683 var promise = req.execute().then(function (response) {3684 try {3685 var resObj = JSON.parse(response);3686 var objects = resObj.results;3687 exports.nbLogger("ObjectBucket.query(), success : size=" + objects.length);3688 if (aQuery != null && aQuery._isCountQuery() === true) {3689 var count = -1;3690 if (resObj.count != null) {3691 count = resObj.count;3692 }3693 return {3694 objects: objects,3695 count: count3696 };3697 }3698 else {3699 return objects;3700 }3701 }3702 catch (e) {3703 exports.nbLogger("ObjectBucket.query(), error : exception=" + e);3704 var errorResult = exports._createError(0, e.toString(), e);3705 return Promise.reject(errorResult);3706 }3707 }, function (err) {3708 exports.nbLogger(("ObjectBucket.query(), error: " + (exports._errorText(err))));3709 return Promise.reject(err);3710 });3711 return exports._promisify(promise, callbacks);3712 };3713 ObjectBucket.prototype._checkOfflineService = function () {3714 if (this._service !== exports.Nebula) {3715 exports.nbError("ObjectBucket.setSyncScope(): Can't use for multitenant instance");3716 throw new Error("No multitenant support");3717 }3718 if (!this._service.isOffline()) {3719 exports.nbError("ObjectBucket.setSyncScope(), supported offline mode only");3720 throw new Error("No offline mode enabled");3721 }3722 };3723 ObjectBucket.prototype.aggregate = function (pipeline, options, callbacks) {3724 exports.nbLogger("ObjectBucket.aggregate()");3725 var path = this.getDataPath("/_aggregate");3726 var req = new HttpRequest(this._service, path);3727 req.setMethod("POST");3728 req.setContentType("application/json");3729 var data = { pipeline: pipeline };3730 if (options != null) {3731 data.options = options;3732 }3733 req.setData(data);3734 var promise = req.execute().then(function (response) {3735 try {3736 var resObj = JSON.parse(response);3737 var objects = resObj.results;3738 exports.nbLogger("ObjectBucket.aggregate(), success : size=" + objects.length);3739 return objects;3740 }3741 catch (e) {3742 exports.nbLogger("ObjectBucket.aggregate(), error : exception=" + e);3743 var errorResult = exports._createError(0, e.toString(), e);3744 return Promise.reject(errorResult);3745 }3746 }, function (err) {3747 exports.nbLogger(("ObjectBucket.aggregate(), error: " + (exports._errorText(err))));3748 return Promise.reject(err);3749 });3750 return exports._promisify(promise, callbacks);3751 };3752 ObjectBucket.prototype.setSyncScope = function (scope, callbacks) {3753 this._checkOfflineService();3754 var req = new _SdeRequest(BaseBucket.getClassName(), "setSyncScope");3755 var body = {};3756 var query = {};3757 if (scope != null) {3758 if (scope.getClause() != null && scope.getClause().json() != null) {3759 query.clause = scope.getClause().json();3760 }3761 body.scope = query;3762 }3763 body.bucketName = this.getBucketName();3764 body.bucketMode = this.getBucketMode();3765 exports.nbLogger("ObjectBucket.setSyncScope(), body=" + JSON.stringify(body));3766 req.setData(body);3767 var promise = req.execute().then(function (response) {3768 exports.nbLogger("ObjectBucket.setSyncScope(), success : response=" + response);3769 return;3770 }, function (err) {3771 exports.nbLogger(("ObjectBucket.setSyncScope(), error: " + (exports._errorText(err))));3772 return Promise.reject(err);3773 });3774 return exports._promisify(promise, callbacks);3775 };3776 ObjectBucket.prototype.getSyncScope = function (callbacks) {3777 this._checkOfflineService();3778 var req = new _SdeRequest(BaseBucket.getClassName(), "getSyncScope");3779 var body = {3780 bucketName: this.getBucketName(),3781 bucketMode: this.getBucketMode()3782 };3783 req.setData(body);3784 var promise = req.execute().then(function (response) {3785 exports.nbLogger("ObjectBucket.getSyncScope(), success : response=" + response);3786 try {3787 var resObj = JSON.parse(response);3788 if (resObj.scope != null) {3789 var query = null;3790 if (!exports._compareObject(resObj.scope, {})) {3791 query = ObjectQuery._toObjectQuery(resObj.scope);3792 }3793 exports.nbLogger("ObjectBucket.getSyncScope(), success : callback_data=" + resObj.scope);3794 return Promise.resolve(query);3795 }3796 else {3797 exports.nbLogger("ObjectBucket.getSyncScope(), error : no scope property");3798 return Promise.reject(exports._createError(0, "Invalid response - no scope property", ""));3799 }3800 }3801 catch (e) {3802 exports.nbLogger("ObjectBucket.getSyncScope(), error : exception=" + e);3803 return Promise.reject(exports._createError(0, e.toString(), e));3804 }3805 }, function (err) {3806 exports.nbLogger(("ObjectBucket.getSyncScope(), error: " + (exports._errorText(err))));3807 return Promise.reject(err);3808 });3809 return exports._promisify(promise, callbacks);3810 };3811 ObjectBucket.prototype.getResolveConflictPolicy = function (callbacks) {3812 exports.nbLogger("ObjectBucket.getResolveConflictPolicy()");3813 this._checkOfflineService();3814 var req = new _SdeRequest(BaseBucket.getClassName(), "getResolveConflictPolicy");3815 var body = {3816 bucketName: this.getBucketName(),3817 bucketMode: this.getBucketMode()3818 };3819 req.setData(body);3820 var promise = req.execute().then(function (response) {3821 exports.nbLogger("ObjectBucket.getResolveConflictPolicy(), success : response=" + response);3822 try {3823 var resObj = JSON.parse(response);3824 if (resObj.results != null) {3825 return Promise.resolve(resObj.results); 3826 }3827 else {3828 exports.nbLogger("ObjectBucket.getResolveConflictPolicy(), error : no results");3829 return Promise.reject(exports._createError(0, "No results", ""));3830 }3831 }3832 catch (e) {3833 exports.nbLogger("ObjectBucket.getResolveConflictPolicy(), error : exception=" + e);3834 return Promise.reject(exports._createError(0, e.toString(), e));3835 }3836 }, function (err) {3837 exports.nbLogger(("ObjectBucket.getResolveConflictPolicy(), error: " + (exports._errorText(err))));3838 return Promise.reject(err);3839 });3840 return exports._promisify(promise, callbacks);3841 };3842 ObjectBucket.prototype.setResolveConflictPolicy = function (policy, callbacks) {3843 exports.nbLogger("ObjectBucket.setResolveConflictPolicy()");3844 this._checkOfflineService();3845 if (policy == null) {3846 exports.nbError("ObjectBucket.setResolveConflictPolicy(), invalid parameter: no policy");3847 throw new Error("No policy");3848 }3849 var req = new _SdeRequest(BaseBucket.getClassName(), "setResolveConflictPolicy");3850 var body = {3851 bucketName: this.getBucketName(),3852 bucketMode: this.getBucketMode(),3853 policy: policy3854 };3855 req.setData(body);3856 var promise = req.execute().then(function (response) {3857 exports.nbLogger("ObjectBucket.setResolveConflictPolicy(), success : response=" + response);3858 return;3859 }, function (err) {3860 exports.nbLogger(("ObjectBucket.setResolveConflictPolicy(), error: " + (exports._errorText(err))));3861 return Promise.reject(err);3862 });3863 return exports._promisify(promise, callbacks);3864 };3865 ObjectBucket.prototype.removeCacheBucket = function (callbacks) {3866 exports.nbLogger("ObjectBucket.removeCacheBucket()");3867 this._checkOfflineService();3868 var req = new _SdeRequest(BaseBucket.getClassName(), "removeCacheBucket");3869 var body = {3870 bucketName: this.getBucketName(),3871 bucketMode: this.getBucketMode()3872 };3873 req.setData(body);3874 var promise = req.execute().then(function (response) {3875 exports.nbLogger("ObjectBucket.removeCacheBucket(), success : response=" + response);3876 return;3877 }, function (err) {3878 exports.nbLogger(("ObjectBucket.removeCacheBucket(), error: " + (exports._errorText(err))));3879 return Promise.reject(err);3880 });3881 return exports._promisify(promise, callbacks);3882 };3883 ObjectBucket.prototype.setSyncEventListener = function (listener) {3884 this._checkOfflineService();3885 return _SdeSyncEventListener.setListener(this, listener);3886 };3887 ObjectBucket.sync = function (callbacks) { return null; };3888 ObjectBucket._sync = function (service, callbacks) {3889 exports.nbLogger("ObjectBucket.sync()");3890 if (service !== exports.Nebula) {3891 exports.nbError("ObjectBucket.setSyncScope(): Can't use for multitenant instance");3892 throw new Error("No multitenant support");3893 }3894 if (!service.isOffline()) {3895 exports.nbError("ObjectBucket.sync(), supported offline mode only");3896 throw new Error("No offline mode enabled");3897 }3898 var req = new _SdeRequest(BaseBucket.getClassName(), "sync");3899 var promise = req.execute().then(function (response) {3900 exports.nbLogger("ObjectBucket.sync(), success : response=" + response);3901 return;3902 }, function (err) {3903 exports.nbLogger(("ObjectBucket.sync(), error: " + (exports._errorText(err))));3904 return Promise.reject(err);3905 });3906 return exports._promisify(promise, callbacks);3907 };3908 ObjectBucket.prototype.syncBucket = function (callbacks) {3909 exports.nbLogger("ObjectBucket.syncBucket()");3910 this._checkOfflineService();3911 var req = new _SdeRequest(BaseBucket.getClassName(), "syncBucket");3912 var body = {3913 bucketName: this.getBucketName(),3914 bucketMode: this.getBucketMode()3915 };3916 req.setData(body);3917 var promise = req.execute().then(function (response) {3918 exports.nbLogger("ObjectBucket.syncBucket(), success : response=" + response);3919 return;3920 }, function (err) {3921 exports.nbLogger(("ObjectBucket.syncBucket(), error: " + (exports._errorText(err))));3922 return Promise.reject(err);3923 });3924 return exports._promisify(promise, callbacks);3925 };3926 ObjectBucket.prototype.resolveConflict = function (objectId, resolve) {3927 exports.nbLogger("ObjectBucket.resolveConflict()");3928 this._checkOfflineService();3929 if (objectId == null || resolve == null || this._resolveId == null) {3930 exports.nbError("ObjectBucket.syncObject(), invalid parameter, objectId=" + objectId + ", resolve=" + resolve + ", resolveId=" + this._resolveId);3931 throw new Error("No objectId/resolve/resolveId");3932 }3933 var data = {3934 bucketName: this.getBucketName(),3935 bucketMode: this.getBucketMode(),3936 objectId: objectId,3937 resolveId: this._getResolveId(),3938 resolve: resolve3939 };3940 return _SdeSyncEventListener.resolveConflict(data);3941 };3942 ObjectBucket.prototype.setIndexToLocal = function (index, callbacks) {3943 exports.nbLogger("ObjectBucket.setIndexLocal()");3944 this._checkOfflineService();3945 if (!index) {3946 exports.nbError("ObjectBucket.setIndexLocal(), parameter is invalid");3947 throw new Error("No index");3948 }3949 if (!index.index) {3950 exports.nbError("ObjectBucket.setIndexLocal(), index is invalid");3951 throw new Error("No index property");3952 }3953 var req = new _SdeRequest(this.getClassName(), "setIndexToLocal");3954 index.bucketName = this.getBucketName();3955 index.bucketMode = this.getBucketMode();3956 req.setData(index);3957 var promise = req.execute().then(function () {3958 exports.nbLogger("ObjectBucket.setIndexLocal(), success");3959 return;3960 }, function (err) {3961 exports.nbLogger(("ObjectBucket.setIndexLocal(), error: " + (exports._errorText(err))));3962 return Promise.reject(err);3963 });3964 return exports._promisify(promise, callbacks);3965 };3966 ObjectBucket.prototype.getIndexFromLocal = function (callbacks) {3967 exports.nbLogger("ObjectBucket.getIndexLocal()");3968 this._checkOfflineService();3969 var req = new _SdeRequest(this.getClassName(), "getIndexFromLocal");3970 var body = {3971 bucketName: this.getBucketName(),3972 bucketMode: this.getBucketMode()3973 };3974 req.setData(body);3975 var promise = req.execute().then(function (response) {3976 exports.nbLogger("ObjectBucket.getIndexLocal(), success");3977 try {3978 var resObj = JSON.parse(response);3979 var index = resObj.results;3980 return index;3981 }3982 catch (e) {3983 exports.nbLogger("ObjectBucket.getIndexLocal(), success : exception=" + e);3984 var errorResult = exports._createError(0, e.toString(), e);3985 return Promise.reject(errorResult);3986 }3987 }, function (err) {3988 exports.nbLogger(("ObjectBucket.getIndexLocal(), error: " + (exports._errorText(err))));3989 return Promise.reject(err);3990 });3991 return exports._promisify(promise, callbacks);3992 };3993 ObjectBucket.prototype.getLastSyncTime = function (callbacks) {3994 exports.nbLogger("ObjectBucket.getLastSyncTime()");3995 this._checkOfflineService();3996 var req = new _SdeRequest(BaseBucket.getClassName(), "getLastSyncTime");3997 var body = {3998 bucketName: this.getBucketName(),3999 bucketMode: this.getBucketMode()4000 };4001 req.setData(body);4002 var promise = req.execute().then(function (response) {4003 exports.nbLogger("ObjectBucket.getLastSyncTime(), success : response=" + response);4004 try {4005 var resObj = JSON.parse(response);4006 if (resObj.results != null) {4007 return resObj.results; 4008 }4009 else {4010 exports.nbLogger("ObjectBucket.getLastSyncTime(), success : no results");4011 return null;4012 }4013 }4014 catch (e) {4015 exports.nbLogger("ObjectBucket.getLastSyncTime(), error : exception=" + e);4016 return Promise.reject(exports._createError(0, e.toString(), e));4017 }4018 }, function (err) {4019 exports.nbLogger(("ObjectBucket.getLastSyncTime(), error: " + (exports._errorText(err))));4020 return Promise.reject(err);4021 });4022 return exports._promisify(promise, callbacks);4023 };4024 ObjectBucket.prototype._getResolveId = function () {4025 exports.nbLogger("ObjectBucket._getResolveId(), resolveId=" + this._resolveId);4026 return this._resolveId;4027 };4028 ObjectBucket.prototype._setResolveId = function (resolveId) {4029 exports.nbLogger("ObjectBucket._setResolveId(), cur=" + this._resolveId + ", new=" + resolveId);4030 return this._resolveId = resolveId;4031 };4032 ObjectBucket.prototype.batch = function (request, callbacks) {4033 var path = this.getDataPath("/_batch");4034 var req = new HttpRequest(this._service, path);4035 req.setMethod("POST");4036 req.setContentType("application/json");4037 req.setData(request.json);4038 var promise = req.execute().then(function (response) {4039 var json = JSON.parse(response);4040 var failedCount = 0;4041 for (var _i = 0, _a = json.results; _i < _a.length; _i++) {4042 var result = _a[_i];4043 if (result.result !== "ok") {4044 failedCount++;4045 }4046 }4047 json.failedCount = failedCount;4048 return json;4049 }, function (err) {4050 return Promise.reject(err);4051 });4052 return exports._promisify(promise, callbacks);4053 };4054 ObjectBucket.useLongQuery = false; 4055 ObjectBucket.CONFLICT_POLICY_MANUAL = 0;4056 ObjectBucket.CONFLICT_POLICY_CLIENT = 1;4057 ObjectBucket.CONFLICT_POLICY_SERVER = 2;4058 ObjectBucket.RESOLVE_CONFLICT_UNDEFINED = -1;4059 ObjectBucket.RESOLVE_CONFLICT_CLIENT = 1;4060 ObjectBucket.RESOLVE_CONFLICT_SERVER = 2;4061 ObjectBucket.SYNC_ERROR_UNDEFINED = -1;4062 ObjectBucket.SYNC_ERROR_PUSH = 0;4063 ObjectBucket.SYNC_ERROR_PULL = 1;4064 ObjectBucket.SYNC_ERROR_OVERLAP_ID = 2;4065 ObjectBucket.SYNC_ERROR_PUSH_RESYNCING = 3;4066 return ObjectBucket;4067}(BaseBucket));4068exports.ObjectBucket = ObjectBucket;4069exports.declareObjectBucket = function (_service) {4070 var _a;4071 _service.ObjectBucket = (_a = (function (_super) {4072 __extends(_ObjectBucket, _super);4073 function _ObjectBucket(name, mode) {4074 if (mode === void 0) { mode = exports.Nebula.BUCKET_MODE_ONLINE; }4075 return _super.call(this, name, mode, _service) || this;4076 }4077 _ObjectBucket.loadBucket = function (name, callbacks, mode) {4078 return _super._loadBucket.call(this, _service, name, callbacks, mode);4079 };4080 _ObjectBucket.getBucketList = function (callbacks) {4081 return _super._getBucketList.call(this, _service, callbacks);4082 };4083 _ObjectBucket.getLocalBucketList = function (callbacks) {4084 return _super._getLocalBucketList.call(this, _service, callbacks);4085 };4086 _ObjectBucket.sync = function (callbacks) {4087 return _super._sync.call(this, _service, callbacks);4088 };4089 return _ObjectBucket;4090 }(ObjectBucket)),4091 _a.useLongQuery = false,4092 _a);4093};4094var FileBucket = (function (_super) {4095 __extends(FileBucket, _super);4096 function FileBucket(name, service) {4097 if (service === void 0) { service = exports.Nebula; }4098 var _this = _super.call(this, service, name, "file") || this;4099 _this._resolveId = null;4100 return _this;4101 }4102 FileBucket.loadBucket = function (name, callbacks) { return null; };4103 FileBucket._loadBucket = function (service, name, callbacks) {4104 exports.nbLogger("FileBucket.loadBucket(), name=" + name + ", callbacks=" + callbacks);4105 return BaseBucket._baseLoadBucket("file", service, name, exports.Nebula.BUCKET_MODE_ONLINE, callbacks);4106 };4107 FileBucket.getBucketList = function (callbacks) { return null; };4108 FileBucket._getBucketList = function (service, callbacks) {4109 return BaseBucket._baseGetBucketList("file", service, false, callbacks);4110 };4111 FileBucket.prototype.saveBucket = function (callbacks) {4112 return _super.prototype.saveBucket.call(this, callbacks);4113 };4114 FileBucket.prototype.deleteBucket = function (callbacks) {4115 return _super.prototype.deleteBucket.call(this, callbacks);4116 };4117 FileBucket.prototype.setAcl = function (acl) {4118 _super.prototype.setAcl.call(this, acl);4119 return this;4120 };4121 FileBucket.prototype.getAcl = function () {4122 return _super.prototype.getAcl.call(this);4123 };4124 FileBucket.prototype.setContentAcl = function (acl) {4125 _super.prototype.setContentAcl.call(this, acl);4126 return this;4127 };4128 FileBucket.prototype.getContentAcl = function () {4129 return _super.prototype.getContentAcl.call(this);4130 };4131 FileBucket.prototype.setDescription = function (description) {4132 _super.prototype.setDescription.call(this, description);4133 return this;4134 };4135 FileBucket.prototype.getDescription = function () {4136 return _super.prototype.getDescription.call(this);4137 };4138 FileBucket.prototype.getBucketName = function () {4139 return _super.prototype.getBucketName.call(this);4140 };4141 FileBucket.prototype._setBucketName = function (name) {4142 _super.prototype.setBucketName.call(this, name);4143 return this;4144 };4145 FileBucket.prototype._save = function (fileName, data, metadata, update, callbacks) {4146 exports.nbLogger("FileBucket._save()");4147 if (!fileName) {4148 exports.nbLogger("FileBucket._save(), Parameter is invalid : fileName");4149 throw new Error("No fileName");4150 }4151 if (!data) {4152 exports.nbLogger("FileBucket._save(), Parameter is invalid : data");4153 throw new Error("No data");4154 }4155 if (!(typeof Blob !== "undefined" && Blob !== null) && !(typeof Buffer !== "undefined" && Buffer !== null)) {4156 exports.nbLogger("FileBucket._save(), Not supported Blob nor Buffer");4157 throw new Error("No Blob/Buffer support");4158 }4159 if ((typeof data !== "string")4160 && (typeof Blob !== "undefined" && Blob !== null && !(data instanceof Blob))4161 && (typeof Buffer !== "undefined" && Buffer !== null && !(Buffer.isBuffer(data)))) {4162 exports.nbLogger("FileBucket._save(), Data is not String, Blob nor Buffer");4163 throw new Error("data is not String, Blob nor Buffer");4164 }4165 if (!update) {4166 if (!metadata || !metadata.getContentType()) {4167 exports.nbLogger("FileBucket._save(), Parameter is invalid : metadata.contentType");4168 throw new Error("No contentType in metadata");4169 }4170 }4171 var path = this.getDataPath("/" + encodeURIComponent(fileName));4172 exports.nbLogger("FileBucket._save(), path=" + path);4173 var req = new HttpRequest(this._service, path);4174 if (update) {4175 req.setMethod("PUT");4176 }4177 else {4178 req.setMethod("POST");4179 req.setContentType(metadata.getContentType());4180 if (metadata.getAcl() != null) {4181 req.addRequestHeader("X-ACL", metadata.getAcl()._toString());4182 }4183 if (metadata.getOptions() != null) {4184 req.addRequestHeader("X-Meta-Options", JSON.stringify(metadata.getOptions()));4185 }4186 }4187 req.setData(data);4188 var promise = req.execute().then(function (response) {4189 try {4190 var resObj = JSON.parse(response);4191 if (metadata === null) {4192 metadata = new FileMetadata();4193 }4194 metadata._setMetadata(resObj);4195 return Promise.resolve(metadata);4196 }4197 catch (e) {4198 exports.nbLogger("FileBucket._save(), success: exception=" + e);4199 var error = exports._createError(0, "Invalid response from server", e, fileName);4200 return Promise.reject(error);4201 }4202 }, function (error) {4203 exports.nbLogger(("FileBucket._save(), error: " + (exports._errorText(error))));4204 error.data = fileName;4205 return Promise.reject(error);4206 });4207 return exports._promisify(promise, callbacks);4208 };4209 FileBucket.prototype.saveAs = function (fileName, data, metadata, callbacks) {4210 return this._save(fileName, data, metadata, false, callbacks);4211 };4212 FileBucket.prototype.save = function (fileName, data, callbacks) {4213 return this._save(fileName, data, null, true, callbacks);4214 };4215 FileBucket.prototype.load = function (fileName, callbacks) {4216 return this._load(fileName, undefined, callbacks);4217 };4218 FileBucket.prototype.loadWithOptions = function (fileName, options, callbacks) {4219 return this._load(fileName, options, callbacks);4220 };4221 FileBucket.prototype._load = function (fileName, options, callbacks) {4222 exports.nbLogger("FileBucket._load()");4223 if (!(typeof fileName !== "undefined" && fileName !== null)) {4224 exports.nbLogger("FileBucket._load(), Parameter is invalid : fileName");4225 throw new Error("No fileName");4226 }4227 var rawRequest = false;4228 if (typeof options !== "undefined") {4229 if (options === null || typeof options !== "object") {4230 exports.nbLogger("FileBucket._load(), Invalid options: " + options);4231 throw new Error("Invalid options: " + options);4232 }4233 if (options["rawRequest"] === true) {4234 if (!(typeof Blob !== "undefined" && Blob !== null) && !(typeof Buffer !== "undefined" && Buffer !== null)) {4235 exports.nbLogger("FileBucket._load(), Not supported Blob nor Buffer");4236 throw new Error("No Blob/Buffer support");4237 }4238 rawRequest = true;4239 }4240 }4241 var path = this.getDataPath("/" + encodeURIComponent(fileName));4242 exports.nbLogger("FileBucket._load(), path=" + path);4243 var req = new HttpRequest(this._service, path);4244 req.setMethod("GET");4245 if (rawRequest) {4246 req.rawMessage = true;4247 }4248 else {4249 if (typeof Blob !== "undefined" && Blob !== null) {4250 req.setResponseType("blob");4251 }4252 else if (typeof Buffer !== "undefined" && Buffer !== null) {4253 req.setResponseType("buffer");4254 }4255 }4256 if (typeof options !== "undefined") {4257 var receiveResponse = options["extraResponse"];4258 if (receiveResponse === true) {4259 req.setReceiveResponseHeaders(true);4260 }4261 var start = options["rangeStart"];4262 var end = options["rangeEnd"];4263 var range = FileBucket._createRangeValue(start, end);4264 if (range !== undefined) {4265 req.addRequestHeader("Range", "bytes=" + range);4266 }4267 var ifMatch = options["ifMatch"];4268 if (typeof ifMatch !== "undefined") {4269 req.addRequestHeader("If-Match", '"' + ifMatch + '"');4270 }4271 var ifRange = options["ifRange"];4272 if (typeof ifRange !== "undefined") {4273 req.addRequestHeader("If-Range", '"' + ifRange + '"');4274 }4275 }4276 var promise = req.execute().then(function (response) {4277 return response;4278 }, function (err) {4279 exports.nbLogger(("FileBucket._load(), error: " + (exports._errorText(err))));4280 err.data = fileName;4281 return Promise.reject(err);4282 });4283 return exports._promisify(promise, callbacks);4284 };4285 FileBucket._createRangeValue = function (start, end) {4286 if (start !== undefined && (!Number.isInteger(start) || start < 0)) {4287 throw new Error("invalid rangeStart value: " + start);4288 }4289 if (end !== undefined && (!Number.isInteger(end) || end < 0)) {4290 throw new Error("invalid rangeEnd value: " + end);4291 }4292 var range = undefined;4293 if (start === undefined && end === undefined) {4294 }4295 else if (start !== undefined && end === undefined) {4296 range = start + "-";4297 }4298 else if (start === undefined && end !== undefined) {4299 range = "-" + end;4300 }4301 else {4302 range = start + "-" + end;4303 }4304 return range;4305 };4306 FileBucket.prototype.remove = function (fileName, callbacks) {4307 exports.nbLogger("FileBucket.delete()");4308 if (!(typeof fileName !== "undefined" && fileName !== null)) {4309 exports.nbLogger("FileBucket.delete(), Parameter is invalid : fileName");4310 throw new Error("No fileName");4311 }4312 var req;4313 if (this._service.isOffline()) {4314 req = new _SdeRequest(this.getClassName(), "delete");4315 var body = {4316 bucketName: this.getBucketName(),4317 fileName: fileName4318 };4319 req.setData(body);4320 }4321 else {4322 var path = this.getDataPath("/" + encodeURIComponent(fileName));4323 exports.nbLogger("FileBucket.delete(), path=" + path);4324 req = new HttpRequest(this._service, path);4325 req.setMethod("DELETE");4326 }4327 var promise = req.execute().then(function (response) {4328 exports.nbLogger("FileBucket.delete(), success: " + fileName);4329 return fileName;4330 }, function (err) {4331 exports.nbLogger(("FileBucket.delete(), error: " + (exports._errorText(err)) + " : " + (fileName)));4332 err.data = fileName;4333 return Promise.reject(err);4334 });4335 return exports._promisify(promise, callbacks);4336 };4337 FileBucket.prototype.delete = function (fileName, callbacks) {4338 return this.remove(fileName, callbacks);4339 };4340 FileBucket.prototype._createMetadata = function (obj) {4341 var metadata = new FileMetadata();4342 metadata._setMetadata(obj);4343 return metadata;4344 };4345 FileBucket.prototype._publish = function (fileName, published, callbacks) {4346 var _this = this;4347 exports.nbLogger("FileBucket._publish(), fileName=" + fileName + ", setFlg=" + published);4348 if (!(typeof fileName !== "undefined" && fileName !== null)) {4349 exports.nbLogger("FileBucket._publish(), Parameter is invalid : fileName");4350 throw new Error("No fileName");4351 }4352 var req;4353 if (this._service.isOffline()) {4354 req = new _SdeRequest(this.getClassName(), "publish");4355 var body = {4356 bucketName: this.getBucketName(),4357 fileName: fileName,4358 published: published4359 };4360 req.setData(body);4361 }4362 else {4363 var path = this.getDataPath("/" + encodeURIComponent(fileName) + "/publish");4364 exports.nbLogger("FileBucket._publish(), path=" + path);4365 req = new HttpRequest(this._service, path);4366 if (published) {4367 req.setMethod("PUT");4368 }4369 else {4370 req.setMethod("DELETE");4371 }4372 }4373 var promise = req.execute().then(function (response) {4374 exports.nbLogger("FileBucket._publish(), success: " + fileName);4375 try {4376 var resObj = JSON.parse(response);4377 var metadata = _this._createMetadata(resObj);4378 return Promise.resolve(metadata);4379 }4380 catch (e) {4381 exports.nbLogger("FileBucket._publish(), success: exception=" + e);4382 var errorResult = exports._createError(0, "Invalid response from server", e);4383 errorResult.data = fileName;4384 return Promise.reject(errorResult);4385 }4386 }, function (err) {4387 exports.nbLogger(("FileBucket._publish(), error: " + (exports._errorText) + " : " + (fileName)));4388 err.data = fileName;4389 return Promise.reject(err);4390 });4391 return exports._promisify(promise, callbacks);4392 };4393 FileBucket.prototype.publish = function (fileName, callbacks) {4394 exports.nbLogger("FileBucket.publish()");4395 return this._publish(fileName, true, callbacks);4396 };4397 FileBucket.prototype.unpublish = function (fileName, callbacks) {4398 exports.nbLogger("FileBucket.unpublish()");4399 return this._publish(fileName, false, callbacks);4400 };4401 FileBucket.prototype._getList = function (published, deleteMark, callbacks) {4402 var _this = this;4403 exports.nbLogger("FileBucket._getList(), published=" + published);4404 var req;4405 if (this._service.isOffline()) {4406 req = new _SdeRequest(this.getClassName(), "getList");4407 var body = {4408 bucketName: this.getBucketName(),4409 published: published,4410 deleteMark: deleteMark4411 };4412 req.setData(body);4413 }4414 else {4415 var path = this.getDataPath();4416 exports.nbLogger("FileBucket._getList(), path=" + path);4417 req = new HttpRequest(this._service, path);4418 req.setMethod("GET");4419 if (published) {4420 req.setQueryParam("published", "1");4421 }4422 if (deleteMark) {4423 req.setQueryParam("deleteMark", "1");4424 }4425 }4426 var promise = req.execute().then(function (response) {4427 exports.nbLogger("FileBucket._getList(), success");4428 try {4429 var resObj = JSON.parse(response);4430 var resArray = resObj.results;4431 var metaList = [];4432 if (resArray != null) {4433 for (var _i = 0, resArray_2 = resArray; _i < resArray_2.length; _i++) {4434 var obj = resArray_2[_i];4435 var metadata = _this._createMetadata(obj);4436 metaList.push(metadata);4437 }4438 }4439 return Promise.resolve(metaList);4440 }4441 catch (e) {4442 exports.nbLogger("FileBucket._getList(), success: exception=" + e);4443 var errorResult = exports._createError(0, "Invalid response from server", e);4444 return Promise.reject(errorResult);4445 }4446 }, function (err) {4447 exports.nbLogger(("FileBucket._getList(), error: " + (exports._errorText(err))));4448 return Promise.reject(err);4449 });4450 return exports._promisify(promise, callbacks);4451 };4452 FileBucket.prototype.getList = function (callbacks) {4453 exports.nbLogger("FileBucket.getList()");4454 return this._getList(false, false, callbacks);4455 };4456 FileBucket.prototype.getPublishedList = function (callbacks) {4457 exports.nbLogger("FileBucket.getPublishedList()");4458 return this._getList(true, false, callbacks);4459 };4460 FileBucket.prototype.getMetadata = function (fileName, callbacks) {4461 var _this = this;4462 exports.nbLogger("FileBucket.getMetadata(), fileName=" + fileName);4463 if (!(typeof fileName !== "undefined" && fileName !== null)) {4464 exports.nbLogger("FileBucket.getMetadata(), Parameter is invalid : fileName");4465 throw new Error("No fileName");4466 }4467 var req;4468 if (this._service.isOffline()) {4469 req = new _SdeRequest(this.getClassName(), "getMetadata");4470 var body = {4471 bucketName: this.getBucketName(),4472 fileName: fileName4473 };4474 req.setData(body);4475 }4476 else {4477 var path = this.getDataPath("/" + encodeURIComponent(fileName) + "/meta");4478 exports.nbLogger("FileBucket.getMetadata(), path=" + path);4479 req = new HttpRequest(this._service, path);4480 req.setMethod("GET");4481 }4482 var promise = req.execute().then(function (response) {4483 exports.nbLogger("FileBucket.getMetadata(), success");4484 try {4485 var resObj = JSON.parse(response);4486 var metadata = _this._createMetadata(resObj);4487 return Promise.resolve(metadata);4488 }4489 catch (e) {4490 exports.nbLogger("FileBucket.getMetadata(), Invalid response : " + response);4491 var errorResult = exports._createError(0, "Invalid response from server", e);4492 errorResult.data = fileName;4493 return Promise.reject(errorResult);4494 }4495 }, function (err) {4496 exports.nbLogger(("FileBucket.getMetadata(), error: " + (exports._errorText(err))));4497 err.data = fileName;4498 return Promise.reject(err);4499 });4500 return exports._promisify(promise, callbacks);4501 };4502 FileBucket.prototype.updateMetadata = function (fileName, metadata, callbacks) {4503 exports.nbLogger("FileBucket.updateMetadata(), fileName=" + fileName);4504 if (fileName == null || fileName === "") {4505 exports.nbLogger("FileBucket.updateMetadata(), Parameter is invalid : fileName");4506 throw new Error("No fileName");4507 }4508 if (!(metadata instanceof FileMetadata)) {4509 exports.nbLogger("FileBucket.updateMetadata(), Parameter is invalid : metadata");4510 throw new Error("metadata is not instance of FileMetadata");4511 }4512 var body = {};4513 var req;4514 if (this._service.isOffline()) {4515 req = new _SdeRequest(this.getClassName(), "updateMetadata");4516 body.bucketName = this.getBucketName();4517 body.targetFileName = fileName;4518 body.cacheDisabled = metadata.isCacheDisabled();4519 }4520 else {4521 var path = this.getDataPath("/" + encodeURIComponent(fileName) + "/meta");4522 exports.nbLogger("FileBucket.updateMetadata(), path=" + path);4523 req = new HttpRequest(this._service, path);4524 req.setMethod("PUT");4525 }4526 if (metadata.getFileName() != null) {4527 body.filename = metadata.getFileName();4528 }4529 if (metadata.getContentType() != null) {4530 body.contentType = metadata.getContentType();4531 }4532 if (metadata.getAcl() != null) {4533 body.ACL = metadata.getAcl()._toJsonObject();4534 }4535 if (metadata.getOptions() != null) {4536 body.options = JSON.stringify(metadata.getOptions());4537 }4538 req.setData(body);4539 var promise = req.execute().then(function (response) {4540 exports.nbLogger("FileBucket.updateMetadata(), success");4541 try {4542 var resObj = JSON.parse(response);4543 metadata._setMetadata(resObj);4544 return Promise.resolve(metadata);4545 }4546 catch (e) {4547 exports.nbLogger("FileBucket.updateMetadata(), success: exception=" + e);4548 var errorResult = exports._createError(0, "Invalid response from server", e);4549 errorResult.data = fileName;4550 return Promise.reject(errorResult);4551 }4552 }, function (err) {4553 exports.nbLogger(("FileBucket.updateMetadata(), error: " + (exports._errorText(err))));4554 err.data = fileName;4555 return Promise.reject(err);4556 });4557 return exports._promisify(promise, callbacks);4558 };4559 FileBucket._checkOfflineService = function (service) {4560 if (service !== exports.Nebula) {4561 exports.nbLogger("ObjectBucket.setSyncScope(): Can't use for multitenant instance");4562 throw new Error("No multitenant support");4563 }4564 if (!service.isOffline()) {4565 exports.nbLogger("ObjectBucket.setSyncScope(), supported offline mode only");4566 throw new Error("No offline mode enabled");4567 }4568 };4569 FileBucket.selectUploadFile = function (callbacks) { return null; };4570 FileBucket._selectUploadFile = function (service, callbacks) {4571 exports.nbLogger("FileBucket.selectUploadFile()");4572 this._checkOfflineService(service);4573 var req = new _SdeRequest(BaseBucket.getClassName("file"), "selectUploadFile");4574 var promise = req.execute().then(function (response) {4575 try {4576 var resObj = JSON.parse(response);4577 return Promise.resolve(resObj);4578 }4579 catch (e) {4580 exports.nbLogger("FileBucket.selectUploadFile(), success: exception=" + e);4581 var errorResult = exports._createError(0, "Invalid response from server", e);4582 return Promise.reject(errorResult);4583 }4584 }, function (err) {4585 exports.nbLogger(("FileBucket.selectUploadFile(), error: " + (exports._errorText(err))));4586 return Promise.reject(err);4587 });4588 return exports._promisify(promise, callbacks);4589 };4590 FileBucket.selectDirectory = function (callbacks) { return null; };4591 FileBucket._selectDirectory = function (service, callbacks) {4592 exports.nbLogger("FileBucket.selectDirectory()");4593 this._checkOfflineService(service);4594 var req = new _SdeRequest(BaseBucket.getClassName("file"), "selectDirectory");4595 var promise = req.execute().then(function (response) {4596 try {4597 var resObj = JSON.parse(response);4598 return Promise.resolve(resObj.path);4599 }4600 catch (e) {4601 exports.nbLogger("FileBucket.selectUploadFile(), success: exception=" + e);4602 var errorResult = exports._createError(0, "Invalid response from server", e);4603 return Promise.reject(errorResult);4604 }4605 }, function (err) {4606 exports.nbLogger(("FileBucket.selectDirectory(), error: " + (exports._errorText(err))));4607 return Promise.reject(err);4608 });4609 return exports._promisify(promise, callbacks);4610 };4611 FileBucket.prototype._uploadFile = function (fileName, filePath, metadata, update, callbacks) {4612 exports.nbLogger("FileBucket._uploadFile()");4613 if (!this._service.isOffline()) {4614 exports.nbLogger("FileBucket._uploadFile(), only offline mode");4615 throw new Error("No offline mode enabled");4616 }4617 if (!fileName || fileName === "") {4618 exports.nbLogger("FileBucket._uploadFile(), Parameter is invalid : fileName");4619 throw new Error("No fileName");4620 }4621 if (!filePath || filePath === "") {4622 exports.nbLogger("FileBucket._uploadFile(), Parameter is invalid : filePath");4623 throw new Error("No filePath");4624 }4625 if (!metadata || !metadata.getContentType() || metadata.getContentType() === "") {4626 exports.nbLogger("FileBucket._uploadFile(), Parameter is invalid : metadata");4627 throw new Error("No metadata.contentType");4628 }4629 var method = "uploadNewFile";4630 if (update) {4631 method = "uploadUpdateFile";4632 }4633 var req = new _SdeRequest(this.getClassName(), method);4634 var body = {};4635 body.bucketName = this.getBucketName();4636 body.fileName = fileName;4637 body.filePath = filePath;4638 body.cacheDisabled = metadata.isCacheDisabled();4639 body.contentType = metadata.getContentType();4640 if (metadata.getAcl() != null) {4641 body.ACL = metadata.getAcl()._toJsonObject();4642 }4643 if (metadata.getOptions() != null) {4644 body.options = JSON.stringify(metadata.getOptions());4645 }4646 req.setData(body);4647 var promise = req.execute().then(function (response) {4648 try {4649 var resObj = JSON.parse(response);4650 if (metadata === null) {4651 metadata = new FileMetadata();4652 }4653 metadata._setMetadata(resObj);4654 return Promise.resolve(metadata);4655 }4656 catch (e) {4657 exports.nbLogger("FileBucket.uploadNewFile(), success: exception=" + e);4658 var errorResult = exports._createError(0, "Invalid response from server", e);4659 errorResult.data = fileName;4660 return Promise.reject(errorResult);4661 }4662 }, function (err) {4663 exports.nbLogger(("FileBucket.uploadNewFile(), error: " + (exports._errorText(err))));4664 err.data = fileName;4665 return Promise.reject(err);4666 });4667 return exports._promisify(promise, callbacks);4668 };4669 FileBucket.prototype.uploadNewFile = function (fileName, filePath, metadata, callbacks) {4670 exports.nbLogger("FileBucket.uploadNewFile()");4671 return this._uploadFile(fileName, filePath, metadata, false, callbacks);4672 };4673 FileBucket.prototype.uploadUpdateFile = function (fileName, filePath, metadata, callbacks) {4674 exports.nbLogger("FileBucket.uploadUpdateFile()");4675 return this._uploadFile(fileName, filePath, metadata, true, callbacks);4676 };4677 FileBucket.prototype.downloadFile = function (fileName, filePath, callbacks) {4678 exports.nbLogger("FileBucket.downloadFile()");4679 FileBucket._checkOfflineService(this._service);4680 if (!fileName || fileName === "") {4681 exports.nbLogger("FileBucket.downloadFile(), Parameter is invalid : fileName");4682 throw new Error("No fileName");4683 }4684 if (!filePath || filePath === "") {4685 exports.nbLogger("FileBucket.downloadFile(), Parameter is invalid : filePath");4686 throw new Error("No filePath");4687 }4688 var req = new _SdeRequest(this.getClassName(), "downloadFile");4689 var body = {4690 bucketName: this.getBucketName(),4691 fileName: fileName,4692 filePath: filePath4693 };4694 req.setData(body);4695 var promise = req.execute().then(function (response) {4696 try {4697 var resObj = JSON.parse(response);4698 exports.nbLogger("FileBucket.downloadFile(), response=" + response);4699 return Promise.resolve(fileName);4700 }4701 catch (e) {4702 exports.nbLogger("FileBucket.downloadFile(), success: exception=" + e);4703 var errorResult = exports._createError(0, "Invalid response from server", e);4704 errorResult.data = fileName;4705 return Promise.reject(errorResult);4706 }4707 }, function (err) {4708 exports.nbLogger(("FileBucket.downloadFile(), error: " + (exports._errorText(err))));4709 err.data = fileName;4710 return Promise.reject(err);4711 });4712 return exports._promisify(promise, callbacks);4713 };4714 FileBucket.prototype.requestCancel = function (fileName, callbacks) {4715 exports.nbLogger("FileBucket.requestCancel()");4716 FileBucket._checkOfflineService(this._service);4717 if (!(typeof fileName !== "undefined" && fileName !== null) || fileName === "") {4718 exports.nbLogger("FileBucket.requestCancel(), Parameter is invalid : fileName");4719 throw new Error("No fileName");4720 }4721 var req = new _SdeRequest(this.getClassName(), "requestCancel");4722 var body = {4723 bucketName: this.getBucketName(),4724 fileName: fileName4725 };4726 req.setData(body);4727 var promise = req.execute().then(function (response) {4728 try {4729 exports.nbLogger("FileBucket.requestCancel(), response=" + response);4730 return Promise.resolve(fileName);4731 }4732 catch (e) {4733 exports.nbLogger("FileBucket.requestCancel(), success: exception=" + e);4734 var errorResult = exports._createError(0, "Invalid response from server", e);4735 errorResult.data = fileName;4736 return Promise.reject(errorResult);4737 }4738 }, function (err) {4739 exports.nbLogger(("FileBucket.requestCancel(), error: " + (exports._errorText(err))));4740 err.data = fileName;4741 return Promise.reject(err);4742 });4743 return exports._promisify(promise, callbacks);4744 };4745 return FileBucket;4746}(BaseBucket));4747exports.FileBucket = FileBucket;4748exports.declareFileBucket = function (_service) {4749 _service.FileBucket = (function (_super) {4750 __extends(_FileBucket, _super);4751 function _FileBucket(name) {4752 return _super.call(this, name, _service) || this;4753 }4754 _FileBucket.loadBucket = function (name, callbacks) {4755 return _super._loadBucket.call(this, _service, name, callbacks);4756 };4757 _FileBucket.getBucketList = function (callbacks) {4758 return _super._getBucketList.call(this, _service, callbacks);4759 };4760 _FileBucket.selectUploadFile = function (callbacks) {4761 return _super._selectUploadFile.call(this, _service, callbacks);4762 };4763 _FileBucket.selectDirectory = function (callbacks) {4764 return _super._selectDirectory.call(this, _service, callbacks);4765 };4766 return _FileBucket;4767 }(FileBucket));4768};4769var CustomApi = (function () {4770 function CustomApi(apiname, method, subpath, service) {4771 if (service === void 0) { service = exports.Nebula; }4772 this._service = service;4773 this.apiname = apiname;4774 this.method = method;4775 this.subpath = subpath;4776 this.headers = {};4777 this.queryParams = {};4778 this.receiveResponseHeaders = false;4779 this.path = "/api/" + apiname;4780 if (subpath) {4781 if (subpath.indexOf("/") !== 0) {4782 this.path += "/";4783 }4784 this.path += subpath;4785 }4786 }4787 CustomApi.prototype.clearHeaders = function () {4788 this.headers = {};4789 };4790 CustomApi.prototype.setContentType = function (contentType) {4791 this.contentType = contentType;4792 return this;4793 };4794 CustomApi.prototype.addHeader = function (name, value) {4795 this.headers[name] = value;4796 return this;4797 };4798 CustomApi.prototype.addQueryParam = function (name, value) {4799 this.queryParams[name] = value;4800 return this;4801 };4802 CustomApi.prototype.setBinaryResponse = function () {4803 if (typeof Blob !== "undefined" && Blob !== null) {4804 this.responseType = "blob";4805 }4806 else if (typeof Buffer !== "undefined" && Buffer !== null) {4807 this.responseType = "buffer";4808 }4809 else {4810 throw new Error("No blob / buffer");4811 }4812 return this;4813 };4814 CustomApi.prototype.setReceiveResponseHeaders = function (receive) {4815 this.receiveResponseHeaders = receive;4816 return this;4817 };4818 CustomApi.prototype.execute = function (data, callbacks) {4819 return this._execute(data, false, callbacks);4820 };4821 CustomApi.prototype.executeRaw = function (data) {4822 return this._execute(data, true);4823 };4824 CustomApi.prototype._execute = function (data, rawMessage, callbacks) {4825 var request = new HttpRequest(this._service, this.path);4826 request.setMethod(this.method);4827 request.addQueryParams(this.queryParams);4828 if (data) {4829 if (this.method === "GET" || this.method === "DELETE") {4830 request.addQueryParams(data);4831 }4832 else {4833 request.setData(data);4834 }4835 }4836 if (!rawMessage) {4837 if (this.responseType != null) {4838 request.setResponseType(this.responseType);4839 }4840 }4841 else {4842 request.rawMessage = true;4843 }4844 if (this.contentType != null) {4845 request.setContentType(this.contentType);4846 }4847 for (var _i = 0, _a = Object.keys(this.headers); _i < _a.length; _i++) {4848 var key = _a[_i];4849 request.addRequestHeader(key, this.headers[key]);4850 }4851 request.setReceiveResponseHeaders(this.receiveResponseHeaders);4852 var promise = request.execute()4853 .then(function (response) {4854 exports.nbLogger("CustomApi#success");4855 return response;4856 })4857 .catch(function (err) {4858 exports.nbLogger("CustomApi#error " + exports._errorText(err));4859 return Promise.reject(err);4860 });4861 return exports._promisify(promise, callbacks);4862 };4863 return CustomApi;4864}());4865exports.CustomApi = CustomApi;4866exports.declareCustomApi = function (_service) {4867 _service.CustomApi = (function (_super) {4868 __extends(_CustomApi, _super);4869 function _CustomApi(apiname, method, subpath) {4870 return _super.call(this, apiname, method, subpath, _service) || this;4871 }4872 return _CustomApi;4873 }(CustomApi));4874};4875var ApnsFields = (function () {4876 function ApnsFields() {4877 this._fields = {};4878 }4879 Object.defineProperty(ApnsFields.prototype, "badge", {4880 get: function () {4881 return this._fields.badge;4882 },4883 set: function (badge) {4884 if (!this._isInteger(badge)) {4885 throw new Error("ApnsFields.badge, Not integer: " + badge);4886 }4887 this._fields.badge = badge;4888 },4889 enumerable: true,4890 configurable: true4891 });4892 Object.defineProperty(ApnsFields.prototype, "sound", {4893 get: function () {4894 return this._fields.sound;4895 },4896 set: function (sound) {4897 if (typeof sound !== "string") {4898 throw new Error("ApnsFields.sound, Not string: " + sound);4899 }4900 this._fields.sound = sound;4901 },4902 enumerable: true,4903 configurable: true4904 });4905 Object.defineProperty(ApnsFields.prototype, "contentAvailable", {4906 get: function () {4907 return this._fields["content-available"];4908 },4909 set: function (contentAvailable) {4910 if (!this._isInteger(contentAvailable)) {4911 throw new Error("ApnsFields.contentAvailable, Not integer: " + contentAvailable);4912 }4913 this._fields["content-available"] = contentAvailable;4914 },4915 enumerable: true,4916 configurable: true4917 });4918 Object.defineProperty(ApnsFields.prototype, "category", {4919 get: function () {4920 return this._fields.category;4921 },4922 set: function (category) {4923 if (typeof category !== "string") {4924 throw new Error("ApnsFields.category, Not string: " + category);4925 }4926 this._fields.category = category;4927 },4928 enumerable: true,4929 configurable: true4930 });4931 ApnsFields.prototype._isInteger = function (value) {4932 return typeof value === 'number' &&4933 isFinite(value) &&4934 Math.floor(value) === value;4935 };4936 return ApnsFields;4937}());4938exports.ApnsFields = ApnsFields;4939var GcmFields = (function () {4940 function GcmFields() {4941 this._fields = {};4942 }4943 Object.defineProperty(GcmFields.prototype, "title", {4944 get: function () {4945 return this._fields.title;4946 },4947 set: function (title) {4948 if (typeof title === "string") {4949 this._fields.title = title;4950 }4951 else {4952 throw new Error("GcmFields.title, Invalid value: " + title);4953 }4954 },4955 enumerable: true,4956 configurable: true4957 });4958 Object.defineProperty(GcmFields.prototype, "uri", {4959 get: function () {4960 return this._fields.uri;4961 },4962 set: function (uri) {4963 if (typeof uri === "string") {4964 this._fields.uri = uri;4965 }4966 else {4967 throw new Error("GcmFields.uri, Invalid value: " + uri);4968 }4969 },4970 enumerable: true,4971 configurable: true4972 });4973 return GcmFields;4974}());4975exports.GcmFields = GcmFields;4976var SseFields = (function () {4977 function SseFields() {4978 this._fields = {};4979 }4980 Object.defineProperty(SseFields.prototype, "eventId", {4981 get: function () {4982 return this._fields.sseEventId;4983 },4984 set: function (eventId) {4985 if (typeof eventId !== "string") {4986 throw new Error("SseFields.eventId, Not string: " + eventId);4987 }4988 this._fields.sseEventId = eventId;4989 },4990 enumerable: true,4991 configurable: true4992 });4993 Object.defineProperty(SseFields.prototype, "eventType", {4994 get: function () {4995 return this._fields.sseEventType;4996 },4997 set: function (eventType) {4998 if (typeof eventType !== "string") {4999 throw new Error("SseFields.eventType, Not string: " + eventType);5000 }5001 this._fields.sseEventType = eventType;5002 },5003 enumerable: true,5004 configurable: true5005 });5006 return SseFields;5007}());5008exports.SseFields = SseFields;5009var PushSender = (function () {5010 function PushSender(service) {5011 if (service === void 0) { service = exports.Nebula; }5012 this._service = service;5013 }5014 PushSender.prototype.send = function (callbacks) {5015 exports.nbLogger("PushSender.send()");5016 var path = "/push/notifications";5017 var request = new HttpRequest(this._service, path);5018 request.setMethod("POST");5019 request.setContentType("application/json");5020 request.setData(this._toJson());5021 var promise = request.execute().then(function (response) {5022 exports.nbLogger("PushSender.send#success : response = " + response);5023 try {5024 return JSON.parse(response);5025 }5026 catch (e) {5027 exports.nbLogger("PushSender.send#error : exception=" + e);5028 var errorResult = exports._createError(0, "Invalid response from server", e);5029 return Promise.reject(errorResult);5030 }5031 }, function (error) {5032 exports.nbLogger(("PushSender.send#error = " + (exports._errorText(error))));5033 return Promise.reject(error);5034 });5035 return exports._promisify(promise, callbacks);5036 };5037 PushSender.prototype._toJson = function () {5038 var json = {};5039 if (this._clause != null) {5040 json.query = this._clause.json();5041 }5042 if (this._message != null) {5043 json.message = this._message;5044 }5045 if (this._allowedReceivers != null) {5046 json.allowedReceivers = this._allowedReceivers;5047 }5048 if (this._apnsFields != null) {5049 this._copyKeys(this._apnsFields._fields, json);5050 }5051 if (this._gcmFields != null) {5052 this._copyKeys(this._gcmFields._fields, json);5053 }5054 if (this._sseFields != null) {5055 this._copyKeys(this._sseFields._fields, json);5056 }5057 return json;5058 };5059 PushSender.prototype._copyKeys = function (from, to) {5060 for (var _i = 0, _a = Object.keys(from); _i < _a.length; _i++) {5061 var key = _a[_i];5062 to[key] = from[key];5063 }5064 };5065 Object.defineProperty(PushSender.prototype, "clause", {5066 get: function () {5067 return this._clause;5068 },5069 set: function (clause) {5070 if (!(clause instanceof Clause)) {5071 throw new Error("PushSender.clause, Invalid type");5072 }5073 this._clause = clause;5074 },5075 enumerable: true,5076 configurable: true5077 });5078 Object.defineProperty(PushSender.prototype, "message", {5079 get: function () {5080 return this._message;5081 },5082 set: function (message) {5083 if (typeof message !== "string") {5084 throw new Error("PushSender.message, Not string: " + message);5085 }5086 this._message = message;5087 exports.nbLogger("push.message = " + this._message);5088 },5089 enumerable: true,5090 configurable: true5091 });5092 Object.defineProperty(PushSender.prototype, "allowedReceivers", {5093 get: function () {5094 return this._allowedReceivers;5095 },5096 set: function (receivers) {5097 if (!Array.isArray(receivers)) {5098 throw new Error("PushSender.allowedReceivers, Not Array");5099 }5100 this._allowedReceivers = receivers;5101 },5102 enumerable: true,5103 configurable: true5104 });5105 Object.defineProperty(PushSender.prototype, "apnsFields", {5106 get: function () {5107 return this._apnsFields;5108 },5109 set: function (fields) {5110 if (!(fields instanceof ApnsFields)) {5111 throw new Error("PushSender.apnsFields, Invalid instance type");5112 }5113 this._apnsFields = fields;5114 },5115 enumerable: true,5116 configurable: true5117 });5118 Object.defineProperty(PushSender.prototype, "gcmFields", {5119 get: function () {5120 return this._gcmFields;5121 },5122 set: function (fields) {5123 if (!(fields instanceof GcmFields)) {5124 throw new Error("PushSender.gcmFields, Invalid instance type");5125 }5126 this._gcmFields = fields;5127 },5128 enumerable: true,5129 configurable: true5130 });5131 Object.defineProperty(PushSender.prototype, "sseFields", {5132 get: function () {5133 return this._sseFields;5134 },5135 set: function (fields) {5136 if (!(fields instanceof SseFields)) {5137 throw new Error("PushSender.sseFields, Invalid instance type");5138 }5139 this._sseFields = fields;5140 },5141 enumerable: true,5142 configurable: true5143 });5144 PushSender.ApnsFields = ApnsFields;5145 PushSender.GcmFields = GcmFields;5146 PushSender.SseFields = SseFields;5147 return PushSender;5148}());5149exports.PushSender = PushSender;5150exports.declarePushSender = function (_service) {5151 _service.PushSender = (function (_super) {5152 __extends(_PushSender, _super);5153 function _PushSender() {5154 return _super.call(this, _service) || this;5155 }5156 return _PushSender;5157 }(PushSender));5158};5159var BatchRequest = (function () {5160 function BatchRequest() {5161 this.requests = [];5162 this.json = { requests: this.requests };5163 }5164 BatchRequest.prototype.addInsertRequest = function (object) {5165 if (object.etag) {5166 throw new Error("ETag exists");5167 }5168 this.requests.push({5169 op: "insert",5170 data: object5171 });5172 };5173 BatchRequest.prototype.addUpdateRequest = function (object) {5174 if (!object._id) {5175 throw new Error("No id");5176 }5177 var req = {5178 op: "update",5179 _id: object._id,5180 data: { "$full_update": object }5181 };5182 if (object.etag) {5183 req.etag = object.etag;5184 }5185 this.requests.push(req);5186 };5187 BatchRequest.prototype.addDeleteRequest = function (object) {5188 if (!object._id) {5189 throw new Error("No id");5190 }5191 var req = {5192 op: "delete",5193 _id: object._id5194 };5195 if (object.etag) {5196 req.etag = object.etag;5197 }5198 this.requests.push(req);5199 };5200 return BatchRequest;5201}());5202exports.BatchRequest = BatchRequest;5203var LocalStorageInMemory = (function () {5204 function LocalStorageInMemory() {5205 this.data = {};5206 }5207 LocalStorageInMemory.prototype.getItem = function (key) {5208 return this.data[key];5209 };5210 LocalStorageInMemory.prototype.setItem = function (key, value) {5211 this.data[key] = value;5212 };5213 LocalStorageInMemory.prototype.removeItem = function (key) {5214 delete this.data[key];5215 };5216 return LocalStorageInMemory;5217}());5218exports.LocalStorageInMemory = LocalStorageInMemory;5219var NebulaConfig = (function () {5220 function NebulaConfig(params) {5221 this.offline = false;5222 this.allowSelfSignedCert = false;5223 this.debugMode = "release";5224 this.enableHttp2 = false;5225 this.tenant = params.tenant;5226 this.appId = params.appId;5227 this.appKey = params.appKey;5228 this.baseUri = params.baseUri;5229 if (this.tenant == null)5230 throw new Error("No tenant");5231 if (this.appId == null)5232 throw new Error("No appId");5233 if (this.appKey == null)5234 throw new Error("No appKey");5235 if (this.baseUri == null)5236 throw new Error("No baseUri");5237 if (this.baseUri.slice(-1) === "/") {5238 this.baseUri = this.baseUri.slice(0, -1);5239 }5240 if (params.offline !== undefined && params.offline === true) {5241 this.offline = params.offline;5242 }5243 if (params.allowSelfSignedCert !== undefined && params.allowSelfSignedCert === true) {5244 this.allowSelfSignedCert = params.allowSelfSignedCert;5245 }5246 if (params.serviceId !== undefined) {5247 this.serviceId = params.serviceId;5248 }5249 if (params.debugMode !== undefined) {5250 this.debugMode = params.debugMode;5251 }5252 if (params.enableHttp2 !== undefined) {5253 this.enableHttp2 = params.enableHttp2;5254 }5255 }5256 return NebulaConfig;5257}());5258exports.NebulaConfig = NebulaConfig;5259var NebulaService = (function () {5260 function NebulaService() {5261 this.BUCKET_MODE_ONLINE = 0;5262 this.BUCKET_MODE_REPLICA = 1;5263 this.BUCKET_MODE_LOCAL = 2;5264 exports.declareUser(this);5265 exports.declareGroup(this);5266 exports.declareObjectBucket(this);5267 exports.declareFileBucket(this);5268 exports.declareCustomApi(this);5269 exports.declarePushSender(this);5270 this.NebulaService = NebulaService;5271 this.HttpRequest = HttpRequest;5272 this.AclPermission = exports.AclPermission;5273 this.AclGroup = exports.AclGroup;5274 this.Acl = Acl;5275 this.RegexOption = exports.RegexOption;5276 this.Clause = Clause;5277 this.ObjectQuery = ObjectQuery;5278 this.FileMetadata = FileMetadata;5279 this.BatchRequest = BatchRequest;5280 this.AccountLink = AccountLink;5281 this._SdeRequest = _SdeRequest;5282 this._SdeNetworkEventListener = _SdeNetworkEventListener;5283 this._SdeSyncEventListener = _SdeSyncEventListener;5284 }5285 NebulaService.prototype.getRestApiVersion = function () {5286 return 1;5287 };5288 NebulaService.prototype.getTenantID = function () {5289 if (this._config === undefined) {5290 return null;5291 }5292 else {5293 return this._config.tenant;5294 }5295 };5296 NebulaService.prototype.getBaseUri = function () {5297 if (this._config === undefined) {5298 return null;5299 }5300 else {5301 return this._config.baseUri;5302 }5303 };5304 NebulaService.prototype.getAppID = function () {5305 if (this._config === undefined) {5306 return null;5307 }5308 else {5309 return this._config.appId;5310 }5311 };5312 NebulaService.prototype.getAppKey = function () {5313 if (this._config === undefined) {5314 return null;5315 }5316 else {5317 return this._config.appKey;5318 }5319 };5320 NebulaService.prototype.setAppKey = function (key) {5321 if (!this._config) {5322 throw new Error("Not initialized");5323 }5324 this._config.appKey = key;5325 return this;5326 };5327 NebulaService.prototype.getServiceID = function () {5328 if (this._config === undefined) {5329 return null;5330 }5331 else {5332 return this._config.serviceId;5333 }5334 };5335 NebulaService.prototype.getDebugMode = function () {5336 if (this._config === undefined) {5337 return null;5338 }5339 else {5340 return this._config.debugMode;5341 }5342 };5343 NebulaService.prototype.isOffline = function () {5344 return this._config.offline;5345 };5346 NebulaService.prototype.isAllowSelfSignedCert = function () {5347 return this._config.allowSelfSignedCert;5348 };5349 NebulaService.prototype.setClientCertificate = function (certInfo) {5350 this._config.clientCertOptions = certInfo;5351 return this;5352 };5353 NebulaService.prototype.isClientCertSet = function () {5354 return (this._config.clientCertOptions != null);5355 };5356 NebulaService.prototype.getCurrentUser = function () {5357 var _saveStr = this._localStorage.getItem(this._userItemKey());5358 if (!_saveStr) {5359 return null;5360 }5361 try {5362 var _jsonObj = JSON.parse(_saveStr);5363 if (!("expire" in _jsonObj) || _jsonObj.expire < new Date().getTime() / 1000) {5364 _jsonObj = null;5365 }5366 return _jsonObj;5367 }5368 catch (e) {5369 exports.nbLogger("Nebula.getCurrentUser#" + e.message);5370 return null;5371 }5372 };5373 NebulaService.prototype.setCurrentUser = function (user) {5374 var _saveObj = {5375 _id: user._id,5376 username: user.username,5377 email: user.email,5378 sessionToken: user.sessionToken,5379 expire: user.expire,5380 options: user.options,5381 groups: user.groups5382 };5383 this._localStorage.setItem(this._userItemKey(), JSON.stringify(_saveObj));5384 return this;5385 };5386 NebulaService.prototype.setSessionToken = function (sessionToken) {5387 var expire = new Date().getTime() / 1000 + (60 * 60 * 24 * 365 * 100);5388 var _json = this.getCurrentUser();5389 if (_json === null) { 5390 _json = {5391 _id: "",5392 username: "",5393 email: "",5394 sessionToken: sessionToken,5395 expire: expire,5396 options: {},5397 groups: []5398 };5399 }5400 else {5401 _json.sessionToken = sessionToken;5402 _json.expire = expire;5403 }5404 this._localStorage.setItem(this._userItemKey(), JSON.stringify(_json));5405 return this;5406 };5407 NebulaService.prototype.removeCurrentUser = function () {5408 this._localStorage.removeItem(this._userItemKey());5409 return this;5410 };5411 NebulaService.prototype._userItemKey = function () {5412 var serviceId = this.getServiceID();5413 if (serviceId !== undefined) {5414 return this.getTenantID() + "_" + this.getAppID() + "_" + serviceId;5415 }5416 else {5417 return this.getTenantID() + "_" + this.getAppID();5418 }5419 };5420 NebulaService.prototype.getHttp2 = function () {5421 return this._config.enableHttp2;5422 };5423 NebulaService.prototype.setHttp2 = function (enable) {5424 this._config.enableHttp2 = enable;5425 };5426 NebulaService.prototype.initialize = function (params) {5427 var _this = this;5428 this._config = new NebulaConfig(params);5429 if (typeof localStorage !== 'undefined' && localStorage != null) {5430 this._localStorage = localStorage;5431 }5432 else {5433 this._localStorage = new LocalStorageInMemory();5434 }5435 if (this._config.offline) {5436 if (this !== exports.Nebula) {5437 throw new Error("No offline mode supported for multi-tenant instance.");5438 }5439 try {5440 var request = new _SdeRequest("Nebula", "initialize");5441 var initializeParams = {5442 tenant: this.getTenantID(),5443 appId: this.getAppID(),5444 appKey: this.getAppKey(),5445 baseUri: this.getBaseUri(),5446 offline: this.isOffline(),5447 allowSelfSignedCert: this.isAllowSelfSignedCert(),5448 debugMode: this.getDebugMode(),5449 enableHttp2: this.getHttp2()5450 };5451 request.setData(initializeParams);5452 request.execute().then(function (response) {5453 exports.nbLogger("Nebula.initialize#Success");5454 exports.nbLogger("Nebula.initialize#response = " + response);5455 }).catch(function (error) {5456 exports.nbLogger("Nebula.initialize#Error = " + exports._errorText(error));5457 _this._config.offline = false;5458 });5459 }5460 catch (e) {5461 exports.nbLogger("Nebula.initialize#" + e.message);5462 this._config.offline = false;5463 }5464 }5465 return this;5466 };5467 NebulaService.prototype.setLoginCacheValidTime = function (expire, callbacks) {5468 exports.nbLogger("Nebula.setLoginCacheValidTime#start");5469 if (expire <= 0) {5470 throw new Error("Nebula.setLoginCacheValidTime: bad expire");5471 }5472 if (!this.isOffline()) {5473 throw new Error("Not offline mode!");5474 }5475 var request = new _SdeRequest("Nebula", "setLoginCacheValidTime");5476 var setLoginCacheValidTimeParams = {5477 expire: expire5478 };5479 request.setData(setLoginCacheValidTimeParams);5480 var promise = request.execute().then(function () {5481 exports.nbLogger("Nebula.setLoginCacheValidTime#Success");5482 return;5483 }).catch(function (error) {5484 exports.nbLogger(("Nebula.setLoginCacheValidTime#error = " + (exports._errorText(error))));5485 return Promise.reject(error);5486 });5487 exports.nbLogger("Nebula.setLoginCacheValidTime#end");5488 return exports._promisify(promise, callbacks);5489 };5490 NebulaService.prototype.getLoginCacheValidTime = function (callbacks) {5491 exports.nbLogger("Nebula.getLoginCacheValidTime#start");5492 if (!this.isOffline()) {5493 throw new Error("Not offline mode!");5494 }5495 var request = new _SdeRequest("Nebula", "getLoginCacheValidTime");5496 var promise = request.execute().then(function (response) {5497 exports.nbLogger("Nebula.getLoginCacheValidTime#Success");5498 var jsonObj;5499 try {5500 jsonObj = JSON.parse(response);5501 }5502 catch (e) {5503 exports.nbError("Nebula.getLoginCacheValidTime#" + e.message);5504 jsonObj = null;5505 }5506 if (jsonObj !== null) {5507 return Promise.resolve(jsonObj.expire);5508 }5509 else {5510 var error = exports._createError(400, "Bad Response", "Response json error.");5511 return Promise.reject(error);5512 }5513 }).catch(function (error) {5514 exports.nbLogger("Nebula.getLoginCacheValidTime#error callback start");5515 exports.nbLogger(("Nebula.getLoginCacheValidTime#error = " + (exports._errorText(error))));5516 return Promise.reject(error);5517 });5518 exports.nbLogger("Nebula.getLoginCacheValidTime#end");5519 return exports._promisify(promise, callbacks);5520 };5521 NebulaService.prototype.setNetworkEventListener = function (listener) {5522 exports.nbLogger("Nebula.setNetworkEventListener#start");5523 var paramOk = false;5524 if (arguments.length === 1) {5525 if (listener != null) {5526 if (listener.onNetworkStateChanged !== undefined) {5527 paramOk = true;5528 }5529 }5530 if (listener === null) {5531 paramOk = true;5532 }5533 }5534 if (!paramOk) {5535 exports.nbError("Nebula.setNetworkEventListener#invalid parameter.");5536 return;5537 }5538 if (this.isOffline()) {5539 _SdeNetworkEventListener.setCallback(listener);5540 }5541 else {5542 exports.nbLogger("Nebula.setNetworkEventListener#Disabled Offline");5543 }5544 exports.nbLogger("Nebula.setNetworkEventListener#end");5545 return this;5546 };5547 NebulaService.prototype.setHttpProxy = function (proxy) {5548 var agent = null;5549 if (proxy != null) {5550 NebulaService.verifyProxy(proxy);5551 agent = exports._node_require('tunnel-fork').httpOverHttp({ proxy: proxy });5552 }5553 HttpRequest.setProxy(proxy);5554 HttpRequest.setHttpAgent(agent);5555 };5556 NebulaService.prototype.setHttpsProxy = function (proxy, options) {5557 var agent = null;5558 if (proxy != null) {5559 if (options == null) {5560 options = {};5561 }5562 options.proxy = proxy;5563 NebulaService.verifyProxy(proxy);5564 agent = exports._node_require('tunnel-fork').httpsOverHttp(options);5565 agent.defaultPort = 443;5566 }5567 HttpRequest.setProxy(proxy);5568 HttpRequest.setHttpsAgent(agent, options);5569 };5570 NebulaService.verifyProxy = function (proxy) {5571 if (typeof proxy !== 'object') {5572 throw new Error("Bad proxy: not object");5573 }5574 if (proxy.host == null || typeof proxy.host !== "string") {5575 throw new Error("Bad proxy: host");5576 }5577 if (proxy.port == null || typeof proxy.port !== "number") {5578 throw new Error("Bad proxy: port");5579 }5580 };5581 return NebulaService;5582}());5583exports.NebulaService = NebulaService;5584exports.initHttpXhr();5585exports.initHttpNode();5586exports.Nebula = new NebulaService();...

Full Screen

Full Screen

NodeDefinition.js

Source:NodeDefinition.js Github

copy

Full Screen

1// Copyright 2012 The Obvious Corporation.2/**3 * @fileoverview Contains the class definition for NodeDefinition which4 * represents a node that has been added to a Graph instance and any5 * dependencies it might have.6 * @author <a href="http://github.com/azulus">Jeremy Stanley</a>7 * @version 1.0.08 */9var util = require('util')10var utils = require('./utils')11var clone = utils.clone12/**13 * A node to be added to a graph which defines a handler for a given14 * unit of work which takes in specific inputs15 *16 * @param {./Graph} graph the graph to add the node to17 * @param {string} name the name of the node to be added18 * @constructor19 */20function NodeDefinition(graph, name) {21 this._description = null22 this._graph = graph23 this._name = name24 this._scope = 'default'25 this._inputArgs = []26 /** @private {Array.<utils.NodeInfo>} */27 this._args = []28 /** @private {Array.<{field: utils.NodeInfo, provides: Array.<Object|string>,29 condition: (NodeCondition|undefined)}>} */30 this._builds = []31 this._modifiers = []32 this._cacheDisabled = false33 this._fn = null34 this._hasGettersEnabled = false35 /** @private {boolean} */36 this._lazyDependency = false37 /** @private {?string} */38 this._lazyContextName = null39 /** @private {Function} */40 this._errorFn = null41 /** @private {boolean} */42 this._singletonScoped = false43}44/**45 * A condition that a built node depends on.46 * @constructor47 */48function NodeCondition(field, value) {49 /** @type {utils.NodeInfo} */50 this.field = field51 /** @type {Array.<Object|string>} */52 this.provides = []53 /**54 * The truthiness value that this will compare against.55 * @type {boolean}56 */57 this.value = value58}59/**60 * Return whether this node requires getter wrapper objects for its inputs61 *62 * @return {boolean}63 */64NodeDefinition.prototype.hasGettersEnabled = function () {65 return this._hasGettersEnabled66}67/**68 * Specify that this node requires getter wrapper objects for its inputs69 *70 * @return {NodeDefinition} the current instance71 */72NodeDefinition.prototype.enableGetters = function () {73 this._hasGettersEnabled = true74 return this75}76/**77 * Retrieve the graph for this node78 *79 * @return {./Graph}80 */81NodeDefinition.prototype.getGraph = function () {82 return this._graph83}84/**85 * Retrieve an array of arguments for this node's function handler, including86 * both input args and built nodes.87 *88 * @return {Array.<utils.NodeInfo>} args89 */90NodeDefinition.prototype.getArgs = function () {91 return this._args92}93/**94 * @return {boolean} Whether this node has exactly one possible output per run(),95 * because it has no arguments and is graph-scoped.96 */97NodeDefinition.prototype.isSingleResult = function () {98 return !this._inputArgs.length && !this.isCacheDisabled()99}100/**101 * Retrieve an array of all nodes to build for this node102 *103 * @return {Array.<Object|string>} builds104 */105NodeDefinition.prototype.getBuilds = function () {106 return this._builds107}108/**109 * Update the name of this node110 *111 * @param {string} name112 */113NodeDefinition.prototype.setName = function (name) {114 this._name = name115}116/**117 * Retrieve the name for this node118 *119 * @return {string}120 */121NodeDefinition.prototype.getName = function () {122 return this._name123}124/**125 * Update the call scope of this node126 *127 * @param {string} scope128 */129NodeDefinition.prototype.setScope = function (scope) {130 this._scope = scope131}132/**133 * Retrieve the call scope for this node134 *135 * @return {string}136 */137NodeDefinition.prototype.getScope = function () {138 return this._scope139}140/**141 * Create a copy of this node and attach it to a specified graph142 *143 * @param {./Graph} graph the graph to add the new node to144 * @return {NodeDefinition} the cloned node145 */146NodeDefinition.prototype.clone = function (graph) {147 var def = new NodeDefinition(graph, this._name)148 def._description = this._description149 def._name = this._name150 def._scope = this._scope151 def._inputArgs = clone(this._inputArgs)152 def._args = clone(this._args)153 def._builds = clone(this._builds)154 def._modifiers = clone(this._modifiers)155 def._fn = this._fn156 def._hasGettersEnabled = this._hasGettersEnabled157 def._cacheDisabled = clone(this._cacheDisabled)158 def._lazyDependency = this._lazyDependency159 def._lazyContextName = this._lazyContextName160 def._errorFn = this._errorFn161 def._singletonScoped = this._singletonScoped162 return def163}164/**165 * Specify that this node and all of this dependencies should be cached per graph.166 *167 * @return {NodeDefinition} returns the current NodeDefinition instance168 */169NodeDefinition.prototype.cacheSingleton = function () {170 this._singletonScoped = true171 // rebuild the callback function172 if (this._fn) {173 this.fn(this._fn)174 }175 return this176}177/**178 * @return {boolean} Whether this is a singleton scoped node.179 */180NodeDefinition.prototype.isSingletonScoped = function () {181 return this._singletonScoped182}183/**184 * Specify that this node should never be cached in a builder context185 *186 * @return {NodeDefinition} returns the current NodeDefinition instance187 */188NodeDefinition.prototype.disableNodeCache = function () {189 this._cacheDisabled = true190 return this191}192/**193 * Check whether the cache is disabled for this node194 *195 * @return {boolean}196 */197NodeDefinition.prototype.isCacheDisabled = function () {198 return this._cacheDisabled199}200/**201 * Set the description for this node202 *203 * @param {string} description204 * @return {NodeDefinition} returns the current NodeDefinition instance205 */206NodeDefinition.prototype.description = function (description) {207 this._description = description208 return this209}210/**211 * Get the description for this node212 *213 * @return {?string} returns the description for this node214 */215NodeDefinition.prototype.getDescription = function () {216 return this._description217}218/**219 * Get the handler function for this node220 *221 * @return {Function}222 */223NodeDefinition.prototype.getFunction = function () {224 return this._fn225}226/**227 * Get the error handler function for this node228 *229 * @return {Function}230 */231NodeDefinition.prototype.getErrorFunction = function () {232 return this._errorFn233}234/**235 * Define any inputs into this node (may be either explicit inputs with236 * no existing node defined *or* nodes with 0 dependencies)237 *238 * @param {string} var_args a variable number of arguments, each of which239 * is a string representing a node name which represents a node with 0240 * arguments or the name of a value that should be passed in by the caller241 * @return {NodeDefinition} returns the current NodeDefinition instance242 */243NodeDefinition.prototype.args = function (var_args) {244 var arr = []245 arr.push.apply(arr, arguments)246 return this.argList(arr)247}248/**249 * Define any inputs into this node (may be either explicit inputs with250 * no existing node defined *or* nodes with 0 dependencies)251 *252 * @param {Array.<string>} argList253 * @return {NodeDefinition} returns the current NodeDefinition instance254 */255NodeDefinition.prototype.argList = function (argList) {256 if (!Array.isArray(argList)) throw new Error('Expected an array, got ' + argList)257 for (var i = 0; i < argList.length; i += 1) {258 var argInfo = utils.getNodeInfoFromBuild(this._graph, argList[i])259 this._args.push(argInfo)260 this._inputArgs.push(argInfo.rootName)261 }262 if (this._argumentMirrors) {263 for (i = 0; i < this._argumentMirrors.length; i++) {264 this._argumentMirrors[i].argList(argList)265 }266 }267 return this268}269/**270 * Start configuring a node for use in .modifiers()271 *272 * @param {string|Object} field273 * @return {NodeDefinition} the current node274 */275NodeDefinition.prototype.configure = function (field) {276 if (typeof field == 'string') {277 return this.builds(utils.OUTPUT_PREFIX_PARTIAL + field)278 } else if (field && (typeof field == 'object')) {279 var keys = Object.keys(field)280 if (keys.length == 1) {281 var newField = {}282 newField[utils.OUTPUT_PREFIX_PARTIAL + keys[0]] = field[keys[0]]283 return this.builds(newField)284 }285 }286 throw new Error('Invalid configure() parameter ' + util.inspect(field))287}288/**289 * Specify that this node should build another node as an input290 *291 * @param {string|Object} field the node to build292 * @return {NodeDefinition} the current node293 */294NodeDefinition.prototype.builds = function (field) {295 var nodeInfo = utils.getNodeInfoFromBuild(this._graph, field)296 if (this._getArgIdx(nodeInfo) !== -1) {297 throw new Error('You may only use the same alias in a .builds() once in a subgraph')298 }299 var nodeName = nodeInfo.fullName300 if (typeof nodeName == 'string' && utils.isLazyArgRef(nodeName)) {301 if (!this._lazyContextName) throw new Error('You may not use lazyargs with non-lazy nodes.')302 var newArgRef = this._lazyContextName + '.args.' + utils.getLazyArgRef(nodeName)303 var newNodeInfo = {}304 newNodeInfo[nodeInfo.getAlias()] = newArgRef305 return this.builds(newNodeInfo).using('args.*')306 }307 this._builds.push({308 field: nodeInfo,309 provides: []310 })311 this._args.push(nodeInfo)312 return this313}314function buildObjectFromKeysAndArguments(keys, var_args) {315 var obj = {}316 for (var i = 0; i < keys.length; i++) {317 obj[keys[i]] = arguments[i + 1]318 }319 return obj320}321/**322 * Specify that a node to be built should take in a list of inputs323 *324 * @param {...(Object|string)} var_args a variable number of arguments325 * which are either node names or a map of arg name to node name326 * @return {NodeDefinition} the current node327 */328NodeDefinition.prototype.using = function (var_args) {329 var args = Array.prototype.slice.call(arguments, 0)330 var nodeIdx = this._builds.length - 1331 for (var i = 0; i < args.length; i++) {332 var arg = args[i]333 var nodeInfo = utils.getNodeInfoFromInput(this._graph, arg)334 var nodeNames = nodeInfo.nodeName335 var wrapperArgs, wrapperUsing, argName, mappingObj, wrapperNodeName, newBuilds, j336 if (Array.isArray(nodeNames)) {337 if (!nodeNames.length) {338 // node has an empty array for inputs339 arg[nodeInfo.arg] = this._graph.literal(/** @type {Array} */ (nodeNames))340 } else {341 // the node has an array for inputs, build that as a separate node342 // and pass it as an input343 wrapperArgs = []344 wrapperUsing = []345 for (j = 0; j < nodeNames.length; j++) {346 argName = 'arg' + (j + 1)347 mappingObj = {}348 mappingObj[argName] = nodeNames[j]349 wrapperArgs.push(argName)350 wrapperUsing.push(mappingObj)351 }352 wrapperNodeName = this._graph.addAnonymous(nodeInfo.arg, this._graph.argsToArray, wrapperArgs)353 newBuilds = this.builds(utils.OUTPUT_PREFIX_IMPORTANT + wrapperNodeName)354 newBuilds.using.apply(newBuilds, wrapperUsing)355 arg[nodeInfo.arg] = wrapperNodeName356 }357 } else if (typeof nodeNames == 'object' && nodeNames != null) {358 // the node has an object for inputs, build that as a separate node359 // and pass it as an input360 wrapperArgs = []361 wrapperUsing = []362 var keys = Object.keys(nodeNames)363 for (j = 0; j < keys.length; j++) {364 argName = 'arg' + (j + 1)365 mappingObj = {}366 mappingObj[argName] = nodeNames[keys[j]]367 wrapperArgs.push(argName)368 wrapperUsing.push(mappingObj)369 }370 wrapperNodeName = this._graph.addAnonymous(nodeInfo.arg, buildObjectFromKeysAndArguments.bind(null, keys), wrapperArgs)371 newBuilds = this.builds(utils.OUTPUT_PREFIX_IMPORTANT + wrapperNodeName)372 newBuilds.using.apply(newBuilds, wrapperUsing)373 arg[nodeInfo.arg] = wrapperNodeName374 } else if (typeof nodeNames == 'string' && utils.isArgRef(nodeNames)) {375 // check that an existing arg is referenced376 var inputArg = utils.getArgRef(nodeNames).split('.')[0]377 if (!utils.isWildcardArgRef(nodeNames) && this._inputArgs.indexOf(inputArg) === -1) {378 throw new Error(nodeNames + ' is referenced but is not provided as an input')379 }380 }381 // If this .using() belongs to a conditional node, append to that,382 // otherwise append to the previous .builds() node.383 var target = this._builds[nodeIdx].condition || this._builds[nodeIdx]384 target.provides.push(arg)385 }386 return this387}388/**389 * Specify that this node should return a specific sub-node if this390 * is a subgraph391 *392 * @param {string} nodeName the name of the node to return393 * @return {NodeDefinition} the current instance394 */395NodeDefinition.prototype.returns = function (nodeName) {396 if (this._fn !== this._graph.subgraph) throw new Error('Only able to call .returns() on a subgraph')397 var wrapperNode = this._graph.addAnonymous(utils.NODE_PREFIX_AGGREGATOR_RETURN_VAL, this._graph.subgraph, ['nodeName'])398 return this.builds(wrapperNode)399 .using({nodeName: nodeName})400}401NodeDefinition.prototype.modifiers = function (var_args) {402 for (var i = 0; i < arguments.length; i += 1) {403 if (this._builds.length) {404 // create a new last field which pulls from the previous last405 var previousField = this._builds[this._builds.length - 1]406 // find a safe name to move this node to407 var nodeInfo = previousField.field408 var nodeName409 var j = 0410 do {411 j++412 nodeName = nodeInfo.aliasRealName + '-modifier' + j413 } while (this._getNode(nodeName))414 // find the existing arg info415 var argIdx = this._getArgIdx(nodeInfo)416 // rename the node417 var newNodeInfo = {}418 newNodeInfo[utils.OUTPUT_PREFIX_IMPORTANT + nodeName] = nodeInfo.fullName419 this._args[argIdx] = previousField.field = utils.getNodeInfoFromBuild(this._graph, newNodeInfo)420 // retrieve the modifier info421 var modifierNodeInfo = utils.getNodeInfoFromModifier(this._graph, arguments[i], nodeInfo.getAlias())422 // create a new field or clone the already configured field423 var fieldData = {}424 fieldData[nodeInfo.getAlias()] = modifierNodeInfo.nodeName425 var fieldDataInfo = utils.getNodeInfoFromBuild(this._graph, fieldData)426 var modifierNode = this._getNode(/** @type {string} */ (modifierNodeInfo.nodeName))427 if (modifierNode) {428 // clone the existing node429 this._builds.push(clone(modifierNode))430 this._builds[this._builds.length - 1].field = fieldDataInfo431 } else {432 // create a new node433 this.builds(fieldData)434 this._args.pop()435 }436 this._args.push(fieldDataInfo)437 // map the old node to the new node438 var usingData = {}439 usingData[modifierNodeInfo.arg] = nodeName440 this.using(usingData)441 } else {442 throw new Error('The ability to add modifiers directly to a graph node has been deprecated')443 }444 }445 return this446}447/**448 * Add a conditional node for the previous input node449 *450 * @param {Object|string} field451 * @param {boolean} condition The truthiness value to compare the452 * conditional against.453 * @return {NodeDefinition} This454 */455NodeDefinition.prototype._addCondition = function(field, condition) {456 var nodeIdx = this._builds.length - 1457 var nodeInfo = utils.getNodeInfoFromInput(this._graph, field)458 var nodeName = nodeInfo.nodeName459 // TODO(kyle): Same logic as in .using(), factor out460 if (typeof nodeName == 'string' && utils.isArgRef(nodeName)) {461 // check that an existing arg is referenced462 var inputArg = utils.getArgRef(nodeName).split('.')[0]463 if (!utils.isWildcardArgRef(nodeName) && this._inputArgs.indexOf(inputArg) === -1) {464 throw new Error(nodeName + ' is referenced but is not provided as an input')465 }466 }467 this._builds[nodeIdx].condition = new NodeCondition(nodeInfo, condition)468 return this469}470NodeDefinition.prototype.when = function(field) {471 return this._addCondition(field, true)472}473NodeDefinition.prototype.unless = function(field) {474 return this._addCondition(field, false)475}476/**477 * Set the handler function for this node478 * @param {!Function} fn479 */480NodeDefinition.prototype.fn = function (fn) {481 if (this._singletonScoped) {482 var called = false483 var singletonScopedResults = this._graph.singletonScopedResultsInternal484 var name = this._name485 this._fn = function () {486 if (!called) {487 singletonScopedResults[name] = fn.apply(null, arguments)488 called = true489 }490 return singletonScopedResults[name]491 }492 } else {493 this._fn = fn494 }495 return this496}497/**498 * Set a handler function that invokes the given constructor.499 * @param {function(new:Object, ...)} Ctor500 */501NodeDefinition.prototype.ctor = function (Ctor) {502 this._setArgsFromFunction(Ctor)503 return this.fn(function () {504 return utils.applyNew(Ctor, arguments)505 })506}507/**508 * Set the handler function for this node, but inject based on parameter name instead509 * of based on order.510 *511 * If the parameters can't be found, this will throw an error.512 *513 * @param {!Function} fn514 */515NodeDefinition.prototype.inject = function (fn) {516 this._setArgsFromFunction(fn)517 return this.fn(fn)518}519/**520 * Re-arrange the node params from the function definition521 *522 * If the parameters can't be found, this will throw an error.523 *524 * @param {!Function} fn525 */526NodeDefinition.prototype._setArgsFromFunction = function (fn) {527 var paramNames = utils.parseFnParams(fn)528 var shortArgsNames = this._args.map(function (arg) {529 return utils.getNodeInjectorName(arg.aliasRealName)530 })531 // Sort the arguments so that the parameters get injected in the532 // right order.533 var newArgs = []534 var i535 for (i = 0; i < paramNames.length; i++) {536 var idx = shortArgsNames.indexOf(paramNames[i])537 if (idx === -1) {538 throw new Error('No injector found for parameter: ' + paramNames[i])539 }540 newArgs.push(this._args[idx])541 this._args.splice(idx, 1)542 shortArgsNames.splice(idx, 1)543 }544 // Push any args that are not included.545 newArgs.push.apply(newArgs, this._args)546 this._args = newArgs547}548/**549 * Set an error handler function for this node.550 * This function cannot do anything to stop the propagation of551 * the exception. It's mostly needed to handle thunk errors appropriately.552 * @param {function(Error, Array)} fn A function that takes two553 * arguments: the error being propagated, and the Array of arguments554 * passed to the normal handler function.555 */556NodeDefinition.prototype.errorFn = function (fn) {557 this._errorFn = fn558 return this559}560/**561 * Proxy function which can be used to chain newBuilder() requests back562 * to the graph563 */564NodeDefinition.prototype.newBuilder = function () {565 return this._graph.newBuilder.apply(this._graph, arguments)566}567/**568 * Proxy function which can be used to chain add() requests back569 * to the graph570 */571NodeDefinition.prototype.add = function () {572 return this._graph.add.apply(this._graph, arguments)573}574/**575 * In thunks, we have a series of nodes that all share the same arguments.576 *577 * Any arguments added to this node need to be mirrored on the mirrorNode.578 *579 * @param {NodeDefinition} mirrorNode580 */581NodeDefinition.prototype.addArgumentMirror = function (mirrorNode) {582 if (!this._argumentMirrors) {583 this._argumentMirrors = []584 }585 this._argumentMirrors.push(mirrorNode)586}587/**588 * If we're building a thunk, we create a lazy dependency from589 * the thunk to its synchronous subtree.590 *591 * This tells the Builder that it's OK to send the thunk function to nodes592 * that require it, event though its dependencies haven't resolved yet.593 *594 * This function should only be called from Graph.js, which sets up the necessary595 * dependencies so that calling the thunk function forces the subtree to resolve.596 *597 * @param {boolean} val598 */599NodeDefinition.prototype.setLazyDependencyInternal = function (val) {600 this._lazyDependency = val601 return this602}603/**604 * If we're building a thunk, this represents the source of deferreds605 * and arguments passed to the function.606 *607 * This function should only be called from Graph.js, which sets up the necessary608 * dependencies609 *610 * @param {NodeDefinition} lazyContext611 */612NodeDefinition.prototype.setLazyContextSourceInternal = function (lazyContext) {613 this._lazyContextName = lazyContext.getName()614 return this615}616/**617 * @return {boolean} Whether this is a lazy dependency.618 */619NodeDefinition.prototype.isLazyDependency = function () {620 return this._lazyDependency621}622/**623 * Get build info for a node that will be built by this node definition by its alias624 *625 * @param {string} alias the alias for the node626 * @return {Object} returns null if the build doesn't exist627 */628NodeDefinition.prototype._getNode = function (alias) {629 for (var i = 0; i < this._builds.length; i++) {630 if (this._builds[i].field.aliasRealName == alias) return this._builds[i]631 }632 return null633}634/**635 * Get the index for a node that will be built by this node definition636 *637 * @param {utils.NodeInfo} nodeInfo The node638 * @return {number} returns -1 if the alias doesn't exist639 */640NodeDefinition.prototype._getArgIdx = function (nodeInfo) {641 for (var i = 0; i < this._args.length; i++) {642 if (nodeInfo.isSameAlias(this._args[i])) return i643 }644 return -1645}...

Full Screen

Full Screen

Worker.mjs

Source:Worker.mjs Github

copy

Full Screen

1/**2 * Main script to use service worker in TeqFW applications.3 *4 * This is standard ES6 module w/o TeqFW DI support (service workers don't allow dynamic `import()`).5 *6 * I suppose that SW files should be cached by browser itself, so these files are not under `./Front/` folder.7 * @namespace TeqFw_Web_Sw_Worker8 */9// MODULE'S IMPORT10import Config from './Config.mjs';11import MSG from '../Front/Mod/Sw/Enum/Message.mjs';12// MODULE'S VARS13const NS = 'TeqFw_Web_Sw_Worker';14/**15 * Service Worker events.16 */17const EVT = {18 ACTIVATE: 'activate',19 CONTENT_DELETE: 'contentdelete',20 FETCH: 'fetch',21 INSTALL: 'install',22 LANGUAGE_CHANGE: 'languagechange',23 MESSAGE: 'message',24 NOTIFICATION_CLICK: 'notificationclick',25 NOTIFICATION_CLOSE: 'notificationclose',26 PERIODIC_SYNC: 'periodicsync',27 PUSH: 'push',28 PUSH_SUBSCRIPTION_CHANGE: 'pushsubscriptionchange',29 SYNC: 'sync',30};31const API_STATIC_FILES = '/api/@teqfw/web/load/files_to_cache'; // get list of files to cache on SW installation32const CACHE_STATIC = 'static-cache-v1'; // store name to cache static resources33const CFG_CACHE_DISABLED = 'cache_disabled';34/**35 * Configuration object for SW. It is stored in IDB and is reloaded on service worker start.36 * @type {TeqFw_Web_Sw_Config}37 */38const _config = new Config();39/**40 * Entry point for the frontend application ('pub', 'admin').41 * @type {string}42 */43let _door;44/** @type {boolean} */45let _cacheDisabled = true; // disable by default TODO: invert logic here and in IndexedDB46/**47 * Log function to trace functionality of this module.48 * @type {function}49 */50let _log;51// MODULE'S FUNCS52/**53 * Send message to `index.html` to start bootstrap.54 */55function onActivate() {56 _log(`[TeqFw_Web_Sw_Worker]: on activate event is here...`);57 self.clients.claim();58}59function onFetch(event) {60 // FUNCS61 /**62 * Analyze route's URL and return 'true' if request should not be cached.63 * @param {Request} req64 * @returns {boolean}65 */66 function detectBypass(req) {67 // see TeqFw_Web_Shared_Defaults.SPACE_...68 const API = /(.*)(\/api\/)(.*)/;69 const CFG = /(.*)(\/cfg\/)(.*)/;70 const EBF = /(.*)(\/ebf\/)(.*)/; // events 'back-to-front'71 const EFB = /(.*)(\/efb\/)(.*)/; // events 'front-to-back'72 const res = !!(73 req.method === 'POST' ||74 req.url.match(API) ||75 req.url.match(CFG) ||76 req.url.match(EFB) ||77 req.url.match(EBF)78 );79 return res;80 }81 async function getFromCacheOrFetchAndCache(event) {82 try {83 const cache = await self.caches.open(CACHE_STATIC);84 const cachedResponse = await cache.match(event.request);85 if (cachedResponse) return cachedResponse;86 // wait until resource will be fetched from server and stored in cache87 const resp = await fetch(event.request);88 await cache.put(event.request, resp.clone());89 return resp;90 } catch (e) {91 _log(`[TeqFw_Web_Sw_Worker] error: ${JSON.stringify(e)}`);92 }93 }94 // MAIN95 const bypass = detectBypass(event.request);96 if (bypass === false)97 if (_cacheDisabled !== true)98 event.respondWith(getFromCacheOrFetchAndCache(event));99}100function onInstall(event) {101 // FUNCS102 /**103 * Load list of static file's URLs to cache locally.104 * @return {Promise<string[]>}105 */106 async function loadFilesToCache() {107 // Get list of static files from the server108 const data = {door: _door}; // see TeqFw_Web_Shared_WAPI_Load_FilesToCache.Request109 const req = new Request(API_STATIC_FILES, {110 method: 'POST',111 headers: {112 'Content-Type': 'application/json'113 },114 body: JSON.stringify({data})115 });116 const resp = await self.fetch(req);117 const json = await resp.json();118 const res = json?.data?.items ?? [];119 _log(`List of static files to cache is loaded (total items: ${res.length}).`);120 return res;121 }122 /**123 * Load urls from server and cache content locally. All URLs are separated to batches up to 10 URLs each.124 * @param {string[]} urls125 * @return {Promise<void>}126 */127 async function cacheStatics(urls) {128 try {129 if (Array.isArray(urls)) {130 // ... and load static files to the local cache131 const cacheStat = await caches.open(CACHE_STATIC);132 // METHOD 1133 // await cacheStat.addAll(files);134 // METHOD 2135 let total = 0;136 const SIZE = 10;137 while (total <= urls.length) {138 const slice = urls.slice(total, total + SIZE);139 await Promise.all(140 slice.map(function (url) {141 return cacheStat.add(url).catch(function (reason) {142 _log(`SW install error: '${url}' failed, ${String(reason)}`);143 });144 })145 );146 total += SIZE;147 const cached = total < urls.length ? total : urls.length;148 _log(`Total '${cached}' URLs are cached.`);149 }150 }151 _log(`Static files are loaded and cached by Service Worker.`);152 } catch (e) {153 _log(`SW iInstallation error: ${JSON.stringify(e)}`);154 }155 }156 // MAIN157 event.waitUntil(158 loadFilesToCache()159 .then(cacheStatics)160 .catch((e) => {161 _log(`[TeqFw_Web_Sw_Worker] error: ${e.message}`);162 })163 );164}165/**166 * @param {MessageEvent} event167 */168async function onMessage(event) {169 // FUNCS170 async function cacheClean() {171 try {172 const cache = await self.caches.open(CACHE_STATIC);173 const keys = await cache.keys();174 keys.forEach((one) => cache.delete(one));175 } catch (e) {176 _log(`[TeqFw_Web_Sw_Worker] error: ${JSON.stringify(e)}`);177 }178 }179 // MAIN180 /** @type {TeqFw_Web_Front_Mod_Sw_Control.Message} */181 const data = event.data;182 const type = data.type;183 const payload = data.payload;184 let out;185 // perform requested operation186 if (type === MSG.CACHE_STATUS_GET) {187 _cacheDisabled = await _config.get(CFG_CACHE_DISABLED);188 out = !_cacheDisabled; // inversion for cache status189 } else if (type === MSG.CACHE_STATUS_SET) {190 _cacheDisabled = !payload; // inversion for cache status191 await _config.set(CFG_CACHE_DISABLED, _cacheDisabled);192 } else if (type === MSG.CACHE_CLEAN) {193 await cacheClean();194 }195 // ... then return result196 const res = Object.assign({}, data);197 res.payload = out;198 // noinspection JSCheckFunctionSignatures199 event.source.postMessage(res);200}201/**202 * Create log-function to trace service worker functionality.203 *204 * @param {string} uuid frontend identifier for service worker instance.205 * @return {(function(string, Object): void)}206 */207function createLogger(uuid) {208 // FUNCS209 /**210 * Log function to send log info to the server.211 * @param {string} msg212 * @param {Object} [meta]213 */214 return function log(msg, meta = {}) {215 if (navigator.onLine) {216 /** @type {TeqFw_Core_Shared_Dto_Log.Dto} */217 const item = {218 date: new Date(),219 isError: false,220 message: msg,221 meta: {},222 source: NS,223 };224 if (typeof meta === 'object') Object.assign(item.meta, meta);225 item.meta.frontUuid = uuid;226 /** @type {TeqFw_Web_Api_Shared_WAPI_Front_Log_Collect.Request} */227 const req = {item};228 fetch('./api/@teqfw/web/front/log/collect', {229 method: 'POST',230 headers: {231 'Content-Type': 'application/json'232 },233 body: JSON.stringify({data: req}),234 });235 }236 }237}238/**239 * Setup function to populate Service Worker global scope.240 * @param {WorkerGlobalScope} scope241 * @param {string} [door]242 * @param {function(string):function} logFactory243 */244function setup({scope, door, logFactory}) {245 _log = logFactory(NS); // create log function for this es6-module246 _door = door;247 _config.get(CFG_CACHE_DISABLED).then((val) => _cacheDisabled = val);248 scope.addEventListener(EVT.ACTIVATE, onActivate);249 scope.addEventListener(EVT.FETCH, onFetch);250 scope.addEventListener(EVT.INSTALL, onInstall);251 scope.addEventListener(EVT.MESSAGE, onMessage);252 const entryPoint = _door ? 'root entry point' : `'${_door}' entry point`;253 _log(`Event listeners are registered for ${entryPoint}.`);254}255// MODULE'S MAIN256// Object.defineProperty(setup, 'namespace', {value: NS});257export {258 createLogger,259 setup...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 await page._client.send('Network.setCacheDisabled', {cacheDisabled: true});6 await page.screenshot({path: 'example.png'});7 await browser.close();8})();9const puppeteer = require('puppeteer');10(async () => {11 const browser = await puppeteer.launch();12 const page = await browser.newPage();13 await page._client.send('Network.setCacheDisabled', {cacheDisabled: true});14 await page.screenshot({path: 'example.png'});15 await browser.close();16})();17const puppeteer = require('puppeteer');18(async () => {19 const browser = await puppeteer.launch();20 const page = await browser.newPage();21 await page._client.send('Network.setCacheDisabled', {cacheDisabled: true});22 await page.screenshot({path: 'example.png'});23 await browser.close();24})();25const puppeteer = require('puppeteer');26(async () => {27 const browser = await puppeteer.launch();28 const page = await browser.newPage();29 await page._client.send('Network.setCacheDisabled', {cacheDisabled: true});30 await page.screenshot({path: 'example.png'});31 await browser.close();32})();33const puppeteer = require('puppeteer');34(async () => {35 const browser = await puppeteer.launch();36 const page = await browser.newPage();37 await page._client.send('Network.setCacheDisabled', {cacheDisabled: true});38 await page.screenshot({path: 'example.png'});39 await browser.close();40})();41const puppeteer = require('puppeteer

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 await page._client.send('Network.setCacheDisabled', {cacheDisabled: true});6 await browser.close();7})();8const puppeteer = require('puppeteer');9(async () => {10 const browser = await puppeteer.launch();11 const page = await browser.newPage();12 await page.setRequestInterception(true);13 page.on('request', (request) => {14 if (request.resourceType() === 'image')15 request.abort();16 request.continue();17 });18 await browser.close();19})();20const puppeteer = require('puppeteer');21(async () => {22 const browser = await puppeteer.launch();23 const page = await browser.newPage();24 await page.setExtraHTTPHeaders({25 'Accept-Language': 'en-GB,en-US;q=0.9,en;q=0.8'26 });27 await browser.close();28})();29const puppeteer = require('puppeteer');30(async () => {31 const browser = await puppeteer.launch();32 const page = await browser.newPage();33 await page.setUserAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36');34 await browser.close();35})();36const puppeteer = require('puppeteer');37(async () => {38 const browser = await puppeteer.launch();39 const page = await browser.newPage();40 await page.emulate({41 viewport: {42 },43 });44 await browser.close();45})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 await page._client.send('Network.setCacheDisabled', {cacheDisabled: true});6 await browser.close();7})();8const puppeteer = require('puppeteer');9(async () => {10 const browser = await puppeteer.launch();11 const page = await browser.newPage();12 await page._client.send('Network.setCacheDisabled', {cacheDisabled: true});13 await browser.close();14})();15const puppeteer = require('puppeteer');16(async () => {17 const browser = await puppeteer.launch();18 const page = await browser.newPage();19 await page._client.send('Network.setCacheDisabled', {cacheDisabled: true});20 await browser.close();21})();22const puppeteer = require('puppeteer');23(async () => {24 const browser = await puppeteer.launch();25 const page = await browser.newPage();26 await page._client.send('Network.setCacheDisabled', {cacheDisabled: true});27 await browser.close();28})();29const puppeteer = require('puppeteer');30(async () => {31 const browser = await puppeteer.launch();32 const page = await browser.newPage();33 await page._client.send('Network.setCacheDisabled', {cacheDisabled: true});34 await browser.close();35})();36const puppeteer = require('puppeteer');37(async () => {38 const browser = await puppeteer.launch();39 const page = await browser.newPage();40 await page._client.send('Network.setCacheDisabled', {cacheDisabled: true});41 await browser.close();42})();

Full Screen

Using AI Code Generation

copy

Full Screen

1(async () => {2 const browser = await puppeteer.launch();3 const page = await browser.newPage();4 await page._client.send('Network.setCacheDisabled', { cacheDisabled: true });5 await browser.close();6})();7(async () => {8 const browser = await puppeteer.launch();9 const page = await browser.newPage();10 await page._client.send('Network.setCacheDisabled', { cacheDisabled: true });11 await browser.close();12})();13(async () => {14 const browser = await puppeteer.launch();15 const page = await browser.newPage();16 await page._client.send('Network.setCacheDisabled', { cacheDisabled: true });17 await browser.close();18})();19(async () => {20 const browser = await puppeteer.launch();21 const page = await browser.newPage();22 await page._client.send('Network.setCacheDisabled', { cacheDisabled: true });23 await browser.close();24})();25(async () => {26 const browser = await puppeteer.launch();27 const page = await browser.newPage();28 await page._client.send('Network.setCacheDisabled', { cacheDisabled: true });29 await browser.close();30})();31(async () => {32 const browser = await puppeteer.launch();33 const page = await browser.newPage();34 await page._client.send('Network.setCacheDisabled', { cacheDisabled: true });35 await browser.close();36})();37(async () => {38 const browser = await puppeteer.launch();39 const page = await browser.newPage();40 await page._client.send('Network.setCacheDisabled', { cacheDisabled: true });

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({ headless: false });4 const page = await browser.newPage();5 await page._client.send('Network.setCacheDisabled', {cacheDisabled: true});6 await page.screenshot({path: 'google.png'});7 await browser.close();8})();9const puppeteer = require('puppeteer');10(async () => {11 const browser = await puppeteer.launch({ headless: false });12 const page = await browser.newPage();13 await page._client.send('Network.setCacheDisabled', {cacheDisabled: false});14 await page.screenshot({path: 'google.png'});15 await browser.close();16})();17const puppeteer = require('puppeteer');18(async () => {19 const browser = await puppeteer.launch({ headless: false });20 const page = await browser.newPage();21 await page._client.send('Network.setCacheDisabled', {cacheDisabled: true});22 await page.screenshot({path: 'google.png'});23 await browser.close();24})();25const puppeteer = require('puppeteer');26(async () => {27 const browser = await puppeteer.launch({ headless: false });28 const page = await browser.newPage();29 await page._client.send('Network.setCacheDisabled', {cacheDisabled: true});30 await page.screenshot({path: 'google.png'});31 await browser.close();32})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({headless: false});4 const page = await browser.newPage();5 await page._client.send('Network.clearBrowserCache');6 await page.reload();7 await browser.close();8})();9const puppeteer = require('puppeteer');10(async () => {11 const browser = await puppeteer.launch({headless: false});12 const page = await browser.newPage();13 await page.setCacheEnabled(false);14 await page.reload();15 await browser.close();16})();17const puppeteer = require('puppeteer');18(async () => {19 const browser = await puppeteer.launch({headless: false});20 const page = await browser.newPage();21 await page.setCacheEnabled(true);22 await page.reload();23 await browser.close();24})();25const puppeteer = require('puppeteer');26(async () => {27 const browser = await puppeteer.launch({headless: false});28 const page = await browser.newPage();29 await page._client.send('Network.clearBrowserCache');30 await page.reload();31 await browser.close();32})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2const browser = await puppeteer.launch();3const page = await browser.newPage();4await page._client.send('Network.enable');5await page._client.send('Network.setCacheDisabled', {cacheDisabled: true});6await page.screenshot({path: 'screenshot.png'});7await browser.close();8const puppeteer = require('puppeteer');9const browser = await puppeteer.launch();10const page = await browser.newPage();11await page._client.send('Network.enable');12await page._client.send('Network.setCacheDisabled', {cacheDisabled: true});13await page.screenshot({path: 'screenshot.png'});14await browser.close();15const puppeteer = require('puppeteer');16const browser = await puppeteer.launch();17const page = await browser.newPage();18await page._client.send('Network.enable');19await page._client.send('Network.setCacheDisabled', {cacheDisabled: true});20await page.screenshot({path: 'screenshot.png'});21await browser.close();22const puppeteer = require('puppeteer');23const browser = await puppeteer.launch();24const page = await browser.newPage();25await page._client.send('Network.enable');26await page._client.send('Network.setCacheDisabled', {cacheDisabled: true});27await page.screenshot({path: 'screenshot.png'});28await browser.close();29const puppeteer = require('puppeteer');30const browser = await puppeteer.launch();31const page = await browser.newPage();32await page._client.send('Network.enable');33await page._client.send('Network.setCacheDisabled', {cacheDisabled: true});34await page.screenshot({path: 'screenshot.png'});35await browser.close();36const puppeteer = require('puppeteer');

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({4 });5 const page = await browser.newPage();6 await page._client.send('Network.clearBrowserCache');7 await page.screenshot({path: 'google.png'});8 await browser.close();9})();10const puppeteer = require('puppeteer');11(async () => {12 const browser = await puppeteer.launch({13 });14 const page = await browser.newPage();15 await page._client.send('Network.clearBrowserCache');16 await page.screenshot({path: 'google.png'});17 await browser.close();18})();19const puppeteer = require('puppeteer');20(async () => {21 const browser = await puppeteer.launch({22 });23 const page = await browser.newPage();24 await page._client.send('Network.clearBrowserCache');25 await page.screenshot({path: 'google.png'});26 await browser.close();27})();28const puppeteer = require('puppeteer');29(async () => {30 const browser = await puppeteer.launch({31 });32 const page = await browser.newPage();33 await page._client.send('Network.clearBrowserCache');34 await page.screenshot({path: 'google.png'});35 await browser.close();36})();37const puppeteer = require('puppeteer');38(async () => {39 const browser = await puppeteer.launch({40 });41 const page = await browser.newPage();42 await page._client.send('Network.clearBrowserCache');43 await page.screenshot({path: 'google.png'});44 await browser.close();45})();46const puppeteer = require('puppeteer

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({4 });5 const page = await browser.newPage();6 await page._client.send('Network.clearBrowserCache');7 await page._client.send('Network.clearBrowserCookies');8 await page._client.send('Network.setCacheDisabled', { cacheDisabled: true });9 await page.waitFor(5000);10 await browser.close();11})();12const puppeteer = require('puppeteer');13(async () => {14 const browser = await puppeteer.launch({15 });16 const page = await browser.newPage();17 await page._client.send('Network.clearBrowserCache');18 await page._client.send('Network.clearBrowserCookies');19 await page._client.send('Network.setCacheDisabled', { cacheDisabled: true });20 await page.waitFor(5000);21 await page._client.send('Network.clearBrowserCache');22 await page._client.send('Network.clearBrowserCookies');23 await page._client.send('Network.setCacheDisabled', { cacheDisabled: true });24 await page.waitFor(5000);25 await browser.close();26})();

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Puppeteer automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful