Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@gaoding/editor-sdk

Package Overview
Dependencies
Maintainers
22
Versions
92
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@gaoding/editor-sdk - npm Package Compare versions

Comparing version 1.1.0-alpha.0 to 1.1.0

src/request.ts

1098

dist/editor-sdk.cjs.js

@@ -368,3 +368,3 @@ "use strict";

frame.setAttribute("frameborder", "0");
frame.src = `${url}?${Object.entries(query).filter(([k, v]) => v !== void 0).map(([k, v]) => `${k}=${v}`).join("&")}`;
frame.src = `${url}?${Object.entries(query).filter(([_, v]) => v !== void 0).map(([k, v]) => `${k}=${v}`).join("&")}`;
const wrapper = document.createElement("div");

@@ -430,2 +430,4 @@ wrapper.style.cssText = `

function toggleScrollSwitch() {
if (hide)
return;
const dom = document.querySelector(".gaoding-editor-iframe-dialog");

@@ -470,4 +472,5 @@ if (!dom)

TEMPLATE_EDITOR_URL: "https://open.gaoding.com/design",
KOUTU_EDITOR_URL: "https://open.gaoding.com/open-clip",
IMAGE_EDITOR_URL: "https://open.gaoding.com/design/image"
KOUTU_EDITOR_URL: "https://open.gaoding.com/clip",
IMAGE_EDITOR_URL: "https://open.gaoding.com/design/image",
OPEN_PLATFORM_ORIGIN: "https://open.gaoding.com"
};

@@ -496,4 +499,8 @@ const defineConfig$2 = {

async function openTemplate(config2) {
assert(!!(config2 == null ? void 0 : config2.id), "openTemplate \u7F3A\u5C11 id \u53C2\u6570");
return new Promise((resolve) => {
assert(!!(config2 == null ? void 0 : config2.categoryId) || !!(config2 == null ? void 0 : config2.id), "openTemplate \u7F3A\u5C11 id \u6216\u8005 categoryId \u53C2\u6570");
let code = "";
if (isAdvancedConfig(c)) {
code = await c.getUserCode();
}
return new Promise((resolve, reject) => {
const q = Object.assign({ version: "TE001" }, query, { id: config2.id, thirdCateId: config2.categoryId });

@@ -528,3 +535,13 @@ const { open, iframe, close } = createIframe(env.TEMPLATE_EDITOR_URL, q, () => resolve(false));

async getUserCode() {
return isAdvancedConfig(c) ? c.getUserCode() : false;
if (code) {
const key = code;
code = "";
return key;
}
try {
return isAdvancedConfig(c) ? c.getUserCode() : false;
} catch (error) {
reject(error);
close();
}
},

@@ -540,4 +557,4 @@ async download(info) {

}
async function create(options = {}) {
return new Promise((resolve) => {
async function create2(options = {}) {
return new Promise((resolve, reject) => {
const q = Object.assign({ version: "TE001" }, query, { thirdCateId: options.categoryId, mode: "create", width: options.width, height: options.height });

@@ -571,3 +588,8 @@ const { open, iframe, close } = createIframe(env.TEMPLATE_EDITOR_URL, q, () => resolve(false));

async getUserCode() {
return isAdvancedConfig(c) ? c.getUserCode() : false;
try {
return isAdvancedConfig(c) ? c.getUserCode() : false;
} catch (error) {
reject(error);
close();
}
},

@@ -585,3 +607,3 @@ async download(info) {

async function importFile(config2 = {}) {
return new Promise((resolve) => {
return new Promise((resolve, reject) => {
const q = Object.assign({ version: "TE001" }, query, { app_id: c.appId, mode: "psd" });

@@ -615,3 +637,8 @@ const { open, close, iframe } = createIframe(`${env.TEMPLATE_EDITOR_URL}`, q, () => resolve(false));

async getUserCode() {
return isAdvancedConfig(c) ? c.getUserCode() : false;
try {
return isAdvancedConfig(c) ? c.getUserCode() : false;
} catch (error) {
reject(error);
close();
}
},

@@ -630,6 +657,904 @@ async download(info) {

importFile,
create,
create: create2,
openTemplate
};
}
function handleFunsErrors(methods) {
return Object.keys(methods).reduce((nweMethods, key) => {
nweMethods[key] = async function(...args) {
try {
return await methods[key](...args);
} catch (error) {
return {
type: "error",
message: error.message
};
}
};
return nweMethods;
}, {});
}
var axios$2 = { exports: {} };
var bind$2 = function bind2(fn, thisArg) {
return function wrap() {
var args = new Array(arguments.length);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i];
}
return fn.apply(thisArg, args);
};
};
var bind$1 = bind$2;
var toString = Object.prototype.toString;
function isArray(val) {
return toString.call(val) === "[object Array]";
}
function isUndefined(val) {
return typeof val === "undefined";
}
function isBuffer(val) {
return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && typeof val.constructor.isBuffer === "function" && val.constructor.isBuffer(val);
}
function isArrayBuffer(val) {
return toString.call(val) === "[object ArrayBuffer]";
}
function isFormData(val) {
return typeof FormData !== "undefined" && val instanceof FormData;
}
function isArrayBufferView(val) {
var result;
if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) {
result = ArrayBuffer.isView(val);
} else {
result = val && val.buffer && val.buffer instanceof ArrayBuffer;
}
return result;
}
function isString(val) {
return typeof val === "string";
}
function isNumber(val) {
return typeof val === "number";
}
function isObject(val) {
return val !== null && typeof val === "object";
}
function isPlainObject(val) {
if (toString.call(val) !== "[object Object]") {
return false;
}
var prototype = Object.getPrototypeOf(val);
return prototype === null || prototype === Object.prototype;
}
function isDate(val) {
return toString.call(val) === "[object Date]";
}
function isFile(val) {
return toString.call(val) === "[object File]";
}
function isBlob(val) {
return toString.call(val) === "[object Blob]";
}
function isFunction(val) {
return toString.call(val) === "[object Function]";
}
function isStream(val) {
return isObject(val) && isFunction(val.pipe);
}
function isURLSearchParams(val) {
return typeof URLSearchParams !== "undefined" && val instanceof URLSearchParams;
}
function trim(str) {
return str.replace(/^\s*/, "").replace(/\s*$/, "");
}
function isStandardBrowserEnv() {
if (typeof navigator !== "undefined" && (navigator.product === "ReactNative" || navigator.product === "NativeScript" || navigator.product === "NS")) {
return false;
}
return typeof window !== "undefined" && typeof document !== "undefined";
}
function forEach(obj, fn) {
if (obj === null || typeof obj === "undefined") {
return;
}
if (typeof obj !== "object") {
obj = [obj];
}
if (isArray(obj)) {
for (var i = 0, l = obj.length; i < l; i++) {
fn.call(null, obj[i], i, obj);
}
} else {
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
fn.call(null, obj[key], key, obj);
}
}
}
}
function merge() {
var result = {};
function assignValue(val, key) {
if (isPlainObject(result[key]) && isPlainObject(val)) {
result[key] = merge(result[key], val);
} else if (isPlainObject(val)) {
result[key] = merge({}, val);
} else if (isArray(val)) {
result[key] = val.slice();
} else {
result[key] = val;
}
}
for (var i = 0, l = arguments.length; i < l; i++) {
forEach(arguments[i], assignValue);
}
return result;
}
function extend(a, b, thisArg) {
forEach(b, function assignValue(val, key) {
if (thisArg && typeof val === "function") {
a[key] = bind$1(val, thisArg);
} else {
a[key] = val;
}
});
return a;
}
function stripBOM(content) {
if (content.charCodeAt(0) === 65279) {
content = content.slice(1);
}
return content;
}
var utils$d = {
isArray,
isArrayBuffer,
isBuffer,
isFormData,
isArrayBufferView,
isString,
isNumber,
isObject,
isPlainObject,
isUndefined,
isDate,
isFile,
isBlob,
isFunction,
isStream,
isURLSearchParams,
isStandardBrowserEnv,
forEach,
merge,
extend,
trim,
stripBOM
};
var utils$c = utils$d;
function encode(val) {
return encodeURIComponent(val).replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "+").replace(/%5B/gi, "[").replace(/%5D/gi, "]");
}
var buildURL$2 = function buildURL2(url, params, paramsSerializer) {
if (!params) {
return url;
}
var serializedParams;
if (paramsSerializer) {
serializedParams = paramsSerializer(params);
} else if (utils$c.isURLSearchParams(params)) {
serializedParams = params.toString();
} else {
var parts = [];
utils$c.forEach(params, function serialize(val, key) {
if (val === null || typeof val === "undefined") {
return;
}
if (utils$c.isArray(val)) {
key = key + "[]";
} else {
val = [val];
}
utils$c.forEach(val, function parseValue(v) {
if (utils$c.isDate(v)) {
v = v.toISOString();
} else if (utils$c.isObject(v)) {
v = JSON.stringify(v);
}
parts.push(encode(key) + "=" + encode(v));
});
});
serializedParams = parts.join("&");
}
if (serializedParams) {
var hashmarkIndex = url.indexOf("#");
if (hashmarkIndex !== -1) {
url = url.slice(0, hashmarkIndex);
}
url += (url.indexOf("?") === -1 ? "?" : "&") + serializedParams;
}
return url;
};
var utils$b = utils$d;
function InterceptorManager$1() {
this.handlers = [];
}
InterceptorManager$1.prototype.use = function use(fulfilled, rejected) {
this.handlers.push({
fulfilled,
rejected
});
return this.handlers.length - 1;
};
InterceptorManager$1.prototype.eject = function eject(id2) {
if (this.handlers[id2]) {
this.handlers[id2] = null;
}
};
InterceptorManager$1.prototype.forEach = function forEach2(fn) {
utils$b.forEach(this.handlers, function forEachHandler(h) {
if (h !== null) {
fn(h);
}
});
};
var InterceptorManager_1 = InterceptorManager$1;
var utils$a = utils$d;
var transformData$1 = function transformData2(data, headers, fns) {
utils$a.forEach(fns, function transform(fn) {
data = fn(data, headers);
});
return data;
};
var isCancel$1 = function isCancel2(value) {
return !!(value && value.__CANCEL__);
};
var utils$9 = utils$d;
var normalizeHeaderName$1 = function normalizeHeaderName2(headers, normalizedName) {
utils$9.forEach(headers, function processHeader(value, name) {
if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {
headers[normalizedName] = value;
delete headers[name];
}
});
};
var enhanceError$1 = function enhanceError2(error, config, code, request2, response) {
error.config = config;
if (code) {
error.code = code;
}
error.request = request2;
error.response = response;
error.isAxiosError = true;
error.toJSON = function toJSON() {
return {
message: this.message,
name: this.name,
description: this.description,
number: this.number,
fileName: this.fileName,
lineNumber: this.lineNumber,
columnNumber: this.columnNumber,
stack: this.stack,
config: this.config,
code: this.code
};
};
return error;
};
var enhanceError = enhanceError$1;
var createError$2 = function createError2(message, config, code, request2, response) {
var error = new Error(message);
return enhanceError(error, config, code, request2, response);
};
var createError$1 = createError$2;
var settle$1 = function settle2(resolve, reject, response) {
var validateStatus2 = response.config.validateStatus;
if (!response.status || !validateStatus2 || validateStatus2(response.status)) {
resolve(response);
} else {
reject(createError$1("Request failed with status code " + response.status, response.config, null, response.request, response));
}
};
var utils$8 = utils$d;
var cookies$1 = utils$8.isStandardBrowserEnv() ? function standardBrowserEnv() {
return {
write: function write(name, value, expires, path, domain, secure) {
var cookie = [];
cookie.push(name + "=" + encodeURIComponent(value));
if (utils$8.isNumber(expires)) {
cookie.push("expires=" + new Date(expires).toGMTString());
}
if (utils$8.isString(path)) {
cookie.push("path=" + path);
}
if (utils$8.isString(domain)) {
cookie.push("domain=" + domain);
}
if (secure === true) {
cookie.push("secure");
}
document.cookie = cookie.join("; ");
},
read: function read(name) {
var match = document.cookie.match(new RegExp("(^|;\\s*)(" + name + ")=([^;]*)"));
return match ? decodeURIComponent(match[3]) : null;
},
remove: function remove(name) {
this.write(name, "", Date.now() - 864e5);
}
};
}() : function nonStandardBrowserEnv() {
return {
write: function write() {
},
read: function read() {
return null;
},
remove: function remove() {
}
};
}();
var isAbsoluteURL$1 = function isAbsoluteURL2(url) {
return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url);
};
var combineURLs$1 = function combineURLs2(baseURL, relativeURL) {
return relativeURL ? baseURL.replace(/\/+$/, "") + "/" + relativeURL.replace(/^\/+/, "") : baseURL;
};
var isAbsoluteURL = isAbsoluteURL$1;
var combineURLs = combineURLs$1;
var buildFullPath$1 = function buildFullPath2(baseURL, requestedURL) {
if (baseURL && !isAbsoluteURL(requestedURL)) {
return combineURLs(baseURL, requestedURL);
}
return requestedURL;
};
var utils$7 = utils$d;
var ignoreDuplicateOf = [
"age",
"authorization",
"content-length",
"content-type",
"etag",
"expires",
"from",
"host",
"if-modified-since",
"if-unmodified-since",
"last-modified",
"location",
"max-forwards",
"proxy-authorization",
"referer",
"retry-after",
"user-agent"
];
var parseHeaders$1 = function parseHeaders2(headers) {
var parsed = {};
var key;
var val;
var i;
if (!headers) {
return parsed;
}
utils$7.forEach(headers.split("\n"), function parser(line) {
i = line.indexOf(":");
key = utils$7.trim(line.substr(0, i)).toLowerCase();
val = utils$7.trim(line.substr(i + 1));
if (key) {
if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {
return;
}
if (key === "set-cookie") {
parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);
} else {
parsed[key] = parsed[key] ? parsed[key] + ", " + val : val;
}
}
});
return parsed;
};
var utils$6 = utils$d;
var isURLSameOrigin$1 = utils$6.isStandardBrowserEnv() ? function standardBrowserEnv2() {
var msie = /(msie|trident)/i.test(navigator.userAgent);
var urlParsingNode = document.createElement("a");
var originURL;
function resolveURL(url) {
var href = url;
if (msie) {
urlParsingNode.setAttribute("href", href);
href = urlParsingNode.href;
}
urlParsingNode.setAttribute("href", href);
return {
href: urlParsingNode.href,
protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, "") : "",
host: urlParsingNode.host,
search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, "") : "",
hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, "") : "",
hostname: urlParsingNode.hostname,
port: urlParsingNode.port,
pathname: urlParsingNode.pathname.charAt(0) === "/" ? urlParsingNode.pathname : "/" + urlParsingNode.pathname
};
}
originURL = resolveURL(window.location.href);
return function isURLSameOrigin2(requestURL) {
var parsed = utils$6.isString(requestURL) ? resolveURL(requestURL) : requestURL;
return parsed.protocol === originURL.protocol && parsed.host === originURL.host;
};
}() : function nonStandardBrowserEnv2() {
return function isURLSameOrigin2() {
return true;
};
}();
var utils$5 = utils$d;
var settle = settle$1;
var cookies = cookies$1;
var buildURL$1 = buildURL$2;
var buildFullPath = buildFullPath$1;
var parseHeaders = parseHeaders$1;
var isURLSameOrigin = isURLSameOrigin$1;
var createError = createError$2;
var xhr = function xhrAdapter(config) {
return new Promise(function dispatchXhrRequest(resolve, reject) {
var requestData = config.data;
var requestHeaders = config.headers;
if (utils$5.isFormData(requestData)) {
delete requestHeaders["Content-Type"];
}
var request2 = new XMLHttpRequest();
if (config.auth) {
var username = config.auth.username || "";
var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : "";
requestHeaders.Authorization = "Basic " + btoa(username + ":" + password);
}
var fullPath = buildFullPath(config.baseURL, config.url);
request2.open(config.method.toUpperCase(), buildURL$1(fullPath, config.params, config.paramsSerializer), true);
request2.timeout = config.timeout;
request2.onreadystatechange = function handleLoad() {
if (!request2 || request2.readyState !== 4) {
return;
}
if (request2.status === 0 && !(request2.responseURL && request2.responseURL.indexOf("file:") === 0)) {
return;
}
var responseHeaders = "getAllResponseHeaders" in request2 ? parseHeaders(request2.getAllResponseHeaders()) : null;
var responseData = !config.responseType || config.responseType === "text" ? request2.responseText : request2.response;
var response = {
data: responseData,
status: request2.status,
statusText: request2.statusText,
headers: responseHeaders,
config,
request: request2
};
settle(resolve, reject, response);
request2 = null;
};
request2.onabort = function handleAbort() {
if (!request2) {
return;
}
reject(createError("Request aborted", config, "ECONNABORTED", request2));
request2 = null;
};
request2.onerror = function handleError() {
reject(createError("Network Error", config, null, request2));
request2 = null;
};
request2.ontimeout = function handleTimeout() {
var timeoutErrorMessage = "timeout of " + config.timeout + "ms exceeded";
if (config.timeoutErrorMessage) {
timeoutErrorMessage = config.timeoutErrorMessage;
}
reject(createError(timeoutErrorMessage, config, "ECONNABORTED", request2));
request2 = null;
};
if (utils$5.isStandardBrowserEnv()) {
var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ? cookies.read(config.xsrfCookieName) : void 0;
if (xsrfValue) {
requestHeaders[config.xsrfHeaderName] = xsrfValue;
}
}
if ("setRequestHeader" in request2) {
utils$5.forEach(requestHeaders, function setRequestHeader(val, key) {
if (typeof requestData === "undefined" && key.toLowerCase() === "content-type") {
delete requestHeaders[key];
} else {
request2.setRequestHeader(key, val);
}
});
}
if (!utils$5.isUndefined(config.withCredentials)) {
request2.withCredentials = !!config.withCredentials;
}
if (config.responseType) {
try {
request2.responseType = config.responseType;
} catch (e) {
if (config.responseType !== "json") {
throw e;
}
}
}
if (typeof config.onDownloadProgress === "function") {
request2.addEventListener("progress", config.onDownloadProgress);
}
if (typeof config.onUploadProgress === "function" && request2.upload) {
request2.upload.addEventListener("progress", config.onUploadProgress);
}
if (config.cancelToken) {
config.cancelToken.promise.then(function onCanceled(cancel) {
if (!request2) {
return;
}
request2.abort();
reject(cancel);
request2 = null;
});
}
if (!requestData) {
requestData = null;
}
request2.send(requestData);
});
};
var utils$4 = utils$d;
var normalizeHeaderName = normalizeHeaderName$1;
var DEFAULT_CONTENT_TYPE = {
"Content-Type": "application/x-www-form-urlencoded"
};
function setContentTypeIfUnset(headers, value) {
if (!utils$4.isUndefined(headers) && utils$4.isUndefined(headers["Content-Type"])) {
headers["Content-Type"] = value;
}
}
function getDefaultAdapter() {
var adapter;
if (typeof XMLHttpRequest !== "undefined") {
adapter = xhr;
} else if (typeof process !== "undefined" && Object.prototype.toString.call(process) === "[object process]") {
adapter = xhr;
}
return adapter;
}
var defaults$2 = {
adapter: getDefaultAdapter(),
transformRequest: [function transformRequest(data, headers) {
normalizeHeaderName(headers, "Accept");
normalizeHeaderName(headers, "Content-Type");
if (utils$4.isFormData(data) || utils$4.isArrayBuffer(data) || utils$4.isBuffer(data) || utils$4.isStream(data) || utils$4.isFile(data) || utils$4.isBlob(data)) {
return data;
}
if (utils$4.isArrayBufferView(data)) {
return data.buffer;
}
if (utils$4.isURLSearchParams(data)) {
setContentTypeIfUnset(headers, "application/x-www-form-urlencoded;charset=utf-8");
return data.toString();
}
if (utils$4.isObject(data)) {
setContentTypeIfUnset(headers, "application/json;charset=utf-8");
return JSON.stringify(data);
}
return data;
}],
transformResponse: [function transformResponse(data) {
if (typeof data === "string") {
try {
data = JSON.parse(data);
} catch (e) {
}
}
return data;
}],
timeout: 0,
xsrfCookieName: "XSRF-TOKEN",
xsrfHeaderName: "X-XSRF-TOKEN",
maxContentLength: -1,
maxBodyLength: -1,
validateStatus: function validateStatus(status) {
return status >= 200 && status < 300;
}
};
defaults$2.headers = {
common: {
"Accept": "application/json, text/plain, */*"
}
};
utils$4.forEach(["delete", "get", "head"], function forEachMethodNoData(method) {
defaults$2.headers[method] = {};
});
utils$4.forEach(["post", "put", "patch"], function forEachMethodWithData(method) {
defaults$2.headers[method] = utils$4.merge(DEFAULT_CONTENT_TYPE);
});
var defaults_1 = defaults$2;
var utils$3 = utils$d;
var transformData = transformData$1;
var isCancel = isCancel$1;
var defaults$1 = defaults_1;
function throwIfCancellationRequested(config) {
if (config.cancelToken) {
config.cancelToken.throwIfRequested();
}
}
var dispatchRequest$1 = function dispatchRequest2(config) {
throwIfCancellationRequested(config);
config.headers = config.headers || {};
config.data = transformData(config.data, config.headers, config.transformRequest);
config.headers = utils$3.merge(config.headers.common || {}, config.headers[config.method] || {}, config.headers);
utils$3.forEach(["delete", "get", "head", "post", "put", "patch", "common"], function cleanHeaderConfig(method) {
delete config.headers[method];
});
var adapter = config.adapter || defaults$1.adapter;
return adapter(config).then(function onAdapterResolution(response) {
throwIfCancellationRequested(config);
response.data = transformData(response.data, response.headers, config.transformResponse);
return response;
}, function onAdapterRejection(reason) {
if (!isCancel(reason)) {
throwIfCancellationRequested(config);
if (reason && reason.response) {
reason.response.data = transformData(reason.response.data, reason.response.headers, config.transformResponse);
}
}
return Promise.reject(reason);
});
};
var utils$2 = utils$d;
var mergeConfig$2 = function mergeConfig2(config1, config2) {
config2 = config2 || {};
var config = {};
var valueFromConfig2Keys = ["url", "method", "data"];
var mergeDeepPropertiesKeys = ["headers", "auth", "proxy", "params"];
var defaultToConfig2Keys = [
"baseURL",
"transformRequest",
"transformResponse",
"paramsSerializer",
"timeout",
"timeoutMessage",
"withCredentials",
"adapter",
"responseType",
"xsrfCookieName",
"xsrfHeaderName",
"onUploadProgress",
"onDownloadProgress",
"decompress",
"maxContentLength",
"maxBodyLength",
"maxRedirects",
"transport",
"httpAgent",
"httpsAgent",
"cancelToken",
"socketPath",
"responseEncoding"
];
var directMergeKeys = ["validateStatus"];
function getMergedValue(target, source2) {
if (utils$2.isPlainObject(target) && utils$2.isPlainObject(source2)) {
return utils$2.merge(target, source2);
} else if (utils$2.isPlainObject(source2)) {
return utils$2.merge({}, source2);
} else if (utils$2.isArray(source2)) {
return source2.slice();
}
return source2;
}
function mergeDeepProperties(prop) {
if (!utils$2.isUndefined(config2[prop])) {
config[prop] = getMergedValue(config1[prop], config2[prop]);
} else if (!utils$2.isUndefined(config1[prop])) {
config[prop] = getMergedValue(void 0, config1[prop]);
}
}
utils$2.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) {
if (!utils$2.isUndefined(config2[prop])) {
config[prop] = getMergedValue(void 0, config2[prop]);
}
});
utils$2.forEach(mergeDeepPropertiesKeys, mergeDeepProperties);
utils$2.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) {
if (!utils$2.isUndefined(config2[prop])) {
config[prop] = getMergedValue(void 0, config2[prop]);
} else if (!utils$2.isUndefined(config1[prop])) {
config[prop] = getMergedValue(void 0, config1[prop]);
}
});
utils$2.forEach(directMergeKeys, function merge2(prop) {
if (prop in config2) {
config[prop] = getMergedValue(config1[prop], config2[prop]);
} else if (prop in config1) {
config[prop] = getMergedValue(void 0, config1[prop]);
}
});
var axiosKeys = valueFromConfig2Keys.concat(mergeDeepPropertiesKeys).concat(defaultToConfig2Keys).concat(directMergeKeys);
var otherKeys = Object.keys(config1).concat(Object.keys(config2)).filter(function filterAxiosKeys(key) {
return axiosKeys.indexOf(key) === -1;
});
utils$2.forEach(otherKeys, mergeDeepProperties);
return config;
};
var utils$1 = utils$d;
var buildURL = buildURL$2;
var InterceptorManager = InterceptorManager_1;
var dispatchRequest = dispatchRequest$1;
var mergeConfig$1 = mergeConfig$2;
function Axios$1(instanceConfig) {
this.defaults = instanceConfig;
this.interceptors = {
request: new InterceptorManager(),
response: new InterceptorManager()
};
}
Axios$1.prototype.request = function request(config) {
if (typeof config === "string") {
config = arguments[1] || {};
config.url = arguments[0];
} else {
config = config || {};
}
config = mergeConfig$1(this.defaults, config);
if (config.method) {
config.method = config.method.toLowerCase();
} else if (this.defaults.method) {
config.method = this.defaults.method.toLowerCase();
} else {
config.method = "get";
}
var chain = [dispatchRequest, void 0];
var promise = Promise.resolve(config);
this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
chain.unshift(interceptor.fulfilled, interceptor.rejected);
});
this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
chain.push(interceptor.fulfilled, interceptor.rejected);
});
while (chain.length) {
promise = promise.then(chain.shift(), chain.shift());
}
return promise;
};
Axios$1.prototype.getUri = function getUri(config) {
config = mergeConfig$1(this.defaults, config);
return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, "");
};
utils$1.forEach(["delete", "get", "head", "options"], function forEachMethodNoData2(method) {
Axios$1.prototype[method] = function(url, config) {
return this.request(mergeConfig$1(config || {}, {
method,
url,
data: (config || {}).data
}));
};
});
utils$1.forEach(["post", "put", "patch"], function forEachMethodWithData2(method) {
Axios$1.prototype[method] = function(url, data, config) {
return this.request(mergeConfig$1(config || {}, {
method,
url,
data
}));
};
});
var Axios_1 = Axios$1;
function Cancel$1(message) {
this.message = message;
}
Cancel$1.prototype.toString = function toString2() {
return "Cancel" + (this.message ? ": " + this.message : "");
};
Cancel$1.prototype.__CANCEL__ = true;
var Cancel_1 = Cancel$1;
var Cancel = Cancel_1;
function CancelToken(executor) {
if (typeof executor !== "function") {
throw new TypeError("executor must be a function.");
}
var resolvePromise;
this.promise = new Promise(function promiseExecutor(resolve) {
resolvePromise = resolve;
});
var token = this;
executor(function cancel(message) {
if (token.reason) {
return;
}
token.reason = new Cancel(message);
resolvePromise(token.reason);
});
}
CancelToken.prototype.throwIfRequested = function throwIfRequested() {
if (this.reason) {
throw this.reason;
}
};
CancelToken.source = function source() {
var cancel;
var token = new CancelToken(function executor(c) {
cancel = c;
});
return {
token,
cancel
};
};
var CancelToken_1 = CancelToken;
var spread = function spread2(callback) {
return function wrap(arr) {
return callback.apply(null, arr);
};
};
var isAxiosError = function isAxiosError2(payload) {
return typeof payload === "object" && payload.isAxiosError === true;
};
var utils = utils$d;
var bind = bind$2;
var Axios = Axios_1;
var mergeConfig = mergeConfig$2;
var defaults = defaults_1;
function createInstance(defaultConfig) {
var context = new Axios(defaultConfig);
var instance = bind(Axios.prototype.request, context);
utils.extend(instance, Axios.prototype, context);
utils.extend(instance, context);
return instance;
}
var axios$1 = createInstance(defaults);
axios$1.Axios = Axios;
axios$1.create = function create(instanceConfig) {
return createInstance(mergeConfig(axios$1.defaults, instanceConfig));
};
axios$1.Cancel = Cancel_1;
axios$1.CancelToken = CancelToken_1;
axios$1.isCancel = isCancel$1;
axios$1.all = function all(promises) {
return Promise.all(promises);
};
axios$1.spread = spread;
axios$1.isAxiosError = isAxiosError;
axios$2.exports = axios$1;
axios$2.exports.default = axios$1;
var axios = axios$2.exports;
class Request {
constructor() {
this.axios = axios.create({ baseURL: env.OPEN_PLATFORM_ORIGIN });
}
async createKoutuRecord(options) {
const url = options.url;
const imgData = await this.axios.get(url, { responseType: "arraybuffer" }).then((res2) => res2.data);
const { width, height } = await new Promise((resolve) => {
const img = document.createElement("img");
img.src = url;
img.onload = () => {
resolve({ width: img.width, height: img.height });
};
});
const res = await this.axios.post("/sdk/api/koutu-records", { url, size: imgData.byteLength, width, height }, {
headers: {
authorization: `Bearer ${options.token}`
}
});
return res.data.work_id;
}
async koutu(options) {
const res = await this.axios.post("/sdk/api/koutus", {
app_id: options.appId,
url: options.url,
ability_code: options.abilityCode,
work_id: options.workId,
use_cert: options.useCert
}, {
headers: {
authorization: `Bearer ${options.token}`
}
});
return res.data.result;
}
async createAuth(code) {
const res = await this.axios.post("/sdk/api/auths", { code });
return res.data.access_token;
}
}
function isKE002Config(config) {

@@ -641,30 +1566,39 @@ return config.version === "KE002";

const c = Object.assign({}, defineConfig$1, config);
const request2 = new Request();
assert(!!(c == null ? void 0 : c.appId), "\u7F3A\u5C11 appId \u53C2\u6570");
async function importFile(file) {
return new Promise(async (resolve) => {
let code = "";
if (isKE002Config(c)) {
code = await c.getUserCode();
}
return new Promise(async (resolve, reject) => {
const { open, close, iframe } = createIframe(`${env.KOUTU_EDITOR_URL}`, { app_id: c.appId, version: c.version || "KE001" }, () => resolve(false));
const child = connectToChild({
iframe,
methods: {
methods: handleFunsErrors({
async onload() {
const service2 = await child.promise;
service2.init({ version: isKE002Config(c) ? c.version : "KE001", appId: c.appId });
service2.init({
version: isKE002Config(c) ? c.version : "KE001",
appId: c.appId
});
},
async getUseRightToken(info) {
const token = isKE002Config(c) ? await c.getUseRightToken(info) : false;
return token;
},
async getUserCode() {
try {
const token = isKE002Config(c) ? await c.getUseRightToken(info) : true;
if (token instanceof Error) {
return {
message: token.message
};
if (code) {
const key = code;
code = "";
return key;
}
return token;
return isKE002Config(c) ? await c.getUserCode() : false;
} catch (error) {
return { message: error.message };
reject(error);
close();
}
},
async getUserCode() {
return isKE002Config(c) ? c.getUserCode() : false;
},
download(info) {
async download(info) {
resolve(info);

@@ -674,3 +1608,3 @@ close();

}
}
})
});

@@ -682,67 +1616,55 @@ open();

}
async function koutu(file) {
const { open, close, iframe } = createIframe(`${env.KOUTU_EDITOR_URL}`, { app_id: c.appId, version: c.version || "KE001" }, void 0, true);
iframe.style.display = "none";
const child = connectToChild({
iframe,
methods: {
async onload() {
const service2 = await child.promise;
service2.init({ version: isKE002Config(c) ? c.version : "KE001", appId: c.appId });
},
async getUseRightToken(info) {
try {
const token = isKE002Config(c) ? await c.getUseRightToken(info) : true;
if (token instanceof Error) {
return {
message: token.message
};
}
return token;
} catch (error) {
return { message: error.message };
}
},
async getUserCode() {
return isKE002Config(c) ? c.getUserCode() : false;
}
}
async function koutu(url) {
if (!isKE002Config(c))
throw new Error("\u81EA\u52A8\u62A0\u56FE\u4E0D\u652F\u6301\u57FA\u7840\u7248\u4F7F\u7528");
const code = await c.getUserCode();
const token = await request2.createAuth(code);
const res = await request2.createKoutuRecord({ token, url });
const useCert = await c.getUseRightToken({
abilityCode: c.version,
appId: c.appId,
workId: res,
useKey: c.version
});
open();
const service = await child.promise;
const res = await service.exportFile(file);
close();
child.destroy();
if (res.message) {
throw new Error(res.message);
if (!useCert) {
throw new Error("\u6CA1\u6709\u6743\u9650");
} else if (useCert instanceof Error) {
throw useCert;
}
return res;
const data = await request2.koutu({
url,
appId: c.appId,
workId: res,
abilityCode: c.version,
useCert,
token
});
return { result: data, workId: res };
}
async function openWork(id2) {
return new Promise(async (resolve) => {
const { open, close, iframe } = createIframe(`${env.KOUTU_EDITOR_URL}`, { app_id: c.appId, version: c.version || "KE001" }, () => resolve(false));
return new Promise(async (resolve, reject) => {
const { open, close, iframe } = createIframe(`${env.KOUTU_EDITOR_URL}`, { app_id: c.appId, version: c.version || "KE001", id: id2 }, () => resolve(false));
const child = connectToChild({
iframe,
methods: {
methods: handleFunsErrors({
async onload() {
const service2 = await child.promise;
service2.init({ version: isKE002Config(c) ? c.version : "KE001", appId: c.appId });
service2.init({
version: isKE002Config(c) ? c.version : "KE001",
appId: c.appId
});
},
async getUseRightToken(info) {
const token = isKE002Config(c) ? await c.getUseRightToken(info) : false;
return token;
},
async getUserCode() {
try {
const token = isKE002Config(c) ? await c.getUseRightToken(info) : true;
if (token instanceof Error) {
return {
message: token.message
};
}
return token;
return isKE002Config(c) ? c.getUserCode() : false;
} catch (error) {
return { message: error.message };
reject(error);
close();
}
},
async getUserCode() {
return isKE002Config(c) ? c.getUserCode() : false;
},
download(info) {
async download(info) {
resolve(info);

@@ -752,3 +1674,3 @@ close();

}
}
})
});

@@ -775,3 +1697,7 @@ open();

async function importFile(file) {
return new Promise(async (resolve) => {
let code = "";
if (isIE002Config(c)) {
code = await c.getUserCode();
}
return new Promise(async (resolve, reject) => {
const { open, close, iframe } = createIframe(`${env.IMAGE_EDITOR_URL}`, { app_id: c.appId, version: c.version || "IE001" }, () => resolve(false));

@@ -795,3 +1721,13 @@ const child = connectToChild({

async getUserCode() {
return isIE002Config(c) ? c.getUserCode() : false;
if (code) {
const key = code;
code = "";
return key;
}
try {
return isIE002Config(c) ? c.getUserCode() : false;
} catch (error) {
reject(error);
close();
}
},

@@ -798,0 +1734,0 @@ download(info2) {

@@ -365,3 +365,3 @@ var __defProp = Object.defineProperty;

frame.setAttribute("frameborder", "0");
frame.src = `${url}?${Object.entries(query).filter(([k, v]) => v !== void 0).map(([k, v]) => `${k}=${v}`).join("&")}`;
frame.src = `${url}?${Object.entries(query).filter(([_, v]) => v !== void 0).map(([k, v]) => `${k}=${v}`).join("&")}`;
const wrapper = document.createElement("div");

@@ -427,2 +427,4 @@ wrapper.style.cssText = `

