Commit f3fc40c4 by 胡建潮

引入androidSDK库

0 parents
Showing with 2414 additions and 0 deletions
declare const jsb: any;
\ No newline at end of file
import { SDKBase, TimeManager } from "simba-sdk";
import { LaunchOptionType } from "simba-sdk/dist/SDKTypes";
import { setNoRewaredAd } from "simba-sdk/dist/SVConfig";
import { SDKConfig } from "simba-sdk/dist/SDKBase";
function compareVersion(v1: string, v2: string) {
let vv1 = v1.split('.');
let vv2 = v2.split('.');
var len = Math.max(vv1.length, vv2.length)
while (vv1.length < len) {
vv1.push('0');
}
while (vv2.length < len) {
vv2.push('0');
}
for (var i = 0; i < len; i++) {
var num1 = parseInt(vv1[i]);
var num2 = parseInt(vv2[i]);
if (num1 > num2) {
return 1;
} else if (num1 < num2) {
return -1;
}
}
return 0;
}
export default class SDKImpl extends SDKBase {
static readonly channel: string = "android";
private _loginResolve: Function
private _loginReject: (reason?: any) => void;
private _showRewardedVideoAdresolve: Function;
getChannel(): string {
return SDKImpl.channel;
}
async init() {
globalThis.SDKImpl = this; //提供给java调用
let androidConfig = SDKConfig.channelConfig.android;
if (androidConfig) {
if (androidConfig.appId) {
this.initCSJADSDK(androidConfig.appId);
}
if (androidConfig.extraParam.appId) {
this.initYLHADSDK(androidConfig.extraParam.appId);
}
setTimeout(() => {
if (androidConfig.rewaredVideoAdId) {
this.loadCSJRewardVideoAd(androidConfig.rewaredVideoAdId);
}
if (androidConfig.bannerAdId) {
this.loadCSJBannerAd(androidConfig.bannerAdId);
}
if (androidConfig.interstitialAdId) {
this.loadCSJInterstitialAd(androidConfig.interstitialAdId);
}
if (androidConfig.extraParam.rewaredVideoAdId) {
this.loadYLHRewardVideoAd(androidConfig.extraParam.rewaredVideoAdId);
}
if (androidConfig.extraParam.bannerAdId) {
this.loadYLHBannerAd(androidConfig.extraParam.bannerAdId);
}
if (androidConfig.extraParam.rewaredVideoAdId) {
this.loadYLHInterstitialAd(androidConfig.extraParam.rewaredVideoAdId);
}
}, 5 * 1000);
} else {
setNoRewaredAd();
}
return super.init().then((value) => {
return value;
});
}
async login(extraParams, timeout = 5000) {
let result = await this._login2();
try {
let resultInfo = JSON.parse(result);
this.loginInfo = {
channelAccessToken: resultInfo.code,
localServerPublicServiceToken: resultInfo.commonToken,
localServerRecordServiceToken: resultInfo.recordToken ? resultInfo.recordToken : resultInfo.commonToken,
localServerRefreshToken: resultInfo.refreshToken,
localServerSubject: resultInfo.subject,
playerId: resultInfo.subject.split("_")[1]
};
await this.downloadRecord();
await this.timeManagerOnLogin();
return Object.assign({}, this.loginInfo);
} catch (error) {
console.error("loginLocalServer", error);
}
}
protected _login2(): Promise<string> {
return new Promise((resolve, reject) => {
this._loginResolve = resolve;
this._loginReject = reject;
jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity", "login", "()V");
});
}
overLogin(str) {
if (str == "fail") {
this._loginReject(str);
} else {
this._loginResolve(str);
}
}
protected _login(): Promise<{ code: string }> {
return new Promise((resolve, reject) => {
let timeout = false;
let timer = setTimeout(() => {
timeout = true;
reject("timeout");
}, 2000);
});
}
exit(): void {
}
initCSJADSDK(appId: string) {
jsb.reflection.callStaticMethod('org/cocos2dx/javascript/AppActivity', 'initCSJADSDK', "(Ljava/lang/String;)V", appId);
}
loadCSJRewardVideoAd(rewardVideoAdId: string) {
jsb.reflection.callStaticMethod('org/cocos2dx/javascript/AppActivity', 'loadCSJRewardVideoAd', "(Ljava/lang/String;)V", rewardVideoAdId);
}
loadCSJBannerAd(bannerAdId: string) {
jsb.reflection.callStaticMethod('org/cocos2dx/javascript/AppActivity', 'loadCSJBannerAd', "(Ljava/lang/String;)V", bannerAdId);
}
loadCSJInterstitialAd(interstitialAdId: string) {
jsb.reflection.callStaticMethod('org/cocos2dx/javascript/AppActivity', 'loadCSJInterstitialAd', "(Ljava/lang/String;)V", interstitialAdId);
}
initYLHADSDK(appId: string) {
jsb.reflection.callStaticMethod('org/cocos2dx/javascript/AppActivity', 'initYLHADSDK', "(Ljava/lang/String;)V", appId);
}
loadYLHRewardVideoAd(rewardVideoAdId: string) {
jsb.reflection.callStaticMethod('org/cocos2dx/javascript/AppActivity', 'loadYLHRewardVideoAd', "(Ljava/lang/String;)V", rewardVideoAdId);
}
loadYLHBannerAd(bannerAdId: string) {
jsb.reflection.callStaticMethod('org/cocos2dx/javascript/AppActivity', 'loadYLHBannerAd', "(Ljava/lang/String;)V", bannerAdId);
}
loadYLHInterstitialAd(interstitialAdId: string) {
jsb.reflection.callStaticMethod('org/cocos2dx/javascript/AppActivity', 'loadYLHInterstitialAd', "(Ljava/lang/String;)V", interstitialAdId);
}
showRewardedVideoAd(): Promise<{ result: "complete" | "cancel" | "fail" }> {
return new Promise((resolve) => {
this._showRewardedVideoAdresolve = resolve;
jsb.reflection.callStaticMethod('org/cocos2dx/javascript/AppActivity', 'showRewardVideoAd', "()V");
});
}
overShowRewardedVideoAd(str) {
let result = JSON.parse(str);
this._showRewardedVideoAdresolve(result);
}
showInterstitialAd(): Promise<boolean> {
return new Promise((resolve) => {
jsb.reflection.callStaticMethod('org/cocos2dx/javascript/AppActivity', 'showInterstitialAd', "()V");
});
}
showBannerAd(style: { left: number; top: number; width: number; height: number; anchorX?: number, anchorY?: number }, refreshInterval?: number): Promise<boolean> {
return new Promise(async (resolve) => {
jsb.reflection.callStaticMethod('org/cocos2dx/javascript/AppActivity', 'showBannerAd', "()V");
});
}
hideBannerAd() {
jsb.reflection.callStaticMethod('org/cocos2dx/javascript/AppActivity', 'hideBannerAd', "()V");
}
shareAppMessage(info: { title?: string, imageUrl?: string, query?: string, imageUrlId?: string }): Promise<boolean> {
return new Promise((resolve) => {
jsb.reflection.callStaticMethod('org/cocos2dx/javascript/AppActivity', 'shareAppMessage', "(Ljava/lang/String;Ljava/lang/String;)V", info.title, info.imageUrl);
setTimeout(() => {
resolve(true);
}, 2 * 1000);
});
}
sharePicture(localUrl: string) {
jsb.reflection.callStaticMethod('org/cocos2dx/javascript/AppActivity', 'sharePicture', "(Ljava/lang/String;)V", localUrl);
}
setClipboardData(data: string) {
return new Promise<void>((resolve, reject) => {
jsb.reflection.callStaticMethod('org/cocos2dx/javascript/AppActivity', 'setClipboardData', "(Ljava/lang/String;)V", data);
resolve();
})
}
onBannerResize = (res: { width: number, height: number }) => { }
hideGameClubButton() { }
showGameClubButton() { }
createGameClubButton(obj): boolean { return false; }
destroyGameClubButton() { }
openProgram(appId: string, extraData?: object): Promise<void> {
return new Promise((resolve, reject) => { });
}
openCustomerServiceConversation(param: {
sessionFrom?: string,
showMessageCard?: boolean,
sendMessageTitle?: string,
sendMessagePath?: string,
sendMessageImg?: string
}): Promise<boolean> {
return new Promise((resolve) => { });
}
getLaunchOptions(): LaunchOptionType {
return {};
}
checkSession(): Promise<boolean> {
return Promise.resolve(true);
}
}
\ No newline at end of file
{
"name": "simba-sdk-android-native",
"version": "1.0.7",
"lockfileVersion": 2,
"requires": true,
"packages": {
"node_modules/simba-eventkit": {
"version": "1.0.1",
"resolved": "http://repository.icesimba.cn/repository/npm-group/simba-eventkit/-/simba-eventkit-1.0.1.tgz",
"integrity": "sha512-UX1lZEOm109MTnKp3OMDS+bSdI46ybiG0k5U1WV5aD5TeanWD06U7p1ec9SqJmbfTmUuUHtsrRCclmhgkJbNgA==",
"license": "ISC"
},
"node_modules/simba-httpclient": {
"version": "1.0.3",
"resolved": "http://repository.icesimba.cn/repository/npm-group/simba-httpclient/-/simba-httpclient-1.0.3.tgz",
"integrity": "sha512-aNuWyaHyFALsDWajZdmYuDETE64TlL7c2W01czCs8r8QLED56i+nqX7DAf7KmozH5R7Dl0o+gK0J4BAzYVOX/A==",
"license": "ISC"
},
"node_modules/simba-localstorage": {
"version": "1.0.0",
"resolved": "http://repository.icesimba.cn/repository/npm-group/simba-localstorage/-/simba-localstorage-1.0.0.tgz",
"integrity": "sha512-3eE8VB4Y32E97OPgmSnyPFTbVUHeIWLXvgBK9ljQCk5nvGevSPyfa821Fcsl0xdFVGbOzWsdGp3fAxaE9sJLxg==",
"license": "ISC"
},
"node_modules/simba-random": {
"version": "1.0.0",
"resolved": "http://repository.icesimba.cn/repository/npm-group/simba-random/-/simba-random-1.0.0.tgz",
"integrity": "sha512-54k04C5iM2hlZX3zgbl0zWrIVLLkB7TmKB1hkcKS7YROziVkbBrwzaMSXjmq2DbiANUxk6bEvmZlgEn3o8qsLA==",
"license": "ISC"
},
"node_modules/simba-sdk": {
"version": "1.0.49",
"resolved": "http://repository.icesimba.cn/repository/npm-group/simba-sdk/-/simba-sdk-1.0.49.tgz",
"integrity": "sha512-RegEvmcrgH0S0Xbph6HoCPQBSGh2YvwiPIkzQ/doYeiDS+8PNUOjwtFZBMmI8GTKvWVqyDy3nb2+4iWpbe3kEQ==",
"license": "ISC",
"dependencies": {
"simba-eventkit": "^1.0.0",
"simba-httpclient": "^1.0.0",
"simba-localstorage": "^1.0.0",
"simba-random": "^1.0.0",
"simba-utils": "^1.0.3"
}
},
"node_modules/simba-utils": {
"version": "1.0.5",
"resolved": "http://repository.icesimba.cn/repository/npm-group/simba-utils/-/simba-utils-1.0.5.tgz",
"integrity": "sha512-BkjSdISzBKOl11Q2rTrkOQyn+gQH5jbr5mO2Va5lGxFpd6mYsPcry6alwO+04D518B39ftFYcZ3v6lPsQ1CnRA==",
"license": "ISC"
}
}
}
export declare class Disposable {
private _disposed;
private _disposalAction;
constructor(disposalAction: () => void);
get disposed(): boolean;
dispose(): void;
}
export declare class CompositeDisposable {
private _disposed;
private _disposables;
constructor(...disposables: Disposable[]);
add(disposable: Disposable): void;
remove(disposable: Disposable): void;
clear(): void;
dispose(): void;
}
export declare class Event<T extends (...args: any[]) => any> {
private emitter;
private name;
constructor(emitter: Emitter, name: string | symbol);
getName(): string | symbol;
toString(): string;
on(handler: T, unshift?: boolean): Disposable;
once(handler: T, unshift?: boolean): Disposable;
readonly emit: (...a: Parameters<T>) => Promise<ReturnType<T>>[];
}
export declare class Emitter {
private _disposed;
private _handlersByEventName;
get disposed(): boolean;
clear(): void;
dispose(): void;
createEvent<T extends (...args: any[]) => void>(eventName?: string | symbol): Event<T>;
on(eventName: string | symbol, handler: (...args: any[]) => any, unshift?: boolean): Disposable;
once(eventName: string | symbol, handler: (...args: any[]) => any, unshift?: boolean): Disposable;
private off;
emit(eventName: string | symbol, ...args: any[]): Promise<any>[];
getEventNames(): string[];
getEventSymbols(): symbol[];
listenerCountForEventName(eventName: string | symbol): number;
getTotalListenerCount(): number;
}
"use strict";
/*
用法1:
import { Emitter, CompositeDisposable } from "event-kit";
class Somthing {
disposables = new CompositeDisposable();
constructor(user: User) {
this.disposables.add(user.onDidChangeName(()=>{}));
this.disposables.add(user.onDidChangePhone(()=>{}));
}
destroy() {
this.disposables.dispose();
}
}
class User {
emitter = new Emitter();
private name: string;
private phone: string;
onDidChangeName(callback: (name: string) => void) {
return this.emitter.on("did-change-name", callback);
}
onDidChangePhone(callback: (phone: string) => void) {
return this.emitter.on("did-change-phone", callback);
}
setName(name: string) {
if (name != this.name) {
this.name = name;
this.emitter.emit("did-change-name", name);
}
}
setPhone(phone: string) {
if (phone != this.phone) {
this.phone = phone;
this.emitter.emit("did-change-phone", phone);
}
}
}
*/
/*
用法2:
class User {
private name: string;
private emitter = new Emitter();
onNameChangeEvent = this.emitter.createEvent<(name: string) => void>("did-change-name");
setName(name: string) {
if (name != this.name) {
this.onNameChangeEvent.emit(this.name);
}
}
}
class Something {
disposables = new CompositeDisposable();
constructor(user: User) {
this.disposables.add(user.onNameChangeEvent.on(() => {}));
}
destroy() {
this.disposables.dispose();
}
}
*/
Object.defineProperty(exports, "__esModule", { value: true });
class Disposable {
constructor(disposalAction) {
this._disposed = false;
this._disposalAction = disposalAction;
}
get disposed() {
return this._disposed;
}
dispose() {
if (!this.disposed) {
this._disposed = true;
if (this._disposalAction) {
this._disposalAction();
this._disposalAction = null;
}
}
}
}
exports.Disposable = Disposable;
class CompositeDisposable {
constructor(...disposables) {
this._disposed = false;
this._disposables = new Set();
for (let disposable of disposables) {
this.add(disposable);
}
}
add(disposable) {
if (!this._disposed) {
if (disposable) {
this._disposables.add(disposable);
}
}
}
remove(disposable) {
if (!this._disposed) {
this._disposables.delete(disposable);
}
}
clear() {
if (!this._disposed) {
this._disposables.clear();
}
}
dispose() {
if (!this._disposed) {
this._disposed = true;
this._disposables.forEach((disposable) => {
disposable.dispose();
});
this._disposables = null;
}
}
}
exports.CompositeDisposable = CompositeDisposable;
class Event {
constructor(emitter, name) {
this.emit = ((...argsparam) => {
argsparam.unshift(this.name);
return this.emitter.emit.apply(this.emitter, argsparam);
});
this.emitter = emitter;
this.name = name;
}
getName() {
return this.name;
}
toString() {
return `[Event ${this.name.toString()}]`;
}
on(handler, unshift = false) {
return this.emitter.on(this.name, handler, unshift);
}
once(handler, unshift = false) {
return this.emitter.once(this.name, handler, unshift);
}
}
exports.Event = Event;
class Emitter {
constructor() {
this._disposed = false;
this._handlersByEventName = new Map();
this.off = (eventName, handlerToRemove) => {
if (this._disposed)
return;
let oldHandlers = this._handlersByEventName.get(eventName);
if (oldHandlers) {
let newHandlers = [];
for (let handler of oldHandlers) {
if (handler != handlerToRemove) {
newHandlers.push(handler);
}
}
if (newHandlers.length) {
this._handlersByEventName.set(eventName, newHandlers);
}
else {
this._handlersByEventName.delete(eventName);
}
}
};
}
get disposed() {
return this._disposed;
}
clear() {
this._handlersByEventName.clear();
}
dispose() {
this._handlersByEventName = null;
this._disposed = true;
}
createEvent(eventName) {
if (!eventName) {
return new Event(this, Symbol("Event"));
}
return new Event(this, eventName);
}
on(eventName, handler, unshift = false) {
if (this._disposed) {
throw new Error("Emitter has been diposed");
}
let currentHandler = this._handlersByEventName.get(eventName);
if (currentHandler) {
if (unshift) {
currentHandler.unshift(handler);
}
else {
currentHandler.push(handler);
}
}
else {
this._handlersByEventName.set(eventName, [handler]);
}
return new Disposable(this.off.bind(this, eventName, handler));
}
once(eventName, handler, unshift = false) {
let wrapped = (...args) => {
disposable.dispose();
return handler(...args);
};
let disposable = this.on(eventName, wrapped, unshift);
return disposable;
}
emit(eventName, ...args) {
let handlers = this._handlersByEventName.get(eventName);
let result = [];
if (handlers) {
for (let handler of handlers) {
try {
let ret = handler(...args);
if (ret === undefined) {
result.push(Promise.resolve());
}
else if (ret instanceof Promise) {
result.push(ret);
}
else {
result.push(Promise.resolve(ret));
}
}
catch (e) {
console.error(e);
}
}
}
return result;
}
getEventNames() {
let ret = [];
for (let k of this._handlersByEventName.keys()) {
if (typeof (k) === 'string') {
ret.push(k);
}
}
return ret;
}
getEventSymbols() {
let ret = [];
for (let k of this._handlersByEventName.keys()) {
if (typeof (k) === 'symbol') {
ret.push(k);
}
}
return ret;
}
listenerCountForEventName(eventName) {
let handlers = this._handlersByEventName.get(eventName);
return handlers ? handlers.length : 0;
}
getTotalListenerCount() {
let result = 0;
for (let eventName of this._handlersByEventName.keys()) {
result += this._handlersByEventName.get(eventName).length;
}
return result;
}
}
exports.Emitter = Emitter;
{
"name": "simba-eventkit",
"version": "1.0.1",
"description": "Event Kit",
"main": "./dist/index.js",
"scripts": {
"build": "tsc"
},
"author": "",
"license": "ISC"
}
\ No newline at end of file
export declare class HttpError extends Error {
status: number;
constructor(status: number, message: string);
}
export interface HttpResponsePromise extends Promise<string | ArrayBuffer> {
abort: () => void;
}
export declare class HttpClient {
private serverBaseUrl;
private authorization;
private maxConcurrency;
private currentRequestNum;
private pendingRequests;
private responsePreprocessor;
constructor(baseUrl: string, maxConcurrency?: number);
setAuthorization(authorization: string): void;
setResponsePreprocessor(func: (response: string | ArrayBuffer | Blob) => string | ArrayBuffer): void;
get(path?: string, timeout?: number, headers?: {
[key: string]: string;
}): HttpResponsePromise;
post(path?: string, timeout?: number, body?: string | ArrayBuffer, contentType?: string, headers?: {
[key: string]: string;
}): HttpResponsePromise;
put(path?: string, timeout?: number, body?: string | ArrayBuffer, contentType?: string, headers?: {
[key: string]: string;
}): HttpResponsePromise;
delete(path?: string, timeout?: number, headers?: {
[key: string]: string;
}): HttpResponsePromise;
private _handleRequest;
private _doRequest;
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class HttpError extends Error {
constructor(status, message) {
super(message);
this.status = status;
}
}
exports.HttpError = HttpError;
class HttpClient {
constructor(baseUrl, maxConcurrency = 0) {
this.serverBaseUrl = "";
this.authorization = null;
this.maxConcurrency = 0;
this.currentRequestNum = 0;
this.pendingRequests = [];
this.serverBaseUrl = baseUrl;
this.maxConcurrency = maxConcurrency;
}
setAuthorization(authorization) {
this.authorization = authorization;
}
setResponsePreprocessor(func) {
this.responsePreprocessor = func;
}
get(path = "", timeout = 5000, headers) {
return this._handleRequest({
path,
method: "GET",
timeout,
headers
});
}
post(path = "", timeout = 5000, body, contentType, headers) {
return this._handleRequest({
path,
method: "POST",
timeout,
contentType,
headers
}, body);
}
put(path = "", timeout = 5000, body, contentType, headers) {
return this._handleRequest({
path,
method: "POST",
timeout,
contentType,
headers
}, body);
}
delete(path = "", timeout = 5000, headers) {
return this._handleRequest({
path,
method: "GET",
timeout,
headers
});
}
_handleRequest(request, body) {
let promise = new Promise((resolve, reject) => {
request.onSuccess = resolve;
request.onError = reject;
if (this.maxConcurrency > 0 && this.currentRequestNum >= this.maxConcurrency) {
this.pendingRequests.push(request);
}
else {
this._doRequest(request, body);
}
});
request.promise = promise;
if (request.abort) {
promise.abort = request.abort;
}
else {
promise.abort = () => {
let idx = this.pendingRequests.indexOf(request);
if (idx >= 0) {
this.pendingRequests.splice(idx, 1);
}
};
}
return promise;
}
_doRequest(request, body) {
this.currentRequestNum++;
const xhr = new XMLHttpRequest();
xhr.timeout = request.timeout;
xhr.open(request.method, this.serverBaseUrl + request.path, true);
if (request.contentType) {
xhr.setRequestHeader("Content-Type", request.contentType);
}
if (request.headers) {
for (let key in request.headers) {
xhr.setRequestHeader(key, request.headers[key]);
}
}
let abort = () => {
xhr.abort();
};
;
if (request.promise) {
request.promise.abort = abort;
}
else {
request.abort = abort;
}
xhr.onreadystatechange = () => {
if (xhr.readyState == 4) {
if (!request.onError)
return;
if (xhr.status == 200) {
let response = xhr.responseText ? xhr.responseText : xhr.response;
if (response && this.responsePreprocessor) {
response = this.responsePreprocessor(response);
}
request.onSuccess(response);
}
else {
request.onError(new HttpError(xhr.status, getHttpStatusError(xhr.status)));
}
if (this.pendingRequests.length) {
this._doRequest(this.pendingRequests.shift());
}
else {
this.currentRequestNum--;
}
}
};
xhr.ontimeout = () => {
if (request.onError) {
request.onError(new HttpError(408, getHttpStatusError(408)));
request.onError = null;
request.onSuccess = null;
if (this.pendingRequests.length) {
this._doRequest(this.pendingRequests.shift());
}
else {
this.currentRequestNum--;
}
}
};
xhr.onabort = () => {
if (request.onError) {
request.onError(new HttpError(-1, "Request abort."));
request.onError = null;
request.onSuccess = null;
if (this.pendingRequests.length) {
this._doRequest(this.pendingRequests.shift());
}
else {
this.currentRequestNum--;
}
}
};
if (this.authorization) {
xhr.setRequestHeader("auth-token", this.authorization);
}
xhr.send(body);
}
}
exports.HttpClient = HttpClient;
function getHttpStatusError(status) {
switch (status) {
case 400: return "Bad request.";
case 401: return "Unauthorized.";
case 402: return "Payment required.";
case 403: return "Forbidden.";
case 404: return "Not found.";
case 405: return "Method not allowed.";
case 406: return "Not acceptable.";
case 407: return "Proxy authentication required.";
case 408: return "Request timeout.";
case 409: return "Conflict.";
case 410: return "Gone.";
case 411: return "Length required.";
case 412: return "Precondition failed.";
case 413: return "Payload too large.";
case 414: return "URI too long.";
case 416: return "Requested range not satisfiable.";
case 417: return "Expectation failed.";
case 427: return "Precondition required.";
case 429: return "Too many requests.";
case 449: return "Retry after doing the appropriate action.";
case 500: return "Internal server error.";
case 501: return "Server does not support the functionality required to fulfill the request.";
case 502: return "Error response received from gateway.";
case 503: return "Temporarily overloaded.";
case 504: return "Timed out waiting for gateway.";
case 505: return "HTTP version not supported.";
}
return "Unknown error code: " + status;
}
{
"name": "simba-httpclient",
"version": "1.0.3",
"description": "Http Client",
"main": "./dist/index.js",
"scripts": {
"build": "tsc",
"pub-local": "tsc && npm publish --registry=http://10.10.8.58:8081/repository/npm-hosted/",
"pub": "tsc && npm publish --registry=http://repository.icesimba.com:8081/repository/npm-hosted/"
},
"author": "",
"license": "ISC"
}
\ No newline at end of file
export declare namespace LocalStorage {
function setBoolean(key: string, value: boolean): void;
function getBoolean(key: string, defaultValue?: boolean): boolean;
function setInt(key: string, value: number): void;
function getInt(key: string, defaultValue?: number): number;
function setFloat(key: string, value: number): void;
function getFloat(key: string, defaultValue?: number): number;
function setString(key: string, value: string): void;
function getString(key: string, defaultValue?: string): string;
function setObject<T>(key: string, value: T): void;
/**
* 传入default, 会生成T的完整实例,而不是一个兼容的json对象.
* @param {string} key
* @param {T} defaultValue
* @returns {T}
*/
function getObject<T>(key: string, defaultValue?: T): T;
function remove(key: string): void;
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var LocalStorage;
(function (LocalStorage) {
let storage = typeof cc === 'undefined' ? localStorage : cc.sys.localStorage;
function setBoolean(key, value) {
storage.setItem(key, value.toString());
}
LocalStorage.setBoolean = setBoolean;
function getBoolean(key, defaultValue) {
if (!defaultValue) {
defaultValue = false;
}
let ret = storage.getItem(key);
if (ret == null || ret.length == 0)
return defaultValue;
if (ret == "true")
return true;
else
return false;
}
LocalStorage.getBoolean = getBoolean;
function setInt(key, value) {
storage.setItem(key, Math.round(value).toString());
}
LocalStorage.setInt = setInt;
function getInt(key, defaultValue) {
if (!defaultValue) {
defaultValue = 0;
}
let ret = storage.getItem(key);
if (ret == null || ret.length == 0)
return Math.round(defaultValue);
return parseInt(ret);
}
LocalStorage.getInt = getInt;
function setFloat(key, value) {
storage.setItem(key, value.toString());
}
LocalStorage.setFloat = setFloat;
function getFloat(key, defaultValue) {
if (!defaultValue) {
defaultValue = 0;
}
let ret = storage.getItem(key);
if (ret == null || ret.length == 0)
return defaultValue;
return parseFloat(ret);
}
LocalStorage.getFloat = getFloat;
function setString(key, value) {
storage.setItem(key, value);
}
LocalStorage.setString = setString;
function getString(key, defaultValue) {
if (!defaultValue) {
defaultValue = "";
}
let ret = storage.getItem(key);
if (!ret || ret.length == 0)
return defaultValue;
return ret;
}
LocalStorage.getString = getString;
function setObject(key, value) {
if (!value) {
storage.setItem(key, "{}");
return;
}
this.setString(key, JSON.stringify(value));
}
LocalStorage.setObject = setObject;
/**
* 传入default, 会生成T的完整实例,而不是一个兼容的json对象.
* @param {string} key
* @param {T} defaultValue
* @returns {T}
*/
function getObject(key, defaultValue) {
let ret = storage.getItem(key);
if (!ret || ret.length == 0)
return defaultValue;
else {
return JSON.parse(ret);
}
}
LocalStorage.getObject = getObject;
function remove(key) {
storage.removeItem(key);
}
LocalStorage.remove = remove;
})(LocalStorage = exports.LocalStorage || (exports.LocalStorage = {}));
{
"name": "simba-localstorage",
"version": "1.0.0",
"description": "Local Storage for cocos and web",
"main": "./dist/index.js",
"scripts": {
"build": "tsc"
},
"author": "",
"license": "ISC"
}
\ No newline at end of file
/**
* 线性同余随机数生成器
*/
export declare class Random {
/**
* 创建一个随机数生成器
*/
constructor(seed: number);
/**
* 设置用于随机数生成器的种子,如果不设置则实际是取当前时间毫秒数
*/
seed: number;
/**
* 返回一个随机数,在0.0~1.0之间
*/
get value(): number;
/**
* 返回半径为1的圆内的一个随机点
*/
get insideUnitCircle(): {
x: number;
y: number;
};
/**
* 返回半径为1的圆边的一个随机点
*/
get onUnitCircle(): {
x: number;
y: number;
};
/**
* 返回一个在min和max之间的随机浮点数
*/
range(min: number, max: number): number;
/**
* 设置用于随机数生成器的种子,如果不设置则实际是取当前时间毫秒数
*/
static seed: number;
/**
* 返回一个随机数,在0.0~1.0之间
*/
static get value(): number;
/**
* 返回半径为1的圆内的一个随机点
*/
static get insideUnitCircle(): {
x: number;
y: number;
};
/**
* 返回半径为1的圆边的一个随机点
*/
static get onUnitCircle(): {
x: number;
y: number;
};
/**
* 返回一个在min和max之间的随机浮点数
*/
static range(min?: number, max?: number): number;
/**
* 返回一个在min和max之间的随机整数,包括最大值
*/
static rangeInt(min: number, max: number): number;
/**返回一个arr[0]到arr[1]之间的随机整数,包括最大值 */
static rangeIntByArr(arr: number[]): number;
/**返回一个arr[0]到arr[1]之间的随机数,包括最大值 */
static rangeByArr(arr: number[]): number;
/**从数组里随机一个元素 */
static rangeFromArr<T>(arr: Array<T>): T;
/**根据权重数组的概率分布,随机抽取值数组里的元素 */
static getValueByWeight<T>(arrValue: Array<T>, arrWeight: Array<number>): T;
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* 线性同余随机数生成器
*/
class Random {
/**
* 创建一个随机数生成器
*/
constructor(seed) {
this.seed = seed;
if (!this.seed && this.seed != 0) {
this.seed = new Date().getTime();
}
}
/**
* 返回一个随机数,在0.0~1.0之间
*/
get value() {
return this.range(0, 1);
}
/**
* 返回半径为1的圆内的一个随机点
*/
get insideUnitCircle() {
var randomAngle = this.range(0, 360);
var randomDis = this.range(1, 0);
var randomX = randomDis * Math.cos(randomAngle * Math.PI / 180);
var randomY = randomDis * Math.sin(randomAngle * Math.PI / 180);
return { x: randomX, y: randomY };
}
/**
* 返回半径为1的圆边的一个随机点
*/
get onUnitCircle() {
var randomAngle = this.range(0, 360);
var randomX = Math.cos(randomAngle * Math.PI / 180);
var randomY = Math.sin(randomAngle * Math.PI / 180);
return { x: randomX, y: randomY };
}
/**
* 返回一个在min和max之间的随机浮点数
*/
range(min, max) {
if (!this.seed && this.seed != 0) {
this.seed = new Date().getTime();
}
max = max || 1;
min = min || 0;
this.seed = (this.seed * 9301 + 49297) % 233280;
var rnd = this.seed / 233280.0;
return min + rnd * (max - min);
}
/**
* 返回一个随机数,在0.0~1.0之间
*/
static get value() {
return this.range(1, 0);
}
/**
* 返回半径为1的圆内的一个随机点
*/
static get insideUnitCircle() {
var randomAngle = this.range(0, 360);
var randomDis = this.range();
var randomX = randomDis * Math.cos(randomAngle * Math.PI / 180);
var randomY = randomDis * Math.sin(randomAngle * Math.PI / 180);
return { x: randomX, y: randomY };
}
/**
* 返回半径为1的圆边的一个随机点
*/
static get onUnitCircle() {
var randomAngle = this.range(0, 360);
var randomX = Math.cos(randomAngle * Math.PI / 180);
var randomY = Math.sin(randomAngle * Math.PI / 180);
return { x: randomX, y: randomY };
}
/**
* 返回一个在min和max之间的随机浮点数
*/
static range(min = 0, max = 1) {
if (!Random.seed && Random.seed != 0) {
Random.seed = new Date().getTime();
}
max = max || 1;
min = min || 0;
Random.seed = (Random.seed * 9301 + 49297) % 233280;
var rnd = Random.seed / 233280.0;
return min + rnd * (max - min);
}
/**
* 返回一个在min和max之间的随机整数,包括最大值
*/
static rangeInt(min, max) {
var Range = max - min;
var Rand = Random.range(0, 1);
return (min + Math.round(Rand * Range));
}
/**返回一个arr[0]到arr[1]之间的随机整数,包括最大值 */
static rangeIntByArr(arr) {
if (arr.length < 2) {
return 0;
}
return Random.rangeInt(arr[0], arr[1]);
}
/**返回一个arr[0]到arr[1]之间的随机数,包括最大值 */
static rangeByArr(arr) {
if (arr.length < 2) {
return 0;
}
return Random.range(arr[0], arr[1]);
}
/**从数组里随机一个元素 */
static rangeFromArr(arr) {
let idx = Random.rangeInt(0, arr.length - 1);
return arr[idx];
}
/**根据权重数组的概率分布,随机抽取值数组里的元素 */
static getValueByWeight(arrValue, arrWeight) {
let random = Random.range();
// cc.log("getValueByWeight random range===>>> ", random)
let temp = 0;
for (let i = 0; i < arrValue.length; i++) {
const weight = arrWeight[i] + temp;
if (random <= weight) {
// cc.log("getValueByWeight 随到了===>>> ", arrValue[i])
return arrValue[i];
}
temp = weight;
}
// cc.log("getValueByWeight 没随到 ")
return null;
}
}
exports.Random = Random;
{
"name": "simba-random",
"version": "1.0.0",
"description": "Functions to generate random numbers",
"main": "./dist/index.js",
"scripts": {
"build": "tsc"
},
"author": "",
"license": "ISC"
}
\ No newline at end of file
import { LaunchOptionType, LoginDataType, LoginDataTypeV2, SDKConfigType, SDKConfigTypeV2 } from "./SDKTypes";
import { DeepReadonly } from "simba-utils";
export declare let V2: boolean;
export declare let SDKConfig: Readonly<SDKConfigType> | Readonly<SDKConfigTypeV2>;
export declare let SDKConfigV2: Readonly<SDKConfigTypeV2>;
export declare function setConfig(config: Readonly<SDKConfigType>): void;
export declare function setConfigV2(config: Readonly<SDKConfigTypeV2>): void;
export declare abstract class SDKBase {
protected loginInfo?: LoginDataType | LoginDataTypeV2;
readonly systemInfo: {
deviceInfo: {
model: string;
brand: string;
platform: string;
system: string;
version: string;
SDKVersion: string;
};
displayInfo: {
windowSize: {
width: number;
height: number;
};
safeArea: {
left: number;
top: number;
right: number;
bottom: number;
};
};
};
init(): Promise<boolean>;
protected abstract _login(): Promise<{
code: string;
}>;
abstract getChannel(): string;
/**构建登录传给服务器的参数 */
buildLoginParam(param: any): any;
login(extraParams?: {
[key: string]: string;
}, timeout?: number): Promise<LoginDataType | LoginDataTypeV2>;
/**原生平台不能调用 getSDKRecord*/
timeManagerOnLogin(): Promise<void>;
/**下载存档 */
downloadRecord(): Promise<void>;
/**静默获取token */
refreshLocalServerToken(): Promise<void>;
getHttpHeaders(): {
IcesimbaToken: string;
IcesimbaSession: string;
"Content-Type": string;
};
isLoggedIn(): boolean;
getLoginInfo(): DeepReadonly<LoginDataType> | DeepReadonly<LoginDataTypeV2> | undefined;
uploadGameRecord(data: Object): void;
getGameRecord(): Object;
bi(category: string, id: string, gameBasicMetrics: {
user_register_version: string;
login_duration: number;
total_duration: number;
daily_duration: number;
[key: string]: any;
}, gameData: Object): Promise<string | ArrayBuffer>;
abstract getLaunchOptions(): LaunchOptionType;
abstract checkSession(): Promise<boolean>;
abstract exit(): void;
abstract showRewardedVideoAd(): Promise<{
result: "complete" | "cancel" | "fail";
}>;
abstract showInterstitialAd(): Promise<boolean>;
abstract showBannerAd(style: {
left: number;
top: number;
width: number;
height: number;
anchorX?: number;
anchorY?: number;
}, refreshInterval?: number): Promise<boolean>;
abstract hideBannerAd(): void;
abstract shareAppMessage(info: {
title?: string;
imageUrl?: string;
query?: string;
imageUrlId?: string;
}): Promise<boolean>;
abstract setClipboardData(data: string): Promise<void>;
abstract createGameClubButton(obj: {
type: 'text' | 'image';
text?: string;
image?: string;
style: {
left: number;
top: number;
width: number;
height: number;
backgroundColor?: string;
borderColor?: string;
borderWidth?: number;
borderRadius?: number;
textAlign?: 'left' | 'center' | 'right';
fontSize?: number;
lineHeight?: number;
};
icon: 'green' | 'white' | 'dark' | 'light';
}): boolean;
abstract hideGameClubButton(): void;
abstract showGameClubButton(): void;
abstract destroyGameClubButton(): void;
abstract openProgram(appId: string, extraData?: object): Promise<void>;
abstract openCustomerServiceConversation(param: {
sessionFrom?: string;
showMessageCard?: boolean;
sendMessageTitle?: string;
sendMessagePath?: string;
sendMessageImg?: string;
}): Promise<boolean>;
}
export declare namespace SDKEvents {
const AppShow: import("simba-eventkit").Event<(query?: {
[key: string]: string;
}) => void>;
const AppHide: import("simba-eventkit").Event<() => void>;
const OnGameClubBtnTap: import("simba-eventkit").Event<() => void>;
const OnTimeSync: import("simba-eventkit").Event<() => void>;
const enum SDKErrorType {
NO_REWARDED_VIDEO_AVAILABLE = 0
}
const SDKError: import("simba-eventkit").Event<(error: SDKErrorType, ...params: any[]) => void>;
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SDKEvents = void 0;
const simba_eventkit_1 = require("simba-eventkit");
var SDKEvents;
(function (SDKEvents) {
let emitter = new simba_eventkit_1.Emitter;
SDKEvents.AppShow = emitter.createEvent();
SDKEvents.AppHide = emitter.createEvent();
SDKEvents.OnGameClubBtnTap = emitter.createEvent();
SDKEvents.OnTimeSync = emitter.createEvent();
SDKEvents.SDKError = emitter.createEvent();
})(SDKEvents = exports.SDKEvents || (exports.SDKEvents = {}));
declare let sdkRecords: {
sdk: Object;
game: Object;
};
export declare function downloadSDKRecord(_gameId: string, _headers: {
[key: string]: string;
}): Promise<void>;
export declare function downloadSDKRecordV2(_gameId: string, url: string, _headers: {
[key: string]: string;
}): Promise<boolean>;
export declare function uploadSDKRecord(record: Partial<typeof sdkRecords>): Promise<void>;
export declare function getSDKRecord(): {
sdk: Object;
game: Object;
};
export {};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getSDKRecord = exports.uploadSDKRecord = exports.downloadSDKRecordV2 = exports.downloadSDKRecord = void 0;
const SDKServer_1 = require("./SDKServer");
const TimeManager_1 = require("./TimeManager");
const SDKEvents_1 = require("./SDKEvents");
const SDKBase_1 = require("./SDKBase");
const _1 = require(".");
let sdkRecords = { sdk: {}, game: {} };
let gameId;
let headers;
async function downloadSDKRecord(_gameId, _headers) {
gameId = _gameId;
headers = _headers;
let tryCount = 0;
while (tryCount < 5) {
try {
console.log("downloadSDKRecord tryCount = ", tryCount);
let response = await SDKServer_1.default.mapleServer.post("/maple/client/v1/archive/download", 5000, JSON.stringify({ game_id: gameId }), "application/json", headers);
let data = JSON.parse(response);
console.log('拉取服务器存档:', data);
if ("0" === data["code"] && data["obj"] && data["obj"]["data"]) {
console.log("valid record succeed");
sdkRecords = data["obj"]["data"];
if (!sdkRecords.game) { // 兼容之前存档格式
sdkRecords = { sdk: {}, game: sdkRecords };
}
sdkRecords.sdk = sdkRecords.sdk || {};
console.log("sdkRecords.sdk = ", sdkRecords.sdk);
}
break;
}
catch (e) {
console.error(e);
}
tryCount++;
}
}
exports.downloadSDKRecord = downloadSDKRecord;
/**token错误 */
var ETokenErrorCode;
(function (ETokenErrorCode) {
ETokenErrorCode[ETokenErrorCode["TokenInvalid"] = -1001] = "TokenInvalid";
ETokenErrorCode[ETokenErrorCode["TokenExpired"] = -1002] = "TokenExpired";
})(ETokenErrorCode || (ETokenErrorCode = {}));
async function downloadSDKRecordV2(_gameId, url, _headers) {
gameId = _gameId;
headers = _headers;
let tryCount = 0;
let err = false;
while (tryCount < 5) {
try {
// console.log("downloadSDKRecord tryCount = ", tryCount);
let downloadRecordStr = await SDKServer_1.default.downloadRecordServerHttp.get(url, 5000, headers);
// console.log("downloadRecord response = ", downloadRecordStr);
if (downloadRecordStr && "" !== downloadRecordStr.trim()) {
let downloadRecordJson = JSON.parse(downloadRecordStr);
if (downloadRecordJson && downloadRecordJson["body"]) {
sdkRecords = downloadRecordJson["body"];
if (!sdkRecords.game) { // 兼容之前存档格式
sdkRecords = { sdk: {}, game: sdkRecords };
}
sdkRecords.sdk = sdkRecords.sdk || {};
// console.log("sdkRecords.sdk = ", sdkRecords.sdk);
return true;
}
else if (ETokenErrorCode.TokenExpired === downloadRecordJson["code"] || ETokenErrorCode.TokenInvalid === downloadRecordJson["code"]) {
console.log("ETokenErrorCode.TokenExpired || ETokenErrorCode.TokenInvalid ");
err = true;
}
}
else {
console.log("downloadSDKRecordV2 error", downloadRecordStr);
err = true;
}
if (err) {
return false;
}
}
catch (e) {
console.error(e);
}
tryCount++;
}
}
exports.downloadSDKRecordV2 = downloadSDKRecordV2;
async function uploadSDKRecord(record) {
Object.assign(sdkRecords, record);
sdkRecords.sdk["game_time"] = TimeManager_1.TimeManager.getTimeRecord();
if (SDKBase_1.V2) {
let url = SDKBase_1.SDKConfigV2.debug ? SDKBase_1.SDKConfigV2.localServerRecordServiceUrlDEV : SDKBase_1.SDKConfigV2.localServerRecordServiceUrlRELEASE;
let logininfo = _1.SDK.getLoginInfo();
let data = {
"appId": SDKBase_1.SDKConfigV2.gameId,
"appName": SDKBase_1.SDKConfigV2.gameName,
"userId": logininfo.playerId,
"platformId": logininfo.playerId,
"body": sdkRecords
};
let uploadRecordStr = await SDKServer_1.default.uploadRecordServerHttp.post(url, 5000, JSON.stringify(data), "application/json", { "Authorization": `Bearer ${logininfo.localServerRecordServiceToken}` });
console.log("uploadRecord response = ", uploadRecordStr);
if (uploadRecordStr && "" !== uploadRecordStr.trim()) {
let jsonObj = JSON.parse(uploadRecordStr);
if (ETokenErrorCode.TokenExpired === jsonObj["code"] || ETokenErrorCode.TokenInvalid === jsonObj["code"]) {
await _1.SDK.refreshLocalServerToken();
uploadSDKRecord(record);
}
}
}
else {
let response = await SDKServer_1.default.mapleServer.post("/maple/client/v1/archive/upload/all", 5000, JSON.stringify({ game_id: gameId, data: sdkRecords }), "application/json", headers);
console.log("Upload record response", response);
}
}
exports.uploadSDKRecord = uploadSDKRecord;
function getSDKRecord() {
return sdkRecords;
}
exports.getSDKRecord = getSDKRecord;
SDKEvents_1.SDKEvents.OnTimeSync.on(() => {
uploadSDKRecord({});
});
import { HttpClient } from "simba-httpclient";
declare namespace SDKServer {
let mapleServer: HttpClient;
let eventServer: HttpClient;
let timeServer: HttpClient;
/**登录服务的http */
let loginLocalServerHttp: HttpClient;
/**上传存档服务的http */
let uploadRecordServerHttp: HttpClient;
/**下载存档服务的http */
let downloadRecordServerHttp: HttpClient;
/**刷新token服务的http */
let refreshTokenServerHttp: HttpClient;
}
export default SDKServer;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const simba_httpclient_1 = require("simba-httpclient");
var SDKServer;
(function (SDKServer) {
SDKServer.eventServer = new simba_httpclient_1.HttpClient("https://eventstat.icesimba.com");
//v2 add
/**登录服务的http */
SDKServer.loginLocalServerHttp = new simba_httpclient_1.HttpClient("");
/**上传存档服务的http */
SDKServer.uploadRecordServerHttp = new simba_httpclient_1.HttpClient("");
/**下载存档服务的http */
SDKServer.downloadRecordServerHttp = new simba_httpclient_1.HttpClient("");
/**刷新token服务的http */
SDKServer.refreshTokenServerHttp = new simba_httpclient_1.HttpClient("");
})(SDKServer || (SDKServer = {}));
exports.default = SDKServer;
export interface SDKConfigType {
gameId: string;
gameName: string;
debug: boolean;
shareConfigUrl: string;
gameVersion: string;
useLocalTime?: boolean;
channelConfig: {
wechat?: ChannelConfigType;
qq?: ChannelConfigType;
kuaikan?: ChannelConfigType;
vivo?: ChannelConfigType;
oppo?: ChannelConfigType;
baidu?: ChannelConfigType;
kuaishou?: ChannelConfigType;
douyin?: ChannelConfigType;
xiaomi?: ChannelConfigType;
huawei?: ChannelConfigType;
android?: ChannelConfigType;
gamebox4399?: ChannelConfigType;
};
}
export interface ChannelConfigType {
appId?: string;
rewaredVideoAdId?: string;
interstitialAdId?: string;
bannerAdId?: string;
/**扩展参数 */
extraParam?: any;
}
export interface LaunchOptionType {
query?: {
[key: string]: string;
};
referrerInfo?: {
appId: string;
extraData: {
[key: string]: any;
};
};
}
export interface LoginDataType {
session: string;
token: string;
playerId: string;
createTime: string;
profileVersion: number;
}
export interface ShareDataType {
title: string;
imageUrl: string;
imageUrlId?: string;
query?: string;
}
export interface SVConfigItem {
sharePercent: number;
sharePercents: number[];
disableShareFallback?: boolean;
syncTitleAndImage?: boolean;
titles: {
id: string;
value: string;
}[];
imageUrls: {
id: string;
value: string;
urlId?: string;
}[];
}
interface VideoPointType {
type: "video";
disableShareFallback?: boolean;
}
interface SharePointType {
type: "share";
}
export declare type SVPoint = (VideoPointType | SharePointType) & {
id: string;
};
/**配置表 */
export interface SDKConfigTypeV2 {
gameId: string;
gameName: string;
debug: boolean;
shareConfigUrl: string;
gameVersion: string;
useLocalTime?: boolean;
channelConfig: {
wechat?: ChannelConfigType;
qq?: ChannelConfigType;
kuaikan?: ChannelConfigType;
vivo?: ChannelConfigType;
oppo?: ChannelConfigType;
baidu?: ChannelConfigType;
kuaishou?: ChannelConfigType;
douyin?: ChannelConfigType;
xiaomi?: ChannelConfigType;
huawei?: ChannelConfigType;
android?: ChannelConfigType;
gamebox4399?: ChannelConfigType;
};
/**登录本地服务器时的渠道标识id */
localServerLoginSource: string;
/**登录本地服时,测试服务的链接【可不填,默认使用sdk中写死的】 */
loginLocalServerServiceUrlDEV: string;
/**登录本地服时,正式服务的链接 可不填,默认使用sdk中写死的】*/
loginLocalServerServiceUrlRELEASE: string;
/**本地存档服务,测试服务的链接 */
localServerRecordServiceUrlDEV: string;
/**本地存档服务,正式服务的链接 */
localServerRecordServiceUrlRELEASE: string;
/**同步时间的服务,测试服链接 */
syncTimeServiceUrlDEV: string;
/**同步时间的服务,正式服链接 */
syncTimeServiceUrlRELEASE: string;
/**和服务器同步时间的频率ms */
syncTimeRate: number;
/**测试服刷新token的服务 */
refreshlocalServerTokenServiceUrlDEV: string;
/**正式服刷新token的服务 */
refreshlocalServerTokenServiceUrlRELEASE: string;
}
/**登录数据 */
export interface LoginDataTypeV2 {
/**渠道认证token */
channelAccessToken: string;
/**本地服公共服务访问token */
localServerPublicServiceToken: string;
/**本地服存档服务访问token */
localServerRecordServiceToken: string;
/**本地服刷新token */
localServerRefreshToken: string;
/**本地服返回的subject */
localServerSubject: string;
/**玩家id */
playerId: string;
}
export {};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
import { DeepReadonly } from "simba-utils";
import { SVConfigItem, SVPoint, SDKConfigType } from "./SDKTypes";
export declare function setNoRewaredAd(): void;
export declare function initShareConfig(SDKConfig: Readonly<SDKConfigType>): Promise<unknown>;
export declare function initShareConfigV2(gId: string, url: string): Promise<unknown>;
export declare function getSVConfigById(svPointId: string): DeepReadonly<SVConfigItem> | undefined;
export declare function getShareContent(svPointId: string): DeepReadonly<{
title: {
id: string;
value: string;
};
imageUrl: {
id: string;
value: string;
urlId?: string;
};
}>;
export declare function getSVPointById(svPointId: string, forceShare?: boolean): DeepReadonly<SVPoint>;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getSVPointById = exports.getShareContent = exports.getSVConfigById = exports.initShareConfigV2 = exports.initShareConfig = exports.setNoRewaredAd = void 0;
const simba_httpclient_1 = require("simba-httpclient");
const simba_localstorage_1 = require("simba-localstorage");
const simba_random_1 = require("simba-random");
const SDKEvents_1 = require("./SDKEvents");
let configs = {};
let gameId;
let noRewardedAd = false;
function setNoRewaredAd() {
noRewardedAd = true;
}
exports.setNoRewaredAd = setNoRewaredAd;
function initShareConfig(SDKConfig) {
gameId = SDKConfig.gameId;
return new Promise(async (resolve, reject) => {
(new simba_httpclient_1.HttpClient(SDKConfig.shareConfigUrl)).get("").then((ret) => {
try {
configs = JSON.parse(ret);
for (let key in configs) {
if (configs[key]["ref"]) {
configs[key] = configs[configs[key]["ref"]];
}
}
resolve({});
}
catch (e) {
reject(e);
}
}).catch((e) => {
reject(e);
});
});
}
exports.initShareConfig = initShareConfig;
function initShareConfigV2(gId, url) {
gameId = gId;
return new Promise(async (resolve, reject) => {
(new simba_httpclient_1.HttpClient(url)).get("").then((ret) => {
try {
configs = JSON.parse(ret);
for (let key in configs) {
if (configs[key]["ref"]) {
configs[key] = configs[configs[key]["ref"]];
}
}
resolve({});
}
catch (e) {
reject(e);
}
}).catch((e) => {
reject(e);
});
});
}
exports.initShareConfigV2 = initShareConfigV2;
let svData;
function getSVConfigById(svPointId) {
return configs[svPointId];
}
exports.getSVConfigById = getSVConfigById;
function getShareContent(svPointId) {
let config = configs[svPointId];
if (config) {
function getTitleAndImage() {
let titleIdx = Math.floor(simba_random_1.Random.range(0, config.titles.length));
if (config.syncTitleAndImage) {
return { title: config.titles[titleIdx], imageUrl: config.imageUrls[titleIdx], urlId: config.imageUrls[titleIdx].urlId };
}
else {
let imageIdx = Math.floor(simba_random_1.Random.range(0, config.imageUrls.length));
return { title: config.titles[titleIdx], imageUrl: config.imageUrls[imageIdx], urlId: config.imageUrls[titleIdx].urlId };
}
}
return Object.assign({}, getTitleAndImage());
}
throw new Error("Invalid share point " + svPointId);
}
exports.getShareContent = getShareContent;
function getSVPointById(svPointId, forceShare) {
let config = configs[svPointId];
if (config) {
// function getTitleAndImage() {
// let titleIdx = Math.floor(Random.range(0, config.titles.length));
// if (config.syncTitleAndImage) {
// return { title: config.titles[titleIdx], imageUrl: config.imageUrls[titleIdx] };
// } else {
// let imageIdx = Math.floor(Random.range(0, config.imageUrls.length));
// return { title: config.titles[titleIdx], imageUrl: config.imageUrls[imageIdx] };
// }
// }
let percent = forceShare ? 100 : config.sharePercent;
if (config.sharePercents.length && !forceShare) {
svData = svData || simba_localstorage_1.LocalStorage.getObject(gameId + "-sv-data", {});
let count = 0;
if (!svData[svPointId]) {
svData[svPointId].count = 0;
}
count = svData[svPointId].count;
if (count < config.sharePercents.length) {
percent = config.sharePercents[count];
svData[svPointId].count = count + 1;
simba_localstorage_1.LocalStorage.setObject(gameId + "-sv-data", svData);
}
}
if (noRewardedAd) {
if (config.disableShareFallback) {
SDKEvents_1.SDKEvents.SDKError.emit(0 /* NO_REWARDED_VIDEO_AVAILABLE */);
return undefined;
}
percent = 100;
}
if (percent === 0) {
return { id: svPointId, type: "video", disableShareFallback: config.disableShareFallback };
}
else if (percent === 100) {
return { id: svPointId, type: "share" };
}
else {
let p = simba_random_1.Random.range(0, 100);
if (p < percent) {
return { id: svPointId, type: "share" };
}
else {
return { id: svPointId, type: "video" };
}
}
}
else {
throw new Error("Invalid share/video point " + svPointId);
}
}
exports.getSVPointById = getSVPointById;
export declare namespace TimeManager {
function init(_useLocalTime: boolean): Promise<void>;
function onLogin(sdkRecord: any): Promise<void>;
function getTimeRecord(): any;
function getGameTime(): number;
function getTodayGameTime(): number;
function getTotalGameTime(): number;
function getTime(): number;
function syncTime(): Promise<void>;
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TimeManager = void 0;
const SDKServer_1 = require("./SDKServer");
const SDKEvents_1 = require("./SDKEvents");
const SDKBase_1 = require("./SDKBase");
var TimeManager;
(function (TimeManager) {
let loginTime = 0;
let currDate = 0;
let todayGameTime = 0;
let todayGameFromZero = false;
let totalGameTime = 0;
let timeOffset = 0;
let useLocalTime = false;
let lastSyncTime = 0;
async function init(_useLocalTime) {
useLocalTime = _useLocalTime;
}
TimeManager.init = init;
async function onLogin(sdkRecord) {
console.log("TimeManager onLogin,start to syncTime");
await syncTime();
loginTime = getTime();
let time = new Date(loginTime);
currDate = time.getDate();
if (sdkRecord["game_time"]) {
let timeStr = `${time.getFullYear()}${time.getMonth()}${time.getDate()}`;
todayGameTime = sdkRecord["game_time"][timeStr];
totalGameTime = sdkRecord["game_time"]["total"];
}
setInterval(() => {
syncTime();
}, 30000);
}
TimeManager.onLogin = onLogin;
function getTimeRecord() {
let time = new Date(getTime());
let timeStr = `${time.getFullYear()}${time.getMonth()}${time.getDate()}`;
let ret = {
total: getTotalGameTime()
};
ret[timeStr] = getTodayGameTime();
return ret;
}
TimeManager.getTimeRecord = getTimeRecord;
function getGameTime() {
return getTime() - loginTime - appInBgDuration;
}
TimeManager.getGameTime = getGameTime;
function getTodayGameTime() {
let time = new Date(loginTime);
let date = time.getDate();
if (!todayGameFromZero && currDate !== date) {
currDate = date;
todayGameFromZero = true;
}
if (todayGameFromZero) { // 登录后跨天
return (time.getHours() * 3600 + time.getMinutes() * 60 + time.getSeconds()) * 1000;
}
return todayGameTime + getGameTime();
}
TimeManager.getTodayGameTime = getTodayGameTime;
function getTotalGameTime() {
return totalGameTime + getGameTime();
}
TimeManager.getTotalGameTime = getTotalGameTime;
function getTime() {
return Date.now() + timeOffset;
}
TimeManager.getTime = getTime;
async function syncTime() {
console.log("syncTime");
if (useLocalTime) {
SDKEvents_1.SDKEvents.OnTimeSync.emit();
console.log("syncTime useLocalTime, will return");
return;
}
let l1 = lastSyncTime = Date.now();
console.log("syncTime gettime from server ");
let ret = JSON.parse(await SDKServer_1.default.timeServer.get(""));
if (SDKBase_1.V2) {
if (ret["time"]) {
let s = ret["time"];
let l2 = Math.round((Date.now() + l1) / 2 / 1000) * 1000;
timeOffset = s - l2;
}
}
else {
if (ret.code === "0") {
let s = ret.obj.unix_time * 1000;
let l2 = Math.round((Date.now() + l1) / 2 / 1000) * 1000;
timeOffset = s - l2;
}
}
SDKEvents_1.SDKEvents.OnTimeSync.emit();
}
TimeManager.syncTime = syncTime;
let appHideTime = 0;
let appInBgDuration = 0;
SDKEvents_1.SDKEvents.AppHide.on(() => {
appHideTime = getTime();
});
SDKEvents_1.SDKEvents.AppShow.on(async () => {
await syncTime();
if (appHideTime > 0) {
appInBgDuration += getTime() - appHideTime;
appHideTime = 0;
}
});
})(TimeManager = exports.TimeManager || (exports.TimeManager = {}));
import { SDKBase } from "./SDKBase";
import { SDKConfigType, SDKConfigTypeV2 } from "./SDKTypes";
import { SDKEvents } from "./SDKEvents";
import { TimeManager } from "./TimeManager";
export declare let SDK: SDKBase;
export declare function setSDKConfig(config: SDKConfigType, sdk: {
new (): SDKBase;
}): void;
export { SDKBase, SDKConfigType, SDKEvents, TimeManager };
export declare function setSDKConfigV2(config: SDKConfigTypeV2, sdk: {
new (): SDKBase;
}): void;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.setSDKConfigV2 = exports.TimeManager = exports.SDKEvents = exports.SDKBase = exports.setSDKConfig = exports.SDK = void 0;
const SDKBase_1 = require("./SDKBase");
Object.defineProperty(exports, "SDKBase", { enumerable: true, get: function () { return SDKBase_1.SDKBase; } });
const SDKEvents_1 = require("./SDKEvents");
Object.defineProperty(exports, "SDKEvents", { enumerable: true, get: function () { return SDKEvents_1.SDKEvents; } });
const TimeManager_1 = require("./TimeManager");
Object.defineProperty(exports, "TimeManager", { enumerable: true, get: function () { return TimeManager_1.TimeManager; } });
function setSDKConfig(config, sdk) {
SDKBase_1.setConfig(config);
exports.SDK = new sdk;
}
exports.setSDKConfig = setSDKConfig;
//v2
function setSDKConfigV2(config, sdk) {
SDKBase_1.setConfigV2(config);
exports.SDK = new sdk;
}
exports.setSDKConfigV2 = setSDKConfigV2;
{
"name": "simba-sdk",
"version": "1.0.49",
"description": "game sdk for mini games",
"main": "./dist/index.js",
"scripts": {
"build": "tsc",
"install-deps-local": "npm --registry http://repository.icesimba.cn:10412/repository/npm-group/ install",
"pub-local": "tsc && npm publish --registry=http://repository.icesimba.cn:10412/repository/npm-hosted/",
"pub": "tsc && npm publish --registry=http://repository.icesimba.com:8081/repository/npm-hosted/"
},
"author": "",
"license": "ISC",
"dependencies": {
"simba-eventkit": "^1.0.0",
"simba-httpclient": "^1.0.0",
"simba-localstorage": "^1.0.0",
"simba-random": "^1.0.0",
"simba-utils": "^1.0.3"
}
}
export = A;
declare function A(n: any, t: any, r: any): string;
!function (n) {
"use strict";
function t(n, t) { var r = (65535 & n) + (65535 & t), e = (n >> 16) + (t >> 16) + (r >> 16); return e << 16 | 65535 & r; }
function r(n, t) { return n << t | n >>> 32 - t; }
function e(n, e, o, u, c, f) { return t(r(t(t(e, n), t(u, f)), c), o); }
function o(n, t, r, o, u, c, f) { return e(t & r | ~t & o, n, t, u, c, f); }
function u(n, t, r, o, u, c, f) { return e(t & o | r & ~o, n, t, u, c, f); }
function c(n, t, r, o, u, c, f) { return e(t ^ r ^ o, n, t, u, c, f); }
function f(n, t, r, o, u, c, f) { return e(r ^ (t | ~o), n, t, u, c, f); }
function i(n, r) { n[r >> 5] |= 128 << r % 32, n[(r + 64 >>> 9 << 4) + 14] = r; var e, i, a, h, d, l = 1732584193, g = -271733879, v = -1732584194, m = 271733878; for (e = 0; e < n.length; e += 16)
i = l, a = g, h = v, d = m, l = o(l, g, v, m, n[e], 7, -680876936), m = o(m, l, g, v, n[e + 1], 12, -389564586), v = o(v, m, l, g, n[e + 2], 17, 606105819), g = o(g, v, m, l, n[e + 3], 22, -1044525330), l = o(l, g, v, m, n[e + 4], 7, -176418897), m = o(m, l, g, v, n[e + 5], 12, 1200080426), v = o(v, m, l, g, n[e + 6], 17, -1473231341), g = o(g, v, m, l, n[e + 7], 22, -45705983), l = o(l, g, v, m, n[e + 8], 7, 1770035416), m = o(m, l, g, v, n[e + 9], 12, -1958414417), v = o(v, m, l, g, n[e + 10], 17, -42063), g = o(g, v, m, l, n[e + 11], 22, -1990404162), l = o(l, g, v, m, n[e + 12], 7, 1804603682), m = o(m, l, g, v, n[e + 13], 12, -40341101), v = o(v, m, l, g, n[e + 14], 17, -1502002290), g = o(g, v, m, l, n[e + 15], 22, 1236535329), l = u(l, g, v, m, n[e + 1], 5, -165796510), m = u(m, l, g, v, n[e + 6], 9, -1069501632), v = u(v, m, l, g, n[e + 11], 14, 643717713), g = u(g, v, m, l, n[e], 20, -373897302), l = u(l, g, v, m, n[e + 5], 5, -701558691), m = u(m, l, g, v, n[e + 10], 9, 38016083), v = u(v, m, l, g, n[e + 15], 14, -660478335), g = u(g, v, m, l, n[e + 4], 20, -405537848), l = u(l, g, v, m, n[e + 9], 5, 568446438), m = u(m, l, g, v, n[e + 14], 9, -1019803690), v = u(v, m, l, g, n[e + 3], 14, -187363961), g = u(g, v, m, l, n[e + 8], 20, 1163531501), l = u(l, g, v, m, n[e + 13], 5, -1444681467), m = u(m, l, g, v, n[e + 2], 9, -51403784), v = u(v, m, l, g, n[e + 7], 14, 1735328473), g = u(g, v, m, l, n[e + 12], 20, -1926607734), l = c(l, g, v, m, n[e + 5], 4, -378558), m = c(m, l, g, v, n[e + 8], 11, -2022574463), v = c(v, m, l, g, n[e + 11], 16, 1839030562), g = c(g, v, m, l, n[e + 14], 23, -35309556), l = c(l, g, v, m, n[e + 1], 4, -1530992060), m = c(m, l, g, v, n[e + 4], 11, 1272893353), v = c(v, m, l, g, n[e + 7], 16, -155497632), g = c(g, v, m, l, n[e + 10], 23, -1094730640), l = c(l, g, v, m, n[e + 13], 4, 681279174), m = c(m, l, g, v, n[e], 11, -358537222), v = c(v, m, l, g, n[e + 3], 16, -722521979), g = c(g, v, m, l, n[e + 6], 23, 76029189), l = c(l, g, v, m, n[e + 9], 4, -640364487), m = c(m, l, g, v, n[e + 12], 11, -421815835), v = c(v, m, l, g, n[e + 15], 16, 530742520), g = c(g, v, m, l, n[e + 2], 23, -995338651), l = f(l, g, v, m, n[e], 6, -198630844), m = f(m, l, g, v, n[e + 7], 10, 1126891415), v = f(v, m, l, g, n[e + 14], 15, -1416354905), g = f(g, v, m, l, n[e + 5], 21, -57434055), l = f(l, g, v, m, n[e + 12], 6, 1700485571), m = f(m, l, g, v, n[e + 3], 10, -1894986606), v = f(v, m, l, g, n[e + 10], 15, -1051523), g = f(g, v, m, l, n[e + 1], 21, -2054922799), l = f(l, g, v, m, n[e + 8], 6, 1873313359), m = f(m, l, g, v, n[e + 15], 10, -30611744), v = f(v, m, l, g, n[e + 6], 15, -1560198380), g = f(g, v, m, l, n[e + 13], 21, 1309151649), l = f(l, g, v, m, n[e + 4], 6, -145523070), m = f(m, l, g, v, n[e + 11], 10, -1120210379), v = f(v, m, l, g, n[e + 2], 15, 718787259), g = f(g, v, m, l, n[e + 9], 21, -343485551), l = t(l, i), g = t(g, a), v = t(v, h), m = t(m, d); return [l, g, v, m]; }
function a(n) { var t, r = "", e = 32 * n.length; for (t = 0; t < e; t += 8)
r += String.fromCharCode(n[t >> 5] >>> t % 32 & 255); return r; }
function h(n) { var t, r = []; for (r[(n.length >> 2) - 1] = void 0, t = 0; t < r.length; t += 1)
r[t] = 0; var e = 8 * n.length; for (t = 0; t < e; t += 8)
r[t >> 5] |= (255 & n.charCodeAt(t / 8)) << t % 32; return r; }
function d(n) { return a(i(h(n), 8 * n.length)); }
function l(n, t) { var r, e, o = h(n), u = [], c = []; for (u[15] = c[15] = void 0, o.length > 16 && (o = i(o, 8 * n.length)), r = 0; r < 16; r += 1)
u[r] = 909522486 ^ o[r], c[r] = 1549556828 ^ o[r]; return e = i(u.concat(h(t)), 512 + 8 * t.length), a(i(c.concat(e), 640)); }
function g(n) { var t, r, e = "0123456789abcdef", o = ""; for (r = 0; r < n.length; r += 1)
t = n.charCodeAt(r), o += e.charAt(t >>> 4 & 15) + e.charAt(15 & t); return o; }
function v(n) { return unescape(encodeURIComponent(n)); }
function m(n) { return d(v(n)); }
function p(n) { return g(m(n)); }
function s(n, t) { return l(v(n), v(t)); }
function C(n, t) { return g(s(n, t)); }
function A(n, t, r) { return t ? r ? s(t, n) : C(t, n) : r ? m(n) : p(n); }
"function" == typeof define && define.amd ? define(function () { return A; }) : "object" == typeof module && module.exports ? module.exports = A : n.md5 = A;
}(this);
export declare type DeepReadonly<T> = T extends (infer R)[] ? DeepReadonlyArray<R> : T extends Function ? T : T extends object ? DeepReadonlyObject<T> : T;
export interface DeepReadonlyArray<T> extends ReadonlyArray<DeepReadonly<T>> {
}
export declare type DeepReadonlyObject<T> = {
readonly [P in keyof T]: DeepReadonly<T[P]>;
};
export declare function delay(timeSecond: number): Promise<void>;
export declare function deepCopy<T>(obj: T): T;
export declare function deepFreeze<T>(obj: T): DeepReadonly<T>;
export declare function shallowEqual(objA: any, objB: any): boolean;
export declare function deepEqual(x: any, y: any): boolean;
/**
* @param [wait] - A zero-or-greater delay in milliseconds. For event callbacks, values around 100 or 250 (or even higher) are most useful.
* @param [noTrailing] - Optional, defaults to false. If noTrailing is true, callback will only execute every `delay` milliseconds while the
* throttled-function is being called. If noTrailing is false or unspecified, callback will be executed one final time
* after the last throttled-function call. (After the throttled-function has not been called for `delay` milliseconds,
* the internal counter is reset).
*/
export declare function throttle<T extends Function>(func: T, wait?: number, immediate?: boolean, noTrailing?: boolean): T & {
clear: () => void;
};
export declare function debounce<T extends Function>(func: T, wait?: number, immediate?: boolean): T & {
clear: () => void;
flush: () => void;
};
export declare function uniqArray<T>(array: T[]): T[];
export declare function assign(object: any, obj2: any): any;
export declare function assignM(object: any, ...objs: any[]): any;
export declare function md5(str: string): string;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
async function delay(timeSecond) {
return new Promise(resolve => {
setTimeout(() => {
resolve();
}, timeSecond * 1000);
});
}
exports.delay = delay;
function deepCopy(obj) {
return JSON.parse(JSON.stringify(obj));
}
exports.deepCopy = deepCopy;
function deepFreeze(obj) {
let propNames = Object.getOwnPropertyNames(obj);
propNames.forEach((name) => {
let prop = obj[name];
if (typeof prop == 'object' && prop !== null)
deepFreeze(prop);
});
return Object.freeze(obj);
}
exports.deepFreeze = deepFreeze;
// 这个函数实际上是Object.is()的polyfill
function is(x, y) {
if (x === y) {
return x !== 0 || y !== 0 || 1 / x === 1 / y;
}
else {
return x !== x && y !== y;
}
}
function shallowEqual(objA, objB) {
// 首先对基本数据类型的比较
if (is(objA, objB))
return true;
// 由于Obejct.is()可以对基本数据类型做一个精确的比较, 所以如果不等
// 只有一种情况是误判的,那就是object,所以在判断两个对象都不是object
// 之后,就可以返回false了
if (typeof objA !== 'object' || objA === null ||
typeof objB !== 'object' || objB === null) {
return false;
}
// 过滤掉基本数据类型之后,就是对对象的比较了
// 首先拿出key值,对key的长度进行对比
const keysA = Object.keys(objA);
const keysB = Object.keys(objB);
// 长度不等直接返回false
if (keysA.length !== keysB.length)
return false;
// key相等的情况下,在去循环比较
for (let i = 0; i < keysA.length; i++) {
// key值相等的时候
// 借用原型链上真正的 hasOwnProperty 方法,判断ObjB里面是否有A的key的key值
// 属性的顺序不影响结果也就是{name:'daisy', age:'24'} 跟{age:'24',name:'daisy' }是一样的
// 最后,对对象的value进行一个基本数据类型的比较,返回结果
if (!Object.prototype.hasOwnProperty.call(objB, keysA[i]) ||
!is(objA[keysA[i]], objB[keysA[i]])) {
return false;
}
}
return true;
}
exports.shallowEqual = shallowEqual;
function deepEqual(x, y) {
if (x === y) {
return true;
}
else if ((typeof x == "object" && x != null) && (typeof y == "object" && y != null)) {
if (Object.keys(x).length != Object.keys(y).length)
return false;
for (var prop in x) {
if (y.hasOwnProperty(prop)) {
if (!deepEqual(x[prop], y[prop]))
return false;
}
else
return false;
}
return true;
}
else
return false;
}
exports.deepEqual = deepEqual;
/**
* @param [wait] - A zero-or-greater delay in milliseconds. For event callbacks, values around 100 or 250 (or even higher) are most useful.
* @param [noTrailing] - Optional, defaults to false. If noTrailing is true, callback will only execute every `delay` milliseconds while the
* throttled-function is being called. If noTrailing is false or unspecified, callback will be executed one final time
* after the last throttled-function call. (After the throttled-function has not been called for `delay` milliseconds,
* the internal counter is reset).
*/
function throttle(func, wait = 100, immediate = false, noTrailing = false) {
let timeoutID;
let cancelled = false;
let lastExec = 0;
function clearExistingTimeout() {
if (timeoutID) {
clearTimeout(timeoutID);
timeoutID = undefined;
}
}
function cancel() {
clearExistingTimeout();
cancelled = true;
}
if (!noTrailing) {
}
let wrapper = function (...arguments_) {
let self = this;
let elapsed = lastExec ? Date.now() - lastExec : 0;
if (cancelled)
return;
function exec() {
lastExec = Date.now();
func.apply(self, arguments_);
}
function clear() {
timeoutID = undefined;
}
if (immediate) {
if (!timeoutID) {
exec();
timeoutID = setTimeout(clear, wait);
}
else {
clearExistingTimeout();
if (noTrailing) {
timeoutID = setTimeout(clear, wait - elapsed);
}
else {
timeoutID = setTimeout(() => { exec(); timeoutID = setTimeout(clear, wait); }, wait - elapsed);
}
}
}
else {
if (!timeoutID) {
lastExec = Date.now();
timeoutID = setTimeout(exec, wait);
}
else {
clearExistingTimeout();
timeoutID = setTimeout(exec, wait - elapsed);
}
}
};
wrapper.cancel = cancel;
return wrapper;
}
exports.throttle = throttle;
function debounce(func, wait = 100, immediate = false) {
let timer, args, context, timestamp, result;
function later() {
let last = Date.now() - timestamp;
if (last < wait && last >= 0) {
timer = setTimeout(later, wait - last);
}
else {
timer = null;
if (!immediate) {
result = func.apply(context, args);
context = args = null;
}
}
}
;
let debounced = function () {
context = this;
args = arguments;
timestamp = Date.now();
let callNow = immediate && !timer;
if (!timer)
timer = setTimeout(later, wait);
if (callNow) {
result = func.apply(context, args);
context = args = null;
}
return result;
};
debounced.clear = function () {
if (timer) {
clearTimeout(timer);
timer = null;
}
};
debounced.flush = function () {
if (timer) {
result = func.apply(context, args);
context = args = null;
clearTimeout(timer);
timer = null;
}
};
return debounced;
}
exports.debounce = debounce;
function uniqArray(array) {
let temp = [];
for (var i = 0; i < array.length; i++) {
if (temp.indexOf(array[i]) == -1) {
temp.push(array[i]);
}
}
return temp;
}
exports.uniqArray = uniqArray;
//合并两个对象到一起.
function assign(object, obj2) {
object = object || {};
if (!object.assign) {
Object.defineProperty(object, "assign", {
enumerable: false,
configurable: true,
writable: true,
value: function (target, firstSource) {
"use strict";
if (target === undefined || target === null)
throw new TypeError("Cannot convert first argument to object");
var to = Object(target);
for (var i = 1; i < arguments.length; i++) {
var nextSource = arguments[i];
if (nextSource === undefined || nextSource === null)
continue;
var keysArray = Object.keys(Object(nextSource));
for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
var nextKey = keysArray[nextIndex];
var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
if (desc !== undefined && desc.enumerable)
to[nextKey] = nextSource[nextKey];
}
}
return to;
}
});
}
if (!obj2) {
return object;
}
return object.assign(object, obj2);
}
exports.assign = assign;
//合并多个对象到一起.
function assignM(object, ...objs) {
console.log("合并对象:", objs);
let ret = object;
for (let i in objs) {
ret = assign(ret, objs[i]);
}
return ret;
}
exports.assignM = assignM;
function md5(str) {
return require("./Md5")(str);
}
exports.md5 = md5;
{
"name": "simba-utils",
"version": "1.0.5",
"description": "Utility ts/js functions",
"main": "./dist/index.js",
"scripts": {
"build": "tsc"
},
"author": "",
"license": "ISC"
}
\ No newline at end of file
{
"name": "simba-sdk-android-native",
"version": "1.0.7",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "simba-sdk-android-native",
"version": "1.0.7",
"license": "ISC",
"dependencies": {
"simba-sdk": "^1.0.49"
}
},
"node_modules/simba-eventkit": {
"version": "1.0.1",
"resolved": "http://repository.icesimba.cn/repository/npm-group/simba-eventkit/-/simba-eventkit-1.0.1.tgz",
"integrity": "sha512-UX1lZEOm109MTnKp3OMDS+bSdI46ybiG0k5U1WV5aD5TeanWD06U7p1ec9SqJmbfTmUuUHtsrRCclmhgkJbNgA==",
"license": "ISC"
},
"node_modules/simba-httpclient": {
"version": "1.0.3",
"resolved": "http://repository.icesimba.cn/repository/npm-group/simba-httpclient/-/simba-httpclient-1.0.3.tgz",
"integrity": "sha512-aNuWyaHyFALsDWajZdmYuDETE64TlL7c2W01czCs8r8QLED56i+nqX7DAf7KmozH5R7Dl0o+gK0J4BAzYVOX/A==",
"license": "ISC"
},
"node_modules/simba-localstorage": {
"version": "1.0.0",
"resolved": "http://repository.icesimba.cn/repository/npm-group/simba-localstorage/-/simba-localstorage-1.0.0.tgz",
"integrity": "sha512-3eE8VB4Y32E97OPgmSnyPFTbVUHeIWLXvgBK9ljQCk5nvGevSPyfa821Fcsl0xdFVGbOzWsdGp3fAxaE9sJLxg==",
"license": "ISC"
},
"node_modules/simba-random": {
"version": "1.0.0",
"resolved": "http://repository.icesimba.cn/repository/npm-group/simba-random/-/simba-random-1.0.0.tgz",
"integrity": "sha512-54k04C5iM2hlZX3zgbl0zWrIVLLkB7TmKB1hkcKS7YROziVkbBrwzaMSXjmq2DbiANUxk6bEvmZlgEn3o8qsLA==",
"license": "ISC"
},
"node_modules/simba-sdk": {
"version": "1.0.49",
"resolved": "http://repository.icesimba.cn/repository/npm-group/simba-sdk/-/simba-sdk-1.0.49.tgz",
"integrity": "sha512-RegEvmcrgH0S0Xbph6HoCPQBSGh2YvwiPIkzQ/doYeiDS+8PNUOjwtFZBMmI8GTKvWVqyDy3nb2+4iWpbe3kEQ==",
"license": "ISC",
"dependencies": {
"simba-eventkit": "^1.0.0",
"simba-httpclient": "^1.0.0",
"simba-localstorage": "^1.0.0",
"simba-random": "^1.0.0",
"simba-utils": "^1.0.3"
}
},
"node_modules/simba-utils": {
"version": "1.0.5",
"resolved": "http://repository.icesimba.cn/repository/npm-group/simba-utils/-/simba-utils-1.0.5.tgz",
"integrity": "sha512-BkjSdISzBKOl11Q2rTrkOQyn+gQH5jbr5mO2Va5lGxFpd6mYsPcry6alwO+04D518B39ftFYcZ3v6lPsQ1CnRA==",
"license": "ISC"
}
},
"dependencies": {
"simba-eventkit": {
"version": "1.0.1",
"resolved": "http://repository.icesimba.cn/repository/npm-group/simba-eventkit/-/simba-eventkit-1.0.1.tgz",
"integrity": "sha512-UX1lZEOm109MTnKp3OMDS+bSdI46ybiG0k5U1WV5aD5TeanWD06U7p1ec9SqJmbfTmUuUHtsrRCclmhgkJbNgA=="
},
"simba-httpclient": {
"version": "1.0.3",
"resolved": "http://repository.icesimba.cn/repository/npm-group/simba-httpclient/-/simba-httpclient-1.0.3.tgz",
"integrity": "sha512-aNuWyaHyFALsDWajZdmYuDETE64TlL7c2W01czCs8r8QLED56i+nqX7DAf7KmozH5R7Dl0o+gK0J4BAzYVOX/A=="
},
"simba-localstorage": {
"version": "1.0.0",
"resolved": "http://repository.icesimba.cn/repository/npm-group/simba-localstorage/-/simba-localstorage-1.0.0.tgz",
"integrity": "sha512-3eE8VB4Y32E97OPgmSnyPFTbVUHeIWLXvgBK9ljQCk5nvGevSPyfa821Fcsl0xdFVGbOzWsdGp3fAxaE9sJLxg=="
},
"simba-random": {
"version": "1.0.0",
"resolved": "http://repository.icesimba.cn/repository/npm-group/simba-random/-/simba-random-1.0.0.tgz",
"integrity": "sha512-54k04C5iM2hlZX3zgbl0zWrIVLLkB7TmKB1hkcKS7YROziVkbBrwzaMSXjmq2DbiANUxk6bEvmZlgEn3o8qsLA=="
},
"simba-sdk": {
"version": "1.0.49",
"resolved": "http://repository.icesimba.cn/repository/npm-group/simba-sdk/-/simba-sdk-1.0.49.tgz",
"integrity": "sha512-RegEvmcrgH0S0Xbph6HoCPQBSGh2YvwiPIkzQ/doYeiDS+8PNUOjwtFZBMmI8GTKvWVqyDy3nb2+4iWpbe3kEQ==",
"requires": {
"simba-eventkit": "^1.0.0",
"simba-httpclient": "^1.0.0",
"simba-localstorage": "^1.0.0",
"simba-random": "^1.0.0",
"simba-utils": "^1.0.3"
}
},
"simba-utils": {
"version": "1.0.5",
"resolved": "http://repository.icesimba.cn/repository/npm-group/simba-utils/-/simba-utils-1.0.5.tgz",
"integrity": "sha512-BkjSdISzBKOl11Q2rTrkOQyn+gQH5jbr5mO2Va5lGxFpd6mYsPcry6alwO+04D518B39ftFYcZ3v6lPsQ1CnRA=="
}
}
}
{
"name": "simba-sdk-android-native",
"version": "1.0.7",
"description": "Android native channel implement for simba-sdk",
"main": "./dist/index.js",
"scripts": {
"build": "tsc",
"install-deps-local": "npm --registry http://repository.icesimba.cn/repository/npm-group/ install"
},
"author": "",
"license": "ISC",
"dependencies": {
"simba-sdk": "^1.0.49"
}
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!