@manifoldco/manifold-init
Advanced tools
Comparing version 0.4.0 to 0.4.1
@@ -5,8 +5,8 @@ 'use strict'; | ||
const core = require('./core-894a498f.js'); | ||
const core$1 = require('./core-b1e5083c.js'); | ||
const index = require('./index-30f9981c.js'); | ||
const core = require('./core-7e6ee5a9.js'); | ||
const ConnectedButton = class { | ||
constructor(hostRef) { | ||
core.registerInstance(this, hostRef); | ||
index.registerInstance(this, hostRef); | ||
this.getDataSuccess = async () => { | ||
@@ -44,9 +44,9 @@ const response = await this.connection.graphqlFetch({ | ||
version: 0, | ||
componentVersion: '0.4.0', | ||
componentVersion: '0.4.1', | ||
}); | ||
} | ||
render() { | ||
return (core.h("div", null, core.h("button", { type: "button", onClick: this.getDataSuccess }, "Send (success)"), this.success && (core.h("p", null, "Response: ", core.h("pre", null, this.success))), core.h("hr", null), core.h("button", { type: "button", onClick: this.getDataBadRequest }, "Send (bad request)"), this.badRequest && (core.h("p", null, "Response: ", core.h("pre", null, this.badRequest))), core.h("hr", null), core.h("button", { type: "button", onClick: this.getDataUnauthenticated }, "Send (unauthenticated)"), this.unauthenticated && (core.h("p", null, "Response: ", core.h("pre", null, this.unauthenticated))), core.h("hr", null), core.h("button", { type: "button", onClick: this.getPlanCost }, "Send (plan cost)"), this.planCost && (core.h("p", null, "Response: ", core.h("pre", null, this.planCost))))); | ||
return (index.h("div", null, index.h("button", { type: "button", onClick: this.getDataSuccess }, "Send (success)"), this.success && (index.h("p", null, "Response: ", index.h("pre", null, this.success))), index.h("hr", null), index.h("button", { type: "button", onClick: this.getDataBadRequest }, "Send (bad request)"), this.badRequest && (index.h("p", null, "Response: ", index.h("pre", null, this.badRequest))), index.h("hr", null), index.h("button", { type: "button", onClick: this.getDataUnauthenticated }, "Send (unauthenticated)"), this.unauthenticated && (index.h("p", null, "Response: ", index.h("pre", null, this.unauthenticated))), index.h("hr", null), index.h("button", { type: "button", onClick: this.getPlanCost }, "Send (plan cost)"), this.planCost && (index.h("p", null, "Response: ", index.h("pre", null, this.planCost))))); | ||
} | ||
get el() { return core.getElement(this); } | ||
get el() { return index.getElement(this); } | ||
}; | ||
@@ -56,11 +56,24 @@ | ||
constructor(hostRef) { | ||
core.registerInstance(this, hostRef); | ||
index.registerInstance(this, hostRef); | ||
this.env = 'prod'; | ||
this.authType = 'oauth'; | ||
this.clearAuthToken = () => { | ||
this.authToken = undefined; | ||
}; | ||
this.clear = index.createEvent(this, "manifold-auth-token-clear", 7); | ||
this.receive = index.createEvent(this, "manifold-auth-token-receive", 7); | ||
} | ||
tokenChanged(newValue, oldValue) { | ||
if (oldValue && !newValue) { | ||
this.clear.emit(); | ||
} | ||
else if (newValue && oldValue !== newValue) { | ||
this.receive.emit(newValue); | ||
} | ||
} | ||
async initialize(options) { | ||
const { version, componentVersion, element } = options; | ||
return core$1.initialize({ | ||
return core.initialize({ | ||
env: this.env, | ||
authToken: this.authToken, | ||
getAuthToken: () => this.authToken, | ||
authType: this.authType, | ||
@@ -71,2 +84,3 @@ version, | ||
clientId: this.clientId, | ||
clearAuthToken: this.clearAuthToken, | ||
}); | ||
@@ -77,2 +91,5 @@ } | ||
} | ||
static get watchers() { return { | ||
"authToken": ["tokenChanged"] | ||
}; } | ||
}; | ||
@@ -79,0 +96,0 @@ |
@@ -5,3 +5,3 @@ 'use strict'; | ||
const core = require('./core-b1e5083c.js'); | ||
const core = require('./core-7e6ee5a9.js'); | ||
@@ -8,0 +8,0 @@ |
@@ -5,10 +5,8 @@ 'use strict'; | ||
const core = require('./core-894a498f.js'); | ||
const index = require('./index-30f9981c.js'); | ||
const defineCustomElements = (win, options) => { | ||
return core.patchEsm().then(() => { | ||
core.bootstrapLazy([["connected-button_2.cjs",[[0,"connected-button",{"success":[32],"badRequest":[32],"unauthenticated":[32],"planCost":[32]}],[0,"manifold-init",{"env":[1],"authToken":[1,"auth-token"],"authType":[1,"auth-type"],"clientId":[1,"client-id"],"initialize":[64]}]]]], options); | ||
}); | ||
}; | ||
const defineCustomElements = (win, options) => index.patchEsm().then(() => { | ||
return index.bootstrapLazy([["connected-button_2.cjs",[[0,"connected-button",{"success":[32],"badRequest":[32],"unauthenticated":[32],"planCost":[32]}],[0,"manifold-init",{"env":[1],"authToken":[1025,"auth-token"],"authType":[1,"auth-type"],"clientId":[1,"client-id"],"initialize":[64]}]]]], options); | ||
}); | ||
exports.defineCustomElements = defineCustomElements; |
'use strict'; | ||
const core = require('./core-894a498f.js'); | ||
const index = require('./index-30f9981c.js'); | ||
core.patchBrowser().then(options => { | ||
return core.bootstrapLazy([["connected-button_2.cjs",[[0,"connected-button",{"success":[32],"badRequest":[32],"unauthenticated":[32],"planCost":[32]}],[0,"manifold-init",{"env":[1],"authToken":[1,"auth-token"],"authType":[1,"auth-type"],"clientId":[1,"client-id"],"initialize":[64]}]]]], options); | ||
index.patchBrowser().then(options => { | ||
return index.bootstrapLazy([["connected-button_2.cjs",[[0,"connected-button",{"success":[32],"badRequest":[32],"unauthenticated":[32],"planCost":[32]}],[0,"manifold-init",{"env":[1],"authToken":[1025,"auth-token"],"authType":[1,"auth-type"],"clientId":[1,"client-id"],"initialize":[64]}]]]], options); | ||
}); |
{ | ||
"entries": [ | ||
"components/connected-button/connected-button.js", | ||
"components/manifold-init/manifold-init.js" | ||
"./components/manifold-init/manifold-init.js", | ||
"./components/connected-button/connected-button.js" | ||
], | ||
"compiler": { | ||
"name": "@stencil/core", | ||
"version": "1.8.4", | ||
"typescriptVersion": "3.7.2" | ||
"version": "1.11.2", | ||
"typescriptVersion": "3.8.3" | ||
}, | ||
@@ -11,0 +11,0 @@ "collections": [], |
@@ -1,2 +0,2 @@ | ||
import { h } from "@stencil/core"; | ||
import { Component, Element, State, h } from '@stencil/core'; | ||
export class ConnectedButton { | ||
@@ -3,0 +3,0 @@ constructor() { |
@@ -0,1 +1,2 @@ | ||
import { Component, Prop, Method, Event, Watch } from '@stencil/core'; | ||
import * as core from '../../core'; | ||
@@ -6,3 +7,14 @@ export class ManifoldInit { | ||
this.authType = 'oauth'; | ||
this.clearAuthToken = () => { | ||
this.authToken = undefined; | ||
}; | ||
} | ||
tokenChanged(newValue, oldValue) { | ||
if (oldValue && !newValue) { | ||
this.clear.emit(); | ||
} | ||
else if (newValue && oldValue !== newValue) { | ||
this.receive.emit(newValue); | ||
} | ||
} | ||
async initialize(options) { | ||
@@ -12,3 +24,3 @@ const { version, componentVersion, element } = options; | ||
env: this.env, | ||
authToken: this.authToken, | ||
getAuthToken: () => this.authToken, | ||
authType: this.authType, | ||
@@ -19,2 +31,3 @@ version, | ||
clientId: this.clientId, | ||
clearAuthToken: this.clearAuthToken, | ||
}); | ||
@@ -31,4 +44,4 @@ } | ||
"complexType": { | ||
"original": "'stage' | 'prod'", | ||
"resolved": "\"prod\" | \"stage\"", | ||
"original": "'local' | 'stage' | 'prod'", | ||
"resolved": "\"local\" | \"prod\" | \"stage\"", | ||
"references": {} | ||
@@ -48,3 +61,3 @@ }, | ||
"type": "string", | ||
"mutable": false, | ||
"mutable": true, | ||
"complexType": { | ||
@@ -100,2 +113,33 @@ "original": "string", | ||
}; } | ||
static get events() { return [{ | ||
"method": "clear", | ||
"name": "manifold-auth-token-clear", | ||
"bubbles": true, | ||
"cancelable": true, | ||
"composed": true, | ||
"docs": { | ||
"tags": [], | ||
"text": "" | ||
}, | ||
"complexType": { | ||
"original": "any", | ||
"resolved": "any", | ||
"references": {} | ||
} | ||
}, { | ||
"method": "receive", | ||
"name": "manifold-auth-token-receive", | ||
"bubbles": true, | ||
"cancelable": true, | ||
"composed": true, | ||
"docs": { | ||
"tags": [], | ||
"text": "" | ||
}, | ||
"complexType": { | ||
"original": "string", | ||
"resolved": "string", | ||
"references": {} | ||
} | ||
}]; } | ||
static get methods() { return { | ||
@@ -128,2 +172,6 @@ "initialize": { | ||
}; } | ||
static get watchers() { return [{ | ||
"propName": "authToken", | ||
"methodName": "tokenChanged" | ||
}]; } | ||
} |
import connection from './v0'; | ||
const getConnection = (options) => { | ||
const { version, element, env, componentVersion, clientId } = options; | ||
export function initialize(options) { | ||
const { version, element, env, componentVersion, clientId, getAuthToken, clearAuthToken, } = options; | ||
switch (version) { | ||
@@ -12,2 +12,4 @@ case undefined: // latest | ||
clientId, | ||
getAuthToken, | ||
clearAuthToken, | ||
}); | ||
@@ -17,5 +19,2 @@ default: | ||
} | ||
}; | ||
export function initialize(options) { | ||
return getConnection(options); | ||
} |
export { initialize } from './core'; |
@@ -0,0 +0,0 @@ export const endpoint = { |
@@ -0,0 +0,0 @@ import { ManifoldError, ErrorType } from './ManifoldError'; |
import { ManifoldError, ErrorType } from './ManifoldError'; | ||
import { waitForAuthToken } from '../utils/auth'; | ||
function wait(ms) { | ||
@@ -19,3 +20,3 @@ return new Promise(resolve => setTimeout(resolve, ms)); | ||
const findAuthError = (errors = []) => errors.find(e => e.extensions && e.extensions.type === 'AuthFailed'); | ||
export function createGraphqlFetch({ element, endpoint = () => 'https://api.manifold.co/graphql', version, retries = 3, clientId, }) { | ||
export function createGraphqlFetch({ element, endpoint = () => 'https://api.manifold.co/graphql', getAuthToken, clearAuthToken, version, retries = 3, clientId, analytics, waitTime = 15000, }) { | ||
const options = { | ||
@@ -30,5 +31,10 @@ method: 'POST', | ||
}; | ||
const token = getAuthToken(); | ||
if (clientId) { | ||
options.headers['Manifold-Client-ID'] = clientId; | ||
} | ||
if (token) { | ||
/* eslint-disable-next-line dot-notation */ | ||
options.headers['Authorization'] = `Bearer ${token}`; | ||
} | ||
async function graphqlFetch(args, attempts) { | ||
@@ -72,5 +78,20 @@ const canRetry = attempts < retries; | ||
const authError = findAuthError(body.errors); | ||
if (authError && canRetry) { | ||
// TODO retry auth | ||
return Promise.reject(new ManifoldError({ type: ErrorType.AuthorizationError, message: authError.message })); | ||
if (authError) { | ||
if (!canRetry) { | ||
throw new ManifoldError({ | ||
type: ErrorType.AuthorizationError, | ||
message: 'Auth token expired', | ||
}); | ||
} | ||
try { | ||
clearAuthToken(); | ||
return waitForAuthToken(getAuthToken, waitTime, () => graphqlFetch(args, attempts + 1)); | ||
} | ||
catch (e) { | ||
analytics.report({ | ||
message: e.message, | ||
name: 'manifold-init-error', | ||
}); | ||
throw new ManifoldError({ type: ErrorType.AuthorizationError, message: authError.message }); | ||
} | ||
} | ||
@@ -77,0 +98,0 @@ return body; |
@@ -5,3 +5,4 @@ import createAnalytics from './analytics'; | ||
const connection = (options) => { | ||
const { componentVersion, element, env, clientId } = options; | ||
const { componentVersion, element, env, clientId, getAuthToken, clearAuthToken } = options; | ||
const analytics = createAnalytics({ env, element, componentVersion, clientId }); | ||
return { | ||
@@ -14,3 +15,3 @@ gateway: createGateway({ | ||
case 'local': | ||
return 'https://api.arigato.tools/v1'; | ||
return 'http://api.gateway.arigato.tools/v1'; | ||
default: | ||
@@ -24,3 +25,6 @@ return 'https://api.manifold.co/v1'; | ||
version: componentVersion, | ||
getAuthToken, | ||
clearAuthToken, | ||
clientId, | ||
analytics, | ||
endpoint: () => { | ||
@@ -31,3 +35,3 @@ switch (env) { | ||
case 'local': | ||
return 'https://api.arigato.tools/graphql'; | ||
return 'http://graphql.arigato.tools/graphql'; | ||
default: | ||
@@ -38,5 +42,5 @@ return 'https://api.manifold.co/graphql'; | ||
}), | ||
analytics: createAnalytics({ env, element, componentVersion, clientId }), | ||
analytics, | ||
}; | ||
}; | ||
export default connection; |
@@ -0,0 +0,0 @@ export var ErrorType; |
@@ -1,162 +0,88 @@ | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (_) try { | ||
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
}; | ||
import { r as registerInstance, h, g as getElement } from './core-14d8f2fa.js'; | ||
import { i as initialize } from './core-4493eb04.js'; | ||
var ConnectedButton = /** @class */ (function () { | ||
function class_1(hostRef) { | ||
var _this = this; | ||
import { r as registerInstance, h, g as getElement, c as createEvent } from './index-a264feef.js'; | ||
import { i as initialize } from './core-acc7e452.js'; | ||
const ConnectedButton = class { | ||
constructor(hostRef) { | ||
registerInstance(this, hostRef); | ||
this.getDataSuccess = function () { return __awaiter(_this, void 0, void 0, function () { | ||
var response; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, this.connection.graphqlFetch({ | ||
query: "{ product(label: \"jawsdb-mysql\") { displayName } }", | ||
})]; | ||
case 1: | ||
response = _a.sent(); | ||
this.success = JSON.stringify(response, null, 2); | ||
return [2 /*return*/]; | ||
} | ||
this.getDataSuccess = async () => { | ||
const response = await this.connection.graphqlFetch({ | ||
query: `{ product(label: "jawsdb-mysql") { displayName } }`, | ||
}); | ||
}); }; | ||
this.getDataBadRequest = function () { return __awaiter(_this, void 0, void 0, function () { | ||
var response; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, this.connection.graphqlFetch({ | ||
query: "{ product(label: \"jawsdb-mysql\") { notAField } }", | ||
})]; | ||
case 1: | ||
response = _a.sent(); | ||
this.badRequest = JSON.stringify(response, null, 2); | ||
return [2 /*return*/]; | ||
} | ||
this.success = JSON.stringify(response, null, 2); | ||
}; | ||
this.getDataBadRequest = async () => { | ||
const response = await this.connection.graphqlFetch({ | ||
query: `{ product(label: "jawsdb-mysql") { notAField } }`, | ||
}); | ||
}); }; | ||
this.getDataUnauthenticated = function () { return __awaiter(_this, void 0, void 0, function () { | ||
var response; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, this.connection.graphqlFetch({ | ||
query: "{ resource(label: \"jawsdb-mysql\") { label } }", | ||
})]; | ||
case 1: | ||
response = _a.sent(); | ||
this.unauthenticated = JSON.stringify(response, null, 2); | ||
return [2 /*return*/]; | ||
} | ||
this.badRequest = JSON.stringify(response, null, 2); | ||
}; | ||
this.getDataUnauthenticated = async () => { | ||
const response = await this.connection.graphqlFetch({ | ||
query: `{ resource(label: "jawsdb-mysql") { label } }`, | ||
}); | ||
}); }; | ||
this.getPlanCost = function () { return __awaiter(_this, void 0, void 0, function () { | ||
var selection, response; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
selection = { | ||
features: { backups: 1, instance_class: 'db.t2.micro', redundancy: false, storage: 5 }, | ||
}; | ||
return [4 /*yield*/, this.connection.gateway.post('/id/plan/235exy25wvzpxj52p87bh87gbnj4y/cost', selection)]; | ||
case 1: | ||
response = _a.sent(); | ||
this.planCost = JSON.stringify(response, null, 2); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); }; | ||
this.unauthenticated = JSON.stringify(response, null, 2); | ||
}; | ||
this.getPlanCost = async () => { | ||
const selection = { | ||
features: { backups: 1, instance_class: 'db.t2.micro', redundancy: false, storage: 5 }, | ||
}; | ||
const response = await this.connection.gateway.post('/id/plan/235exy25wvzpxj52p87bh87gbnj4y/cost', selection); | ||
this.planCost = JSON.stringify(response, null, 2); | ||
}; | ||
} | ||
class_1.prototype.componentWillLoad = function () { | ||
return __awaiter(this, void 0, void 0, function () { | ||
var core, _a; | ||
return __generator(this, function (_b) { | ||
switch (_b.label) { | ||
case 0: return [4 /*yield*/, customElements.whenDefined('manifold-init')]; | ||
case 1: | ||
_b.sent(); | ||
core = document.querySelector('manifold-init'); | ||
_a = this; | ||
return [4 /*yield*/, core.initialize({ | ||
element: this.el, | ||
version: 0, | ||
componentVersion: '0.4.0', | ||
})]; | ||
case 2: | ||
_a.connection = _b.sent(); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
async componentWillLoad() { | ||
await customElements.whenDefined('manifold-init'); | ||
const core = document.querySelector('manifold-init'); | ||
this.connection = await core.initialize({ | ||
element: this.el, | ||
version: 0, | ||
componentVersion: '0.4.1', | ||
}); | ||
}; | ||
class_1.prototype.render = function () { | ||
} | ||
render() { | ||
return (h("div", null, h("button", { type: "button", onClick: this.getDataSuccess }, "Send (success)"), this.success && (h("p", null, "Response: ", h("pre", null, this.success))), h("hr", null), h("button", { type: "button", onClick: this.getDataBadRequest }, "Send (bad request)"), this.badRequest && (h("p", null, "Response: ", h("pre", null, this.badRequest))), h("hr", null), h("button", { type: "button", onClick: this.getDataUnauthenticated }, "Send (unauthenticated)"), this.unauthenticated && (h("p", null, "Response: ", h("pre", null, this.unauthenticated))), h("hr", null), h("button", { type: "button", onClick: this.getPlanCost }, "Send (plan cost)"), this.planCost && (h("p", null, "Response: ", h("pre", null, this.planCost))))); | ||
}; | ||
Object.defineProperty(class_1.prototype, "el", { | ||
get: function () { return getElement(this); }, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
return class_1; | ||
}()); | ||
var ManifoldInit = /** @class */ (function () { | ||
function class_2(hostRef) { | ||
} | ||
get el() { return getElement(this); } | ||
}; | ||
const ManifoldInit = class { | ||
constructor(hostRef) { | ||
registerInstance(this, hostRef); | ||
this.env = 'prod'; | ||
this.authType = 'oauth'; | ||
this.clearAuthToken = () => { | ||
this.authToken = undefined; | ||
}; | ||
this.clear = createEvent(this, "manifold-auth-token-clear", 7); | ||
this.receive = createEvent(this, "manifold-auth-token-receive", 7); | ||
} | ||
class_2.prototype.initialize = function (options) { | ||
return __awaiter(this, void 0, void 0, function () { | ||
var version, componentVersion, element; | ||
return __generator(this, function (_a) { | ||
version = options.version, componentVersion = options.componentVersion, element = options.element; | ||
return [2 /*return*/, initialize({ | ||
env: this.env, | ||
authToken: this.authToken, | ||
authType: this.authType, | ||
version: version, | ||
componentVersion: componentVersion, | ||
element: element, | ||
clientId: this.clientId, | ||
})]; | ||
}); | ||
tokenChanged(newValue, oldValue) { | ||
if (oldValue && !newValue) { | ||
this.clear.emit(); | ||
} | ||
else if (newValue && oldValue !== newValue) { | ||
this.receive.emit(newValue); | ||
} | ||
} | ||
async initialize(options) { | ||
const { version, componentVersion, element } = options; | ||
return initialize({ | ||
env: this.env, | ||
getAuthToken: () => this.authToken, | ||
authType: this.authType, | ||
version, | ||
componentVersion, | ||
element, | ||
clientId: this.clientId, | ||
clearAuthToken: this.clearAuthToken, | ||
}); | ||
}; | ||
class_2.prototype.render = function () { | ||
} | ||
render() { | ||
return null; | ||
}; | ||
return class_2; | ||
}()); | ||
} | ||
static get watchers() { return { | ||
"authToken": ["tokenChanged"] | ||
}; } | ||
}; | ||
export { ConnectedButton as connected_button, ManifoldInit as manifold_init }; |
@@ -1,3 +0,3 @@ | ||
import { r as registerInstance, h, g as getElement } from './core-14d8f2fa.js'; | ||
import { i as initialize } from './core-4493eb04.js'; | ||
import { r as registerInstance, h, g as getElement, c as createEvent } from './index-a264feef.js'; | ||
import { i as initialize } from './core-acc7e452.js'; | ||
@@ -39,3 +39,3 @@ const ConnectedButton = class { | ||
version: 0, | ||
componentVersion: '0.4.0', | ||
componentVersion: '0.4.1', | ||
}); | ||
@@ -54,3 +54,16 @@ } | ||
this.authType = 'oauth'; | ||
this.clearAuthToken = () => { | ||
this.authToken = undefined; | ||
}; | ||
this.clear = createEvent(this, "manifold-auth-token-clear", 7); | ||
this.receive = createEvent(this, "manifold-auth-token-receive", 7); | ||
} | ||
tokenChanged(newValue, oldValue) { | ||
if (oldValue && !newValue) { | ||
this.clear.emit(); | ||
} | ||
else if (newValue && oldValue !== newValue) { | ||
this.receive.emit(newValue); | ||
} | ||
} | ||
async initialize(options) { | ||
@@ -60,3 +73,3 @@ const { version, componentVersion, element } = options; | ||
env: this.env, | ||
authToken: this.authToken, | ||
getAuthToken: () => this.authToken, | ||
authType: this.authType, | ||
@@ -67,2 +80,3 @@ version, | ||
clientId: this.clientId, | ||
clearAuthToken: this.clearAuthToken, | ||
}); | ||
@@ -73,4 +87,7 @@ } | ||
} | ||
static get watchers() { return { | ||
"authToken": ["tokenChanged"] | ||
}; } | ||
}; | ||
export { ConnectedButton as connected_button, ManifoldInit as manifold_init }; |
@@ -1,658 +0,1 @@ | ||
/* | ||
Extremely simple css parser. Intended to be not more than what we need | ||
and definitely not necessarily correct =). | ||
*/ | ||
/** @unrestricted */ | ||
var StyleNode = /** @class */ (function () { | ||
function StyleNode() { | ||
this.start = 0; | ||
this.end = 0; | ||
this.previous = null; | ||
this.parent = null; | ||
this.rules = null; | ||
this.parsedCssText = ''; | ||
this.cssText = ''; | ||
this.atRule = false; | ||
this.type = 0; | ||
this.keyframesName = ''; | ||
this.selector = ''; | ||
this.parsedSelector = ''; | ||
} | ||
return StyleNode; | ||
}()); | ||
// given a string of css, return a simple rule tree | ||
/** | ||
* @param {string} text | ||
* @return {StyleNode} | ||
*/ | ||
function parse(text) { | ||
text = clean(text); | ||
return parseCss(lex(text), text); | ||
} | ||
// remove stuff we don't care about that may hinder parsing | ||
/** | ||
* @param {string} cssText | ||
* @return {string} | ||
*/ | ||
function clean(cssText) { | ||
return cssText.replace(RX.comments, '').replace(RX.port, ''); | ||
} | ||
// super simple {...} lexer that returns a node tree | ||
/** | ||
* @param {string} text | ||
* @return {StyleNode} | ||
*/ | ||
function lex(text) { | ||
var root = new StyleNode(); | ||
root['start'] = 0; | ||
root['end'] = text.length; | ||
var n = root; | ||
for (var i = 0, l = text.length; i < l; i++) { | ||
if (text[i] === OPEN_BRACE) { | ||
if (!n['rules']) { | ||
n['rules'] = []; | ||
} | ||
var p = n; | ||
var previous = p['rules'][p['rules'].length - 1] || null; | ||
n = new StyleNode(); | ||
n['start'] = i + 1; | ||
n['parent'] = p; | ||
n['previous'] = previous; | ||
p['rules'].push(n); | ||
} | ||
else if (text[i] === CLOSE_BRACE) { | ||
n['end'] = i + 1; | ||
n = n['parent'] || root; | ||
} | ||
} | ||
return root; | ||
} | ||
// add selectors/cssText to node tree | ||
/** | ||
* @param {StyleNode} node | ||
* @param {string} text | ||
* @return {StyleNode} | ||
*/ | ||
function parseCss(node, text) { | ||
var t = text.substring(node['start'], node['end'] - 1); | ||
node['parsedCssText'] = node['cssText'] = t.trim(); | ||
if (node.parent) { | ||
var ss = node.previous ? node.previous['end'] : node.parent['start']; | ||
t = text.substring(ss, node['start'] - 1); | ||
t = _expandUnicodeEscapes(t); | ||
t = t.replace(RX.multipleSpaces, ' '); | ||
// TODO(sorvell): ad hoc; make selector include only after last ; | ||
// helps with mixin syntax | ||
t = t.substring(t.lastIndexOf(';') + 1); | ||
var s = node['parsedSelector'] = node['selector'] = t.trim(); | ||
node['atRule'] = (s.indexOf(AT_START) === 0); | ||
// note, support a subset of rule types... | ||
if (node['atRule']) { | ||
if (s.indexOf(MEDIA_START) === 0) { | ||
node['type'] = types.MEDIA_RULE; | ||
} | ||
else if (s.match(RX.keyframesRule)) { | ||
node['type'] = types.KEYFRAMES_RULE; | ||
node['keyframesName'] = node['selector'].split(RX.multipleSpaces).pop(); | ||
} | ||
} | ||
else { | ||
if (s.indexOf(VAR_START) === 0) { | ||
node['type'] = types.MIXIN_RULE; | ||
} | ||
else { | ||
node['type'] = types.STYLE_RULE; | ||
} | ||
} | ||
} | ||
var r$ = node['rules']; | ||
if (r$) { | ||
for (var i = 0, l = r$.length, r = void 0; (i < l) && (r = r$[i]); i++) { | ||
parseCss(r, text); | ||
} | ||
} | ||
return node; | ||
} | ||
/** | ||
* conversion of sort unicode escapes with spaces like `\33 ` (and longer) into | ||
* expanded form that doesn't require trailing space `\000033` | ||
* @param {string} s | ||
* @return {string} | ||
*/ | ||
function _expandUnicodeEscapes(s) { | ||
return s.replace(/\\([0-9a-f]{1,6})\s/gi, function () { | ||
var code = arguments[1], repeat = 6 - code.length; | ||
while (repeat--) { | ||
code = '0' + code; | ||
} | ||
return '\\' + code; | ||
}); | ||
} | ||
/** @enum {number} */ | ||
var types = { | ||
STYLE_RULE: 1, | ||
KEYFRAMES_RULE: 7, | ||
MEDIA_RULE: 4, | ||
MIXIN_RULE: 1000 | ||
}; | ||
var OPEN_BRACE = '{'; | ||
var CLOSE_BRACE = '}'; | ||
// helper regexp's | ||
var RX = { | ||
comments: /\/\*[^*]*\*+([^/*][^*]*\*+)*\//gim, | ||
port: /@import[^;]*;/gim, | ||
customProp: /(?:^[^;\-\s}]+)?--[^;{}]*?:[^{};]*?(?:[;\n]|$)/gim, | ||
mixinProp: /(?:^[^;\-\s}]+)?--[^;{}]*?:[^{};]*?{[^}]*?}(?:[;\n]|$)?/gim, | ||
mixinApply: /@apply\s*\(?[^);]*\)?\s*(?:[;\n]|$)?/gim, | ||
varApply: /[^;:]*?:[^;]*?var\([^;]*\)(?:[;\n]|$)?/gim, | ||
keyframesRule: /^@[^\s]*keyframes/, | ||
multipleSpaces: /\s+/g | ||
}; | ||
var VAR_START = '--'; | ||
var MEDIA_START = '@media'; | ||
var AT_START = '@'; | ||
function findRegex(regex, cssText, offset) { | ||
regex['lastIndex'] = 0; | ||
var r = cssText.substring(offset).match(regex); | ||
if (r) { | ||
var start = offset + r['index']; | ||
return { | ||
start: start, | ||
end: start + r[0].length | ||
}; | ||
} | ||
return null; | ||
} | ||
var VAR_USAGE_START = /\bvar\(/; | ||
var VAR_ASSIGN_START = /\B--[\w-]+\s*:/; | ||
var COMMENTS = /\/\*[^*]*\*+([^/*][^*]*\*+)*\//gim; | ||
var TRAILING_LINES = /^[\t ]+\n/gm; | ||
function resolveVar(props, prop, fallback) { | ||
if (props[prop]) { | ||
return props[prop]; | ||
} | ||
if (fallback) { | ||
return executeTemplate(fallback, props); | ||
} | ||
return ''; | ||
} | ||
function findVarEndIndex(cssText, offset) { | ||
var count = 0; | ||
var i = offset; | ||
for (; i < cssText.length; i++) { | ||
var c = cssText[i]; | ||
if (c === '(') { | ||
count++; | ||
} | ||
else if (c === ')') { | ||
count--; | ||
if (count <= 0) { | ||
return i + 1; | ||
} | ||
} | ||
} | ||
return i; | ||
} | ||
function parseVar(cssText, offset) { | ||
var varPos = findRegex(VAR_USAGE_START, cssText, offset); | ||
if (!varPos) { | ||
return null; | ||
} | ||
var endVar = findVarEndIndex(cssText, varPos.start); | ||
var varContent = cssText.substring(varPos.end, endVar - 1); | ||
var _a = varContent.split(','), propName = _a[0], fallback = _a.slice(1); | ||
return { | ||
start: varPos.start, | ||
end: endVar, | ||
propName: propName.trim(), | ||
fallback: fallback.length > 0 ? fallback.join(',').trim() : undefined | ||
}; | ||
} | ||
function compileVar(cssText, template, offset) { | ||
var varMeta = parseVar(cssText, offset); | ||
if (!varMeta) { | ||
template.push(cssText.substring(offset, cssText.length)); | ||
return cssText.length; | ||
} | ||
var propName = varMeta.propName; | ||
var fallback = varMeta.fallback != null ? compileTemplate(varMeta.fallback) : undefined; | ||
template.push(cssText.substring(offset, varMeta.start), function (params) { return resolveVar(params, propName, fallback); }); | ||
return varMeta.end; | ||
} | ||
function executeTemplate(template, props) { | ||
var final = ''; | ||
for (var i = 0; i < template.length; i++) { | ||
var s = template[i]; | ||
final += (typeof s === 'string') | ||
? s | ||
: s(props); | ||
} | ||
return final; | ||
} | ||
function findEndValue(cssText, offset) { | ||
var onStr = false; | ||
var double = false; | ||
var i = offset; | ||
for (; i < cssText.length; i++) { | ||
var c = cssText[i]; | ||
if (onStr) { | ||
if (double && c === '"') { | ||
onStr = false; | ||
} | ||
if (!double && c === '\'') { | ||
onStr = false; | ||
} | ||
} | ||
else { | ||
if (c === '"') { | ||
onStr = true; | ||
double = true; | ||
} | ||
else if (c === '\'') { | ||
onStr = true; | ||
double = false; | ||
} | ||
else if (c === ';') { | ||
return i + 1; | ||
} | ||
else if (c === '}') { | ||
return i; | ||
} | ||
} | ||
} | ||
return i; | ||
} | ||
function removeCustomAssigns(cssText) { | ||
var final = ''; | ||
var offset = 0; | ||
while (true) { | ||
var assignPos = findRegex(VAR_ASSIGN_START, cssText, offset); | ||
var start = assignPos ? assignPos.start : cssText.length; | ||
final += cssText.substring(offset, start); | ||
if (assignPos) { | ||
offset = findEndValue(cssText, start); | ||
} | ||
else { | ||
break; | ||
} | ||
} | ||
return final; | ||
} | ||
function compileTemplate(cssText) { | ||
var index = 0; | ||
cssText = cssText.replace(COMMENTS, ''); | ||
cssText = removeCustomAssigns(cssText) | ||
.replace(TRAILING_LINES, ''); | ||
var segments = []; | ||
while (index < cssText.length) { | ||
index = compileVar(cssText, segments, index); | ||
} | ||
return segments; | ||
} | ||
function resolveValues(selectors) { | ||
var props = {}; | ||
selectors.forEach(function (selector) { | ||
selector.declarations.forEach(function (dec) { | ||
props[dec.prop] = dec.value; | ||
}); | ||
}); | ||
var propsValues = {}; | ||
var entries = Object.entries(props); | ||
var _loop_1 = function (i) { | ||
var dirty = false; | ||
entries.forEach(function (_a) { | ||
var key = _a[0], value = _a[1]; | ||
var propValue = executeTemplate(value, propsValues); | ||
if (propValue !== propsValues[key]) { | ||
propsValues[key] = propValue; | ||
dirty = true; | ||
} | ||
}); | ||
if (!dirty) { | ||
return "break"; | ||
} | ||
}; | ||
for (var i = 0; i < 10; i++) { | ||
var state_1 = _loop_1(i); | ||
if (state_1 === "break") | ||
break; | ||
} | ||
return propsValues; | ||
} | ||
function getSelectors(root, index) { | ||
if (index === void 0) { index = 0; } | ||
if (!root.rules) { | ||
return []; | ||
} | ||
var selectors = []; | ||
root.rules | ||
.filter(function (rule) { return rule.type === types.STYLE_RULE; }) | ||
.forEach(function (rule) { | ||
var declarations = getDeclarations(rule.cssText); | ||
if (declarations.length > 0) { | ||
rule.parsedSelector.split(',').forEach(function (selector) { | ||
selector = selector.trim(); | ||
selectors.push({ | ||
selector: selector, | ||
declarations: declarations, | ||
specificity: computeSpecificity(), | ||
nu: index | ||
}); | ||
}); | ||
} | ||
index++; | ||
}); | ||
return selectors; | ||
} | ||
function computeSpecificity(_selector) { | ||
return 1; | ||
} | ||
var IMPORTANT = '!important'; | ||
var FIND_DECLARATIONS = /(?:^|[;\s{]\s*)(--[\w-]*?)\s*:\s*(?:((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};{])+)|\{([^}]*)\}(?:(?=[;\s}])|$))/gm; | ||
function getDeclarations(cssText) { | ||
var declarations = []; | ||
var xArray; | ||
while (xArray = FIND_DECLARATIONS.exec(cssText.trim())) { | ||
var _a = normalizeValue(xArray[2]), value = _a.value, important = _a.important; | ||
declarations.push({ | ||
prop: xArray[1].trim(), | ||
value: compileTemplate(value), | ||
important: important, | ||
}); | ||
} | ||
return declarations; | ||
} | ||
function normalizeValue(value) { | ||
var regex = /\s+/gim; | ||
value = value.replace(regex, ' ').trim(); | ||
var important = value.endsWith(IMPORTANT); | ||
if (important) { | ||
value = value.substr(0, value.length - IMPORTANT.length).trim(); | ||
} | ||
return { | ||
value: value, | ||
important: important | ||
}; | ||
} | ||
function getActiveSelectors(hostEl, hostScopeMap, globalScopes) { | ||
// computes the css scopes that might affect this particular element | ||
// avoiding using spread arrays to avoid ts helper fns when in es5 | ||
var scopes = []; | ||
var scopesForElement = getScopesForElement(hostScopeMap, hostEl); | ||
// globalScopes are always took into account | ||
globalScopes.forEach(function (s) { return scopes.push(s); }); | ||
// the parent scopes are computed by walking parent dom until <html> is reached | ||
scopesForElement.forEach(function (s) { return scopes.push(s); }); | ||
// each scope might have an array of associated selectors | ||
// let's flatten the complete array of selectors from all the scopes | ||
var selectorSet = getSelectorsForScopes(scopes); | ||
// we filter to only the selectors that matches the hostEl | ||
var activeSelectors = selectorSet.filter(function (selector) { return matches(hostEl, selector.selector); }); | ||
// sort selectors by specifity | ||
return sortSelectors(activeSelectors); | ||
} | ||
function getScopesForElement(hostTemplateMap, node) { | ||
var scopes = []; | ||
while (node) { | ||
var scope = hostTemplateMap.get(node); | ||
if (scope) { | ||
scopes.push(scope); | ||
} | ||
node = node.parentElement; | ||
} | ||
return scopes; | ||
} | ||
function getSelectorsForScopes(scopes) { | ||
var selectors = []; | ||
scopes.forEach(function (scope) { | ||
selectors.push.apply(selectors, scope.selectors); | ||
}); | ||
return selectors; | ||
} | ||
function sortSelectors(selectors) { | ||
selectors.sort(function (a, b) { | ||
if (a.specificity === b.specificity) { | ||
return a.nu - b.nu; | ||
} | ||
return a.specificity - b.specificity; | ||
}); | ||
return selectors; | ||
} | ||
function matches(el, selector) { | ||
return selector === ':root' || selector === 'html' || el.matches(selector); | ||
} | ||
function parseCSS(original) { | ||
var ast = parse(original); | ||
var template = compileTemplate(original); | ||
var selectors = getSelectors(ast); | ||
return { | ||
original: original, | ||
template: template, | ||
selectors: selectors, | ||
usesCssVars: template.length > 1 | ||
}; | ||
} | ||
function addGlobalStyle(globalScopes, styleEl) { | ||
if (globalScopes.some(function (css) { return css.styleEl === styleEl; })) { | ||
return false; | ||
} | ||
var css = parseCSS(styleEl.textContent); | ||
css.styleEl = styleEl; | ||
globalScopes.push(css); | ||
return true; | ||
} | ||
function updateGlobalScopes(scopes) { | ||
var selectors = getSelectorsForScopes(scopes); | ||
var props = resolveValues(selectors); | ||
scopes.forEach(function (scope) { | ||
if (scope.usesCssVars) { | ||
scope.styleEl.textContent = executeTemplate(scope.template, props); | ||
} | ||
}); | ||
} | ||
function reScope(scope, scopeId) { | ||
var template = scope.template.map(function (segment) { | ||
return (typeof segment === 'string') | ||
? replaceScope(segment, scope.scopeId, scopeId) | ||
: segment; | ||
}); | ||
var selectors = scope.selectors.map(function (sel) { | ||
return Object.assign(Object.assign({}, sel), { selector: replaceScope(sel.selector, scope.scopeId, scopeId) }); | ||
}); | ||
return Object.assign(Object.assign({}, scope), { template: template, | ||
selectors: selectors, | ||
scopeId: scopeId }); | ||
} | ||
function replaceScope(original, oldScopeId, newScopeId) { | ||
original = replaceAll(original, "\\." + oldScopeId, "." + newScopeId); | ||
return original; | ||
} | ||
function replaceAll(input, find, replace) { | ||
return input.replace(new RegExp(find, 'g'), replace); | ||
} | ||
function loadDocument(doc, globalScopes) { | ||
loadDocumentStyles(doc, globalScopes); | ||
return loadDocumentLinks(doc, globalScopes).then(function () { | ||
updateGlobalScopes(globalScopes); | ||
}); | ||
} | ||
function startWatcher(doc, globalScopes) { | ||
var mutation = new MutationObserver(function () { | ||
if (loadDocumentStyles(doc, globalScopes)) { | ||
updateGlobalScopes(globalScopes); | ||
} | ||
}); | ||
mutation.observe(document.head, { childList: true }); | ||
} | ||
function loadDocumentLinks(doc, globalScopes) { | ||
var promises = []; | ||
var linkElms = doc.querySelectorAll('link[rel="stylesheet"][href]:not([data-no-shim])'); | ||
for (var i = 0; i < linkElms.length; i++) { | ||
promises.push(addGlobalLink(doc, globalScopes, linkElms[i])); | ||
} | ||
return Promise.all(promises); | ||
} | ||
function loadDocumentStyles(doc, globalScopes) { | ||
var styleElms = Array.from(doc.querySelectorAll('style:not([data-styles]):not([data-no-shim])')); | ||
return styleElms | ||
.map(function (style) { return addGlobalStyle(globalScopes, style); }) | ||
.some(Boolean); | ||
} | ||
function addGlobalLink(doc, globalScopes, linkElm) { | ||
var url = linkElm.href; | ||
return fetch(url).then(function (rsp) { return rsp.text(); }).then(function (text) { | ||
if (hasCssVariables(text) && linkElm.parentNode) { | ||
if (hasRelativeUrls(text)) { | ||
text = fixRelativeUrls(text, url); | ||
} | ||
var styleEl = doc.createElement('style'); | ||
styleEl.setAttribute('data-styles', ''); | ||
styleEl.textContent = text; | ||
addGlobalStyle(globalScopes, styleEl); | ||
linkElm.parentNode.insertBefore(styleEl, linkElm); | ||
linkElm.remove(); | ||
} | ||
}).catch(function (err) { | ||
console.error(err); | ||
}); | ||
} | ||
// This regexp tries to determine when a variable is declared, for example: | ||
// | ||
// .my-el { --highlight-color: green; } | ||
// | ||
// but we don't want to trigger when a classname uses "--" or a pseudo-class is | ||
// used. We assume that the only characters that can preceed a variable | ||
// declaration are "{", from an opening block, ";" from a preceeding rule, or a | ||
// space. This prevents the regexp from matching a word in a selector, since | ||
// they would need to start with a "." or "#". (We assume element names don't | ||
// start with "--"). | ||
var CSS_VARIABLE_REGEXP = /[\s;{]--[-a-zA-Z0-9]+\s*:/m; | ||
function hasCssVariables(css) { | ||
return css.indexOf('var(') > -1 || CSS_VARIABLE_REGEXP.test(css); | ||
} | ||
// This regexp find all url() usages with relative urls | ||
var CSS_URL_REGEXP = /url[\s]*\([\s]*['"]?(?!(?:https?|data)\:|\/)([^\'\"\)]*)[\s]*['"]?\)[\s]*/gim; | ||
function hasRelativeUrls(css) { | ||
CSS_URL_REGEXP.lastIndex = 0; | ||
return CSS_URL_REGEXP.test(css); | ||
} | ||
function fixRelativeUrls(css, originalUrl) { | ||
// get the basepath from the original import url | ||
var basePath = originalUrl.replace(/[^/]*$/, ''); | ||
// replace the relative url, with the new relative url | ||
return css.replace(CSS_URL_REGEXP, function (fullMatch, url) { | ||
// rhe new relative path is the base path + uri | ||
// TODO: normalize relative URL | ||
var relativeUrl = basePath + url; | ||
return fullMatch.replace(url, relativeUrl); | ||
}); | ||
} | ||
var CustomStyle = /** @class */ (function () { | ||
function CustomStyle(win, doc) { | ||
this.win = win; | ||
this.doc = doc; | ||
this.count = 0; | ||
this.hostStyleMap = new WeakMap(); | ||
this.hostScopeMap = new WeakMap(); | ||
this.globalScopes = []; | ||
this.scopesMap = new Map(); | ||
this.didInit = false; | ||
} | ||
CustomStyle.prototype.initShim = function () { | ||
var _this = this; | ||
if (this.didInit) { | ||
return Promise.resolve(); | ||
} | ||
else { | ||
this.didInit = true; | ||
return new Promise(function (resolve) { | ||
_this.win.requestAnimationFrame(function () { | ||
startWatcher(_this.doc, _this.globalScopes); | ||
loadDocument(_this.doc, _this.globalScopes).then(function () { return resolve(); }); | ||
}); | ||
}); | ||
} | ||
}; | ||
CustomStyle.prototype.addLink = function (linkEl) { | ||
var _this = this; | ||
return addGlobalLink(this.doc, this.globalScopes, linkEl).then(function () { | ||
_this.updateGlobal(); | ||
}); | ||
}; | ||
CustomStyle.prototype.addGlobalStyle = function (styleEl) { | ||
if (addGlobalStyle(this.globalScopes, styleEl)) { | ||
this.updateGlobal(); | ||
} | ||
}; | ||
CustomStyle.prototype.createHostStyle = function (hostEl, cssScopeId, cssText, isScoped) { | ||
if (this.hostScopeMap.has(hostEl)) { | ||
throw new Error('host style already created'); | ||
} | ||
var baseScope = this.registerHostTemplate(cssText, cssScopeId, isScoped); | ||
var styleEl = this.doc.createElement('style'); | ||
styleEl.setAttribute('data-no-shim', ''); | ||
if (!baseScope.usesCssVars) { | ||
// This component does not use (read) css variables | ||
styleEl.textContent = cssText; | ||
} | ||
else if (isScoped) { | ||
// This component is dynamic: uses css var and is scoped | ||
styleEl['s-sc'] = cssScopeId = baseScope.scopeId + "-" + this.count; | ||
styleEl.textContent = '/*needs update*/'; | ||
this.hostStyleMap.set(hostEl, styleEl); | ||
this.hostScopeMap.set(hostEl, reScope(baseScope, cssScopeId)); | ||
this.count++; | ||
} | ||
else { | ||
// This component uses css vars, but it's no-encapsulation (global static) | ||
baseScope.styleEl = styleEl; | ||
if (!baseScope.usesCssVars) { | ||
styleEl.textContent = executeTemplate(baseScope.template, {}); | ||
} | ||
this.globalScopes.push(baseScope); | ||
this.updateGlobal(); | ||
this.hostScopeMap.set(hostEl, baseScope); | ||
} | ||
return styleEl; | ||
}; | ||
CustomStyle.prototype.removeHost = function (hostEl) { | ||
var css = this.hostStyleMap.get(hostEl); | ||
if (css) { | ||
css.remove(); | ||
} | ||
this.hostStyleMap.delete(hostEl); | ||
this.hostScopeMap.delete(hostEl); | ||
}; | ||
CustomStyle.prototype.updateHost = function (hostEl) { | ||
var scope = this.hostScopeMap.get(hostEl); | ||
if (scope && scope.usesCssVars && scope.isScoped) { | ||
var styleEl = this.hostStyleMap.get(hostEl); | ||
if (styleEl) { | ||
var selectors = getActiveSelectors(hostEl, this.hostScopeMap, this.globalScopes); | ||
var props = resolveValues(selectors); | ||
styleEl.textContent = executeTemplate(scope.template, props); | ||
} | ||
} | ||
}; | ||
CustomStyle.prototype.updateGlobal = function () { | ||
updateGlobalScopes(this.globalScopes); | ||
}; | ||
CustomStyle.prototype.registerHostTemplate = function (cssText, scopeId, isScoped) { | ||
var scope = this.scopesMap.get(scopeId); | ||
if (!scope) { | ||
scope = parseCSS(cssText); | ||
scope.scopeId = scopeId; | ||
scope.isScoped = isScoped; | ||
this.scopesMap.set(scopeId, scope); | ||
} | ||
return scope; | ||
}; | ||
return CustomStyle; | ||
}()); | ||
var win = window; | ||
function needsShim() { | ||
return !(win.CSS && win.CSS.supports && win.CSS.supports('color', 'var(--c)')); | ||
} | ||
if (!win.__stencil_cssshim && needsShim()) { | ||
win.__stencil_cssshim = new CustomStyle(win, document); | ||
} | ||
var StyleNode=function(){this.start=0,this.end=0,this.previous=null,this.parent=null,this.rules=null,this.parsedCssText="",this.cssText="",this.atRule=!1,this.type=0,this.keyframesName="",this.selector="",this.parsedSelector=""};function parse(e){return parseCss(lex(e=clean(e)),e)}function clean(e){return e.replace(RX.comments,"").replace(RX.port,"")}function lex(e){var t=new StyleNode;t.start=0,t.end=e.length;for(var r=t,n=0,s=e.length;n<s;n++)if(e[n]===OPEN_BRACE){r.rules||(r.rules=[]);var o=r,a=o.rules[o.rules.length-1]||null;(r=new StyleNode).start=n+1,r.parent=o,r.previous=a,o.rules.push(r)}else e[n]===CLOSE_BRACE&&(r.end=n+1,r=r.parent||t);return t}function parseCss(e,t){var r=t.substring(e.start,e.end-1);if(e.parsedCssText=e.cssText=r.trim(),e.parent){var n=e.previous?e.previous.end:e.parent.start;r=(r=(r=_expandUnicodeEscapes(r=t.substring(n,e.start-1))).replace(RX.multipleSpaces," ")).substring(r.lastIndexOf(";")+1);var s=e.parsedSelector=e.selector=r.trim();e.atRule=0===s.indexOf(AT_START),e.atRule?0===s.indexOf(MEDIA_START)?e.type=types.MEDIA_RULE:s.match(RX.keyframesRule)&&(e.type=types.KEYFRAMES_RULE,e.keyframesName=e.selector.split(RX.multipleSpaces).pop()):0===s.indexOf(VAR_START)?e.type=types.MIXIN_RULE:e.type=types.STYLE_RULE}var o=e.rules;if(o)for(var a=0,i=o.length,l=void 0;a<i&&(l=o[a]);a++)parseCss(l,t);return e}function _expandUnicodeEscapes(e){return e.replace(/\\([0-9a-f]{1,6})\s/gi,(function(){for(var e=arguments[1],t=6-e.length;t--;)e="0"+e;return"\\"+e}))}var types={STYLE_RULE:1,KEYFRAMES_RULE:7,MEDIA_RULE:4,MIXIN_RULE:1e3},OPEN_BRACE="{",CLOSE_BRACE="}",RX={comments:/\/\*[^*]*\*+([^/*][^*]*\*+)*\//gim,port:/@import[^;]*;/gim,customProp:/(?:^[^;\-\s}]+)?--[^;{}]*?:[^{};]*?(?:[;\n]|$)/gim,mixinProp:/(?:^[^;\-\s}]+)?--[^;{}]*?:[^{};]*?{[^}]*?}(?:[;\n]|$)?/gim,mixinApply:/@apply\s*\(?[^);]*\)?\s*(?:[;\n]|$)?/gim,varApply:/[^;:]*?:[^;]*?var\([^;]*\)(?:[;\n]|$)?/gim,keyframesRule:/^@[^\s]*keyframes/,multipleSpaces:/\s+/g},VAR_START="--",MEDIA_START="@media",AT_START="@";function findRegex(e,t,r){e.lastIndex=0;var n=t.substring(r).match(e);if(n){var s=r+n.index;return{start:s,end:s+n[0].length}}return null}var VAR_USAGE_START=/\bvar\(/,VAR_ASSIGN_START=/\B--[\w-]+\s*:/,COMMENTS=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//gim,TRAILING_LINES=/^[\t ]+\n/gm;function resolveVar(e,t,r){return e[t]?e[t]:r?executeTemplate(r,e):""}function findVarEndIndex(e,t){for(var r=0,n=t;n<e.length;n++){var s=e[n];if("("===s)r++;else if(")"===s&&--r<=0)return n+1}return n}function parseVar(e,t){var r=findRegex(VAR_USAGE_START,e,t);if(!r)return null;var n=findVarEndIndex(e,r.start),s=e.substring(r.end,n-1).split(","),o=s[0],a=s.slice(1);return{start:r.start,end:n,propName:o.trim(),fallback:a.length>0?a.join(",").trim():void 0}}function compileVar(e,t,r){var n=parseVar(e,r);if(!n)return t.push(e.substring(r,e.length)),e.length;var s=n.propName,o=null!=n.fallback?compileTemplate(n.fallback):void 0;return t.push(e.substring(r,n.start),(function(e){return resolveVar(e,s,o)})),n.end}function executeTemplate(e,t){for(var r="",n=0;n<e.length;n++){var s=e[n];r+="string"==typeof s?s:s(t)}return r}function findEndValue(e,t){for(var r=!1,n=!1,s=t;s<e.length;s++){var o=e[s];if(r)n&&'"'===o&&(r=!1),n||"'"!==o||(r=!1);else if('"'===o)r=!0,n=!0;else if("'"===o)r=!0,n=!1;else{if(";"===o)return s+1;if("}"===o)return s}}return s}function removeCustomAssigns(e){for(var t="",r=0;;){var n=findRegex(VAR_ASSIGN_START,e,r),s=n?n.start:e.length;if(t+=e.substring(r,s),!n)break;r=findEndValue(e,s)}return t}function compileTemplate(e){var t=0;e=removeCustomAssigns(e=e.replace(COMMENTS,"")).replace(TRAILING_LINES,"");for(var r=[];t<e.length;)t=compileVar(e,r,t);return r}function resolveValues(e){var t={};e.forEach((function(e){e.declarations.forEach((function(e){t[e.prop]=e.value}))}));for(var r={},n=Object.entries(t),s=function(e){var t=!1;if(n.forEach((function(e){var n=e[0],s=executeTemplate(e[1],r);s!==r[n]&&(r[n]=s,t=!0)})),!t)return"break"},o=0;o<10;o++){if("break"===s())break}return r}function getSelectors(e,t){if(void 0===t&&(t=0),!e.rules)return[];var r=[];return e.rules.filter((function(e){return e.type===types.STYLE_RULE})).forEach((function(e){var n=getDeclarations(e.cssText);n.length>0&&e.parsedSelector.split(",").forEach((function(e){e=e.trim(),r.push({selector:e,declarations:n,specificity:computeSpecificity(),nu:t})})),t++})),r}function computeSpecificity(e){return 1}var IMPORTANT="!important",FIND_DECLARATIONS=/(?:^|[;\s{]\s*)(--[\w-]*?)\s*:\s*(?:((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};{])+)|\{([^}]*)\}(?:(?=[;\s}])|$))/gm;function getDeclarations(e){for(var t,r=[];t=FIND_DECLARATIONS.exec(e.trim());){var n=normalizeValue(t[2]),s=n.value,o=n.important;r.push({prop:t[1].trim(),value:compileTemplate(s),important:o})}return r}function normalizeValue(e){var t=(e=e.replace(/\s+/gim," ").trim()).endsWith(IMPORTANT);return t&&(e=e.substr(0,e.length-IMPORTANT.length).trim()),{value:e,important:t}}function getActiveSelectors(e,t,r){var n=[],s=getScopesForElement(t,e);return r.forEach((function(e){return n.push(e)})),s.forEach((function(e){return n.push(e)})),sortSelectors(getSelectorsForScopes(n).filter((function(t){return matches(e,t.selector)})))}function getScopesForElement(e,t){for(var r=[];t;){var n=e.get(t);n&&r.push(n),t=t.parentElement}return r}function getSelectorsForScopes(e){var t=[];return e.forEach((function(e){t.push.apply(t,e.selectors)})),t}function sortSelectors(e){return e.sort((function(e,t){return e.specificity===t.specificity?e.nu-t.nu:e.specificity-t.specificity})),e}function matches(e,t){return":root"===t||"html"===t||e.matches(t)}function parseCSS(e){var t=parse(e),r=compileTemplate(e);return{original:e,template:r,selectors:getSelectors(t),usesCssVars:r.length>1}}function addGlobalStyle(e,t){if(e.some((function(e){return e.styleEl===t})))return!1;var r=parseCSS(t.textContent);return r.styleEl=t,e.push(r),!0}function updateGlobalScopes(e){var t=resolveValues(getSelectorsForScopes(e));e.forEach((function(e){e.usesCssVars&&(e.styleEl.textContent=executeTemplate(e.template,t))}))}function reScope(e,t){var r=e.template.map((function(r){return"string"==typeof r?replaceScope(r,e.scopeId,t):r})),n=e.selectors.map((function(r){return Object.assign(Object.assign({},r),{selector:replaceScope(r.selector,e.scopeId,t)})}));return Object.assign(Object.assign({},e),{template:r,selectors:n,scopeId:t})}function replaceScope(e,t,r){return e=replaceAll(e,"\\."+t,"."+r)}function replaceAll(e,t,r){return e.replace(new RegExp(t,"g"),r)}function loadDocument(e,t){return loadDocumentStyles(e,t),loadDocumentLinks(e,t).then((function(){updateGlobalScopes(t)}))}function startWatcher(e,t){"undefined"!=typeof MutationObserver&&new MutationObserver((function(){loadDocumentStyles(e,t)&&updateGlobalScopes(t)})).observe(document.head,{childList:!0})}function loadDocumentLinks(e,t){for(var r=[],n=e.querySelectorAll('link[rel="stylesheet"][href]:not([data-no-shim])'),s=0;s<n.length;s++)r.push(addGlobalLink(e,t,n[s]));return Promise.all(r)}function loadDocumentStyles(e,t){return Array.from(e.querySelectorAll("style:not([data-styles]):not([data-no-shim])")).map((function(e){return addGlobalStyle(t,e)})).some(Boolean)}function addGlobalLink(e,t,r){var n=r.href;return fetch(n).then((function(e){return e.text()})).then((function(s){if(hasCssVariables(s)&&r.parentNode){hasRelativeUrls(s)&&(s=fixRelativeUrls(s,n));var o=e.createElement("style");o.setAttribute("data-styles",""),o.textContent=s,addGlobalStyle(t,o),r.parentNode.insertBefore(o,r),r.remove()}})).catch((function(e){console.error(e)}))}var CSS_VARIABLE_REGEXP=/[\s;{]--[-a-zA-Z0-9]+\s*:/m;function hasCssVariables(e){return e.indexOf("var(")>-1||CSS_VARIABLE_REGEXP.test(e)}var CSS_URL_REGEXP=/url[\s]*\([\s]*['"]?(?!(?:https?|data)\:|\/)([^\'\"\)]*)[\s]*['"]?\)[\s]*/gim;function hasRelativeUrls(e){return CSS_URL_REGEXP.lastIndex=0,CSS_URL_REGEXP.test(e)}function fixRelativeUrls(e,t){var r=t.replace(/[^/]*$/,"");return e.replace(CSS_URL_REGEXP,(function(e,t){var n=r+t;return e.replace(t,n)}))}var CustomStyle=function(){function e(e,t){this.win=e,this.doc=t,this.count=0,this.hostStyleMap=new WeakMap,this.hostScopeMap=new WeakMap,this.globalScopes=[],this.scopesMap=new Map,this.didInit=!1}return e.prototype.i=function(){var e=this;return this.didInit||!this.win.requestAnimationFrame?Promise.resolve():(this.didInit=!0,new Promise((function(t){e.win.requestAnimationFrame((function(){startWatcher(e.doc,e.globalScopes),loadDocument(e.doc,e.globalScopes).then((function(){return t()}))}))})))},e.prototype.addLink=function(e){var t=this;return addGlobalLink(this.doc,this.globalScopes,e).then((function(){t.updateGlobal()}))},e.prototype.addGlobalStyle=function(e){addGlobalStyle(this.globalScopes,e)&&this.updateGlobal()},e.prototype.createHostStyle=function(e,t,r,n){if(this.hostScopeMap.has(e))throw new Error("host style already created");var s=this.registerHostTemplate(r,t,n),o=this.doc.createElement("style");return o.setAttribute("data-no-shim",""),s.usesCssVars?n?(o["s-sc"]=t=s.scopeId+"-"+this.count,o.textContent="/*needs update*/",this.hostStyleMap.set(e,o),this.hostScopeMap.set(e,reScope(s,t)),this.count++):(s.styleEl=o,s.usesCssVars||(o.textContent=executeTemplate(s.template,{})),this.globalScopes.push(s),this.updateGlobal(),this.hostScopeMap.set(e,s)):o.textContent=r,o},e.prototype.removeHost=function(e){var t=this.hostStyleMap.get(e);t&&t.remove(),this.hostStyleMap.delete(e),this.hostScopeMap.delete(e)},e.prototype.updateHost=function(e){var t=this.hostScopeMap.get(e);if(t&&t.usesCssVars&&t.isScoped){var r=this.hostStyleMap.get(e);if(r){var n=resolveValues(getActiveSelectors(e,this.hostScopeMap,this.globalScopes));r.textContent=executeTemplate(t.template,n)}}},e.prototype.updateGlobal=function(){updateGlobalScopes(this.globalScopes)},e.prototype.registerHostTemplate=function(e,t,r){var n=this.scopesMap.get(t);return n||((n=parseCSS(e)).scopeId=t,n.isScoped=r,this.scopesMap.set(t,n)),n},e}();!function(e){!e||e.__cssshim||e.CSS&&e.CSS.supports&&e.CSS.supports("color","var(--c)")||(e.__cssshim=new CustomStyle(e,e.document))}("undefined"!=typeof window&&window); |
@@ -41,47 +41,10 @@ (function(){ | ||
// Polyfill document.baseURI | ||
if (typeof document.baseURI !== 'string') { | ||
Object.defineProperty(Document.prototype, 'baseURI', { | ||
enumerable: true, | ||
configurable: true, | ||
get: function () { | ||
var base = document.querySelector('base'); | ||
if (base && base.href) { | ||
return base.href; | ||
} | ||
return document.URL; | ||
} | ||
}); | ||
} | ||
"string"!==typeof document.baseURI&&Object.defineProperty(Document.prototype,"baseURI",{enumerable:!0,configurable:!0,get:function(){var a=document.querySelector("base");return a&&a.href?a.href:document.URL}}); | ||
// Polyfill CustomEvent | ||
if (typeof window.CustomEvent !== 'function') { | ||
window.CustomEvent = function CustomEvent(event, params) { | ||
params = params || { bubbles: false, cancelable: false, detail: undefined }; | ||
var evt = document.createEvent( 'CustomEvent' ); | ||
evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail ); | ||
return evt; | ||
} | ||
window.CustomEvent.prototype = window.Event.prototype; | ||
} | ||
"function"!==typeof window.CustomEvent&&(window.CustomEvent=function(c,a){a=a||{bubbles:!1,cancelable:!1,detail:void 0};var b=document.createEvent("CustomEvent");b.initCustomEvent(c,a.bubbles,a.cancelable,a.detail);return b},window.CustomEvent.prototype=window.Event.prototype); | ||
// Event.composedPath | ||
(function(E, d, w) { | ||
if(!E.composedPath) { | ||
E.composedPath = function() { | ||
if (this.path) { | ||
return this.path; | ||
} | ||
var target = this.target; | ||
(function(b,c,d){b.composedPath||(b.composedPath=function(){if(this.path)return this.path;var a=this.target;for(this.path=[];null!==a.parentNode;)this.path.push(a),a=a.parentNode;this.path.push(c,d);return this.path})})(Event.prototype,document,window); | ||
this.path = []; | ||
while (target.parentNode !== null) { | ||
this.path.push(target); | ||
target = target.parentNode; | ||
} | ||
this.path.push(d, w); | ||
return this.path; | ||
} | ||
} | ||
})(Event.prototype, document, window); | ||
/*! | ||
@@ -102,14 +65,3 @@ Element.closest and Element.matches | ||
*/ | ||
(function(prototype) { | ||
if (!("isConnected" in prototype)) { | ||
Object.defineProperty(prototype, 'isConnected', { | ||
configurable: true, | ||
enumerable: true, | ||
get: function() { | ||
var root = this.getRootNode({composed: true}); | ||
return root && root.nodeType === 9; | ||
} | ||
}) | ||
} | ||
})(Element.prototype); | ||
(function(a){"isConnected"in a||Object.defineProperty(a,"isConnected",{configurable:!0,enumerable:!0,get:function(){var a=this.getRootNode({composed:!0});return a&&9===a.nodeType}})})(Element.prototype); | ||
@@ -129,21 +81,2 @@ /*! | ||
*/ | ||
(function(prototype){ | ||
try { | ||
document.body.classList.add(); | ||
} catch (e) { | ||
var originalAdd = prototype.add; | ||
var originalRemove = prototype.remove; | ||
prototype.add = function() { | ||
for (var i = 0; i < arguments.length; i++) { | ||
originalAdd.call(this, arguments[i]); | ||
} | ||
}; | ||
prototype.remove = function() { | ||
for (var i = 0; i < arguments.length; i++) { | ||
originalRemove.call(this, arguments[i]); | ||
} | ||
}; | ||
} | ||
}(DOMTokenList.prototype)); | ||
(function(b){try{document.body.classList.add()}catch(e){var c=b.add,d=b.remove;b.add=function(){for(var a=0;a<arguments.length;a++)c.call(this,arguments[a])};b.remove=function(){for(var a=0;a<arguments.length;a++)d.call(this,arguments[a])}}})(DOMTokenList.prototype); |
@@ -1,18 +0,1 @@ | ||
(function() { | ||
if ( | ||
// No Reflect, no classes, no need for shim because native custom elements | ||
// require ES2015 classes or Reflect. | ||
window.Reflect === undefined || | ||
window.customElements === undefined | ||
) { | ||
return; | ||
} | ||
var BuiltInHTMLElement = HTMLElement; | ||
window.HTMLElement = /** @this {!Object} */ function HTMLElement() { | ||
return Reflect.construct( | ||
BuiltInHTMLElement, [], /** @type {!Function} */ (this.constructor)); | ||
}; | ||
HTMLElement.prototype = BuiltInHTMLElement.prototype; | ||
HTMLElement.prototype.constructor = HTMLElement; | ||
Object.setPrototypeOf(HTMLElement, BuiltInHTMLElement); | ||
})(); | ||
(function(){if("undefined"!==typeof window&&void 0!==window.Reflect&&void 0!==window.customElements){var a=HTMLElement;window.HTMLElement=function(){return Reflect.construct(a,[],this.constructor)};HTMLElement.prototype=a.prototype;HTMLElement.prototype.constructor=HTMLElement;Object.setPrototypeOf(HTMLElement,a)}})(); |
export function applyPolyfills() { | ||
var promises = []; | ||
if (typeof window !== 'undefined') { | ||
var win = window; | ||
var promises = []; | ||
if (!win.customElements || (win.Element && (!win.Element.prototype.closest || !win.Element.prototype.matches || !win.Element.prototype.remove))) { | ||
promises.push(import('./dom.js')); | ||
promises.push(import(/* webpackChunkName: "stencil-polyfills-dom" */ './dom.js')); | ||
} | ||
@@ -30,7 +29,6 @@ | ||
) { | ||
promises.push(import('./core-js.js')); | ||
promises.push(import(/* webpackChunkName: "stencil-polyfills-core-js" */ './core-js.js')); | ||
} | ||
return Promise.all(promises); | ||
} | ||
return Promise.resolve(); | ||
return Promise.all(promises); | ||
} |
/** | ||
* SystemJS 4.0.2 | ||
* MANUAL PATCH: remove script.crossOrigin = "anonymous" | ||
* MANUAL PATCH: add conditionally apply, n.System=n.System||new u | ||
*/ | ||
!function(){var e="undefined"!=typeof self,n=e?self:global;var t;if("undefined"!=typeof document){var e=document.querySelector("base[href]");e&&(t=e.href)}if(!t&&"undefined"!=typeof location){var e=(t=location.href.split("#")[0].split("?")[0]).lastIndexOf("/");-1!==e&&(t=t.slice(0,e+1))}var r=/\\/g,o="undefined"!=typeof Symbol,i=o&&Symbol.toStringTag,c=o?Symbol():"@";function u(){this[c]={}}var s=u.prototype;var l;s.import=function(e,n){var t=this;return Promise.resolve(t.resolve(e,n)).then(function(e){var n=function e(n,t,r){var o=n[c][t];if(o)return o;var u=[],s=Object.create(null);i&&Object.defineProperty(s,i,{value:"Module"});var l=Promise.resolve().then(function(){return n.instantiate(t,r)}).then(function(e){if(!e)throw Error("Module "+t+" did not instantiate");var r=e[1](function(e,n){o.h=!0;var t=!1;if("object"!=typeof e)e in s&&s[e]===n||(s[e]=n,t=!0);else for(var n in e){var r=e[n];n in s&&s[n]===r||(s[n]=r,t=!0)}if(t)for(var e=0;e<u.length;e++)u[e](s);return n},2===e[1].length?{import:function(e){return n.import(e,t)},meta:n.createContext(t)}:void 0);return o.e=r.execute||function(){},[e[0],r.setters||[]]});var f=l.then(function(r){return Promise.all(r[0].map(function(o,i){var c=r[1][i];return Promise.resolve(n.resolve(o,t)).then(function(r){var o=e(n,r,t);return Promise.resolve(o.I).then(function(){return c&&(o.i.push(c),!o.h&&o.I||c(o.n)),o})})})).then(function(e){o.d=e})});return f.catch(function(e){o.e=null,o.er=e}),o=n[c][t]={id:t,i:u,n:s,I:l,L:f,h:!1,d:void 0,e:void 0,er:void 0,E:void 0,C:void 0}}(t,e);return n.C||function(e,n){return n.C=function e(n,t,r){if(!r[t.id])return r[t.id]=!0,Promise.resolve(t.L).then(function(){return Promise.all(t.d.map(function(t){return e(n,t,r)}))})}(e,n,{}).then(function(){return function e(n,t,r){if(r[t.id])return;if(r[t.id]=!0,!t.e){if(t.er)throw t.er;return t.E?t.E:void 0}var o;return t.d.forEach(function(t){{var i=e(n,t,r);i&&(o=o||[]).push(i)}}),o?Promise.all(o).then(i):i();function i(){try{var e=t.e.call(f);if(e)return e=e.then(function(){t.C=t.n,t.E=null}),t.E=t.E||e;t.C=t.n}catch(e){throw t.er=e,e}finally{t.L=t.I=void 0,t.e=null}}}(e,n,{})}).then(function(){return n.n})}(t,n)})},s.createContext=function(e){return{url:e}},s.register=function(e,n){l=[e,n]},s.getRegister=function(){var e=l;return l=void 0,e};var f=Object.freeze(Object.create(null));n.System=new u;var d=s.register;s.register=function(e,n){d.call(this,e,n)},s.instantiate=function(e,n){var t=this;return".json"===e.substr(-5)?fetch(e).then(function(e){return e.text()}).then(function(e){return[[],function(n){return{execute:function(){n("default",JSON.parse(e))}}}]}):new Promise(function(r,o){var i;function c(n){n.filename===e&&(i=n.error)}window.addEventListener("error",c);var u=document.createElement("script");u.charset="utf-8",u.async=!0,u.addEventListener("error",function(){window.removeEventListener("error",c),o(Error("Error loading "+e+(n?" from "+n:"")))}),u.addEventListener("load",function(){window.removeEventListener("error",c),document.head.removeChild(u),i?o(i):r(t.getRegister())}),u.src=e,document.head.appendChild(u)})},e&&"function"==typeof importScripts&&(s.instantiate=function(e){var n=this;return new Promise(function(t,r){try{importScripts(e)}catch(e){r(e)}t(n.getRegister())})}),s.resolve=function(e,n){var o=function(e,n){if(-1!==e.indexOf("\\")&&(e=e.replace(r,"/")),"/"===e[0]&&"/"===e[1])return n.slice(0,n.indexOf(":")+1)+e;if("."===e[0]&&("/"===e[1]||"."===e[1]&&("/"===e[2]||2===e.length&&(e+="/"))||1===e.length&&(e+="/"))||"/"===e[0]){var t=n.slice(0,n.indexOf(":")+1);var r;if(r="/"===n[t.length+1]?"file:"!==t?(r=n.slice(t.length+2)).slice(r.indexOf("/")+1):n.slice(8):n.slice(t.length+("/"===n[t.length])),"/"===e[0])return n.slice(0,n.length-r.length-1)+e;var o=r.slice(0,r.lastIndexOf("/")+1)+e,i=[];var c=-1;for(var e=0;e<o.length;e++)-1!==c?"/"===o[e]&&(i.push(o.slice(c,e+1)),c=-1):"."===o[e]?"."!==o[e+1]||"/"!==o[e+2]&&e+2!==o.length?"/"===o[e+1]||e+1===o.length?e+=1:c=e:(i.pop(),e+=2):c=e;return-1!==c&&i.push(o.slice(c)),n.slice(0,n.length-r.length)+i.join("")}}(e,n||t);if(!o){if(-1!==e.indexOf(":"))return Promise.resolve(e);throw Error('Cannot resolve "'+e+(n?'" from '+n:'"'))}return Promise.resolve(o)}}(); | ||
!function(){var e="undefined"!=typeof self,n=e?self:global;var t;if("undefined"!=typeof document){var e=document.querySelector("base[href]");e&&(t=e.href)}if(!t&&"undefined"!=typeof location){var e=(t=location.href.split("#")[0].split("?")[0]).lastIndexOf("/");-1!==e&&(t=t.slice(0,e+1))}var r=/\\/g,o="undefined"!=typeof Symbol,i=o&&Symbol.toStringTag,c=o?Symbol():"@";function u(){this[c]={}}var s=u.prototype;var l;s.import=function(e,n){var t=this;return Promise.resolve(t.resolve(e,n)).then(function(e){var n=function e(n,t,r){var o=n[c][t];if(o)return o;var u=[],s=Object.create(null);i&&Object.defineProperty(s,i,{value:"Module"});var l=Promise.resolve().then(function(){return n.instantiate(t,r)}).then(function(e){if(!e)throw Error("Module "+t+" did not instantiate");var r=e[1](function(e,n){o.h=!0;var t=!1;if("object"!=typeof e)e in s&&s[e]===n||(s[e]=n,t=!0);else for(var n in e){var r=e[n];n in s&&s[n]===r||(s[n]=r,t=!0)}if(t)for(var e=0;e<u.length;e++)u[e](s);return n},2===e[1].length?{import:function(e){return n.import(e,t)},meta:n.createContext(t)}:void 0);return o.e=r.execute||function(){},[e[0],r.setters||[]]});var f=l.then(function(r){return Promise.all(r[0].map(function(o,i){var c=r[1][i];return Promise.resolve(n.resolve(o,t)).then(function(r){var o=e(n,r,t);return Promise.resolve(o.I).then(function(){return c&&(o.i.push(c),!o.h&&o.I||c(o.n)),o})})})).then(function(e){o.d=e})});return f.catch(function(e){o.e=null,o.er=e}),o=n[c][t]={id:t,i:u,n:s,I:l,L:f,h:!1,d:void 0,e:void 0,er:void 0,E:void 0,C:void 0}}(t,e);return n.C||function(e,n){return n.C=function e(n,t,r){if(!r[t.id])return r[t.id]=!0,Promise.resolve(t.L).then(function(){return Promise.all(t.d.map(function(t){return e(n,t,r)}))})}(e,n,{}).then(function(){return function e(n,t,r){if(r[t.id])return;if(r[t.id]=!0,!t.e){if(t.er)throw t.er;return t.E?t.E:void 0}var o;return t.d.forEach(function(t){{var i=e(n,t,r);i&&(o=o||[]).push(i)}}),o?Promise.all(o).then(i):i();function i(){try{var e=t.e.call(f);if(e)return e=e.then(function(){t.C=t.n,t.E=null}),t.E=t.E||e;t.C=t.n}catch(e){throw t.er=e,e}finally{t.L=t.I=void 0,t.e=null}}}(e,n,{})}).then(function(){return n.n})}(t,n)})},s.createContext=function(e){return{url:e}},s.register=function(e,n){l=[e,n]},s.getRegister=function(){var e=l;return l=void 0,e};var f=Object.freeze(Object.create(null));n.System=n.System||new u;var d=s.register;s.register=function(e,n){d.call(this,e,n)},s.instantiate=function(e,n){var t=this;return".json"===e.substr(-5)?fetch(e).then(function(e){return e.text()}).then(function(e){return[[],function(n){return{execute:function(){n("default",JSON.parse(e))}}}]}):new Promise(function(r,o){var i;function c(n){n.filename===e&&(i=n.error)}window.addEventListener("error",c);var u=document.createElement("script");u.charset="utf-8",u.async=!0,u.addEventListener("error",function(){window.removeEventListener("error",c),o(Error("Error loading "+e+(n?" from "+n:"")))}),u.addEventListener("load",function(){window.removeEventListener("error",c),document.head.removeChild(u),i?o(i):r(t.getRegister())}),u.src=e,document.head.appendChild(u)})},e&&"function"==typeof importScripts&&(s.instantiate=function(e){var n=this;return new Promise(function(t,r){try{importScripts(e)}catch(e){r(e)}t(n.getRegister())})}),s.resolve=function(e,n){var o=function(e,n){if(-1!==e.indexOf("\\")&&(e=e.replace(r,"/")),"/"===e[0]&&"/"===e[1])return n.slice(0,n.indexOf(":")+1)+e;if("."===e[0]&&("/"===e[1]||"."===e[1]&&("/"===e[2]||2===e.length&&(e+="/"))||1===e.length&&(e+="/"))||"/"===e[0]){var t=n.slice(0,n.indexOf(":")+1);var r;if(r="/"===n[t.length+1]?"file:"!==t?(r=n.slice(t.length+2)).slice(r.indexOf("/")+1):n.slice(8):n.slice(t.length+("/"===n[t.length])),"/"===e[0])return n.slice(0,n.length-r.length-1)+e;var o=r.slice(0,r.lastIndexOf("/")+1)+e,i=[];var c=-1;for(var e=0;e<o.length;e++)-1!==c?"/"===o[e]&&(i.push(o.slice(c,e+1)),c=-1):"."===o[e]?"."!==o[e+1]||"/"!==o[e+2]&&e+2!==o.length?"/"===o[e+1]||e+1===o.length?e+=1:c=e:(i.pop(),e+=2):c=e;return-1!==c&&i.push(o.slice(c)),n.slice(0,n.length-r.length)+i.join("")}}(e,n||t);if(!o){if(-1!==e.indexOf(":"))return Promise.resolve(e);throw Error('Cannot resolve "'+e+(n?'" from '+n:'"'))}return Promise.resolve(o)}}(); |
@@ -1,1 +0,1 @@ | ||
module.exports = require('./cjs/index.cjs.js'); | ||
module.exports = require('./cjs/index.cjs.js'); |
@@ -1,1 +0,1 @@ | ||
export{i as initialize}from"./p-398af787.js"; | ||
export{i as initialize}from"./p-33ed1e2c.js"; |
@@ -1,1 +0,1 @@ | ||
import{p as t,b as e}from"./p-211aed1b.js";t().then(t=>e([["p-swvbezp6",[[0,"connected-button",{success:[32],badRequest:[32],unauthenticated:[32],planCost:[32]}],[0,"manifold-init",{env:[1],authToken:[1,"auth-token"],authType:[1,"auth-type"],clientId:[1,"client-id"],initialize:[64]}]]]],t)); | ||
import{p as t,b as e}from"./p-f0c70a7a.js";t().then(t=>e([["p-1dcfe8b8",[[0,"connected-button",{success:[32],badRequest:[32],unauthenticated:[32],planCost:[32]}],[0,"manifold-init",{env:[1],authToken:[1025,"auth-token"],authType:[1,"auth-type"],clientId:[1,"client-id"],initialize:[64]}]]]],t)); |
@@ -7,67 +7,61 @@ /* eslint-disable */ | ||
*/ | ||
import { HTMLStencilElement, JSXBase } from './stencil.core'; | ||
import { | ||
Connection, | ||
} from './components/manifold-init/manifold-init'; | ||
import { HTMLStencilElement, JSXBase } from "./stencil-public-runtime"; | ||
import { Connection, } from "./components/manifold-init/manifold-init"; | ||
export namespace Components { | ||
interface ConnectedButton {} | ||
interface ManifoldInit { | ||
'authToken'?: string; | ||
'authType'?: 'manual' | 'oauth'; | ||
'clientId'?: string; | ||
'env'?: 'stage' | 'prod'; | ||
'initialize': (options: { element: HTMLElement; componentVersion: string; version: number; }) => Promise<Connection>; | ||
} | ||
interface ConnectedButton { | ||
} | ||
interface ManifoldInit { | ||
"authToken"?: string; | ||
"authType"?: "manual" | "oauth"; | ||
"clientId"?: string; | ||
"env"?: "local" | "stage" | "prod"; | ||
"initialize": (options: { | ||
element: HTMLElement; | ||
componentVersion: string; | ||
version: number; | ||
}) => Promise<Connection>; | ||
} | ||
} | ||
declare global { | ||
interface HTMLConnectedButtonElement extends Components.ConnectedButton, HTMLStencilElement {} | ||
var HTMLConnectedButtonElement: { | ||
prototype: HTMLConnectedButtonElement; | ||
new (): HTMLConnectedButtonElement; | ||
}; | ||
interface HTMLManifoldInitElement extends Components.ManifoldInit, HTMLStencilElement {} | ||
var HTMLManifoldInitElement: { | ||
prototype: HTMLManifoldInitElement; | ||
new (): HTMLManifoldInitElement; | ||
}; | ||
interface HTMLElementTagNameMap { | ||
'connected-button': HTMLConnectedButtonElement; | ||
'manifold-init': HTMLManifoldInitElement; | ||
} | ||
interface HTMLConnectedButtonElement extends Components.ConnectedButton, HTMLStencilElement { | ||
} | ||
var HTMLConnectedButtonElement: { | ||
prototype: HTMLConnectedButtonElement; | ||
new (): HTMLConnectedButtonElement; | ||
}; | ||
interface HTMLManifoldInitElement extends Components.ManifoldInit, HTMLStencilElement { | ||
} | ||
var HTMLManifoldInitElement: { | ||
prototype: HTMLManifoldInitElement; | ||
new (): HTMLManifoldInitElement; | ||
}; | ||
interface HTMLElementTagNameMap { | ||
"connected-button": HTMLConnectedButtonElement; | ||
"manifold-init": HTMLManifoldInitElement; | ||
} | ||
} | ||
declare namespace LocalJSX { | ||
interface ConnectedButton {} | ||
interface ManifoldInit { | ||
'authToken'?: string; | ||
'authType'?: 'manual' | 'oauth'; | ||
'clientId'?: string; | ||
'env'?: 'stage' | 'prod'; | ||
} | ||
interface IntrinsicElements { | ||
'connected-button': ConnectedButton; | ||
'manifold-init': ManifoldInit; | ||
} | ||
interface ConnectedButton { | ||
} | ||
interface ManifoldInit { | ||
"authToken"?: string; | ||
"authType"?: "manual" | "oauth"; | ||
"clientId"?: string; | ||
"env"?: "local" | "stage" | "prod"; | ||
"onManifold-auth-token-clear"?: (event: CustomEvent<any>) => void; | ||
"onManifold-auth-token-receive"?: (event: CustomEvent<string>) => void; | ||
} | ||
interface IntrinsicElements { | ||
"connected-button": ConnectedButton; | ||
"manifold-init": ManifoldInit; | ||
} | ||
} | ||
export { LocalJSX as JSX }; | ||
declare module "@stencil/core" { | ||
export namespace JSX { | ||
interface IntrinsicElements { | ||
'connected-button': LocalJSX.ConnectedButton & JSXBase.HTMLAttributes<HTMLConnectedButtonElement>; | ||
'manifold-init': LocalJSX.ManifoldInit & JSXBase.HTMLAttributes<HTMLManifoldInitElement>; | ||
export namespace JSX { | ||
interface IntrinsicElements { | ||
"connected-button": LocalJSX.ConnectedButton & JSXBase.HTMLAttributes<HTMLConnectedButtonElement>; | ||
"manifold-init": LocalJSX.ManifoldInit & JSXBase.HTMLAttributes<HTMLManifoldInitElement>; | ||
} | ||
} | ||
} | ||
} | ||
@@ -0,1 +1,2 @@ | ||
import { EventEmitter } from '../../stencil-public-runtime'; | ||
import * as core from '../../core'; | ||
@@ -5,6 +6,10 @@ export interface Connection extends core.Connection { | ||
export declare class ManifoldInit { | ||
env?: 'stage' | 'prod'; | ||
env?: 'local' | 'stage' | 'prod'; | ||
authToken?: string; | ||
authType?: 'manual' | 'oauth'; | ||
clientId?: string; | ||
clear: EventEmitter; | ||
receive: EventEmitter<string>; | ||
tokenChanged(newValue?: string, oldValue?: string): void; | ||
clearAuthToken: () => void; | ||
initialize(options: { | ||
@@ -11,0 +16,0 @@ element: HTMLElement; |
import { Connection as Connection_v0 } from './v0'; | ||
interface InitOptions { | ||
authType?: 'manual' | 'oauth'; | ||
env?: 'stage' | 'prod'; | ||
authToken?: string; | ||
env?: 'local' | 'stage' | 'prod'; | ||
getAuthToken: () => string | undefined; | ||
clearAuthToken: () => void; | ||
clientId?: string; | ||
@@ -7,0 +8,0 @@ componentVersion: string; |
@@ -0,1 +1,5 @@ | ||
export interface Analytics { | ||
track: (evt: AnalyticsEvent) => Promise<Response>; | ||
report: (det: ErrorDetail) => void; | ||
} | ||
/** | ||
@@ -76,6 +80,3 @@ * Properties that should be found in every analytics event | ||
} | ||
export default function createAnalytics(args: CreateAnalytics): { | ||
track: (evt: AnalyticsEvent) => Promise<Response>; | ||
report: (detail: ErrorDetail) => void; | ||
}; | ||
export default function createAnalytics(args: CreateAnalytics): Analytics; | ||
export {}; |
@@ -0,3 +1,6 @@ | ||
import { Analytics } from './analytics'; | ||
interface CreateGraphqlFetch { | ||
endpoint?: () => string; | ||
getAuthToken: () => string | undefined; | ||
clearAuthToken: () => void; | ||
clientId?: string; | ||
@@ -7,2 +10,4 @@ element: HTMLElement; | ||
retries?: number; | ||
waitTime?: number; | ||
analytics: Analytics; | ||
} | ||
@@ -36,3 +41,3 @@ declare type GraphqlRequest = { | ||
export declare type GraphqlFetch = <T>(args: GraphqlRequest) => Promise<GraphqlResponseBody<T>>; | ||
export declare function createGraphqlFetch({ element, endpoint, version, retries, clientId, }: CreateGraphqlFetch): GraphqlFetch; | ||
export declare function createGraphqlFetch({ element, endpoint, getAuthToken, clearAuthToken, version, retries, clientId, analytics, waitTime, }: CreateGraphqlFetch): GraphqlFetch; | ||
export {}; |
@@ -17,3 +17,5 @@ import { AnalyticsEvent, ErrorDetail } from './analytics'; | ||
clientId?: string; | ||
getAuthToken: () => string; | ||
clearAuthToken: () => void; | ||
}) => Connection; | ||
export default connection; |
@@ -12,3 +12,3 @@ | ||
} | ||
export declare function defineCustomElements(win: Window, opts?: CustomElementsDefineOptions): Promise<void>; | ||
export declare function defineCustomElements(win?: Window, opts?: CustomElementsDefineOptions): Promise<void>; | ||
export declare function applyPolyfills(): Promise<void>; |
@@ -18,3 +18,3 @@ { | ||
], | ||
"version": "0.4.0", | ||
"version": "0.4.1", | ||
"description": "Manifold UI Initialization", | ||
@@ -21,0 +21,0 @@ "main": "dist/index.js", |
@@ -7,67 +7,61 @@ /* eslint-disable */ | ||
*/ | ||
import { HTMLStencilElement, JSXBase } from '@stencil/core/internal'; | ||
import { | ||
Connection, | ||
} from './components/manifold-init/manifold-init'; | ||
import { HTMLStencilElement, JSXBase } from "@stencil/core/internal"; | ||
import { Connection, } from "./components/manifold-init/manifold-init"; | ||
export namespace Components { | ||
interface ConnectedButton {} | ||
interface ManifoldInit { | ||
'authToken'?: string; | ||
'authType'?: 'manual' | 'oauth'; | ||
'clientId'?: string; | ||
'env'?: 'stage' | 'prod'; | ||
'initialize': (options: { element: HTMLElement; componentVersion: string; version: number; }) => Promise<Connection>; | ||
} | ||
interface ConnectedButton { | ||
} | ||
interface ManifoldInit { | ||
"authToken"?: string; | ||
"authType"?: "manual" | "oauth"; | ||
"clientId"?: string; | ||
"env"?: "local" | "stage" | "prod"; | ||
"initialize": (options: { | ||
element: HTMLElement; | ||
componentVersion: string; | ||
version: number; | ||
}) => Promise<Connection>; | ||
} | ||
} | ||
declare global { | ||
interface HTMLConnectedButtonElement extends Components.ConnectedButton, HTMLStencilElement {} | ||
var HTMLConnectedButtonElement: { | ||
prototype: HTMLConnectedButtonElement; | ||
new (): HTMLConnectedButtonElement; | ||
}; | ||
interface HTMLManifoldInitElement extends Components.ManifoldInit, HTMLStencilElement {} | ||
var HTMLManifoldInitElement: { | ||
prototype: HTMLManifoldInitElement; | ||
new (): HTMLManifoldInitElement; | ||
}; | ||
interface HTMLElementTagNameMap { | ||
'connected-button': HTMLConnectedButtonElement; | ||
'manifold-init': HTMLManifoldInitElement; | ||
} | ||
interface HTMLConnectedButtonElement extends Components.ConnectedButton, HTMLStencilElement { | ||
} | ||
var HTMLConnectedButtonElement: { | ||
prototype: HTMLConnectedButtonElement; | ||
new (): HTMLConnectedButtonElement; | ||
}; | ||
interface HTMLManifoldInitElement extends Components.ManifoldInit, HTMLStencilElement { | ||
} | ||
var HTMLManifoldInitElement: { | ||
prototype: HTMLManifoldInitElement; | ||
new (): HTMLManifoldInitElement; | ||
}; | ||
interface HTMLElementTagNameMap { | ||
"connected-button": HTMLConnectedButtonElement; | ||
"manifold-init": HTMLManifoldInitElement; | ||
} | ||
} | ||
declare namespace LocalJSX { | ||
interface ConnectedButton {} | ||
interface ManifoldInit { | ||
'authToken'?: string; | ||
'authType'?: 'manual' | 'oauth'; | ||
'clientId'?: string; | ||
'env'?: 'stage' | 'prod'; | ||
} | ||
interface IntrinsicElements { | ||
'connected-button': ConnectedButton; | ||
'manifold-init': ManifoldInit; | ||
} | ||
interface ConnectedButton { | ||
} | ||
interface ManifoldInit { | ||
"authToken"?: string; | ||
"authType"?: "manual" | "oauth"; | ||
"clientId"?: string; | ||
"env"?: "local" | "stage" | "prod"; | ||
"onManifold-auth-token-clear"?: (event: CustomEvent<any>) => void; | ||
"onManifold-auth-token-receive"?: (event: CustomEvent<string>) => void; | ||
} | ||
interface IntrinsicElements { | ||
"connected-button": ConnectedButton; | ||
"manifold-init": ManifoldInit; | ||
} | ||
} | ||
export { LocalJSX as JSX }; | ||
declare module "@stencil/core" { | ||
export namespace JSX { | ||
interface IntrinsicElements { | ||
'connected-button': LocalJSX.ConnectedButton & JSXBase.HTMLAttributes<HTMLConnectedButtonElement>; | ||
'manifold-init': LocalJSX.ManifoldInit & JSXBase.HTMLAttributes<HTMLManifoldInitElement>; | ||
export namespace JSX { | ||
interface IntrinsicElements { | ||
"connected-button": LocalJSX.ConnectedButton & JSXBase.HTMLAttributes<HTMLConnectedButtonElement>; | ||
"manifold-init": LocalJSX.ManifoldInit & JSXBase.HTMLAttributes<HTMLManifoldInitElement>; | ||
} | ||
} | ||
} | ||
} | ||
@@ -10,10 +10,18 @@ # mui-core | ||
| Property | Attribute | Description | Type | Default | | ||
| ----------- | ------------ | ----------- | --------------------- | ----------- | | ||
| `authToken` | `auth-token` | | `string` | `undefined` | | ||
| `authType` | `auth-type` | | `"manual" \| "oauth"` | `'oauth'` | | ||
| `clientId` | `client-id` | | `string` | `undefined` | | ||
| `env` | `env` | | `"prod" \| "stage"` | `'prod'` | | ||
| Property | Attribute | Description | Type | Default | | ||
| ----------- | ------------ | ----------- | ------------------------------ | ----------- | | ||
| `authToken` | `auth-token` | | `string` | `undefined` | | ||
| `authType` | `auth-type` | | `"manual" \| "oauth"` | `'oauth'` | | ||
| `clientId` | `client-id` | | `string` | `undefined` | | ||
| `env` | `env` | | `"local" \| "prod" \| "stage"` | `'prod'` | | ||
## Events | ||
| Event | Description | Type | | ||
| ----------------------------- | ----------- | --------------------- | | ||
| `manifold-auth-token-clear` | | `CustomEvent<any>` | | ||
| `manifold-auth-token-receive` | | `CustomEvent<string>` | | ||
## Methods | ||
@@ -20,0 +28,0 @@ |
@@ -5,4 +5,5 @@ import connection, { Connection as Connection_v0 } from './v0'; | ||
authType?: 'manual' | 'oauth'; | ||
env?: 'stage' | 'prod'; | ||
authToken?: string; | ||
env?: 'local' | 'stage' | 'prod'; | ||
getAuthToken: () => string | undefined; | ||
clearAuthToken: () => void; | ||
clientId?: string; | ||
@@ -14,5 +15,15 @@ componentVersion: string; | ||
const getConnection = (options: InitOptions) => { | ||
const { version, element, env, componentVersion, clientId } = options; | ||
export type Connection = Connection_v0; | ||
export function initialize(options: InitOptions): Connection { | ||
const { | ||
version, | ||
element, | ||
env, | ||
componentVersion, | ||
clientId, | ||
getAuthToken, | ||
clearAuthToken, | ||
} = options; | ||
switch (version) { | ||
@@ -26,2 +37,4 @@ case undefined: // latest | ||
clientId, | ||
getAuthToken, | ||
clearAuthToken, | ||
}); | ||
@@ -33,8 +46,2 @@ default: | ||
} | ||
}; | ||
export type Connection = Connection_v0; | ||
export function initialize(options: InitOptions): Connection { | ||
return getConnection(options); | ||
} |
@@ -19,2 +19,5 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ | ||
element: document.createElement('custom-element'), | ||
getAuthToken: () => undefined, | ||
clearAuthToken: () => {}, | ||
analytics: { track: jest.fn(), report: jest.fn() }, | ||
version: 'version', | ||
@@ -38,2 +41,5 @@ }); | ||
endpoint: () => graphqlEndpoint, | ||
getAuthToken: () => undefined, | ||
clearAuthToken: () => {}, | ||
analytics: { track: jest.fn(), report: jest.fn() }, | ||
element: document.createElement('custom-element'), | ||
@@ -60,2 +66,5 @@ version: 'test', | ||
endpoint: () => graphqlEndpoint, | ||
getAuthToken: () => undefined, | ||
clearAuthToken: () => {}, | ||
analytics: { track: jest.fn(), report: jest.fn() }, | ||
element: document.createElement('custom-element'), | ||
@@ -84,2 +93,5 @@ version: 'test', | ||
endpoint: () => graphqlEndpoint, | ||
getAuthToken: () => undefined, | ||
clearAuthToken: () => {}, | ||
analytics: { track: jest.fn(), report: jest.fn() }, | ||
version, | ||
@@ -95,2 +107,76 @@ element, | ||
}); | ||
describe('Expired auth tokens', () => { | ||
describe('with no retries', () => { | ||
it('throws when expired', async () => { | ||
const fetcher = createGraphqlFetch({ | ||
endpoint: () => graphqlEndpoint, | ||
getAuthToken: () => undefined, | ||
clearAuthToken: () => {}, | ||
analytics: { track: jest.fn(), report: jest.fn() }, | ||
element: document.createElement('custom-element'), | ||
version: 'test', | ||
retries: 0, | ||
waitTime: 0, | ||
}); | ||
fetchMock.mock(graphqlEndpoint, { | ||
status: 200, | ||
body: { errors: [{ extensions: { type: 'AuthFailed' } }] }, | ||
}); | ||
expect.assertions(2); | ||
return fetcher({ query: '' }).catch(result => { | ||
expect(fetchMock.called(graphqlEndpoint)).toBe(true); | ||
expect(result).toEqual( | ||
new ManifoldError({ type: ErrorType.AuthorizationError, message: 'Auth token expired' }) | ||
); | ||
}); | ||
}); | ||
}); | ||
describe('with retries', () => { | ||
it('will retry if the token is refreshed', async () => { | ||
const clearAuthToken = jest.fn(); | ||
const fetcher = createGraphqlFetch({ | ||
endpoint: () => graphqlEndpoint, | ||
getAuthToken: () => undefined, | ||
clearAuthToken, | ||
analytics: { track: jest.fn(), report: jest.fn() }, | ||
element: document.createElement('custom-element'), | ||
version: 'test', | ||
retries: 1, | ||
waitTime: 0, | ||
}); | ||
const body = { data: { title: 'test' } }; | ||
fetchMock | ||
.once(graphqlEndpoint, { | ||
status: 200, | ||
body: { errors: [{ extensions: { type: 'AuthFailed' } }] }, | ||
}) | ||
.mock(graphqlEndpoint, { status: 200, body }, { overwriteRoutes: false }); | ||
const fetch = fetcher({ query: '' }); | ||
/* Queue the dispatch back a tick to allow listeners to be set up */ | ||
await new Promise(resolve => { | ||
setTimeout(() => { | ||
document.dispatchEvent( | ||
new CustomEvent('manifold-auth-token-receive', { detail: { token: '12344' } }) | ||
); | ||
resolve(); | ||
}); | ||
}); | ||
const result = await fetch; | ||
expect(clearAuthToken).toHaveBeenCalled(); | ||
expect(fetchMock.calls()).toHaveLength(2); | ||
expect(result).toEqual(body); | ||
}); | ||
}); | ||
}); | ||
}); |
@@ -0,1 +1,6 @@ | ||
export interface Analytics { | ||
track: (evt: AnalyticsEvent) => Promise<Response>; | ||
report: (det: ErrorDetail) => void; | ||
} | ||
/** | ||
@@ -91,3 +96,3 @@ * Properties that should be found in every analytics event | ||
export default function createAnalytics(args: CreateAnalytics) { | ||
export default function createAnalytics(args: CreateAnalytics): Analytics { | ||
function stringifyProperties(evt: AnalyticsEvent) { | ||
@@ -94,0 +99,0 @@ return { |
import { ManifoldError, ErrorType } from './ManifoldError'; | ||
import { Analytics } from './analytics'; | ||
import { waitForAuthToken } from '../utils/auth'; | ||
@@ -27,2 +29,4 @@ function wait(ms) { | ||
endpoint?: () => string; | ||
getAuthToken: () => string | undefined; | ||
clearAuthToken: () => void; | ||
clientId?: string; | ||
@@ -32,2 +36,4 @@ element: HTMLElement; | ||
retries?: number; | ||
waitTime?: number; | ||
analytics: Analytics; | ||
} | ||
@@ -64,5 +70,9 @@ | ||
endpoint = () => 'https://api.manifold.co/graphql', | ||
getAuthToken, | ||
clearAuthToken, | ||
version, | ||
retries = 3, | ||
clientId, | ||
analytics, | ||
waitTime = 15000, | ||
}: CreateGraphqlFetch): GraphqlFetch { | ||
@@ -79,2 +89,4 @@ const options: RequestInit = { | ||
const token = getAuthToken(); | ||
if (clientId) { | ||
@@ -84,2 +96,7 @@ options.headers['Manifold-Client-ID'] = clientId; | ||
if (token) { | ||
/* eslint-disable-next-line dot-notation */ | ||
options.headers['Authorization'] = `Bearer ${token}`; | ||
} | ||
async function graphqlFetch<T>( | ||
@@ -135,7 +152,21 @@ args: GraphqlRequest, | ||
const authError = findAuthError(body.errors); | ||
if (authError && canRetry) { | ||
// TODO retry auth | ||
return Promise.reject( | ||
new ManifoldError({ type: ErrorType.AuthorizationError, message: authError.message }) | ||
); | ||
if (authError) { | ||
if (!canRetry) { | ||
throw new ManifoldError({ | ||
type: ErrorType.AuthorizationError, | ||
message: 'Auth token expired', | ||
}); | ||
} | ||
try { | ||
clearAuthToken(); | ||
return waitForAuthToken(getAuthToken, waitTime, () => graphqlFetch(args, attempts + 1)); | ||
} catch (e) { | ||
analytics.report({ | ||
message: e.message, | ||
name: 'manifold-init-error', | ||
}); | ||
throw new ManifoldError({ type: ErrorType.AuthorizationError, message: authError.message }); | ||
} | ||
} | ||
@@ -142,0 +173,0 @@ |
@@ -19,5 +19,9 @@ import createAnalytics, { AnalyticsEvent, ErrorDetail } from './analytics'; | ||
clientId?: string; | ||
getAuthToken: () => string | undefined; | ||
clearAuthToken: () => void; | ||
}): Connection => { | ||
const { componentVersion, element, env, clientId } = options; | ||
const { componentVersion, element, env, clientId, getAuthToken, clearAuthToken } = options; | ||
const analytics = createAnalytics({ env, element, componentVersion, clientId }); | ||
return { | ||
@@ -30,3 +34,3 @@ gateway: createGateway({ | ||
case 'local': | ||
return 'https://api.arigato.tools/v1'; | ||
return 'http://api.gateway.arigato.tools/v1'; | ||
default: | ||
@@ -40,3 +44,6 @@ return 'https://api.manifold.co/v1'; | ||
version: componentVersion, | ||
getAuthToken, | ||
clearAuthToken, | ||
clientId, | ||
analytics, | ||
endpoint: () => { | ||
@@ -47,3 +54,3 @@ switch (env) { | ||
case 'local': | ||
return 'https://api.arigato.tools/graphql'; | ||
return 'http://graphql.arigato.tools/graphql'; | ||
default: | ||
@@ -54,3 +61,3 @@ return 'https://api.manifold.co/graphql'; | ||
}), | ||
analytics: createAnalytics({ env, element, componentVersion, clientId }), | ||
analytics, | ||
}; | ||
@@ -57,0 +64,0 @@ }; |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
Dynamic require
Supply chain riskDynamic require can indicate the package is performing dangerous or unsafe dynamic code execution.
Found 1 instance in 1 package
98
0
717347
9485
29