function toggleScrollSwitch() {
if (hide)
return;
const dom = document.querySelector(".gaoding-editor-iframe-dialog");

@@ -467,4 +469,5 @@ if (!dom)

TEMPLATE_EDITOR_URL: "https://open.gaoding.com/design",
KOUTU_EDITOR_URL: "https://open.gaoding.com/open-clip",
IMAGE_EDITOR_URL: "https://open.gaoding.com/design/image"
KOUTU_EDITOR_URL: "https://open.gaoding.com/clip",
IMAGE_EDITOR_URL: "https://open.gaoding.com/design/image",
OPEN_PLATFORM_ORIGIN: "https://open.gaoding.com"
};

@@ -493,4 +496,8 @@ const defineConfig$2 = {

async function openTemplate(config2) {
assert(!!(config2 == null ? void 0 : config2.id), "openTemplate \u7F3A\u5C11 id \u53C2\u6570");
return new Promise((resolve) => {
assert(!!(config2 == null ? void 0 : config2.categoryId) || !!(config2 == null ? void 0 : config2.id), "openTemplate \u7F3A\u5C11 id \u6216\u8005 categoryId \u53C2\u6570");
let code = "";
if (isAdvancedConfig(c)) {
code = await c.getUserCode();
}
return new Promise((resolve, reject) => {
const q = Object.assign({ version: "TE001" }, query, { id: config2.id, thirdCateId: config2.categoryId });

@@ -525,3 +532,13 @@ const { open, iframe, close } = createIframe(env.TEMPLATE_EDITOR_URL, q, () => resolve(false));

async getUserCode() {
return isAdvancedConfig(c) ? c.getUserCode() : false;
if (code) {
const key = code;
code = "";
return key;
}
try {
return isAdvancedConfig(c) ? c.getUserCode() : false;
} catch (error) {
reject(error);
close();
}
},

@@ -537,4 +554,4 @@ async download(info) {

}
async function create(options = {}) {
return new Promise((resolve) => {
async function create2(options = {}) {
return new Promise((resolve, reject) => {
const q = Object.assign({ version: "TE001" }, query, { thirdCateId: options.categoryId, mode: "create", width: options.width, height: options.height });

@@ -568,3 +585,8 @@ const { open, iframe, close } = createIframe(env.TEMPLATE_EDITOR_URL, q, () => resolve(false));

async getUserCode() {
return isAdvancedConfig(c) ? c.getUserCode() : false;
try {
return isAdvancedConfig(c) ? c.getUserCode() : false;
} catch (error) {
reject(error);
close();
}
},

@@ -582,3 +604,3 @@ async download(info) {

async function importFile(config2 = {}) {
return new Promise((resolve) => {
return new Promise((resolve, reject) => {
const q = Object.assign({ version: "TE001" }, query, { app_id: c.appId, mode: "psd" });

@@ -612,3 +634,8 @@ const { open, close, iframe } = createIframe(`${env.TEMPLATE_EDITOR_URL}`, q, () => resolve(false));

async getUserCode() {
return isAdvancedConfig(c) ? c.getUserCode() : false;
try {
return isAdvancedConfig(c) ? c.getUserCode() : false;
} catch (error) {
reject(error);
close();
}
},

@@ -627,6 +654,904 @@ async download(info) {

importFile,
create,
create: create2,
openTemplate
};
}
function handleFunsErrors(methods) {
return Object.keys(methods).reduce((nweMethods, key) => {
nweMethods[key] = async function(...args) {
try {
return await methods[key](...args);
} catch (error) {
return {
type: "error",
message: error.message
};
}
};
return nweMethods;
}, {});
}
var axios$2 = { exports: {} };
var bind$2 = function bind(fn, thisArg) {
return function wrap() {
var args = new Array(arguments.length);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i];
}
return fn.apply(thisArg, args);
};
};
var bind$1 = bind$2;
var toString = Object.prototype.toString;
function isArray(val) {
return toString.call(val) === "[object Array]";
}
function isUndefined(val) {
return typeof val === "undefined";
}
function isBuffer(val) {
return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && typeof val.constructor.isBuffer === "function" && val.constructor.isBuffer(val);
}
function isArrayBuffer(val) {
return toString.call(val) === "[object ArrayBuffer]";
}
function isFormData(val) {
return typeof FormData !== "undefined" && val instanceof FormData;
}
function isArrayBufferView(val) {
var result;
if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) {
result = ArrayBuffer.isView(val);
} else {
result = val && val.buffer && val.buffer instanceof ArrayBuffer;
}
return result;
}
function isString(val) {
return typeof val === "string";
}
function isNumber(val) {
return typeof val === "number";
}
function isObject(val) {
return val !== null && typeof val === "object";
}
function isPlainObject(val) {
if (toString.call(val) !== "[object Object]") {
return false;
}
var prototype = Object.getPrototypeOf(val);
return prototype === null || prototype === Object.prototype;
}
function isDate(val) {
return toString.call(val) === "[object Date]";
}
function isFile(val) {
return toString.call(val) === "[object File]";
}
function isBlob(val) {
return toString.call(val) === "[object Blob]";
}
function isFunction(val) {
return toString.call(val) === "[object Function]";
}
function isStream(val) {
return isObject(val) && isFunction(val.pipe);
}
function isURLSearchParams(val) {
return typeof URLSearchParams !== "undefined" && val instanceof URLSearchParams;
}
function trim(str) {
return str.replace(/^\s*/, "").replace(/\s*$/, "");
}
function isStandardBrowserEnv() {
if (typeof navigator !== "undefined" && (navigator.product === "ReactNative" || navigator.product === "NativeScript" || navigator.product === "NS")) {
return false;
}
return typeof window !== "undefined" && typeof document !== "undefined";
}
function forEach(obj, fn) {
if (obj === null || typeof obj === "undefined") {
return;
}
if (typeof obj !== "object") {
obj = [obj];
}
if (isArray(obj)) {
for (var i = 0, l = obj.length; i < l; i++) {
fn.call(null, obj[i], i, obj);
}
} else {
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
fn.call(null, obj[key], key, obj);
}
}
}
}
function merge() {
var result = {};
function assignValue(val, key) {
if (isPlainObject(result[key]) && isPlainObject(val)) {
result[key] = merge(result[key], val);
} else if (isPlainObject(val)) {
result[key] = merge({}, val);
} else if (isArray(val)) {
result[key] = val.slice();
} else {
result[key] = val;
}
}
for (var i = 0, l = arguments.length; i < l; i++) {
forEach(arguments[i], assignValue);
}
return result;
}
function extend(a, b, thisArg) {
forEach(b, function assignValue(val, key) {
if (thisArg && typeof val === "function") {
a[key] = bind$1(val, thisArg);
} else {
a[key] = val;
}
});
return a;
}
function stripBOM(content) {
if (content.charCodeAt(0) === 65279) {
content = content.slice(1);
}
return content;
}
var utils$d = {
isArray,
isArrayBuffer,
isBuffer,
isFormData,
isArrayBufferView,
isString,
isNumber,
isObject,
isPlainObject,
isUndefined,
isDate,
isFile,
isBlob,
isFunction,
isStream,
isURLSearchParams,
isStandardBrowserEnv,
forEach,
merge,
extend,
trim,
stripBOM
};
var utils$c = utils$d;
function encode(val) {
return encodeURIComponent(val).replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "+").replace(/%5B/gi, "[").replace(/%5D/gi, "]");
}
var buildURL$2 = function buildURL(url, params, paramsSerializer) {
if (!params) {
return url;
}
var serializedParams;
if (paramsSerializer) {
serializedParams = paramsSerializer(params);
} else if (utils$c.isURLSearchParams(params)) {
serializedParams = params.toString();
} else {
var parts = [];
utils$c.forEach(params, function serialize(val, key) {
if (val === null || typeof val === "undefined") {
return;
}
if (utils$c.isArray(val)) {
key = key + "[]";
} else {
val = [val];
}
utils$c.forEach(val, function parseValue(v) {
if (utils$c.isDate(v)) {
v = v.toISOString();
} else if (utils$c.isObject(v)) {
v = JSON.stringify(v);
}
parts.push(encode(key) + "=" + encode(v));
});
});
serializedParams = parts.join("&");
}
if (serializedParams) {
var hashmarkIndex = url.indexOf("#");
if (hashmarkIndex !== -1) {
url = url.slice(0, hashmarkIndex);
}
url += (url.indexOf("?") === -1 ? "?" : "&") + serializedParams;
}
return url;
};
var utils$b = utils$d;
function InterceptorManager$1() {
this.handlers = [];
}
InterceptorManager$1.prototype.use = function use(fulfilled, rejected) {
this.handlers.push({
fulfilled,
rejected
});
return this.handlers.length - 1;
};
InterceptorManager$1.prototype.eject = function eject(id2) {
if (this.handlers[id2]) {
this.handlers[id2] = null;
}
};
InterceptorManager$1.prototype.forEach = function forEach2(fn) {
utils$b.forEach(this.handlers, function forEachHandler(h) {
if (h !== null) {
fn(h);
}
});
};
var InterceptorManager_1 = InterceptorManager$1;
var utils$a = utils$d;
var transformData$1 = function transformData(data, headers, fns) {
utils$a.forEach(fns, function transform(fn) {
data = fn(data, headers);
});
return data;
};
var isCancel$1 = function isCancel(value) {
return !!(value && value.__CANCEL__);
};
var utils$9 = utils$d;
var normalizeHeaderName$1 = function normalizeHeaderName(headers, normalizedName) {
utils$9.forEach(headers, function processHeader(value, name) {
if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {
headers[normalizedName] = value;
delete headers[name];
}
});
};
var enhanceError$1 = function enhanceError(error, config, code, request2, response) {
error.config = config;
if (code) {
error.code = code;
}
error.request = request2;
error.response = response;
error.isAxiosError = true;
error.toJSON = function toJSON() {
return {
message: this.message,
name: this.name,
description: this.description,
number: this.number,
fileName: this.fileName,
lineNumber: this.lineNumber,
columnNumber: this.columnNumber,
stack: this.stack,
config: this.config,
code: this.code
};
};
return error;
};
var enhanceError2 = enhanceError$1;
var createError$2 = function createError(message, config, code, request2, response) {
var error = new Error(message);
return enhanceError2(error, config, code, request2, response);
};
var createError$1 = createError$2;
var settle$1 = function settle(resolve, reject, response) {
var validateStatus2 = response.config.validateStatus;
if (!response.status || !validateStatus2 || validateStatus2(response.status)) {
resolve(response);
} else {
reject(createError$1("Request failed with status code " + response.status, response.config, null, response.request, response));
}
};
var utils$8 = utils$d;
var cookies$1 = utils$8.isStandardBrowserEnv() ? function standardBrowserEnv() {
return {
write: function write(name, value, expires, path, domain, secure) {
var cookie = [];
cookie.push(name + "=" + encodeURIComponent(value));
if (utils$8.isNumber(expires)) {
cookie.push("expires=" + new Date(expires).toGMTString());
}
if (utils$8.isString(path)) {
cookie.push("path=" + path);
}
if (utils$8.isString(domain)) {
cookie.push("domain=" + domain);
}
if (secure === true) {
cookie.push("secure");
}
document.cookie = cookie.join("; ");
},
read: function read(name) {
var match = document.cookie.match(new RegExp("(^|;\\s*)(" + name + ")=([^;]*)"));
return match ? decodeURIComponent(match[3]) : null;
},
remove: function remove(name) {
this.write(name, "", Date.now() - 864e5);
}
};
}() : function nonStandardBrowserEnv() {
return {
write: function write() {
},
read: function read() {
return null;
},
remove: function remove() {
}
};
}();
var isAbsoluteURL$1 = function isAbsoluteURL(url) {
return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url);
};
var combineURLs$1 = function combineURLs(baseURL, relativeURL) {
return relativeURL ? baseURL.replace(/\/+$/, "") + "/" + relativeURL.replace(/^\/+/, "") : baseURL;
};
var isAbsoluteURL2 = isAbsoluteURL$1;
var combineURLs2 = combineURLs$1;
var buildFullPath$1 = function buildFullPath(baseURL, requestedURL) {
if (baseURL && !isAbsoluteURL2(requestedURL)) {
return combineURLs2(baseURL, requestedURL);
}
return requestedURL;
};
var utils$7 = utils$d;
var ignoreDuplicateOf = [
"age",
"authorization",
"content-length",
"content-type",
"etag",
"expires",
"from",
"host",
"if-modified-since",
"if-unmodified-since",
"last-modified",
"location",
"max-forwards",
"proxy-authorization",
"referer",
"retry-after",
"user-agent"
];
var parseHeaders$1 = function parseHeaders(headers) {
var parsed = {};
var key;
var val;
var i;
if (!headers) {
return parsed;
}
utils$7.forEach(headers.split("\n"), function parser(line) {
i = line.indexOf(":");
key = utils$7.trim(line.substr(0, i)).toLowerCase();
val = utils$7.trim(line.substr(i + 1));
if (key) {
if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {
return;
}
if (key === "set-cookie") {
parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);
} else {
parsed[key] = parsed[key] ? parsed[key] + ", " + val : val;
}
}
});
return parsed;
};
var utils$6 = utils$d;
var isURLSameOrigin$1 = utils$6.isStandardBrowserEnv() ? function standardBrowserEnv2() {
var msie = /(msie|trident)/i.test(navigator.userAgent);
var urlParsingNode = document.createElement("a");
var originURL;
function resolveURL(url) {
var href = url;
if (msie) {
urlParsingNode.setAttribute("href", href);
href = urlParsingNode.href;
}
urlParsingNode.setAttribute("href", href);
return {
href: urlParsingNode.href,
protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, "") : "",
host: urlParsingNode.host,
search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, "") : "",
hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, "") : "",
hostname: urlParsingNode.hostname,
port: urlParsingNode.port,
pathname: urlParsingNode.pathname.charAt(0) === "/" ? urlParsingNode.pathname : "/" + urlParsingNode.pathname
};
}
originURL = resolveURL(window.location.href);
return function isURLSameOrigin2(requestURL) {
var parsed = utils$6.isString(requestURL) ? resolveURL(requestURL) : requestURL;
return parsed.protocol === originURL.protocol && parsed.host === originURL.host;
};
}() : function nonStandardBrowserEnv2() {
return function isURLSameOrigin2() {
return true;
};
}();
var utils$5 = utils$d;
var settle2 = settle$1;
var cookies = cookies$1;
var buildURL$1 = buildURL$2;
var buildFullPath2 = buildFullPath$1;
var parseHeaders2 = parseHeaders$1;
var isURLSameOrigin = isURLSameOrigin$1;
var createError2 = createError$2;
var xhr = function xhrAdapter(config) {
return new Promise(function dispatchXhrRequest(resolve, reject) {
var requestData = config.data;
var requestHeaders = config.headers;
if (utils$5.isFormData(requestData)) {
delete requestHeaders["Content-Type"];
}
var request2 = new XMLHttpRequest();
if (config.auth) {
var username = config.auth.username || "";
var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : "";
requestHeaders.Authorization = "Basic " + btoa(username + ":" + password);
}
var fullPath = buildFullPath2(config.baseURL, config.url);
request2.open(config.method.toUpperCase(), buildURL$1(fullPath, config.params, config.paramsSerializer), true);
request2.timeout = config.timeout;
request2.onreadystatechange = function handleLoad() {
if (!request2 || request2.readyState !== 4) {
return;
}
if (request2.status === 0 && !(request2.responseURL && request2.responseURL.indexOf("file:") === 0)) {
return;
}
var responseHeaders = "getAllResponseHeaders" in request2 ? parseHeaders2(request2.getAllResponseHeaders()) : null;
var responseData = !config.responseType || config.responseType === "text" ? request2.responseText : request2.response;
var response = {
data: responseData,
status: request2.status,
statusText: request2.statusText,
headers: responseHeaders,
config,
request: request2
};
settle2(resolve, reject, response);
request2 = null;
};
request2.onabort = function handleAbort() {
if (!request2) {
return;
}
reject(createError2("Request aborted", config, "ECONNABORTED", request2));
request2 = null;
};
request2.onerror = function handleError() {
reject(createError2("Network Error", config, null, request2));
request2 = null;
};
request2.ontimeout = function handleTimeout() {
var timeoutErrorMessage = "timeout of " + config.timeout + "ms exceeded";
if (config.timeoutErrorMessage) {
timeoutErrorMessage = config.timeoutErrorMessage;
}
reject(createError2(timeoutErrorMessage, config, "ECONNABORTED", request2));
request2 = null;
};
if (utils$5.isStandardBrowserEnv()) {
var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ? cookies.read(config.xsrfCookieName) : void 0;
if (xsrfValue) {
requestHeaders[config.xsrfHeaderName] = xsrfValue;
}
}
if ("setRequestHeader" in request2) {
utils$5.forEach(requestHeaders, function setRequestHeader(val, key) {
if (typeof requestData === "undefined" && key.toLowerCase() === "content-type") {
delete requestHeaders[key];
} else {
request2.setRequestHeader(key, val);
}
});
}
if (!utils$5.isUndefined(config.withCredentials)) {
request2.withCredentials = !!config.withCredentials;
}
if (config.responseType) {
try {
request2.responseType = config.responseType;
} catch (e) {
if (config.responseType !== "json") {
throw e;
}
}
}
if (typeof config.onDownloadProgress === "function") {
request2.addEventListener("progress", config.onDownloadProgress);
}
if (typeof config.onUploadProgress === "function" && request2.upload) {
request2.upload.addEventListener("progress", config.onUploadProgress);
}
if (config.cancelToken) {
config.cancelToken.promise.then(function onCanceled(cancel) {
if (!request2) {
return;
}
request2.abort();
reject(cancel);
request2 = null;
});
}
if (!requestData) {
requestData = null;
}
request2.send(requestData);
});
};
var utils$4 = utils$d;
var normalizeHeaderName2 = normalizeHeaderName$1;
var DEFAULT_CONTENT_TYPE = {
"Content-Type": "application/x-www-form-urlencoded"
};
function setContentTypeIfUnset(headers, value) {
if (!utils$4.isUndefined(headers) && utils$4.isUndefined(headers["Content-Type"])) {
headers["Content-Type"] = value;
}
}
function getDefaultAdapter() {
var adapter;
if (typeof XMLHttpRequest !== "undefined") {
adapter = xhr;
} else if (typeof process !== "undefined" && Object.prototype.toString.call(process) === "[object process]") {
adapter = xhr;
}
return adapter;
}
var defaults$2 = {
adapter: getDefaultAdapter(),
transformRequest: [function transformRequest(data, headers) {
normalizeHeaderName2(headers, "Accept");
normalizeHeaderName2(headers, "Content-Type");
if (utils$4.isFormData(data) || utils$4.isArrayBuffer(data) || utils$4.isBuffer(data) || utils$4.isStream(data) || utils$4.isFile(data) || utils$4.isBlob(data)) {
return data;
}
if (utils$4.isArrayBufferView(data)) {
return data.buffer;
}
if (utils$4.isURLSearchParams(data)) {
setContentTypeIfUnset(headers, "application/x-www-form-urlencoded;charset=utf-8");
return data.toString();
}
if (utils$4.isObject(data)) {
setContentTypeIfUnset(headers, "application/json;charset=utf-8");
return JSON.stringify(data);
}
return data;
}],
transformResponse: [function transformResponse(data) {
if (typeof data === "string") {
try {
data = JSON.parse(data);
} catch (e) {
}
}
return data;
}],
timeout: 0,
xsrfCookieName: "XSRF-TOKEN",
xsrfHeaderName: "X-XSRF-TOKEN",
maxContentLength: -1,
maxBodyLength: -1,
validateStatus: function validateStatus(status) {
return status >= 200 && status < 300;
}
};
defaults$2.headers = {
common: {
"Accept": "application/json, text/plain, */*"
}
};
utils$4.forEach(["delete", "get", "head"], function forEachMethodNoData(method) {
defaults$2.headers[method] = {};
});
utils$4.forEach(["post", "put", "patch"], function forEachMethodWithData(method) {
defaults$2.headers[method] = utils$4.merge(DEFAULT_CONTENT_TYPE);
});
var defaults_1 = defaults$2;
var utils$3 = utils$d;
var transformData2 = transformData$1;
var isCancel2 = isCancel$1;
var defaults$1 = defaults_1;
function throwIfCancellationRequested(config) {
if (config.cancelToken) {
config.cancelToken.throwIfRequested();
}
}
var dispatchRequest$1 = function dispatchRequest(config) {
throwIfCancellationRequested(config);
config.headers = config.headers || {};
config.data = transformData2(config.data, config.headers, config.transformRequest);
config.headers = utils$3.merge(config.headers.common || {}, config.headers[config.method] || {}, config.headers);
utils$3.forEach(["delete", "get", "head", "post", "put", "patch", "common"], function cleanHeaderConfig(method) {
delete config.headers[method];
});
var adapter = config.adapter || defaults$1.adapter;
return adapter(config).then(function onAdapterResolution(response) {
throwIfCancellationRequested(config);
response.data = transformData2(response.data, response.headers, config.transformResponse);
return response;
}, function onAdapterRejection(reason) {
if (!isCancel2(reason)) {
throwIfCancellationRequested(config);
if (reason && reason.response) {
reason.response.data = transformData2(reason.response.data, reason.response.headers, config.transformResponse);
}
}
return Promise.reject(reason);
});
};
var utils$2 = utils$d;
var mergeConfig$2 = function mergeConfig(config1, config2) {
config2 = config2 || {};
var config = {};
var valueFromConfig2Keys = ["url", "method", "data"];
var mergeDeepPropertiesKeys = ["headers", "auth", "proxy", "params"];
var defaultToConfig2Keys = [
"baseURL",
"transformRequest",
"transformResponse",
"paramsSerializer",
"timeout",
"timeoutMessage",
"withCredentials",
"adapter",
"responseType",
"xsrfCookieName",
"xsrfHeaderName",
"onUploadProgress",
"onDownloadProgress",
"decompress",
"maxContentLength",
"maxBodyLength",
"maxRedirects",
"transport",
"httpAgent",
"httpsAgent",
"cancelToken",
"socketPath",
"responseEncoding"
];
var directMergeKeys = ["validateStatus"];
function getMergedValue(target, source2) {
if (utils$2.isPlainObject(target) && utils$2.isPlainObject(source2)) {
return utils$2.merge(target, source2);
} else if (utils$2.isPlainObject(source2)) {
return utils$2.merge({}, source2);
} else if (utils$2.isArray(source2)) {
return source2.slice();
}
return source2;
}
function mergeDeepProperties(prop) {
if (!utils$2.isUndefined(config2[prop])) {
config[prop] = getMergedValue(config1[prop], config2[prop]);
} else if (!utils$2.isUndefined(config1[prop])) {
config[prop] = getMergedValue(void 0, config1[prop]);
}
}
utils$2.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) {
if (!utils$2.isUndefined(config2[prop])) {
config[prop] = getMergedValue(void 0, config2[prop]);
}
});
utils$2.forEach(mergeDeepPropertiesKeys, mergeDeepProperties);
utils$2.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) {
if (!utils$2.isUndefined(config2[prop])) {
config[prop] = getMergedValue(void 0, config2[prop]);
} else if (!utils$2.isUndefined(config1[prop])) {
config[prop] = getMergedValue(void 0, config1[prop]);
}
});
utils$2.forEach(directMergeKeys, function merge2(prop) {
if (prop in config2) {
config[prop] = getMergedValue(config1[prop], config2[prop]);
} else if (prop in config1) {
config[prop] = getMergedValue(void 0, config1[prop]);
}
});
var axiosKeys = valueFromConfig2Keys.concat(mergeDeepPropertiesKeys).concat(defaultToConfig2Keys).concat(directMergeKeys);
var otherKeys = Object.keys(config1).concat(Object.keys(config2)).filter(function filterAxiosKeys(key) {
return axiosKeys.indexOf(key) === -1;
});
utils$2.forEach(otherKeys, mergeDeepProperties);
return config;
};
var utils$1 = utils$d;
var buildURL2 = buildURL$2;
var InterceptorManager = InterceptorManager_1;
var dispatchRequest2 = dispatchRequest$1;
var mergeConfig$1 = mergeConfig$2;
function Axios$1(instanceConfig) {
this.defaults = instanceConfig;
this.interceptors = {
request: new InterceptorManager(),
response: new InterceptorManager()
};
}
Axios$1.prototype.request = function request(config) {
if (typeof config === "string") {
config = arguments[1] || {};
config.url = arguments[0];
} else {
config = config || {};
}
config = mergeConfig$1(this.defaults, config);
if (config.method) {
config.method = config.method.toLowerCase();
} else if (this.defaults.method) {
config.method = this.defaults.method.toLowerCase();
} else {
config.method = "get";
}
var chain = [dispatchRequest2, void 0];
var promise = Promise.resolve(config);
this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
chain.unshift(interceptor.fulfilled, interceptor.rejected);
});
this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
chain.push(interceptor.fulfilled, interceptor.rejected);
});
while (chain.length) {
promise = promise.then(chain.shift(), chain.shift());
}
return promise;
};
Axios$1.prototype.getUri = function getUri(config) {
config = mergeConfig$1(this.defaults, config);
return buildURL2(config.url, config.params, config.paramsSerializer).replace(/^\?/, "");
};
utils$1.forEach(["delete", "get", "head", "options"], function forEachMethodNoData2(method) {
Axios$1.prototype[method] = function(url, config) {
return this.request(mergeConfig$1(config || {}, {
method,
url,
data: (config || {}).data
}));
};
});
utils$1.forEach(["post", "put", "patch"], function forEachMethodWithData2(method) {
Axios$1.prototype[method] = function(url, data, config) {
return this.request(mergeConfig$1(config || {}, {
method,
url,
data
}));
};
});
var Axios_1 = Axios$1;
function Cancel$1(message) {
this.message = message;
}
Cancel$1.prototype.toString = function toString2() {
return "Cancel" + (this.message ? ": " + this.message : "");
};
Cancel$1.prototype.__CANCEL__ = true;
var Cancel_1 = Cancel$1;
var Cancel = Cancel_1;
function CancelToken(executor) {
if (typeof executor !== "function") {
throw new TypeError("executor must be a function.");
}
var resolvePromise;
this.promise = new Promise(function promiseExecutor(resolve) {
resolvePromise = resolve;
});
var token = this;
executor(function cancel(message) {
if (token.reason) {
return;
}
token.reason = new Cancel(message);
resolvePromise(token.reason);
});
}
CancelToken.prototype.throwIfRequested = function throwIfRequested() {
if (this.reason) {
throw this.reason;
}
};
CancelToken.source = function source() {
var cancel;
var token = new CancelToken(function executor(c) {
cancel = c;
});
return {
token,
cancel
};
};
var CancelToken_1 = CancelToken;
var spread = function spread2(callback) {
return function wrap(arr) {
return callback.apply(null, arr);
};
};
var isAxiosError = function isAxiosError2(payload) {
return typeof payload === "object" && payload.isAxiosError === true;
};
var utils = utils$d;
var bind2 = bind$2;
var Axios = Axios_1;
var mergeConfig2 = mergeConfig$2;
var defaults = defaults_1;
function createInstance(defaultConfig) {
var context = new Axios(defaultConfig);
var instance = bind2(Axios.prototype.request, context);
utils.extend(instance, Axios.prototype, context);
utils.extend(instance, context);
return instance;
}
var axios$1 = createInstance(defaults);
axios$1.Axios = Axios;
axios$1.create = function create(instanceConfig) {
return createInstance(mergeConfig2(axios$1.defaults, instanceConfig));
};
axios$1.Cancel = Cancel_1;
axios$1.CancelToken = CancelToken_1;
axios$1.isCancel = isCancel$1;
axios$1.all = function all(promises) {
return Promise.all(promises);
};
axios$1.spread = spread;
axios$1.isAxiosError = isAxiosError;
axios$2.exports = axios$1;
axios$2.exports.default = axios$1;
var axios = axios$2.exports;
class Request {
constructor() {
this.axios = axios.create({ baseURL: env.OPEN_PLATFORM_ORIGIN });
}
async createKoutuRecord(options) {
const url = options.url;
const imgData = await this.axios.get(url, { responseType: "arraybuffer" }).then((res2) => res2.data);
const { width, height } = await new Promise((resolve) => {
const img = document.createElement("img");
img.src = url;
img.onload = () => {
resolve({ width: img.width, height: img.height });
};
});
const res = await this.axios.post("/sdk/api/koutu-records", { url, size: imgData.byteLength, width, height }, {
headers: {
authorization: `Bearer ${options.token}`
}
});
return res.data.work_id;
}
async koutu(options) {
const res = await this.axios.post("/sdk/api/koutus", {
app_id: options.appId,
url: options.url,
ability_code: options.abilityCode,
work_id: options.workId,
use_cert: options.useCert
}, {
headers: {
authorization: `Bearer ${options.token}`
}
});
return res.data.result;
}
async createAuth(code) {
const res = await this.axios.post("/sdk/api/auths", { code });
return res.data.access_token;
}
}
function isKE002Config(config) {

@@ -638,30 +1563,39 @@ return config.version === "KE002";

const c = Object.assign({}, defineConfig$1, config);
const request2 = new Request();
assert(!!(c == null ? void 0 : c.appId), "\u7F3A\u5C11 appId \u53C2\u6570");
async function importFile(file) {
return new Promise(async (resolve) => {
let code = "";
if (isKE002Config(c)) {
code = await c.getUserCode();
}
return new Promise(async (resolve, reject) => {
const { open, close, iframe } = createIframe(`${env.KOUTU_EDITOR_URL}`, { app_id: c.appId, version: c.version || "KE001" }, () => resolve(false));
const child = connectToChild({
iframe,
methods: {
methods: handleFunsErrors({
async onload() {
const service2 = await child.promise;
service2.init({ version: isKE002Config(c) ? c.version : "KE001", appId: c.appId });
service2.init({
version: isKE002Config(c) ? c.version : "KE001",
appId: c.appId
});
},
async getUseRightToken(info) {
const token = isKE002Config(c) ? await c.getUseRightToken(info) : false;
return token;
},
async getUserCode() {
try {
const token = isKE002Config(c) ? await c.getUseRightToken(info) : true;
if (token instanceof Error) {
return {
message: token.message
};
if (code) {
const key = code;
code = "";
return key;
}
return token;
return isKE002Config(c) ? await c.getUserCode() : false;
} catch (error) {
return { message: error.message };
reject(error);
close();
}
},
async getUserCode() {
return isKE002Config(c) ? c.getUserCode() : false;
},
download(info) {
async download(info) {
resolve(info);

@@ -671,3 +1605,3 @@ close();

}
}
})
});

@@ -679,67 +1613,55 @@ open();

}
async function koutu(file) {
const { open, close, iframe } = createIframe(`${env.KOUTU_EDITOR_URL}`, { app_id: c.appId, version: c.version || "KE001" }, void 0, true);
iframe.style.display = "none";
const child = connectToChild({
iframe,
methods: {
async onload() {
const service2 = await child.promise;
service2.init({ version: isKE002Config(c) ? c.version : "KE001", appId: c.appId });
},
async getUseRightToken(info) {
try {
const token = isKE002Config(c) ? await c.getUseRightToken(info) : true;
if (token instanceof Error) {
return {
message: token.message
};
}
return token;
} catch (error) {
return { message: error.message };
}
},
async getUserCode() {
return isKE002Config(c) ? c.getUserCode() : false;
}
}
async function koutu(url) {
if (!isKE002Config(c))
throw new Error("\u81EA\u52A8\u62A0\u56FE\u4E0D\u652F\u6301\u57FA\u7840\u7248\u4F7F\u7528");
const code = await c.getUserCode();
const token = await request2.createAuth(code);
const res = await request2.createKoutuRecord({ token, url });
const useCert = await c.getUseRightToken({
abilityCode: c.version,
appId: c.appId,
workId: res,
useKey: c.version
});
open();
const service = await child.promise;
const res = await service.exportFile(file);
close();
child.destroy();
if (res.message) {
throw new Error(res.message);
if (!useCert) {
throw new Error("\u6CA1\u6709\u6743\u9650");
} else if (useCert instanceof Error) {
throw useCert;
}
return res;
const data = await request2.koutu({
url,
appId: c.appId,
workId: res,
abilityCode: c.version,
useCert,
token
});
return { result: data, workId: res };
}
async function openWork(id2) {
return new Promise(async (resolve) => {
const { open, close, iframe } = createIframe(`${env.KOUTU_EDITOR_URL}`, { app_id: c.appId, version: c.version || "KE001" }, () => resolve(false));
return new Promise(async (resolve, reject) => {
const { open, close, iframe } = createIframe(`${env.KOUTU_EDITOR_URL}`, { app_id: c.appId, version: c.version || "KE001", id: id2 }, () => resolve(false));
const child = connectToChild({
iframe,
methods: {
methods: handleFunsErrors({
async onload() {
const service2 = await child.promise;
service2.init({ version: isKE002Config(c) ? c.version : "KE001", appId: c.appId });
service2.init({
version: isKE002Config(c) ? c.version : "KE001",
appId: c.appId
});
},
async getUseRightToken(info) {
const token = isKE002Config(c) ? await c.getUseRightToken(info) : false;
return token;
},
async getUserCode() {
try {
const token = isKE002Config(c) ? await c.getUseRightToken(info) : true;
if (token instanceof Error) {
return {
message: token.message
};
}
return token;
return isKE002Config(c) ? c.getUserCode() : false;
} catch (error) {
return { message: error.message };
reject(error);
close();
}
},
async getUserCode() {
return isKE002Config(c) ? c.getUserCode() : false;
},
download(info) {
async download(info) {
resolve(info);

@@ -749,3 +1671,3 @@ close();

}
}
})
});

@@ -772,3 +1694,7 @@ open();

async function importFile(file) {
return new Promise(async (resolve) => {
let code = "";
if (isIE002Config(c)) {
code = await c.getUserCode();
}
return new Promise(async (resolve, reject) => {
const { open, close, iframe } = createIframe(`${env.IMAGE_EDITOR_URL}`, { app_id: c.appId, version: c.version || "IE001" }, () => resolve(false));

@@ -792,3 +1718,13 @@ const child = connectToChild({

async getUserCode() {
return isIE002Config(c) ? c.getUserCode() : false;
if (code) {
const key = code;
code = "";
return key;
}
try {
return isIE002Config(c) ? c.getUserCode() : false;
} catch (error) {
reject(error);
close();
}
},

@@ -795,0 +1731,0 @@ download(info2) {

10

package.json
{
"name": "@gaoding/editor-sdk",
"description": "稿定编辑器对外 SDK",
"version": "1.1.0-alpha.0",
"version": "1.1.0",
"scripts": {
"build": "vite build",
"serve": "vite preview",
"watch": "vite build -w"
"watch": "vite build -w",
"prepublishOnly": "npm run build"
},

@@ -22,2 +23,3 @@ "files": [

"dependencies": {
"axios": "^0.21.1",
"penpal": "^5.3.0"

@@ -27,5 +29,5 @@ },

"typescript": "^4.3.2",
"vite": "^2.3.8"
"vite": "2.4.4"
},
"gitHead": "23c34432cb9fdaa6d583714adc14215d8ed8db06"
"gitHead": "76bf62e8c2e1d56897fe7bed3211719c71745d13"
}
export const env = {
TEMPLATE_EDITOR_URL: import.meta.env.VITE_TEMPLATE_EDITOR_URL,
KOUTU_EDITOR_URL: import.meta.env.VITE_KOUTU_EDITOR_URL,
IMAGE_EDITOR_URL: import.meta.env.VITE_IMAGE_EDITOR_URL
}
IMAGE_EDITOR_URL: import.meta.env.VITE_IMAGE_EDITOR_URL,
OPEN_PLATFORM_ORIGIN: import.meta.env.VITE_OPEN_PLATFORM_ORIGIN,
};
export * from 'penpal';
export function createIframe(url: string, query: {[k: string]: any }, onClose?: () => void, hide = false) {
export function createIframe(
url: string,
query: { [k: string]: any },
onClose?: () => void,
hide = false,
) {
const frame = document.createElement('iframe');

@@ -11,3 +16,6 @@ frame.style.cssText = `

frame.setAttribute('frameborder', '0');
frame.src = `${url}?${Object.entries(query).filter(([k, v]) => v !== undefined).map(([k, v]) => `${k}=${v}`).join('&')}`;
frame.src = `${url}?${Object.entries(query)
.filter(([_, v]) => v !== undefined)
.map(([k, v]) => `${k}=${v}`)
.join('&')}`;

@@ -82,3 +90,2 @@ const wrapper = document.createElement('div');

let isOpen = false;

@@ -88,2 +95,3 @@ let overflowValue = '';

function toggleScrollSwitch() {
if (hide) return;
const dom: HTMLElement | null = document.querySelector('.gaoding-editor-iframe-dialog');

@@ -118,4 +126,4 @@ if (!dom) return;

open,
close
close,
};
}

@@ -42,3 +42,7 @@ import { createIframe, connectToChild } from './iframe';

async function importFile(file: (string | Blob)[]) {
return new Promise<{ files: Blob[]; urls: string[] } | false>(async resolve => {
let code = '';
if (isIE002Config(c)) {
code = await c.getUserCode();
}
return new Promise<{ files: Blob[]; urls: string[] } | false>(async (resolve, reject) => {
const { open, close, iframe } = createIframe(`${env.IMAGE_EDITOR_URL}`, { app_id: c.appId, version: c.version || 'IE001' }, () => resolve(false));

@@ -62,3 +66,13 @@ const child = connectToChild<ImageEditorService>({

async getUserCode() {
return isIE002Config(c) ? c.getUserCode() : false;
if (code) {
const key = code;
code = '';
return key;
}
try {
return isIE002Config(c) ? c.getUserCode() : false;
} catch (error) {
reject(error);
close();
}
},

@@ -65,0 +79,0 @@ download(info: { files: Blob[]; urls: string[] }) {

@@ -5,4 +5,5 @@ import { createIframe, connectToChild } from './iframe';

import { KoutuEditorMethods, KoutuEditorService } from './type';
import { handleFunsErrors } from './utils';
import { Request } from './request';
interface Config {

@@ -14,7 +15,12 @@ // 应用ID, 在控制台应用详情查看

interface KE002Config extends Config {
version: 'KE002',
version: 'KE002';
/**
* 获取用户权益授权码
*/
getUseRightToken(info: { appId: string; useKey: string; abilityCode: string; workId: string }): Promise<string | false | Error>;
* 获取用户权益授权码
*/
getUseRightToken(info: {
appId: string;
useKey: string;
abilityCode: string;
workId: string;
}): Promise<string | false | Error>;
/**

@@ -30,8 +36,7 @@ * 获取用户标识code

const defineConfig: Partial<Config> = {
const defineConfig: Partial<Config> = {};
};
export function createKoutuEditor(config: Config | KE002Config) {
const c = Object.assign({}, defineConfig, config) as Required<KE002Config>;
const request = new Request();

@@ -41,33 +46,45 @@ assert(!!c?.appId, '缺少 appId 参数');

async function importFile(file: string | Blob) {
return new Promise<{ files: Blob[]; urls: string[] } | false>(async resolve => {
const { open, close, iframe } = createIframe(`${env.KOUTU_EDITOR_URL}`, { app_id: c.appId, version: c.version || 'KE001' }, () => resolve(false));
let code = '';
if (isKE002Config(c)) {
code = await c.getUserCode();
}
return new Promise<{ files: Blob[]; urls: string[] } | false>(async (resolve, reject) => {
const { open, close, iframe } = createIframe(
`${env.KOUTU_EDITOR_URL}`,
{ app_id: c.appId, version: c.version || 'KE001' },
() => resolve(false),
);
const child = connectToChild<KoutuEditorService>({
iframe: iframe,
methods: {
methods: handleFunsErrors({
async onload() {
const service = await child.promise as KoutuEditorService;
service.init({ version: isKE002Config(c) ? c.version : 'KE001', appId: c.appId });
const service = (await child.promise) as KoutuEditorService;
service.init({
version: isKE002Config(c) ? c.version : 'KE001',
appId: c.appId,
});
},
async getUseRightToken(info) {
const token = isKE002Config(c) ? await c.getUseRightToken(info) : false;
return token;
},
async getUserCode() {
try {
const token = isKE002Config(c) ? await c.getUseRightToken(info) : true;
if (token instanceof Error) {
return {
message: token.message
};
if (code) {
const key = code;
code = '';
return key;
}
return token;
return isKE002Config(c) ? await c.getUserCode() : false;
} catch (error) {
return { message: error.message };
reject(error);
close();
}
},
async getUserCode() {
return isKE002Config(c) ? c.getUserCode() : false;
},
download(info: { files: Blob[]; urls: string[] }) {
async download(info: { files: Blob[]; urls: string[] }) {
resolve(info);
close();
child.destroy();
}
} as KoutuEditorMethods
},
}) as KoutuEditorMethods,
});

@@ -80,73 +97,64 @@ open();

async function koutu(file: string | Blob) {
const { open, close, iframe } = createIframe(`${env.KOUTU_EDITOR_URL}`, { app_id: c.appId, version: c.version || 'KE001' }, undefined, true);
iframe.style.display = 'none';
const child = connectToChild<KoutuEditorService>({
iframe: iframe,
methods: {
async onload() {
const service = await child.promise as KoutuEditorService;
service.init({ version: isKE002Config(c) ? c.version : 'KE001', appId: c.appId });
},
async getUseRightToken(info) {
try {
const token = isKE002Config(c) ? await c.getUseRightToken(info) : true;
if (token instanceof Error) {
return {
message: token.message
};
}
return token;
} catch (error) {
return { message: error.message };
}
},
async getUserCode() {
return isKE002Config(c) ? c.getUserCode() : false;
},
} as KoutuEditorMethods
async function koutu(url: string) {
if (!isKE002Config(c)) throw new Error('自动抠图不支持基础版使用');
const code = await c.getUserCode();
const token = await request.createAuth(code);
const res = await request.createKoutuRecord({ token, url });
const useCert = await c.getUseRightToken({
abilityCode: c.version,
appId: c.appId,
workId: res,
useKey: c.version,
});
open();
const service = await child.promise as KoutuEditorService;
const res = await service.exportFile(file);
close();
child.destroy();
if ((res as any).message) {
throw new Error((res as any).message);
if (!useCert) {
throw new Error('没有权限');
} else if (useCert instanceof Error) {
throw useCert;
}
return res;
const data = await request.koutu({
url,
appId: c.appId,
workId: res,
abilityCode: c.version,
useCert,
token,
});
return { result: data, workId: res };
}
async function openWork(id: string) {
return new Promise<{ files: Blob[]; urls: string[] } | false>(async resolve => {
const { open, close, iframe } = createIframe(`${env.KOUTU_EDITOR_URL}`, { app_id: c.appId, version: c.version || 'KE001' }, () => resolve(false));
return new Promise<{ files: Blob[]; urls: string[] } | false>(async (resolve, reject) => {
const { open, close, iframe } = createIframe(
`${env.KOUTU_EDITOR_URL}`,
{ app_id: c.appId, version: c.version || 'KE001', id },
() => resolve(false),
);
const child = connectToChild<KoutuEditorService>({
iframe: iframe,
methods: {
methods: handleFunsErrors({
async onload() {
const service = await child.promise as KoutuEditorService;
service.init({ version: isKE002Config(c) ? c.version : 'KE001', appId: c.appId });
const service = (await child.promise) as KoutuEditorService;
service.init({
version: isKE002Config(c) ? c.version : 'KE001',
appId: c.appId,
});
},
async getUseRightToken(info) {
const token = isKE002Config(c) ? await c.getUseRightToken(info) : false;
return token;
},
async getUserCode() {
try {
const token = isKE002Config(c) ? await c.getUseRightToken(info) : true;
if (token instanceof Error) {
return {
message: token.message
};
}
return token;
return isKE002Config(c) ? c.getUserCode() : false;
} catch (error) {
return { message: error.message };
reject(error);
close();
}
},
async getUserCode() {
return isKE002Config(c) ? c.getUserCode() : false;
},
download(info: { files: Blob[]; urls: string[] }) {
async download(info: { files: Blob[]; urls: string[] }) {
resolve(info);
close();
child.destroy();
}
} as KoutuEditorMethods
},
}) as KoutuEditorMethods,
});

@@ -162,5 +170,4 @@ open();

openWork,
koutu
koutu,
};
}

@@ -64,4 +64,2 @@ import { createIframe, connectToChild } from './iframe';

interface OpenTemplateConfig {
id: string;
categoryId?: string;
onload?: (e: TemplateEditorService) => void;

@@ -71,6 +69,9 @@ onTemplateLoad?: (e: TemplateEditorService) => void;

async function openTemplate(config: OpenTemplateConfig) {
assert(!!config?.id, 'openTemplate 缺少 id 参数');
return new Promise<{ files: Blob[]; urls: string[] } | false>(resolve => {
async function openTemplate(config: OpenTemplateConfig & ({ id: string; categoryId?: string } | { id?: string; categoryId: string })) {
assert((!!config?.categoryId || !!config?.id), 'openTemplate 缺少 id 或者 categoryId 参数');
let code = '';
if (isAdvancedConfig(c)) {
code = await c.getUserCode();
}
return new Promise<{ files: Blob[]; urls: string[] } | false>((resolve, reject) => {
const q = Object.assign({ version: 'TE001' }, query, { id: config.id, thirdCateId: config.categoryId });

@@ -105,3 +106,13 @@ const { open, iframe, close } = createIframe(env.TEMPLATE_EDITOR_URL, q, () => resolve(false));

async getUserCode() {
return isAdvancedConfig(c) ? c.getUserCode() : false;
if (code) {
const key = code;
code = '';
return key;
}
try {
return isAdvancedConfig(c) ? c.getUserCode() : false;
} catch (error) {
reject(error);
close();
}
},

@@ -125,3 +136,3 @@ async download(info: { urls: string[]; files: Blob[] }) {

} = {}) {
return new Promise<{ files: Blob[]; urls: string[] } | false>(resolve => {
return new Promise<{ files: Blob[]; urls: string[] } | false>((resolve, reject) => {
const q = Object.assign({ version: 'TE001' }, query, { thirdCateId: options.categoryId, mode: 'create', width: options.width, height: options.height });

@@ -155,3 +166,8 @@ const { open, iframe, close } = createIframe(env.TEMPLATE_EDITOR_URL, q, () => resolve(false));

async getUserCode() {
return isAdvancedConfig(c) ? c.getUserCode() : false;
try {
return isAdvancedConfig(c) ? c.getUserCode() : false;
} catch (error) {
reject(error);
close();
}
},

@@ -170,3 +186,3 @@ async download(info: { urls: string[]; files: Blob[] }) {

async function importFile(config: { onload?: (e: TemplateEditorService) => void; onTemplateLoad?: (e: TemplateEditorService) => void; } = {}) {
return new Promise<{ files: Blob[]; urls: string[] } | false>(resolve => {
return new Promise<{ files: Blob[]; urls: string[] } | false>((resolve, reject) => {
const q = Object.assign({ version: 'TE001' }, query, { app_id: c.appId, mode: 'psd' });

@@ -202,3 +218,8 @@

async getUserCode() {
return isAdvancedConfig(c) ? c.getUserCode() : false;
try {
return isAdvancedConfig(c) ? c.getUserCode() : false;
} catch (error) {
reject(error);
close();
}
},

@@ -205,0 +226,0 @@ async download(info: { urls: string[]; files: Blob[] }) {

@@ -14,4 +14,4 @@ interface BaseEditorMethods {

onTemplateLoad(): Promise<void>;
[index: string]: Function; //eslint-disable-line

@@ -23,3 +23,3 @@ }

download(info: { urls: string[]; files: Blob[], workId: string; }): Promise<void>;
onTemplateLoad(): Promise<void>;
}

@@ -26,0 +26,0 @@

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc